civetweb.c 602 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625
  1. /* Copyright (c) 2013-2021 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #include "civetdefines.h"
  23. #if defined(__GNUC__) || defined(__MINGW32__)
  24. #ifndef GCC_VERSION
  25. #define GCC_VERSION \
  26. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  27. #endif
  28. #if GCC_VERSION >= 40500
  29. /* gcc diagnostic pragmas available */
  30. #define GCC_DIAGNOSTIC
  31. #endif
  32. #endif
  33. #if defined(GCC_DIAGNOSTIC)
  34. /* Disable unused macros warnings - not all defines are required
  35. * for all systems and all compilers. */
  36. #pragma GCC diagnostic ignored "-Wunused-macros"
  37. /* A padding warning is just plain useless */
  38. #pragma GCC diagnostic ignored "-Wpadded"
  39. #endif
  40. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  41. /* We must set some flags for the headers we include. These flags
  42. * are reserved ids according to C99, so we need to disable a
  43. * warning for that. */
  44. #pragma GCC diagnostic push
  45. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  46. #endif
  47. #if defined(_WIN32)
  48. #if !defined(_CRT_SECURE_NO_WARNINGS)
  49. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  50. #endif
  51. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  52. #define _WIN32_WINNT 0x0502
  53. #endif
  54. #else
  55. #if !defined(_GNU_SOURCE)
  56. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  57. #endif
  58. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  59. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  60. #endif
  61. #if defined(__LSB_VERSION__) || defined(__sun)
  62. #define NEED_TIMEGM
  63. #define NO_THREAD_NAME
  64. #endif
  65. #if !defined(_LARGEFILE_SOURCE)
  66. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  67. #endif
  68. #if !defined(_FILE_OFFSET_BITS)
  69. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  70. #endif
  71. #if !defined(__STDC_FORMAT_MACROS)
  72. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  73. #endif
  74. #if !defined(__STDC_LIMIT_MACROS)
  75. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  76. #endif
  77. #if !defined(_DARWIN_UNLIMITED_SELECT)
  78. #define _DARWIN_UNLIMITED_SELECT
  79. #endif
  80. #if defined(__sun)
  81. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  82. #define __inline inline /* not recognized on older compiler versions */
  83. #endif
  84. #endif
  85. #if defined(__clang__)
  86. /* Enable reserved-id-macro warning again. */
  87. #pragma GCC diagnostic pop
  88. #endif
  89. #if defined(USE_LUA)
  90. #define USE_TIMERS
  91. #endif
  92. #if defined(_MSC_VER)
  93. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  94. #pragma warning(disable : 4306)
  95. /* conditional expression is constant: introduced by FD_SET(..) */
  96. #pragma warning(disable : 4127)
  97. /* non-constant aggregate initializer: issued due to missing C99 support */
  98. #pragma warning(disable : 4204)
  99. /* padding added after data member */
  100. #pragma warning(disable : 4820)
  101. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  102. #pragma warning(disable : 4668)
  103. /* no function prototype given: converting '()' to '(void)' */
  104. #pragma warning(disable : 4255)
  105. /* function has been selected for automatic inline expansion */
  106. #pragma warning(disable : 4711)
  107. #endif
  108. /* This code uses static_assert to check some conditions.
  109. * Unfortunately some compilers still do not support it, so we have a
  110. * replacement function here. */
  111. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  112. #define mg_static_assert _Static_assert
  113. #elif defined(__cplusplus) && __cplusplus >= 201103L
  114. #define mg_static_assert static_assert
  115. #else
  116. char static_assert_replacement[1];
  117. #define mg_static_assert(cond, txt) \
  118. extern char static_assert_replacement[(cond) ? 1 : -1]
  119. #endif
  120. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  121. "int data type size check");
  122. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  123. "pointer data type size check");
  124. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  125. /* Select queue implementation. Diagnosis features originally only implemented
  126. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  127. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  128. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  129. * implementation, since the queue length is independent from the number of
  130. * worker threads there, while the new queue is one element per worker thread.
  131. *
  132. */
  133. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  134. /* The queues are exclusive or - only one can be used. */
  135. #error \
  136. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  137. #endif
  138. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  139. /* Use a default implementation */
  140. #define NO_ALTERNATIVE_QUEUE
  141. #endif
  142. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  143. /* File system access:
  144. * NO_FILES = do not serve any files from the file system automatically.
  145. * However, with NO_FILES CivetWeb may still write log files, read access
  146. * control files, default error page files or use API functions like
  147. * mg_send_file in callbacks to send files from the server local
  148. * file system.
  149. * NO_FILES only disables the automatic mapping between URLs and local
  150. * file names.
  151. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  152. * devices without file system. Logging to files in not available
  153. * (use callbacks instead) and API functions like mg_send_file are not
  154. * available.
  155. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  156. */
  157. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  158. #endif
  159. /* DTL -- including winsock2.h works better if lean and mean */
  160. #if !defined(WIN32_LEAN_AND_MEAN)
  161. #define WIN32_LEAN_AND_MEAN
  162. #endif
  163. #if defined(__SYMBIAN32__)
  164. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  165. * Symbian is no longer maintained since 2014-01-01.
  166. * Support for Symbian has been removed from CivetWeb
  167. */
  168. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  169. #endif /* __SYMBIAN32__ */
  170. #if defined(ESP_PLATFORM)
  171. #include <esp_pthread.h>
  172. #include <esp_task.h>
  173. #include <ctype.h>
  174. #include <fcntl.h>
  175. #include <netdb.h>
  176. #include <pthread.h>
  177. #include <stdio.h>
  178. #include <stdlib.h>
  179. #include <string.h>
  180. #include <sys/socket.h>
  181. #include <netdb.h>
  182. #include <time.h>
  183. #include <sys/time.h>
  184. #include "lwip/ip_addr.h"
  185. #include <esp_pthread.h>
  186. #include <esp_task.h>
  187. #include <freertos/FreeRTOS.h>
  188. #include <freertos/timers.h>
  189. #include <freertos/task.h>
  190. #define NEED_TIMEGM
  191. #define NI_NUMERICHOST (1)
  192. #define EAI_OVERFLOW 14
  193. int getnameinfo(const struct sockaddr *sa, socklen_t salen,
  194. char *host, socklen_t hostlen,
  195. char *serv, socklen_t servlen, int flags)
  196. {
  197. if (flags & ~(NI_NUMERICHOST | NI_NUMERICSERV)) {
  198. return EAI_BADFLAGS;
  199. }
  200. const struct sockaddr_in *sinp = (const struct sockaddr_in *) sa;
  201. switch (sa->sa_family) {
  202. case AF_INET:
  203. if (flags & NI_NUMERICHOST) {
  204. if (inet_ntop (AF_INET, &sinp->sin_addr, host, hostlen) == NULL) {
  205. return EAI_OVERFLOW;
  206. }
  207. }
  208. if (flags & NI_NUMERICSERV) {
  209. if (snprintf(serv, servlen, "%d", ntohs (sinp->sin_port)) < 0) {
  210. return EAI_OVERFLOW;
  211. }
  212. }
  213. break;
  214. }
  215. return 0;
  216. }
  217. #define HTTP_ESP_STACK (1024 * 16)
  218. #endif
  219. #if defined(__ZEPHYR__)
  220. #include <ctype.h>
  221. #include <fcntl.h>
  222. #include <netdb.h>
  223. #include <poll.h>
  224. #include <pthread.h>
  225. #include <stdio.h>
  226. #include <stdlib.h>
  227. #include <string.h>
  228. #include <sys/socket.h>
  229. #include <time.h>
  230. #include <zephyr/kernel.h>
  231. /* Max worker threads is the max of pthreads minus the main application thread
  232. * and minus the main civetweb thread, thus -2
  233. */
  234. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  235. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  236. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  237. #else
  238. #define ZEPHYR_STACK_SIZE (1024 * 16)
  239. #endif
  240. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  241. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  242. MAX_WORKER_THREADS,
  243. ZEPHYR_STACK_SIZE);
  244. static int zephyr_worker_stack_index;
  245. #endif
  246. #if !defined(CIVETWEB_HEADER_INCLUDED)
  247. /* Include the header file here, so the CivetWeb interface is defined for the
  248. * entire implementation, including the following forward definitions. */
  249. #include "civetweb.h"
  250. #endif
  251. #if !defined(DEBUG_TRACE)
  252. #if defined(DEBUG)
  253. static void DEBUG_TRACE_FUNC(const char *func,
  254. unsigned line,
  255. PRINTF_FORMAT_STRING(const char *fmt),
  256. ...) PRINTF_ARGS(3, 4);
  257. #define DEBUG_TRACE(fmt, ...) \
  258. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  259. #define NEED_DEBUG_TRACE_FUNC
  260. #if !defined(DEBUG_TRACE_STREAM)
  261. #define DEBUG_TRACE_STREAM stdout
  262. #endif
  263. #else
  264. #define DEBUG_TRACE(fmt, ...) \
  265. do { \
  266. } while (0)
  267. #endif /* DEBUG */
  268. #endif /* DEBUG_TRACE */
  269. #if !defined(DEBUG_ASSERT)
  270. #if defined(DEBUG)
  271. #include <stdlib.h>
  272. #define DEBUG_ASSERT(cond) \
  273. do { \
  274. if (!(cond)) { \
  275. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  276. exit(2); /* Exit with error */ \
  277. } \
  278. } while (0)
  279. #else
  280. #define DEBUG_ASSERT(cond)
  281. #endif /* DEBUG */
  282. #endif
  283. #if defined(ESP_PLATFORM)
  284. typedef struct {
  285. TaskHandle_t task_handle;
  286. StaticTask_t* task_buffer;
  287. StackType_t* x_stack;
  288. size_t stack_size;
  289. mg_thread_func_t entry_func;
  290. void* param;
  291. } cw_freertos_handle;
  292. typedef cw_freertos_handle cw_thread_handle_t;
  293. static void freeRTOSTaskEntryFunc(void* handle) {
  294. cw_thread_handle_t* task_param = (cw_thread_handle_t*) handle;
  295. task_param->entry_func(task_param->param);
  296. // TCB are cleanup in IDLE task, so give it some time
  297. // TODO: IMPLEMENT TCB CLEANUP
  298. vTaskDelete(NULL);
  299. }
  300. static bool cw_is_thread_null(cw_thread_handle_t* handle) {
  301. return handle->task_handle == NULL;
  302. }
  303. static void cw_stop_thread(cw_thread_handle_t* handle) {
  304. handle->task_handle = NULL;
  305. }
  306. #endif
  307. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  308. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  309. __attribute__((no_instrument_function));
  310. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  311. __attribute__((no_instrument_function));
  312. void
  313. __cyg_profile_func_enter(void *this_fn, void *call_site)
  314. {
  315. if ((void *)this_fn != (void *)printf) {
  316. printf("E %p %p\n", this_fn, call_site);
  317. }
  318. }
  319. void
  320. __cyg_profile_func_exit(void *this_fn, void *call_site)
  321. {
  322. if ((void *)this_fn != (void *)printf) {
  323. printf("X %p %p\n", this_fn, call_site);
  324. }
  325. }
  326. #endif
  327. #if !defined(IGNORE_UNUSED_RESULT)
  328. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  329. #endif
  330. #if defined(__GNUC__) || defined(__MINGW32__)
  331. /* GCC unused function attribute seems fundamentally broken.
  332. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  333. * OR UNUSED" for individual functions failed.
  334. * Either the compiler creates an "unused-function" warning if a
  335. * function is not marked with __attribute__((unused)).
  336. * On the other hand, if the function is marked with this attribute,
  337. * but is used, the compiler raises a completely idiotic
  338. * "used-but-marked-unused" warning - and
  339. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  340. * raises error: unknown option after "#pragma GCC diagnostic".
  341. * Disable this warning completely, until the GCC guys sober up
  342. * again.
  343. */
  344. #pragma GCC diagnostic ignored "-Wunused-function"
  345. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  346. #else
  347. #define FUNCTION_MAY_BE_UNUSED
  348. #endif
  349. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  350. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  351. #include <errno.h>
  352. #include <fcntl.h>
  353. #include <signal.h>
  354. #include <stdlib.h>
  355. #include <sys/stat.h>
  356. #include <sys/types.h>
  357. #endif /* !_WIN32_WCE */
  358. #if defined(__clang__)
  359. /* When using -Weverything, clang does not accept it's own headers
  360. * in a release build configuration. Disable what is too much in
  361. * -Weverything. */
  362. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  363. #endif
  364. #if defined(__GNUC__) || defined(__MINGW32__)
  365. /* Who on earth came to the conclusion, using __DATE__ should rise
  366. * an "expansion of date or time macro is not reproducible"
  367. * warning. That's exactly what was intended by using this macro.
  368. * Just disable this nonsense warning. */
  369. /* And disabling them does not work either:
  370. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  371. * #pragma clang diagnostic ignored "-Wdate-time"
  372. * So we just have to disable ALL warnings for some lines
  373. * of code.
  374. * This seems to be a known GCC bug, not resolved since 2012:
  375. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  376. */
  377. #endif
  378. #if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
  379. #if defined(__clang__)
  380. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  381. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  382. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  383. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  384. #endif
  385. #endif
  386. #ifndef CLOCK_MONOTONIC
  387. #define CLOCK_MONOTONIC (1)
  388. #endif
  389. #ifndef CLOCK_REALTIME
  390. #define CLOCK_REALTIME (2)
  391. #endif
  392. #include <mach/clock.h>
  393. #include <mach/mach.h>
  394. #include <mach/mach_time.h>
  395. #include <sys/errno.h>
  396. #include <sys/time.h>
  397. /* clock_gettime is not implemented on OSX prior to 10.12 */
  398. static int
  399. _civet_clock_gettime(int clk_id, struct timespec *t)
  400. {
  401. memset(t, 0, sizeof(*t));
  402. if (clk_id == CLOCK_REALTIME) {
  403. struct timeval now;
  404. int rv = gettimeofday(&now, NULL);
  405. if (rv) {
  406. return rv;
  407. }
  408. t->tv_sec = now.tv_sec;
  409. t->tv_nsec = now.tv_usec * 1000;
  410. return 0;
  411. } else if (clk_id == CLOCK_MONOTONIC) {
  412. static uint64_t clock_start_time = 0;
  413. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  414. uint64_t now = mach_absolute_time();
  415. if (clock_start_time == 0) {
  416. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  417. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  418. /* appease "unused variable" warning for release builds */
  419. (void)mach_status;
  420. clock_start_time = now;
  421. }
  422. now = (uint64_t)((double)(now - clock_start_time)
  423. * (double)timebase_ifo.numer
  424. / (double)timebase_ifo.denom);
  425. t->tv_sec = now / 1000000000;
  426. t->tv_nsec = now % 1000000000;
  427. return 0;
  428. }
  429. return -1; /* EINVAL - Clock ID is unknown */
  430. }
  431. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  432. #if defined(__CLOCK_AVAILABILITY)
  433. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  434. * declared but it may be NULL at runtime. So we need to check before using
  435. * it. */
  436. static int
  437. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  438. {
  439. if (clock_gettime) {
  440. return clock_gettime(clk_id, t);
  441. }
  442. return _civet_clock_gettime(clk_id, t);
  443. }
  444. #define clock_gettime _civet_safe_clock_gettime
  445. #else
  446. #define clock_gettime _civet_clock_gettime
  447. #endif
  448. #endif
  449. #if !defined(_WIN32)
  450. /* Unix might return different error codes indicating to try again.
  451. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  452. * decades ago, but better check both and let the compile optimize it. */
  453. #define ERROR_TRY_AGAIN(err) \
  454. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  455. #endif
  456. #if defined(USE_ZLIB)
  457. #include "zconf.h"
  458. #include "zlib.h"
  459. #endif
  460. /********************************************************************/
  461. /* CivetWeb configuration defines */
  462. /********************************************************************/
  463. /* Maximum number of threads that can be configured.
  464. * The number of threads actually created depends on the "num_threads"
  465. * configuration parameter, but this is the upper limit. */
  466. #if !defined(MAX_WORKER_THREADS)
  467. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  468. #endif
  469. /* Timeout interval for select/poll calls.
  470. * The timeouts depend on "*_timeout_ms" configuration values, but long
  471. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  472. * This reduces the time required to stop the server. */
  473. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  474. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  475. #endif
  476. /* Do not try to compress files smaller than this limit. */
  477. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  478. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  479. #endif
  480. #if !defined(PASSWORDS_FILE_NAME)
  481. #define PASSWORDS_FILE_NAME ".htpasswd"
  482. #endif
  483. /* Initial buffer size for all CGI environment variables. In case there is
  484. * not enough space, another block is allocated. */
  485. #if !defined(CGI_ENVIRONMENT_SIZE)
  486. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  487. #endif
  488. /* Maximum number of environment variables. */
  489. #if !defined(MAX_CGI_ENVIR_VARS)
  490. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  491. #endif
  492. /* General purpose buffer size. */
  493. #if !defined(MG_BUF_LEN) /* in bytes */
  494. #define MG_BUF_LEN (1024 * 4)
  495. #endif
  496. /********************************************************************/
  497. /* Helper makros */
  498. #if !defined(ARRAY_SIZE)
  499. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  500. #endif
  501. #include <stdint.h>
  502. /* Standard defines */
  503. #if !defined(INT64_MAX)
  504. #define INT64_MAX (9223372036854775807)
  505. #endif
  506. #define SHUTDOWN_RD (0)
  507. #define SHUTDOWN_WR (1)
  508. #define SHUTDOWN_BOTH (2)
  509. mg_static_assert(MAX_WORKER_THREADS >= 1,
  510. "worker threads must be a positive number");
  511. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  512. "size_t data type size check");
  513. #if defined(_WIN32) /* WINDOWS include block */
  514. #include <malloc.h> /* *alloc( */
  515. #include <stdlib.h> /* *alloc( */
  516. #include <time.h> /* struct timespec */
  517. #include <windows.h>
  518. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  519. #include <ws2tcpip.h>
  520. #include <stdbool.h>
  521. typedef const char *SOCK_OPT_TYPE;
  522. /* For a detailed description of these *_PATH_MAX defines, see
  523. * https://github.com/civetweb/civetweb/issues/937. */
  524. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  525. * null termination, rounded up to the next 4 bytes boundary */
  526. #define UTF8_PATH_MAX (3 * 260)
  527. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  528. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  529. #define UTF16_PATH_MAX (260)
  530. #if !defined(_IN_PORT_T)
  531. #if !defined(in_port_t)
  532. #define in_port_t u_short
  533. #endif
  534. #endif
  535. #if defined(_WIN32_WCE)
  536. #error "WinCE support has ended"
  537. #endif
  538. #include <direct.h>
  539. #include <io.h>
  540. #include <process.h>
  541. #define MAKEUQUAD(lo, hi) \
  542. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  543. #define RATE_DIFF (10000000) /* 100 nsecs */
  544. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  545. #define SYS2UNIX_TIME(lo, hi) \
  546. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  547. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  548. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  549. * Also use _strtoui64 on modern M$ compilers */
  550. #if defined(_MSC_VER)
  551. #if (_MSC_VER < 1300)
  552. #define STRX(x) #x
  553. #define STR(x) STRX(x)
  554. #define __func__ __FILE__ ":" STR(__LINE__)
  555. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  556. #define strtoll(x, y, z) (_atoi64(x))
  557. #else
  558. #define __func__ __FUNCTION__
  559. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  560. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  561. #endif
  562. #endif /* _MSC_VER */
  563. #define ERRNO ((int)(GetLastError()))
  564. #define NO_SOCKLEN_T
  565. #if defined(_WIN64) || defined(__MINGW64__)
  566. #if !defined(SSL_LIB)
  567. #if defined(OPENSSL_API_3_0)
  568. #define SSL_LIB "libssl-3-x64.dll"
  569. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  570. #endif
  571. #if defined(OPENSSL_API_1_1)
  572. #define SSL_LIB "libssl-1_1-x64.dll"
  573. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  574. #endif /* OPENSSL_API_1_1 */
  575. #if defined(OPENSSL_API_1_0)
  576. #define SSL_LIB "ssleay64.dll"
  577. #define CRYPTO_LIB "libeay64.dll"
  578. #endif /* OPENSSL_API_1_0 */
  579. #endif
  580. #else /* defined(_WIN64) || defined(__MINGW64__) */
  581. #if !defined(SSL_LIB)
  582. #if defined(OPENSSL_API_3_0)
  583. #define SSL_LIB "libssl-3.dll"
  584. #define CRYPTO_LIB "libcrypto-3.dll"
  585. #endif
  586. #if defined(OPENSSL_API_1_1)
  587. #define SSL_LIB "libssl-1_1.dll"
  588. #define CRYPTO_LIB "libcrypto-1_1.dll"
  589. #endif /* OPENSSL_API_1_1 */
  590. #if defined(OPENSSL_API_1_0)
  591. #define SSL_LIB "ssleay32.dll"
  592. #define CRYPTO_LIB "libeay32.dll"
  593. #endif /* OPENSSL_API_1_0 */
  594. #endif /* SSL_LIB */
  595. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  596. #define O_NONBLOCK (0)
  597. #if !defined(W_OK)
  598. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  599. #endif
  600. #define _POSIX_
  601. #define INT64_FMT "I64d"
  602. #define UINT64_FMT "I64u"
  603. #define WINCDECL __cdecl
  604. #define vsnprintf_impl _vsnprintf
  605. #define access _access
  606. #define mg_sleep(x) (Sleep(x))
  607. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  608. #if !defined(popen)
  609. #define popen(x, y) (_popen(x, y))
  610. #endif
  611. #if !defined(pclose)
  612. #define pclose(x) (_pclose(x))
  613. #endif
  614. #define close(x) (_close(x))
  615. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  616. #define RTLD_LAZY (0)
  617. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  618. #define fdopen(x, y) (_fdopen((x), (y)))
  619. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  620. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  621. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  622. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  623. #define sleep(x) (Sleep((x)*1000))
  624. #define rmdir(x) (_rmdir(x))
  625. #if defined(_WIN64) || !defined(__MINGW32__)
  626. /* Only MinGW 32 bit is missing this function */
  627. #define timegm(x) (_mkgmtime(x))
  628. #else
  629. time_t timegm(struct tm *tm);
  630. #define NEED_TIMEGM
  631. #endif
  632. #if !defined(fileno)
  633. #define fileno(x) (_fileno(x))
  634. #endif /* !fileno MINGW #defines fileno */
  635. typedef struct {
  636. CRITICAL_SECTION sec; /* Immovable */
  637. } pthread_mutex_t;
  638. typedef DWORD pthread_key_t;
  639. typedef HANDLE pthread_t;
  640. typedef pthread_t cw_thread_handle_t;
  641. typedef struct {
  642. pthread_mutex_t threadIdSec;
  643. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  644. } pthread_cond_t;
  645. #if !defined(__clockid_t_defined)
  646. typedef DWORD clockid_t;
  647. #endif
  648. #if !defined(CLOCK_MONOTONIC)
  649. #define CLOCK_MONOTONIC (1)
  650. #endif
  651. #if !defined(CLOCK_REALTIME)
  652. #define CLOCK_REALTIME (2)
  653. #endif
  654. #if !defined(CLOCK_THREAD)
  655. #define CLOCK_THREAD (3)
  656. #endif
  657. #if !defined(CLOCK_PROCESS)
  658. #define CLOCK_PROCESS (4)
  659. #endif
  660. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  661. #define _TIMESPEC_DEFINED
  662. #endif
  663. #if !defined(_TIMESPEC_DEFINED)
  664. struct timespec {
  665. time_t tv_sec; /* seconds */
  666. long tv_nsec; /* nanoseconds */
  667. };
  668. #endif
  669. #if !defined(WIN_PTHREADS_TIME_H)
  670. #define MUST_IMPLEMENT_CLOCK_GETTIME
  671. #endif
  672. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  673. #define clock_gettime mg_clock_gettime
  674. static int
  675. clock_gettime(clockid_t clk_id, struct timespec *tp)
  676. {
  677. FILETIME ft;
  678. ULARGE_INTEGER li, li2;
  679. BOOL ok = FALSE;
  680. double d;
  681. static double perfcnt_per_sec = 0.0;
  682. static BOOL initialized = FALSE;
  683. if (!initialized) {
  684. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  685. perfcnt_per_sec = 1.0 / li.QuadPart;
  686. initialized = TRUE;
  687. }
  688. if (tp) {
  689. memset(tp, 0, sizeof(*tp));
  690. if (clk_id == CLOCK_REALTIME) {
  691. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  692. GetSystemTimeAsFileTime(&ft);
  693. li.LowPart = ft.dwLowDateTime;
  694. li.HighPart = ft.dwHighDateTime;
  695. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  696. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  697. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  698. ok = TRUE;
  699. /* END: CLOCK_REALTIME */
  700. } else if (clk_id == CLOCK_MONOTONIC) {
  701. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  702. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  703. d = li.QuadPart * perfcnt_per_sec;
  704. tp->tv_sec = (time_t)d;
  705. d -= (double)tp->tv_sec;
  706. tp->tv_nsec = (long)(d * 1.0E9);
  707. ok = TRUE;
  708. /* END: CLOCK_MONOTONIC */
  709. } else if (clk_id == CLOCK_THREAD) {
  710. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  711. FILETIME t_create, t_exit, t_kernel, t_user;
  712. if (GetThreadTimes(GetCurrentThread(),
  713. &t_create,
  714. &t_exit,
  715. &t_kernel,
  716. &t_user)) {
  717. li.LowPart = t_user.dwLowDateTime;
  718. li.HighPart = t_user.dwHighDateTime;
  719. li2.LowPart = t_kernel.dwLowDateTime;
  720. li2.HighPart = t_kernel.dwHighDateTime;
  721. li.QuadPart += li2.QuadPart;
  722. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  723. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  724. ok = TRUE;
  725. }
  726. /* END: CLOCK_THREAD */
  727. } else if (clk_id == CLOCK_PROCESS) {
  728. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  729. FILETIME t_create, t_exit, t_kernel, t_user;
  730. if (GetProcessTimes(GetCurrentProcess(),
  731. &t_create,
  732. &t_exit,
  733. &t_kernel,
  734. &t_user)) {
  735. li.LowPart = t_user.dwLowDateTime;
  736. li.HighPart = t_user.dwHighDateTime;
  737. li2.LowPart = t_kernel.dwLowDateTime;
  738. li2.HighPart = t_kernel.dwHighDateTime;
  739. li.QuadPart += li2.QuadPart;
  740. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  741. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  742. ok = TRUE;
  743. }
  744. /* END: CLOCK_PROCESS */
  745. } else {
  746. /* BEGIN: unknown clock */
  747. /* ok = FALSE; already set by init */
  748. /* END: unknown clock */
  749. }
  750. }
  751. return ok ? 0 : -1;
  752. }
  753. #endif
  754. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  755. static int pthread_mutex_lock(pthread_mutex_t *);
  756. static int pthread_mutex_unlock(pthread_mutex_t *);
  757. static void path_to_unicode(const struct mg_connection *conn,
  758. const char *path,
  759. wchar_t *wbuf,
  760. size_t wbuf_len);
  761. /* All file operations need to be rewritten to solve #246. */
  762. struct mg_file;
  763. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  764. static bool cw_is_thread_null(cw_thread_handle_t* handle) {
  765. return *handle == 0;
  766. }
  767. static void cw_stop_thread(cw_thread_handle_t* handle) {
  768. *handle = 0;
  769. }
  770. /* POSIX dirent interface */
  771. struct dirent {
  772. char d_name[UTF8_PATH_MAX];
  773. };
  774. typedef struct DIR {
  775. HANDLE handle;
  776. WIN32_FIND_DATAW info;
  777. struct dirent result;
  778. } DIR;
  779. #if defined(HAVE_POLL)
  780. #define mg_pollfd pollfd
  781. #else
  782. struct mg_pollfd {
  783. SOCKET fd;
  784. short events;
  785. short revents;
  786. };
  787. #endif
  788. /* Mark required libraries */
  789. #if defined(_MSC_VER)
  790. #pragma comment(lib, "Ws2_32.lib")
  791. #endif
  792. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  793. #include <inttypes.h>
  794. /* Linux & co. internally use UTF8 */
  795. #define UTF8_PATH_MAX (PATH_MAX)
  796. typedef const void *SOCK_OPT_TYPE;
  797. #if defined(ANDROID)
  798. typedef unsigned short int in_port_t;
  799. #endif
  800. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  801. #include <arpa/inet.h>
  802. #include <ctype.h>
  803. #include <dirent.h>
  804. #include <grp.h>
  805. #include <limits.h>
  806. #include <netdb.h>
  807. #include <netinet/in.h>
  808. #include <netinet/tcp.h>
  809. #include <pthread.h>
  810. #include <pwd.h>
  811. #include <stdarg.h>
  812. #include <stddef.h>
  813. #include <stdio.h>
  814. #include <stdlib.h>
  815. #include <string.h>
  816. #include <sys/poll.h>
  817. #include <sys/socket.h>
  818. #include <sys/time.h>
  819. #include <sys/utsname.h>
  820. #include <sys/wait.h>
  821. #include <time.h>
  822. #include <unistd.h>
  823. #include <stdbool.h>
  824. typedef pthread_t cw_thread_handle_t;
  825. static bool cw_is_thread_null(cw_thread_handle_t* handle) {
  826. return *handle == 0;
  827. }
  828. static void cw_stop_thread(cw_thread_handle_t* handle) {
  829. *handle = 0;
  830. }
  831. #if defined(USE_X_DOM_SOCKET)
  832. #include <sys/un.h>
  833. #endif
  834. #endif
  835. #define vsnprintf_impl vsnprintf
  836. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  837. #include <dlfcn.h>
  838. #endif
  839. #if defined(__MACH__) && defined(__APPLE__)
  840. #define SSL_LIB "libssl.dylib"
  841. #define CRYPTO_LIB "libcrypto.dylib"
  842. #else
  843. #if !defined(SSL_LIB)
  844. #define SSL_LIB "libssl.so"
  845. #endif
  846. #if !defined(CRYPTO_LIB)
  847. #define CRYPTO_LIB "libcrypto.so"
  848. #endif
  849. #endif
  850. #if !defined(O_BINARY)
  851. #define O_BINARY (0)
  852. #endif /* O_BINARY */
  853. #define closesocket(a) (close(a))
  854. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  855. #define mg_remove(conn, x) (remove(x))
  856. #define mg_sleep(x) (usleep((x)*1000))
  857. #define mg_opendir(conn, x) (opendir(x))
  858. #define mg_closedir(x) (closedir(x))
  859. #define mg_readdir(x) (readdir(x))
  860. #define ERRNO (errno)
  861. #define INVALID_SOCKET (-1)
  862. #define INT64_FMT PRId64
  863. #define UINT64_FMT PRIu64
  864. typedef int SOCKET;
  865. #define WINCDECL
  866. #if defined(__hpux)
  867. /* HPUX 11 does not have monotonic, fall back to realtime */
  868. #if !defined(CLOCK_MONOTONIC)
  869. #define CLOCK_MONOTONIC CLOCK_REALTIME
  870. #endif
  871. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  872. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  873. * the prototypes use int* rather than socklen_t* which matches the
  874. * actual library expectation. When called with the wrong size arg
  875. * accept() returns a zero client inet addr and check_acl() always
  876. * fails. Since socklen_t is widely used below, just force replace
  877. * their typedef with int. - DTL
  878. */
  879. #define socklen_t int
  880. #endif /* hpux */
  881. #define mg_pollfd pollfd
  882. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  883. /* In case our C library is missing "timegm", provide an implementation */
  884. #if defined(NEED_TIMEGM)
  885. static inline int
  886. is_leap(int y)
  887. {
  888. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  889. }
  890. static inline int
  891. count_leap(int y)
  892. {
  893. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  894. }
  895. time_t
  896. timegm(struct tm *tm)
  897. {
  898. static const unsigned short ydays[] = {
  899. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  900. int year = tm->tm_year + 1900;
  901. int mon = tm->tm_mon;
  902. int mday = tm->tm_mday - 1;
  903. int hour = tm->tm_hour;
  904. int min = tm->tm_min;
  905. int sec = tm->tm_sec;
  906. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  907. || (mday >= ydays[mon + 1] - ydays[mon]
  908. + (mon == 1 && is_leap(year) ? 1 : 0))
  909. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  910. return -1;
  911. time_t res = year - 1970;
  912. res *= 365;
  913. res += mday;
  914. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  915. res += count_leap(year);
  916. res *= 24;
  917. res += hour;
  918. res *= 60;
  919. res += min;
  920. res *= 60;
  921. res += sec;
  922. return res;
  923. }
  924. #endif /* NEED_TIMEGM */
  925. /* va_copy should always be a macro, C99 and C++11 - DTL */
  926. #if !defined(va_copy)
  927. #define va_copy(x, y) ((x) = (y))
  928. #endif
  929. #if defined(_WIN32)
  930. /* Create substitutes for POSIX functions in Win32. */
  931. #if defined(GCC_DIAGNOSTIC)
  932. /* Show no warning in case system functions are not used. */
  933. #pragma GCC diagnostic push
  934. #pragma GCC diagnostic ignored "-Wunused-function"
  935. #endif
  936. static pthread_mutex_t global_log_file_lock;
  937. FUNCTION_MAY_BE_UNUSED
  938. static DWORD
  939. pthread_self(void)
  940. {
  941. return GetCurrentThreadId();
  942. }
  943. FUNCTION_MAY_BE_UNUSED
  944. static int
  945. pthread_key_create(
  946. pthread_key_t *key,
  947. void (*_ignored)(void *) /* destructor not supported for Windows */
  948. )
  949. {
  950. (void)_ignored;
  951. if ((key != 0)) {
  952. *key = TlsAlloc();
  953. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  954. }
  955. return -2;
  956. }
  957. FUNCTION_MAY_BE_UNUSED
  958. static int
  959. pthread_key_delete(pthread_key_t key)
  960. {
  961. return TlsFree(key) ? 0 : 1;
  962. }
  963. FUNCTION_MAY_BE_UNUSED
  964. static int
  965. pthread_setspecific(pthread_key_t key, void *value)
  966. {
  967. return TlsSetValue(key, value) ? 0 : 1;
  968. }
  969. FUNCTION_MAY_BE_UNUSED
  970. static void *
  971. pthread_getspecific(pthread_key_t key)
  972. {
  973. return TlsGetValue(key);
  974. }
  975. #if defined(GCC_DIAGNOSTIC)
  976. /* Enable unused function warning again */
  977. #pragma GCC diagnostic pop
  978. #endif
  979. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  980. #else
  981. static pthread_mutexattr_t pthread_mutex_attr;
  982. #endif /* _WIN32 */
  983. #if defined(GCC_DIAGNOSTIC)
  984. /* Show no warning in case system functions are not used. */
  985. #pragma GCC diagnostic push
  986. #pragma GCC diagnostic ignored "-Wunused-function"
  987. #endif /* defined(GCC_DIAGNOSTIC) */
  988. #if defined(__clang__)
  989. /* Show no warning in case system functions are not used. */
  990. #pragma clang diagnostic push
  991. #pragma clang diagnostic ignored "-Wunused-function"
  992. #endif
  993. static pthread_mutex_t global_lock_mutex;
  994. FUNCTION_MAY_BE_UNUSED
  995. static void
  996. mg_global_lock(void)
  997. {
  998. (void)pthread_mutex_lock(&global_lock_mutex);
  999. }
  1000. FUNCTION_MAY_BE_UNUSED
  1001. static void
  1002. mg_global_unlock(void)
  1003. {
  1004. (void)pthread_mutex_unlock(&global_lock_mutex);
  1005. }
  1006. #if defined(_WIN64)
  1007. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  1008. #elif defined(_WIN32)
  1009. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  1010. #endif
  1011. /* Atomic functions working on ptrdiff_t ("signed size_t").
  1012. * Operations: Increment, Decrement, Add, Maximum.
  1013. * Up to size_t, they do not an atomic "load" operation.
  1014. */
  1015. FUNCTION_MAY_BE_UNUSED
  1016. static ptrdiff_t
  1017. mg_atomic_inc(volatile ptrdiff_t *addr)
  1018. {
  1019. ptrdiff_t ret;
  1020. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1021. ret = InterlockedIncrement64(addr);
  1022. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1023. ret = InterlockedIncrement(addr);
  1024. #elif defined(__GNUC__) \
  1025. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1026. && !defined(NO_ATOMICS)
  1027. ret = __sync_add_and_fetch(addr, 1);
  1028. #else
  1029. mg_global_lock();
  1030. ret = (++(*addr));
  1031. mg_global_unlock();
  1032. #endif
  1033. return ret;
  1034. }
  1035. FUNCTION_MAY_BE_UNUSED
  1036. static ptrdiff_t
  1037. mg_atomic_dec(volatile ptrdiff_t *addr)
  1038. {
  1039. ptrdiff_t ret;
  1040. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1041. ret = InterlockedDecrement64(addr);
  1042. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1043. ret = InterlockedDecrement(addr);
  1044. #elif defined(__GNUC__) \
  1045. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1046. && !defined(NO_ATOMICS)
  1047. ret = __sync_sub_and_fetch(addr, 1);
  1048. #else
  1049. mg_global_lock();
  1050. ret = (--(*addr));
  1051. mg_global_unlock();
  1052. #endif
  1053. return ret;
  1054. }
  1055. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  1056. static ptrdiff_t
  1057. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1058. {
  1059. ptrdiff_t ret;
  1060. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1061. ret = InterlockedAdd64(addr, value);
  1062. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1063. ret = InterlockedExchangeAdd(addr, value) + value;
  1064. #elif defined(__GNUC__) \
  1065. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1066. && !defined(NO_ATOMICS)
  1067. ret = __sync_add_and_fetch(addr, value);
  1068. #else
  1069. mg_global_lock();
  1070. *addr += value;
  1071. ret = (*addr);
  1072. mg_global_unlock();
  1073. #endif
  1074. return ret;
  1075. }
  1076. FUNCTION_MAY_BE_UNUSED
  1077. static ptrdiff_t
  1078. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1079. ptrdiff_t oldval,
  1080. ptrdiff_t newval)
  1081. {
  1082. ptrdiff_t ret;
  1083. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1084. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1085. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1086. ret = InterlockedCompareExchange(addr, newval, oldval);
  1087. #elif defined(__GNUC__) \
  1088. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1089. && !defined(NO_ATOMICS)
  1090. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1091. #else
  1092. mg_global_lock();
  1093. ret = *addr;
  1094. if ((ret != newval) && (ret == oldval)) {
  1095. *addr = newval;
  1096. }
  1097. mg_global_unlock();
  1098. #endif
  1099. return ret;
  1100. }
  1101. static void
  1102. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1103. {
  1104. register ptrdiff_t tmp = *addr;
  1105. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1106. while (tmp < value) {
  1107. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1108. }
  1109. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1110. while (tmp < value) {
  1111. tmp = InterlockedCompareExchange(addr, value, tmp);
  1112. }
  1113. #elif defined(__GNUC__) \
  1114. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1115. && !defined(NO_ATOMICS)
  1116. while (tmp < value) {
  1117. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1118. }
  1119. #else
  1120. mg_global_lock();
  1121. if (*addr < value) {
  1122. *addr = value;
  1123. }
  1124. mg_global_unlock();
  1125. #endif
  1126. }
  1127. static int64_t
  1128. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1129. {
  1130. int64_t ret;
  1131. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1132. ret = InterlockedAdd64(addr, value);
  1133. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1134. ret = InterlockedExchangeAdd64(addr, value) + value;
  1135. #elif defined(__GNUC__) \
  1136. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1137. && !defined(NO_ATOMICS)
  1138. ret = __sync_add_and_fetch(addr, value);
  1139. #else
  1140. mg_global_lock();
  1141. *addr += value;
  1142. ret = (*addr);
  1143. mg_global_unlock();
  1144. #endif
  1145. return ret;
  1146. }
  1147. #endif
  1148. #if defined(GCC_DIAGNOSTIC)
  1149. /* Show no warning in case system functions are not used. */
  1150. #pragma GCC diagnostic pop
  1151. #endif /* defined(GCC_DIAGNOSTIC) */
  1152. #if defined(__clang__)
  1153. /* Show no warning in case system functions are not used. */
  1154. #pragma clang diagnostic pop
  1155. #endif
  1156. #if defined(USE_SERVER_STATS)
  1157. struct mg_memory_stat {
  1158. volatile ptrdiff_t totalMemUsed;
  1159. volatile ptrdiff_t maxMemUsed;
  1160. volatile ptrdiff_t blockCount;
  1161. };
  1162. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1163. static void *
  1164. mg_malloc_ex(size_t size,
  1165. struct mg_context *ctx,
  1166. const char *file,
  1167. unsigned line)
  1168. {
  1169. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1170. void *memory = 0;
  1171. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1172. #if defined(MEMORY_DEBUGGING)
  1173. char mallocStr[256];
  1174. #else
  1175. (void)file;
  1176. (void)line;
  1177. #endif
  1178. if (data) {
  1179. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1180. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1181. mg_atomic_inc(&mstat->blockCount);
  1182. ((uintptr_t *)data)[0] = size;
  1183. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1184. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1185. }
  1186. #if defined(MEMORY_DEBUGGING)
  1187. sprintf(mallocStr,
  1188. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1189. memory,
  1190. (unsigned long)size,
  1191. (unsigned long)mstat->totalMemUsed,
  1192. (unsigned long)mstat->blockCount,
  1193. file,
  1194. line);
  1195. DEBUG_TRACE("%s", mallocStr);
  1196. #endif
  1197. return memory;
  1198. }
  1199. static void *
  1200. mg_calloc_ex(size_t count,
  1201. size_t size,
  1202. struct mg_context *ctx,
  1203. const char *file,
  1204. unsigned line)
  1205. {
  1206. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1207. if (data) {
  1208. memset(data, 0, size * count);
  1209. }
  1210. return data;
  1211. }
  1212. static void
  1213. mg_free_ex(void *memory, const char *file, unsigned line)
  1214. {
  1215. #if defined(MEMORY_DEBUGGING)
  1216. char mallocStr[256];
  1217. #else
  1218. (void)file;
  1219. (void)line;
  1220. #endif
  1221. if (memory) {
  1222. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1223. uintptr_t size = ((uintptr_t *)data)[0];
  1224. struct mg_memory_stat *mstat =
  1225. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1226. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1227. mg_atomic_dec(&mstat->blockCount);
  1228. #if defined(MEMORY_DEBUGGING)
  1229. sprintf(mallocStr,
  1230. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1231. memory,
  1232. (unsigned long)size,
  1233. (unsigned long)mstat->totalMemUsed,
  1234. (unsigned long)mstat->blockCount,
  1235. file,
  1236. line);
  1237. DEBUG_TRACE("%s", mallocStr);
  1238. #endif
  1239. free(data);
  1240. }
  1241. }
  1242. static void *
  1243. mg_realloc_ex(void *memory,
  1244. size_t newsize,
  1245. struct mg_context *ctx,
  1246. const char *file,
  1247. unsigned line)
  1248. {
  1249. void *data;
  1250. void *_realloc;
  1251. uintptr_t oldsize;
  1252. #if defined(MEMORY_DEBUGGING)
  1253. char mallocStr[256];
  1254. #else
  1255. (void)file;
  1256. (void)line;
  1257. #endif
  1258. if (newsize) {
  1259. if (memory) {
  1260. /* Reallocate existing block */
  1261. struct mg_memory_stat *mstat;
  1262. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1263. oldsize = ((uintptr_t *)data)[0];
  1264. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1265. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1266. if (_realloc) {
  1267. data = _realloc;
  1268. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1269. #if defined(MEMORY_DEBUGGING)
  1270. sprintf(mallocStr,
  1271. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1272. memory,
  1273. (unsigned long)oldsize,
  1274. (unsigned long)mstat->totalMemUsed,
  1275. (unsigned long)mstat->blockCount,
  1276. file,
  1277. line);
  1278. DEBUG_TRACE("%s", mallocStr);
  1279. #endif
  1280. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1281. #if defined(MEMORY_DEBUGGING)
  1282. sprintf(mallocStr,
  1283. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1284. memory,
  1285. (unsigned long)newsize,
  1286. (unsigned long)mstat->totalMemUsed,
  1287. (unsigned long)mstat->blockCount,
  1288. file,
  1289. line);
  1290. DEBUG_TRACE("%s", mallocStr);
  1291. #endif
  1292. *(uintptr_t *)data = newsize;
  1293. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1294. } else {
  1295. #if defined(MEMORY_DEBUGGING)
  1296. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1297. #endif
  1298. return _realloc;
  1299. }
  1300. } else {
  1301. /* Allocate new block */
  1302. data = mg_malloc_ex(newsize, ctx, file, line);
  1303. }
  1304. } else {
  1305. /* Free existing block */
  1306. data = 0;
  1307. mg_free_ex(memory, file, line);
  1308. }
  1309. return data;
  1310. }
  1311. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1312. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1313. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1314. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1315. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1316. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1317. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1318. #else /* USE_SERVER_STATS */
  1319. static __inline void *
  1320. mg_malloc(size_t a)
  1321. {
  1322. return malloc(a);
  1323. }
  1324. static __inline void *
  1325. mg_calloc(size_t a, size_t b)
  1326. {
  1327. return calloc(a, b);
  1328. }
  1329. static __inline void *
  1330. mg_realloc(void *a, size_t b)
  1331. {
  1332. return realloc(a, b);
  1333. }
  1334. static __inline void
  1335. mg_free(void *a)
  1336. {
  1337. free(a);
  1338. }
  1339. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1340. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1341. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1342. #define mg_free_ctx(a, c) mg_free(a)
  1343. #endif /* USE_SERVER_STATS */
  1344. static void mg_vsnprintf(const struct mg_connection *conn,
  1345. int *truncated,
  1346. char *buf,
  1347. size_t buflen,
  1348. const char *fmt,
  1349. va_list ap);
  1350. static void mg_snprintf(const struct mg_connection *conn,
  1351. int *truncated,
  1352. char *buf,
  1353. size_t buflen,
  1354. PRINTF_FORMAT_STRING(const char *fmt),
  1355. ...) PRINTF_ARGS(5, 6);
  1356. /* This following lines are just meant as a reminder to use the mg-functions
  1357. * for memory management */
  1358. #if defined(malloc)
  1359. #undef malloc
  1360. #endif
  1361. #if defined(calloc)
  1362. #undef calloc
  1363. #endif
  1364. #if defined(realloc)
  1365. #undef realloc
  1366. #endif
  1367. #if defined(free)
  1368. #undef free
  1369. #endif
  1370. #if defined(snprintf)
  1371. #undef snprintf
  1372. #endif
  1373. #if defined(vsnprintf)
  1374. #undef vsnprintf
  1375. #endif
  1376. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1377. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1378. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1379. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1380. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1381. #if defined(_WIN32)
  1382. /* vsnprintf must not be used in any system,
  1383. * but this define only works well for Windows. */
  1384. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1385. #endif
  1386. /* mg_init_library counter */
  1387. static int mg_init_library_called = 0;
  1388. #if !defined(NO_SSL)
  1389. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1390. || defined(OPENSSL_API_3_0)
  1391. static int mg_openssl_initialized = 0;
  1392. #endif
  1393. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1394. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1395. #error "Please define OPENSSL_API_#_# or USE_MBEDTLS"
  1396. #endif
  1397. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1398. #error "Multiple OPENSSL_API versions defined"
  1399. #endif
  1400. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1401. #error "Multiple OPENSSL_API versions defined"
  1402. #endif
  1403. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1404. #error "Multiple OPENSSL_API versions defined"
  1405. #endif
  1406. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1407. || defined(OPENSSL_API_3_0)) \
  1408. && defined(USE_MBEDTLS)
  1409. #error "Multiple SSL libraries defined"
  1410. #endif
  1411. #endif
  1412. static pthread_key_t sTlsKey; /* Thread local storage index */
  1413. static volatile ptrdiff_t thread_idx_max = 0;
  1414. #if defined(MG_LEGACY_INTERFACE)
  1415. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1416. #endif
  1417. struct mg_workerTLS {
  1418. int is_master;
  1419. unsigned long thread_idx;
  1420. void *user_ptr;
  1421. #if defined(_WIN32)
  1422. HANDLE pthread_cond_helper_mutex;
  1423. struct mg_workerTLS *next_waiting_thread;
  1424. #endif
  1425. const char *alpn_proto;
  1426. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1427. char txtbuf[4];
  1428. #endif
  1429. };
  1430. #if defined(GCC_DIAGNOSTIC)
  1431. /* Show no warning in case system functions are not used. */
  1432. #pragma GCC diagnostic push
  1433. #pragma GCC diagnostic ignored "-Wunused-function"
  1434. #endif /* defined(GCC_DIAGNOSTIC) */
  1435. #if defined(__clang__)
  1436. /* Show no warning in case system functions are not used. */
  1437. #pragma clang diagnostic push
  1438. #pragma clang diagnostic ignored "-Wunused-function"
  1439. #endif
  1440. /* Get a unique thread ID as unsigned long, independent from the data type
  1441. * of thread IDs defined by the operating system API.
  1442. * If two calls to mg_current_thread_id return the same value, they calls
  1443. * are done from the same thread. If they return different values, they are
  1444. * done from different threads. (Provided this function is used in the same
  1445. * process context and threads are not repeatedly created and deleted, but
  1446. * CivetWeb does not do that).
  1447. * This function must match the signature required for SSL id callbacks:
  1448. * CRYPTO_set_id_callback
  1449. */
  1450. FUNCTION_MAY_BE_UNUSED
  1451. static unsigned long
  1452. mg_current_thread_id(void)
  1453. {
  1454. #if defined(_WIN32)
  1455. return GetCurrentThreadId();
  1456. #else
  1457. #if defined(__clang__)
  1458. #pragma clang diagnostic push
  1459. #pragma clang diagnostic ignored "-Wunreachable-code"
  1460. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1461. * or not, so one of the two conditions will be unreachable by construction.
  1462. * Unfortunately the C standard does not define a way to check this at
  1463. * compile time, since the #if preprocessor conditions can not use the
  1464. * sizeof operator as an argument. */
  1465. #endif
  1466. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1467. /* This is the problematic case for CRYPTO_set_id_callback:
  1468. * The OS pthread_t can not be cast to unsigned long. */
  1469. struct mg_workerTLS *tls =
  1470. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1471. if (tls == NULL) {
  1472. /* SSL called from an unknown thread: Create some thread index.
  1473. */
  1474. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1475. tls->is_master = -2; /* -2 means "3rd party thread" */
  1476. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1477. pthread_setspecific(sTlsKey, tls);
  1478. }
  1479. return tls->thread_idx;
  1480. } else {
  1481. /* pthread_t may be any data type, so a simple cast to unsigned long
  1482. * can rise a warning/error, depending on the platform.
  1483. * Here memcpy is used as an anything-to-anything cast. */
  1484. unsigned long ret = 0;
  1485. pthread_t t = pthread_self();
  1486. memcpy(&ret, &t, sizeof(pthread_t));
  1487. return ret;
  1488. }
  1489. #if defined(__clang__)
  1490. #pragma clang diagnostic pop
  1491. #endif
  1492. #endif
  1493. }
  1494. FUNCTION_MAY_BE_UNUSED
  1495. static uint64_t
  1496. mg_get_current_time_ns(void)
  1497. {
  1498. struct timespec tsnow;
  1499. clock_gettime(CLOCK_REALTIME, &tsnow);
  1500. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1501. }
  1502. #if defined(GCC_DIAGNOSTIC)
  1503. /* Show no warning in case system functions are not used. */
  1504. #pragma GCC diagnostic pop
  1505. #endif /* defined(GCC_DIAGNOSTIC) */
  1506. #if defined(__clang__)
  1507. /* Show no warning in case system functions are not used. */
  1508. #pragma clang diagnostic pop
  1509. #endif
  1510. #if defined(NEED_DEBUG_TRACE_FUNC)
  1511. static void
  1512. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1513. {
  1514. va_list args;
  1515. struct timespec tsnow;
  1516. /* Get some operating system independent thread id */
  1517. // unsigned long thread_id = mg_current_thread_id();
  1518. clock_gettime(CLOCK_REALTIME, &tsnow);
  1519. // flockfile(DEBUG_TRACE_STREAM);
  1520. fprintf(DEBUG_TRACE_STREAM,
  1521. "*** %lu.%09lu %s:%u: ",
  1522. (unsigned long)tsnow.tv_sec,
  1523. (unsigned long)tsnow.tv_nsec,
  1524. func,
  1525. line);
  1526. // va_start(args, fmt);
  1527. // vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1528. // va_end(args);
  1529. // putc('\n', DEBUG_TRACE_STREAM);
  1530. // fflush(DEBUG_TRACE_STREAM);
  1531. // funlockfile(DEBUG_TRACE_STREAM);
  1532. }
  1533. #endif /* NEED_DEBUG_TRACE_FUNC */
  1534. #define MD5_STATIC static
  1535. #include "md5.inl"
  1536. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1537. #if defined(NO_SOCKLEN_T)
  1538. typedef int socklen_t;
  1539. #endif /* NO_SOCKLEN_T */
  1540. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1541. #if !defined(MSG_NOSIGNAL)
  1542. #define MSG_NOSIGNAL (0)
  1543. #endif
  1544. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1545. #if defined(USE_MBEDTLS)
  1546. /* mbedTLS */
  1547. #include "mod_mbedtls.inl"
  1548. #elif defined(NO_SSL)
  1549. /* no SSL */
  1550. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1551. typedef struct SSL_CTX SSL_CTX;
  1552. #elif defined(NO_SSL_DL)
  1553. /* OpenSSL without dynamic loading */
  1554. #include <openssl/bn.h>
  1555. #include <openssl/conf.h>
  1556. #include <openssl/crypto.h>
  1557. #include <openssl/dh.h>
  1558. #include <openssl/engine.h>
  1559. #include <openssl/err.h>
  1560. #include <openssl/opensslv.h>
  1561. #include <openssl/pem.h>
  1562. #include <openssl/ssl.h>
  1563. #include <openssl/tls1.h>
  1564. #include <openssl/x509.h>
  1565. #if defined(WOLFSSL_VERSION)
  1566. /* Additional defines for WolfSSL, see
  1567. * https://github.com/civetweb/civetweb/issues/583 */
  1568. #include "wolfssl_extras.inl"
  1569. #endif
  1570. #if defined(OPENSSL_IS_BORINGSSL)
  1571. /* From boringssl/src/include/openssl/mem.h:
  1572. *
  1573. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1574. * However, that was written in a time before Valgrind and ASAN. Since we now
  1575. * have those tools, the OpenSSL allocation functions are simply macros around
  1576. * the standard memory functions.
  1577. *
  1578. * #define OPENSSL_free free */
  1579. #define free free
  1580. // disable for boringssl
  1581. #define CONF_modules_unload(a) ((void)0)
  1582. #define ENGINE_cleanup() ((void)0)
  1583. #endif
  1584. /* If OpenSSL headers are included, automatically select the API version */
  1585. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1586. #if !defined(OPENSSL_API_3_0)
  1587. #define OPENSSL_API_3_0
  1588. #endif
  1589. #define OPENSSL_REMOVE_THREAD_STATE()
  1590. #else
  1591. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1592. #if !defined(OPENSSL_API_1_1)
  1593. #define OPENSSL_API_1_1
  1594. #endif
  1595. #define OPENSSL_REMOVE_THREAD_STATE()
  1596. #else
  1597. #if !defined(OPENSSL_API_1_0)
  1598. #define OPENSSL_API_1_0
  1599. #endif
  1600. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1601. #endif
  1602. #endif
  1603. #else
  1604. /* SSL loaded dynamically from DLL / shared object */
  1605. /* Add all prototypes here, to be independent from OpenSSL source
  1606. * installation. */
  1607. #include "openssl_dl.inl"
  1608. #endif /* Various SSL bindings */
  1609. #if !defined(NO_CACHING)
  1610. static const char month_names[][4] = {"Jan",
  1611. "Feb",
  1612. "Mar",
  1613. "Apr",
  1614. "May",
  1615. "Jun",
  1616. "Jul",
  1617. "Aug",
  1618. "Sep",
  1619. "Oct",
  1620. "Nov",
  1621. "Dec"};
  1622. #endif /* !NO_CACHING */
  1623. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1624. * the union u. */
  1625. union usa {
  1626. struct sockaddr sa;
  1627. struct sockaddr_in sin;
  1628. #if defined(USE_IPV6)
  1629. struct sockaddr_in6 sin6;
  1630. #endif
  1631. #if defined(USE_X_DOM_SOCKET)
  1632. struct sockaddr_un sun;
  1633. #endif
  1634. };
  1635. #if defined(USE_X_DOM_SOCKET)
  1636. static unsigned short
  1637. USA_IN_PORT_UNSAFE(union usa *s)
  1638. {
  1639. if (s->sa.sa_family == AF_INET)
  1640. return s->sin.sin_port;
  1641. #if defined(USE_IPV6)
  1642. if (s->sa.sa_family == AF_INET6)
  1643. return s->sin6.sin6_port;
  1644. #endif
  1645. return 0;
  1646. }
  1647. #endif
  1648. #if defined(USE_IPV6)
  1649. #define USA_IN_PORT_UNSAFE(s) \
  1650. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1651. #else
  1652. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1653. #endif
  1654. /* Describes a string (chunk of memory). */
  1655. struct vec {
  1656. const char *ptr;
  1657. size_t len;
  1658. };
  1659. struct mg_file_stat {
  1660. /* File properties filled by mg_stat: */
  1661. uint64_t size;
  1662. time_t last_modified;
  1663. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1664. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1665. * case we need a "Content-Eencoding: gzip" header */
  1666. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1667. };
  1668. struct mg_file_access {
  1669. /* File properties filled by mg_fopen: */
  1670. FILE *fp;
  1671. };
  1672. struct mg_file {
  1673. struct mg_file_stat stat;
  1674. struct mg_file_access access;
  1675. };
  1676. #define STRUCT_FILE_INITIALIZER \
  1677. { \
  1678. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1679. { \
  1680. (FILE *)NULL \
  1681. } \
  1682. }
  1683. /* Describes listening socket, or socket which was accept()-ed by the master
  1684. * thread and queued for future handling by the worker thread. */
  1685. struct socket {
  1686. SOCKET sock; /* Listening socket */
  1687. union usa lsa; /* Local socket address */
  1688. union usa rsa; /* Remote socket address */
  1689. unsigned char is_ssl; /* Is port SSL-ed */
  1690. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1691. * port */
  1692. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1693. };
  1694. /* Enum const for all options must be in sync with
  1695. * static struct mg_option config_options[]
  1696. * This is tested in the unit test (test/private.c)
  1697. * "Private Config Options"
  1698. */
  1699. enum {
  1700. /* Once for each server */
  1701. LISTENING_PORTS,
  1702. NUM_THREADS,
  1703. RUN_AS_USER,
  1704. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1705. * socket option typedef TCP_NODELAY. */
  1706. MAX_REQUEST_SIZE,
  1707. LINGER_TIMEOUT,
  1708. CONNECTION_QUEUE_SIZE,
  1709. LISTEN_BACKLOG_SIZE,
  1710. #if defined(__linux__)
  1711. ALLOW_SENDFILE_CALL,
  1712. #endif
  1713. #if defined(_WIN32)
  1714. CASE_SENSITIVE_FILES,
  1715. #endif
  1716. THROTTLE,
  1717. ENABLE_KEEP_ALIVE,
  1718. REQUEST_TIMEOUT,
  1719. KEEP_ALIVE_TIMEOUT,
  1720. #if defined(USE_WEBSOCKET)
  1721. WEBSOCKET_TIMEOUT,
  1722. ENABLE_WEBSOCKET_PING_PONG,
  1723. #endif
  1724. DECODE_URL,
  1725. DECODE_QUERY_STRING,
  1726. #if defined(USE_LUA)
  1727. LUA_BACKGROUND_SCRIPT,
  1728. LUA_BACKGROUND_SCRIPT_PARAMS,
  1729. #endif
  1730. #if defined(USE_HTTP2)
  1731. ENABLE_HTTP2,
  1732. #endif
  1733. /* Once for each domain */
  1734. DOCUMENT_ROOT,
  1735. ACCESS_LOG_FILE,
  1736. ERROR_LOG_FILE,
  1737. CGI_EXTENSIONS,
  1738. CGI_ENVIRONMENT,
  1739. CGI_INTERPRETER,
  1740. CGI_INTERPRETER_ARGS,
  1741. #if defined(USE_TIMERS)
  1742. CGI_TIMEOUT,
  1743. #endif
  1744. CGI_BUFFERING,
  1745. CGI2_EXTENSIONS,
  1746. CGI2_ENVIRONMENT,
  1747. CGI2_INTERPRETER,
  1748. CGI2_INTERPRETER_ARGS,
  1749. #if defined(USE_TIMERS)
  1750. CGI2_TIMEOUT,
  1751. #endif
  1752. CGI2_BUFFERING,
  1753. #if defined(USE_4_CGI)
  1754. CGI3_EXTENSIONS,
  1755. CGI3_ENVIRONMENT,
  1756. CGI3_INTERPRETER,
  1757. CGI3_INTERPRETER_ARGS,
  1758. #if defined(USE_TIMERS)
  1759. CGI3_TIMEOUT,
  1760. #endif
  1761. CGI3_BUFFERING,
  1762. CGI4_EXTENSIONS,
  1763. CGI4_ENVIRONMENT,
  1764. CGI4_INTERPRETER,
  1765. CGI4_INTERPRETER_ARGS,
  1766. #if defined(USE_TIMERS)
  1767. CGI4_TIMEOUT,
  1768. #endif
  1769. CGI4_BUFFERING,
  1770. #endif
  1771. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1772. PROTECT_URI,
  1773. AUTHENTICATION_DOMAIN,
  1774. ENABLE_AUTH_DOMAIN_CHECK,
  1775. SSI_EXTENSIONS,
  1776. ENABLE_DIRECTORY_LISTING,
  1777. ENABLE_WEBDAV,
  1778. GLOBAL_PASSWORDS_FILE,
  1779. INDEX_FILES,
  1780. ACCESS_CONTROL_LIST,
  1781. EXTRA_MIME_TYPES,
  1782. SSL_CERTIFICATE,
  1783. SSL_CERTIFICATE_CHAIN,
  1784. URL_REWRITE_PATTERN,
  1785. HIDE_FILES,
  1786. SSL_DO_VERIFY_PEER,
  1787. SSL_CACHE_TIMEOUT,
  1788. SSL_CA_PATH,
  1789. SSL_CA_FILE,
  1790. SSL_VERIFY_DEPTH,
  1791. SSL_DEFAULT_VERIFY_PATHS,
  1792. SSL_CIPHER_LIST,
  1793. SSL_PROTOCOL_VERSION,
  1794. SSL_SHORT_TRUST,
  1795. #if defined(USE_LUA)
  1796. LUA_PRELOAD_FILE,
  1797. LUA_SCRIPT_EXTENSIONS,
  1798. LUA_SERVER_PAGE_EXTENSIONS,
  1799. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1800. LUA_DEBUG_PARAMS,
  1801. #endif
  1802. #endif
  1803. #if defined(USE_DUKTAPE)
  1804. DUKTAPE_SCRIPT_EXTENSIONS,
  1805. #endif
  1806. #if defined(USE_WEBSOCKET)
  1807. WEBSOCKET_ROOT,
  1808. #endif
  1809. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1810. LUA_WEBSOCKET_EXTENSIONS,
  1811. #endif
  1812. ACCESS_CONTROL_ALLOW_ORIGIN,
  1813. ACCESS_CONTROL_ALLOW_METHODS,
  1814. ACCESS_CONTROL_ALLOW_HEADERS,
  1815. ERROR_PAGES,
  1816. #if !defined(NO_CACHING)
  1817. STATIC_FILE_MAX_AGE,
  1818. STATIC_FILE_CACHE_CONTROL,
  1819. #endif
  1820. #if !defined(NO_SSL)
  1821. STRICT_HTTPS_MAX_AGE,
  1822. #endif
  1823. ADDITIONAL_HEADER,
  1824. ALLOW_INDEX_SCRIPT_SUB_RES,
  1825. NUM_OPTIONS
  1826. };
  1827. /* Config option name, config types, default value.
  1828. * Must be in the same order as the enum const above.
  1829. */
  1830. static const struct mg_option config_options[] = {
  1831. /* Once for each server */
  1832. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1833. {"num_threads", MG_CONFIG_TYPE_NUMBER, "4"},
  1834. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1835. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1836. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1837. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1838. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1839. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1840. #if defined(__linux__)
  1841. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1842. #endif
  1843. #if defined(_WIN32)
  1844. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1845. #endif
  1846. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1847. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1848. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1849. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1850. #if defined(USE_WEBSOCKET)
  1851. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1852. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1853. #endif
  1854. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1855. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1856. #if defined(USE_LUA)
  1857. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1858. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1859. #endif
  1860. #if defined(USE_HTTP2)
  1861. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1862. #endif
  1863. /* Once for each domain */
  1864. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1865. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1866. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1867. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1868. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1869. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1870. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1871. #if defined(USE_TIMERS)
  1872. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1873. #endif
  1874. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1875. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1876. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1877. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1878. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1879. #if defined(USE_TIMERS)
  1880. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1881. #endif
  1882. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1883. #if defined(USE_4_CGI)
  1884. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1885. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1886. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1887. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1888. #if defined(USE_TIMERS)
  1889. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1890. #endif
  1891. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1892. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1893. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1894. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1895. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1896. #if defined(USE_TIMERS)
  1897. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1898. #endif
  1899. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1900. #endif
  1901. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1902. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1903. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1904. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1905. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1906. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1907. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1908. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1909. {"index_files",
  1910. MG_CONFIG_TYPE_STRING_LIST,
  1911. #if defined(USE_LUA)
  1912. "index.xhtml,index.html,index.htm,"
  1913. "index.lp,index.lsp,index.lua,index.cgi,"
  1914. "index.shtml,index.php"},
  1915. #else
  1916. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1917. #endif
  1918. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1919. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1920. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1921. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1922. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1923. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1924. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1925. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1926. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1927. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1928. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1929. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1930. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1931. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1932. * as a minimum in 2020 */
  1933. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1934. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1935. #if defined(USE_LUA)
  1936. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1937. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1938. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1939. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1940. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1941. #endif
  1942. #endif
  1943. #if defined(USE_DUKTAPE)
  1944. /* The support for duktape is still in alpha version state.
  1945. * The name of this config option might change. */
  1946. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1947. #endif
  1948. #if defined(USE_WEBSOCKET)
  1949. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1950. #endif
  1951. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1952. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1953. #endif
  1954. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1955. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1956. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1957. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1958. #if !defined(NO_CACHING)
  1959. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1960. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1961. #endif
  1962. #if !defined(NO_SSL)
  1963. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1964. #endif
  1965. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1966. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1967. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1968. /* Check if the config_options and the corresponding enum have compatible
  1969. * sizes. */
  1970. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1971. == (NUM_OPTIONS + 1),
  1972. "config_options and enum not sync");
  1973. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1974. struct mg_handler_info {
  1975. /* Name/Pattern of the URI. */
  1976. char *uri;
  1977. size_t uri_len;
  1978. /* handler type */
  1979. int handler_type;
  1980. /* Handler for http/https or requests. */
  1981. mg_request_handler handler;
  1982. unsigned int refcount;
  1983. int removing;
  1984. /* Handler for ws/wss (websocket) requests. */
  1985. mg_websocket_connect_handler connect_handler;
  1986. mg_websocket_ready_handler ready_handler;
  1987. mg_websocket_data_handler data_handler;
  1988. mg_websocket_close_handler close_handler;
  1989. /* accepted subprotocols for ws/wss requests. */
  1990. struct mg_websocket_subprotocols *subprotocols;
  1991. /* Handler for authorization requests */
  1992. mg_authorization_handler auth_handler;
  1993. /* User supplied argument for the handler function. */
  1994. void *cbdata;
  1995. /* next handler in a linked list */
  1996. struct mg_handler_info *next;
  1997. };
  1998. enum {
  1999. CONTEXT_INVALID,
  2000. CONTEXT_SERVER,
  2001. CONTEXT_HTTP_CLIENT,
  2002. CONTEXT_WS_CLIENT
  2003. };
  2004. struct mg_domain_context {
  2005. SSL_CTX *ssl_ctx; /* SSL context */
  2006. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2007. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2008. int64_t ssl_cert_last_mtime;
  2009. /* Server nonce */
  2010. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2011. unsigned long nonce_count; /* Used nonces, used for authentication */
  2012. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2013. /* linked list of shared lua websockets */
  2014. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2015. #endif
  2016. /* Linked list of domains */
  2017. struct mg_domain_context *next;
  2018. };
  2019. /* Stop flag can be "volatile" or require a lock.
  2020. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  2021. * states a read operation for int is always atomic. */
  2022. #if defined(STOP_FLAG_NEEDS_LOCK)
  2023. typedef ptrdiff_t volatile stop_flag_t;
  2024. static int
  2025. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  2026. {
  2027. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  2028. return (sf == 0);
  2029. }
  2030. static int
  2031. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2032. {
  2033. stop_flag_t sf = mg_atomic_add(f, 0);
  2034. return (sf == 2);
  2035. }
  2036. static void
  2037. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2038. {
  2039. stop_flag_t sf;
  2040. do {
  2041. sf = mg_atomic_compare_and_swap(f, *f, v);
  2042. } while (sf != v);
  2043. }
  2044. #else /* STOP_FLAG_NEEDS_LOCK */
  2045. typedef int volatile stop_flag_t;
  2046. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2047. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2048. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2049. #endif /* STOP_FLAG_NEEDS_LOCK */
  2050. #if !defined(NUM_WEBDAV_LOCKS)
  2051. #define NUM_WEBDAV_LOCKS 10
  2052. #endif
  2053. #if !defined(LOCK_DURATION_S)
  2054. #define LOCK_DURATION_S 60
  2055. #endif
  2056. struct twebdav_lock {
  2057. uint64_t locktime;
  2058. char token[33];
  2059. char path[UTF8_PATH_MAX * 2];
  2060. char user[UTF8_PATH_MAX * 2];
  2061. };
  2062. struct mg_context {
  2063. /* Part 1 - Physical context:
  2064. * This holds threads, ports, timeouts, ...
  2065. * set for the entire server, independent from the
  2066. * addressed hostname.
  2067. */
  2068. /* Connection related */
  2069. int context_type; /* See CONTEXT_* above */
  2070. struct socket *listening_sockets;
  2071. struct mg_pollfd *listening_socket_fds;
  2072. unsigned int num_listening_sockets;
  2073. struct mg_connection *worker_connections; /* The connection struct, pre-
  2074. * allocated for each worker */
  2075. #if defined(USE_SERVER_STATS)
  2076. volatile ptrdiff_t active_connections;
  2077. volatile ptrdiff_t max_active_connections;
  2078. volatile ptrdiff_t total_connections;
  2079. volatile ptrdiff_t total_requests;
  2080. volatile int64_t total_data_read;
  2081. volatile int64_t total_data_written;
  2082. #endif
  2083. /* Thread related */
  2084. stop_flag_t stop_flag; /* Should we stop event loop */
  2085. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2086. cw_thread_handle_t masterthreadid; /* The master thread ID */
  2087. unsigned int
  2088. cfg_worker_threads; /* The number of configured worker threads. */
  2089. cw_thread_handle_t *worker_threadids; /* The worker thread IDs */
  2090. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2091. /* Connection to thread dispatching */
  2092. #if defined(ALTERNATIVE_QUEUE)
  2093. struct socket *client_socks;
  2094. void **client_wait_events;
  2095. #else
  2096. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2097. worker thread */
  2098. volatile int sq_head; /* Head of the socket queue */
  2099. volatile int sq_tail; /* Tail of the socket queue */
  2100. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2101. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2102. volatile int sq_blocked; /* Status information: sq is full */
  2103. int sq_size; /* No of elements in socket queue */
  2104. #if defined(USE_SERVER_STATS)
  2105. int sq_max_fill;
  2106. #endif /* USE_SERVER_STATS */
  2107. #endif /* ALTERNATIVE_QUEUE */
  2108. /* Memory related */
  2109. unsigned int max_request_size; /* The max request size */
  2110. #if defined(USE_SERVER_STATS)
  2111. struct mg_memory_stat ctx_memory;
  2112. #endif
  2113. /* WebDAV lock structures */
  2114. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2115. /* Operating system related */
  2116. char *systemName; /* What operating system is running */
  2117. time_t start_time; /* Server start time, used for authentication
  2118. * and for diagnstics. */
  2119. #if defined(USE_TIMERS)
  2120. struct ttimers *timers;
  2121. #endif
  2122. /* Lua specific: Background operations and shared websockets */
  2123. #if defined(USE_LUA)
  2124. void *lua_background_state; /* lua_State (here as void *) */
  2125. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2126. int lua_bg_log_available; /* Use Lua background state for access log */
  2127. #endif
  2128. /* Server nonce */
  2129. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2130. * ssl_cert_last_mtime, nonce_count, and
  2131. * next (linked list) */
  2132. /* Server callbacks */
  2133. struct mg_callbacks callbacks; /* User-defined callback function */
  2134. void *user_data; /* User-defined data */
  2135. /* Part 2 - Logical domain:
  2136. * This holds hostname, TLS certificate, document root, ...
  2137. * set for a domain hosted at the server.
  2138. * There may be multiple domains hosted at one physical server.
  2139. * The default domain "dd" is the first element of a list of
  2140. * domains.
  2141. */
  2142. struct mg_domain_context dd; /* default domain */
  2143. };
  2144. #if defined(USE_SERVER_STATS)
  2145. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2146. static struct mg_memory_stat *
  2147. get_memory_stat(struct mg_context *ctx)
  2148. {
  2149. if (ctx) {
  2150. return &(ctx->ctx_memory);
  2151. }
  2152. return &mg_common_memory;
  2153. }
  2154. #endif
  2155. enum {
  2156. CONNECTION_TYPE_INVALID = 0,
  2157. CONNECTION_TYPE_REQUEST = 1,
  2158. CONNECTION_TYPE_RESPONSE = 2
  2159. };
  2160. enum {
  2161. PROTOCOL_TYPE_HTTP1 = 0,
  2162. PROTOCOL_TYPE_WEBSOCKET = 1,
  2163. PROTOCOL_TYPE_HTTP2 = 2
  2164. };
  2165. #if defined(USE_HTTP2)
  2166. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2167. #define HTTP2_DYN_TABLE_SIZE (256)
  2168. #endif
  2169. struct mg_http2_connection {
  2170. uint32_t stream_id;
  2171. uint32_t dyn_table_size;
  2172. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2173. };
  2174. #endif
  2175. struct mg_connection {
  2176. int connection_type; /* see CONNECTION_TYPE_* above */
  2177. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2178. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2179. fully sent */
  2180. #if defined(USE_HTTP2)
  2181. struct mg_http2_connection http2;
  2182. #endif
  2183. struct mg_request_info request_info;
  2184. struct mg_response_info response_info;
  2185. struct mg_context *phys_ctx;
  2186. struct mg_domain_context *dom_ctx;
  2187. #if defined(USE_SERVER_STATS)
  2188. int conn_state; /* 0 = undef, numerical value may change in different
  2189. * versions. For the current definition, see
  2190. * mg_get_connection_info_impl */
  2191. #endif
  2192. SSL *ssl; /* SSL descriptor */
  2193. struct socket client; /* Connected client */
  2194. time_t conn_birth_time; /* Time (wall clock) when connection was
  2195. * established */
  2196. #if defined(USE_SERVER_STATS)
  2197. time_t conn_close_time; /* Time (wall clock) when connection was
  2198. * closed (or 0 if still open) */
  2199. double processing_time; /* Procesing time for one request. */
  2200. #endif
  2201. struct timespec req_time; /* Time (since system start) when the request
  2202. * was received */
  2203. int64_t num_bytes_sent; /* Total bytes sent to client */
  2204. int64_t content_len; /* How many bytes of content can be read
  2205. * !is_chunked: Content-Length header value
  2206. * or -1 (until connection closed,
  2207. * not allowed for a request)
  2208. * is_chunked: >= 0, appended gradually
  2209. */
  2210. int64_t consumed_content; /* How many bytes of content have been read */
  2211. int is_chunked; /* Transfer-Encoding is chunked:
  2212. * 0 = not chunked,
  2213. * 1 = chunked, not yet, or some data read,
  2214. * 2 = chunked, has error,
  2215. * 3 = chunked, all data read except trailer,
  2216. * 4 = chunked, all data read
  2217. */
  2218. char *buf; /* Buffer for received data */
  2219. char *path_info; /* PATH_INFO part of the URL */
  2220. int must_close; /* 1 if connection must be closed */
  2221. int accept_gzip; /* 1 if gzip encoding is accepted */
  2222. int in_error_handler; /* 1 if in handler for user defined error
  2223. * pages */
  2224. #if defined(USE_WEBSOCKET)
  2225. int in_websocket_handling; /* 1 if in read_websocket */
  2226. #endif
  2227. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2228. && defined(MG_EXPERIMENTAL_INTERFACES)
  2229. /* Parameters for websocket data compression according to rfc7692 */
  2230. int websocket_deflate_server_max_windows_bits;
  2231. int websocket_deflate_client_max_windows_bits;
  2232. int websocket_deflate_server_no_context_takeover;
  2233. int websocket_deflate_client_no_context_takeover;
  2234. int websocket_deflate_initialized;
  2235. int websocket_deflate_flush;
  2236. z_stream websocket_deflate_state;
  2237. z_stream websocket_inflate_state;
  2238. #endif
  2239. int handled_requests; /* Number of requests handled by this connection
  2240. */
  2241. int buf_size; /* Buffer size */
  2242. int request_len; /* Size of the request + headers in a buffer */
  2243. int data_len; /* Total size of data in a buffer */
  2244. int status_code; /* HTTP reply status code, e.g. 200 */
  2245. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2246. * throttle */
  2247. time_t last_throttle_time; /* Last time throttled data was sent */
  2248. int last_throttle_bytes; /* Bytes sent this second */
  2249. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2250. * atomic transmissions for websockets */
  2251. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2252. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2253. #endif
  2254. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2255. * for quick access */
  2256. };
  2257. /* Directory entry */
  2258. struct de {
  2259. char *file_name;
  2260. struct mg_file_stat file;
  2261. };
  2262. #define mg_cry_internal(conn, fmt, ...) \
  2263. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2264. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2265. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2266. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2267. struct mg_context *ctx,
  2268. const char *func,
  2269. unsigned line,
  2270. const char *fmt,
  2271. ...) PRINTF_ARGS(5, 6);
  2272. #if !defined(NO_THREAD_NAME)
  2273. #if defined(_WIN32) && defined(_MSC_VER)
  2274. /* Set the thread name for debugging purposes in Visual Studio
  2275. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2276. */
  2277. #pragma pack(push, 8)
  2278. typedef struct tagTHREADNAME_INFO {
  2279. DWORD dwType; /* Must be 0x1000. */
  2280. LPCSTR szName; /* Pointer to name (in user addr space). */
  2281. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2282. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2283. } THREADNAME_INFO;
  2284. #pragma pack(pop)
  2285. #elif defined(__linux__)
  2286. #include <sys/prctl.h>
  2287. #include <sys/sendfile.h>
  2288. #if defined(ALTERNATIVE_QUEUE)
  2289. #include <sys/eventfd.h>
  2290. #endif /* ALTERNATIVE_QUEUE */
  2291. #if defined(ALTERNATIVE_QUEUE)
  2292. static void *
  2293. event_create(void)
  2294. {
  2295. int evhdl = eventfd(0, EFD_CLOEXEC);
  2296. int *ret;
  2297. if (evhdl == -1) {
  2298. /* Linux uses -1 on error, Windows NULL. */
  2299. /* However, Linux does not return 0 on success either. */
  2300. return 0;
  2301. }
  2302. ret = (int *)mg_malloc(sizeof(int));
  2303. if (ret) {
  2304. *ret = evhdl;
  2305. } else {
  2306. (void)close(evhdl);
  2307. }
  2308. return (void *)ret;
  2309. }
  2310. static int
  2311. event_wait(void *eventhdl)
  2312. {
  2313. uint64_t u;
  2314. int evhdl, s;
  2315. if (!eventhdl) {
  2316. /* error */
  2317. return 0;
  2318. }
  2319. evhdl = *(int *)eventhdl;
  2320. s = (int)read(evhdl, &u, sizeof(u));
  2321. if (s != sizeof(u)) {
  2322. /* error */
  2323. return 0;
  2324. }
  2325. (void)u; /* the value is not required */
  2326. return 1;
  2327. }
  2328. static int
  2329. event_signal(void *eventhdl)
  2330. {
  2331. uint64_t u = 1;
  2332. int evhdl, s;
  2333. if (!eventhdl) {
  2334. /* error */
  2335. return 0;
  2336. }
  2337. evhdl = *(int *)eventhdl;
  2338. s = (int)write(evhdl, &u, sizeof(u));
  2339. if (s != sizeof(u)) {
  2340. /* error */
  2341. return 0;
  2342. }
  2343. return 1;
  2344. }
  2345. static void
  2346. event_destroy(void *eventhdl)
  2347. {
  2348. int evhdl;
  2349. if (!eventhdl) {
  2350. /* error */
  2351. return;
  2352. }
  2353. evhdl = *(int *)eventhdl;
  2354. close(evhdl);
  2355. mg_free(eventhdl);
  2356. }
  2357. #endif
  2358. #endif
  2359. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2360. struct posix_event {
  2361. pthread_mutex_t mutex;
  2362. pthread_cond_t cond;
  2363. int signaled;
  2364. };
  2365. static void *
  2366. event_create(void)
  2367. {
  2368. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2369. if (ret == 0) {
  2370. /* out of memory */
  2371. return 0;
  2372. }
  2373. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2374. /* pthread mutex not available */
  2375. mg_free(ret);
  2376. return 0;
  2377. }
  2378. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2379. /* pthread cond not available */
  2380. pthread_mutex_destroy(&(ret->mutex));
  2381. mg_free(ret);
  2382. return 0;
  2383. }
  2384. ret->signaled = 0;
  2385. return (void *)ret;
  2386. }
  2387. static int
  2388. event_wait(void *eventhdl)
  2389. {
  2390. struct posix_event *ev = (struct posix_event *)eventhdl;
  2391. pthread_mutex_lock(&(ev->mutex));
  2392. while (!ev->signaled) {
  2393. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2394. }
  2395. ev->signaled = 0;
  2396. pthread_mutex_unlock(&(ev->mutex));
  2397. return 1;
  2398. }
  2399. static int
  2400. event_signal(void *eventhdl)
  2401. {
  2402. struct posix_event *ev = (struct posix_event *)eventhdl;
  2403. pthread_mutex_lock(&(ev->mutex));
  2404. pthread_cond_signal(&(ev->cond));
  2405. ev->signaled = 1;
  2406. pthread_mutex_unlock(&(ev->mutex));
  2407. return 1;
  2408. }
  2409. static void
  2410. event_destroy(void *eventhdl)
  2411. {
  2412. struct posix_event *ev = (struct posix_event *)eventhdl;
  2413. pthread_cond_destroy(&(ev->cond));
  2414. pthread_mutex_destroy(&(ev->mutex));
  2415. mg_free(ev);
  2416. }
  2417. #endif
  2418. static void
  2419. mg_set_thread_name(const char *name)
  2420. {
  2421. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2422. mg_snprintf(
  2423. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2424. #if defined(_WIN32)
  2425. #if defined(_MSC_VER)
  2426. /* Windows and Visual Studio Compiler */
  2427. __try {
  2428. THREADNAME_INFO info;
  2429. info.dwType = 0x1000;
  2430. info.szName = threadName;
  2431. info.dwThreadID = ~0U;
  2432. info.dwFlags = 0;
  2433. RaiseException(0x406D1388,
  2434. 0,
  2435. sizeof(info) / sizeof(ULONG_PTR),
  2436. (ULONG_PTR *)&info);
  2437. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2438. }
  2439. #elif defined(__MINGW32__)
  2440. /* No option known to set thread name for MinGW known */
  2441. #endif
  2442. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2443. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2444. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2445. #if defined(__MACH__) && defined(__APPLE__)
  2446. /* OS X only current thread name can be changed */
  2447. (void)pthread_setname_np(threadName);
  2448. #else
  2449. (void)pthread_setname_np(pthread_self(), threadName);
  2450. #endif
  2451. #elif defined(__linux__)
  2452. /* On Linux we can use the prctl function.
  2453. * When building for Linux Standard Base (LSB) use
  2454. * NO_THREAD_NAME. However, thread names are a big
  2455. * help for debugging, so the stadard is to set them.
  2456. */
  2457. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2458. #endif
  2459. }
  2460. #else /* !defined(NO_THREAD_NAME) */
  2461. static void
  2462. mg_set_thread_name(const char *threadName)
  2463. {
  2464. }
  2465. #endif
  2466. CIVETWEB_API const struct mg_option *
  2467. mg_get_valid_options(void)
  2468. {
  2469. return config_options;
  2470. }
  2471. /* Do not open file (unused) */
  2472. #define MG_FOPEN_MODE_NONE (0)
  2473. /* Open file for read only access */
  2474. #define MG_FOPEN_MODE_READ (1)
  2475. /* Open file for writing, create and overwrite */
  2476. #define MG_FOPEN_MODE_WRITE (2)
  2477. /* Open file for writing, create and append */
  2478. #define MG_FOPEN_MODE_APPEND (4)
  2479. static int
  2480. is_file_opened(const struct mg_file_access *fileacc)
  2481. {
  2482. if (!fileacc) {
  2483. return 0;
  2484. }
  2485. return (fileacc->fp != NULL);
  2486. }
  2487. #if !defined(NO_FILESYSTEMS)
  2488. static int mg_stat(const struct mg_connection *conn,
  2489. const char *path,
  2490. struct mg_file_stat *filep);
  2491. /* Reject files with special characters (for Windows) */
  2492. static int
  2493. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2494. {
  2495. const uint8_t *c = (const uint8_t *)path;
  2496. (void)conn; /* not used */
  2497. if ((c == NULL) || (c[0] == 0)) {
  2498. /* Null pointer or empty path --> suspicious */
  2499. return 1;
  2500. }
  2501. #if defined(_WIN32)
  2502. while (*c) {
  2503. if (*c < 32) {
  2504. /* Control character */
  2505. return 1;
  2506. }
  2507. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2508. /* stdin/stdout redirection character */
  2509. return 1;
  2510. }
  2511. if ((*c == '*') || (*c == '?')) {
  2512. /* Wildcard character */
  2513. return 1;
  2514. }
  2515. if (*c == '"') {
  2516. /* Windows quotation */
  2517. return 1;
  2518. }
  2519. c++;
  2520. }
  2521. #endif
  2522. /* Nothing suspicious found */
  2523. return 0;
  2524. }
  2525. /* mg_fopen will open a file either in memory or on the disk.
  2526. * The input parameter path is a string in UTF-8 encoding.
  2527. * The input parameter mode is MG_FOPEN_MODE_*
  2528. * On success, fp will be set in the output struct mg_file.
  2529. * All status members will also be set.
  2530. * The function returns 1 on success, 0 on error. */
  2531. static int
  2532. mg_fopen(const struct mg_connection *conn,
  2533. const char *path,
  2534. int mode,
  2535. struct mg_file *filep)
  2536. {
  2537. int found;
  2538. if (!filep) {
  2539. return 0;
  2540. }
  2541. filep->access.fp = NULL;
  2542. if (mg_path_suspicious(conn, path)) {
  2543. return 0;
  2544. }
  2545. /* filep is initialized in mg_stat: all fields with memset to,
  2546. * some fields like size and modification date with values */
  2547. found = mg_stat(conn, path, &(filep->stat));
  2548. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2549. /* file does not exist and will not be created */
  2550. return 0;
  2551. }
  2552. #if defined(_WIN32)
  2553. {
  2554. wchar_t wbuf[UTF16_PATH_MAX];
  2555. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2556. switch (mode) {
  2557. case MG_FOPEN_MODE_READ:
  2558. filep->access.fp = _wfopen(wbuf, L"rb");
  2559. break;
  2560. case MG_FOPEN_MODE_WRITE:
  2561. filep->access.fp = _wfopen(wbuf, L"wb");
  2562. break;
  2563. case MG_FOPEN_MODE_APPEND:
  2564. filep->access.fp = _wfopen(wbuf, L"ab");
  2565. break;
  2566. }
  2567. }
  2568. #else
  2569. /* Linux et al already use unicode. No need to convert. */
  2570. switch (mode) {
  2571. case MG_FOPEN_MODE_READ:
  2572. filep->access.fp = fopen(path, "r");
  2573. break;
  2574. case MG_FOPEN_MODE_WRITE:
  2575. filep->access.fp = fopen(path, "w");
  2576. break;
  2577. case MG_FOPEN_MODE_APPEND:
  2578. filep->access.fp = fopen(path, "a");
  2579. break;
  2580. }
  2581. #endif
  2582. if (!found) {
  2583. /* File did not exist before fopen was called.
  2584. * Maybe it has been created now. Get stat info
  2585. * like creation time now. */
  2586. found = mg_stat(conn, path, &(filep->stat));
  2587. (void)found;
  2588. }
  2589. /* return OK if file is opened */
  2590. return (filep->access.fp != NULL);
  2591. }
  2592. /* return 0 on success, just like fclose */
  2593. static int
  2594. mg_fclose(struct mg_file_access *fileacc)
  2595. {
  2596. int ret = -1;
  2597. if (fileacc != NULL) {
  2598. if (fileacc->fp != NULL) {
  2599. ret = fclose(fileacc->fp);
  2600. }
  2601. /* reset all members of fileacc */
  2602. memset(fileacc, 0, sizeof(*fileacc));
  2603. }
  2604. return ret;
  2605. }
  2606. #endif /* NO_FILESYSTEMS */
  2607. static void
  2608. mg_strlcpy(char *dst, const char *src, size_t n)
  2609. {
  2610. for (; *src != '\0' && n > 1; n--) {
  2611. *dst++ = *src++;
  2612. }
  2613. *dst = '\0';
  2614. }
  2615. static int
  2616. lowercase(const char *s)
  2617. {
  2618. return tolower((unsigned char)*s);
  2619. }
  2620. CIVETWEB_API int
  2621. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2622. {
  2623. int diff = 0;
  2624. if (len > 0) {
  2625. do {
  2626. diff = lowercase(s1++) - lowercase(s2++);
  2627. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2628. }
  2629. return diff;
  2630. }
  2631. CIVETWEB_API int
  2632. mg_strcasecmp(const char *s1, const char *s2)
  2633. {
  2634. int diff;
  2635. do {
  2636. diff = lowercase(s1++) - lowercase(s2++);
  2637. } while (diff == 0 && s1[-1] != '\0');
  2638. return diff;
  2639. }
  2640. static char *
  2641. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2642. {
  2643. char *p;
  2644. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2645. * defined */
  2646. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2647. mg_strlcpy(p, ptr, len + 1);
  2648. }
  2649. return p;
  2650. }
  2651. static char *
  2652. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2653. {
  2654. return mg_strndup_ctx(str, strlen(str), ctx);
  2655. }
  2656. static char *
  2657. mg_strdup(const char *str)
  2658. {
  2659. return mg_strndup_ctx(str, strlen(str), NULL);
  2660. }
  2661. static const char *
  2662. mg_strcasestr(const char *big_str, const char *small_str)
  2663. {
  2664. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2665. if (big_len >= small_len) {
  2666. for (i = 0; i <= (big_len - small_len); i++) {
  2667. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2668. return big_str + i;
  2669. }
  2670. }
  2671. }
  2672. return NULL;
  2673. }
  2674. /* Return null terminated string of given maximum length.
  2675. * Report errors if length is exceeded. */
  2676. static void
  2677. mg_vsnprintf(const struct mg_connection *conn,
  2678. int *truncated,
  2679. char *buf,
  2680. size_t buflen,
  2681. const char *fmt,
  2682. va_list ap)
  2683. {
  2684. int n, ok;
  2685. if (buflen == 0) {
  2686. if (truncated) {
  2687. *truncated = 1;
  2688. }
  2689. return;
  2690. }
  2691. #if defined(__clang__)
  2692. #pragma clang diagnostic push
  2693. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2694. /* Using fmt as a non-literal is intended here, since it is mostly called
  2695. * indirectly by mg_snprintf */
  2696. #endif
  2697. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2698. ok = (n >= 0) && ((size_t)n < buflen);
  2699. #if defined(__clang__)
  2700. #pragma clang diagnostic pop
  2701. #endif
  2702. if (ok) {
  2703. if (truncated) {
  2704. *truncated = 0;
  2705. }
  2706. } else {
  2707. if (truncated) {
  2708. *truncated = 1;
  2709. }
  2710. mg_cry_internal(conn,
  2711. "truncating vsnprintf buffer: [%.*s]",
  2712. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2713. buf);
  2714. n = (int)buflen - 1;
  2715. }
  2716. buf[n] = '\0';
  2717. }
  2718. static void
  2719. mg_snprintf(const struct mg_connection *conn,
  2720. int *truncated,
  2721. char *buf,
  2722. size_t buflen,
  2723. const char *fmt,
  2724. ...)
  2725. {
  2726. va_list ap;
  2727. va_start(ap, fmt);
  2728. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2729. va_end(ap);
  2730. }
  2731. static int
  2732. get_option_index(const char *name)
  2733. {
  2734. int i;
  2735. for (i = 0; config_options[i].name != NULL; i++) {
  2736. if (strcmp(config_options[i].name, name) == 0) {
  2737. return i;
  2738. }
  2739. }
  2740. return -1;
  2741. }
  2742. CIVETWEB_API const char *
  2743. mg_get_option(const struct mg_context *ctx, const char *name)
  2744. {
  2745. int i;
  2746. if ((i = get_option_index(name)) == -1) {
  2747. return NULL;
  2748. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2749. return "";
  2750. } else {
  2751. return ctx->dd.config[i];
  2752. }
  2753. }
  2754. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2755. CIVETWEB_API struct mg_context *
  2756. mg_get_context(const struct mg_connection *conn)
  2757. {
  2758. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2759. }
  2760. CIVETWEB_API void *
  2761. mg_get_user_data(const struct mg_context *ctx)
  2762. {
  2763. return (ctx == NULL) ? NULL : ctx->user_data;
  2764. }
  2765. CIVETWEB_API void *
  2766. mg_get_user_context_data(const struct mg_connection *conn)
  2767. {
  2768. return mg_get_user_data(mg_get_context(conn));
  2769. }
  2770. CIVETWEB_API void *
  2771. mg_get_thread_pointer(const struct mg_connection *conn)
  2772. {
  2773. /* both methods should return the same pointer */
  2774. if (conn) {
  2775. /* quick access, in case conn is known */
  2776. return conn->tls_user_ptr;
  2777. } else {
  2778. /* otherwise get pointer from thread local storage (TLS) */
  2779. struct mg_workerTLS *tls =
  2780. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2781. return tls->user_ptr;
  2782. }
  2783. }
  2784. CIVETWEB_API void
  2785. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2786. {
  2787. if (const_conn != NULL) {
  2788. /* Const cast, since "const struct mg_connection *" does not mean
  2789. * the connection object is not modified. Here "const" is used,
  2790. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2791. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2792. conn->request_info.conn_data = data;
  2793. }
  2794. }
  2795. CIVETWEB_API void *
  2796. mg_get_user_connection_data(const struct mg_connection *conn)
  2797. {
  2798. if (conn != NULL) {
  2799. return conn->request_info.conn_data;
  2800. }
  2801. return NULL;
  2802. }
  2803. CIVETWEB_API int
  2804. mg_get_server_ports(const struct mg_context *ctx,
  2805. int size,
  2806. struct mg_server_port *ports)
  2807. {
  2808. int i, cnt = 0;
  2809. if (size <= 0) {
  2810. return -1;
  2811. }
  2812. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2813. if (!ctx) {
  2814. return -1;
  2815. }
  2816. if (!ctx->listening_sockets) {
  2817. return -1;
  2818. }
  2819. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2820. ports[cnt].port =
  2821. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2822. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2823. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2824. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2825. /* IPv4 */
  2826. ports[cnt].protocol = 1;
  2827. cnt++;
  2828. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2829. /* IPv6 */
  2830. ports[cnt].protocol = 3;
  2831. cnt++;
  2832. }
  2833. }
  2834. return cnt;
  2835. }
  2836. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2837. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2838. #endif
  2839. static void
  2840. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2841. {
  2842. buf[0] = '\0';
  2843. if (!usa) {
  2844. return;
  2845. }
  2846. if (usa->sa.sa_family == AF_INET) {
  2847. getnameinfo(&usa->sa,
  2848. sizeof(usa->sin),
  2849. buf,
  2850. (unsigned)len,
  2851. NULL,
  2852. 0,
  2853. NI_NUMERICHOST);
  2854. }
  2855. #if defined(USE_IPV6)
  2856. else if (usa->sa.sa_family == AF_INET6) {
  2857. getnameinfo(&usa->sa,
  2858. sizeof(usa->sin6),
  2859. buf,
  2860. (unsigned)len,
  2861. NULL,
  2862. 0,
  2863. NI_NUMERICHOST);
  2864. }
  2865. #endif
  2866. #if defined(USE_X_DOM_SOCKET)
  2867. else if (usa->sa.sa_family == AF_UNIX) {
  2868. /* TODO: Define a remote address for unix domain sockets.
  2869. * This code will always return "localhost", identical to http+tcp:
  2870. getnameinfo(&usa->sa,
  2871. sizeof(usa->sun),
  2872. buf,
  2873. (unsigned)len,
  2874. NULL,
  2875. 0,
  2876. NI_NUMERICHOST);
  2877. */
  2878. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2879. buf[len] = 0;
  2880. }
  2881. #endif
  2882. }
  2883. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2884. * included in all responses other than 100, 101, 5xx. */
  2885. static void
  2886. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2887. {
  2888. #if !defined(REENTRANT_TIME)
  2889. struct tm *tm;
  2890. tm = ((t != NULL) ? gmtime(t) : NULL);
  2891. if (tm != NULL) {
  2892. #else
  2893. struct tm _tm;
  2894. struct tm *tm = &_tm;
  2895. if (t != NULL) {
  2896. gmtime_r(t, tm);
  2897. #endif
  2898. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2899. } else {
  2900. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2901. buf[buf_len - 1] = '\0';
  2902. }
  2903. }
  2904. /* difftime for struct timespec. Return value is in seconds. */
  2905. static double
  2906. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2907. {
  2908. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2909. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2910. }
  2911. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2912. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2913. const char *func,
  2914. unsigned line,
  2915. const char *fmt,
  2916. va_list ap);
  2917. #include "external_mg_cry_internal_impl.inl"
  2918. #elif !defined(NO_FILESYSTEMS)
  2919. /* Print error message to the opened error log stream. */
  2920. static void
  2921. mg_cry_internal_impl(const struct mg_connection *conn,
  2922. const char *func,
  2923. unsigned line,
  2924. const char *fmt,
  2925. va_list ap)
  2926. {
  2927. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2928. struct mg_file fi;
  2929. time_t timestamp;
  2930. /* Unused, in the RELEASE build */
  2931. (void)func;
  2932. (void)line;
  2933. #if defined(GCC_DIAGNOSTIC)
  2934. #pragma GCC diagnostic push
  2935. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2936. #endif
  2937. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2938. #if defined(GCC_DIAGNOSTIC)
  2939. #pragma GCC diagnostic pop
  2940. #endif
  2941. buf[sizeof(buf) - 1] = 0;
  2942. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2943. if (!conn) {
  2944. puts(buf);
  2945. return;
  2946. }
  2947. /* Do not lock when getting the callback value, here and below.
  2948. * I suppose this is fine, since function cannot disappear in the
  2949. * same way string option can. */
  2950. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2951. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2952. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2953. if (mg_fopen(conn,
  2954. conn->dom_ctx->config[ERROR_LOG_FILE],
  2955. MG_FOPEN_MODE_APPEND,
  2956. &fi)
  2957. == 0) {
  2958. fi.access.fp = NULL;
  2959. }
  2960. } else {
  2961. fi.access.fp = NULL;
  2962. }
  2963. if (fi.access.fp != NULL) {
  2964. flockfile(fi.access.fp);
  2965. timestamp = time(NULL);
  2966. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2967. fprintf(fi.access.fp,
  2968. "[%010lu] [error] [client %s] ",
  2969. (unsigned long)timestamp,
  2970. src_addr);
  2971. if (conn->request_info.request_method != NULL) {
  2972. fprintf(fi.access.fp,
  2973. "%s %s: ",
  2974. conn->request_info.request_method,
  2975. conn->request_info.request_uri
  2976. ? conn->request_info.request_uri
  2977. : "");
  2978. }
  2979. fprintf(fi.access.fp, "%s", buf);
  2980. fputc('\n', fi.access.fp);
  2981. fflush(fi.access.fp);
  2982. funlockfile(fi.access.fp);
  2983. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2984. * mg_cry here anyway ;-) */
  2985. }
  2986. }
  2987. }
  2988. #else
  2989. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2990. #endif /* Externally provided function */
  2991. /* Construct fake connection structure. Used for logging, if connection
  2992. * is not applicable at the moment of logging. */
  2993. static struct mg_connection *
  2994. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2995. {
  2996. static const struct mg_connection conn_zero = {0};
  2997. *fc = conn_zero;
  2998. fc->phys_ctx = ctx;
  2999. fc->dom_ctx = &(ctx->dd);
  3000. return fc;
  3001. }
  3002. static void
  3003. mg_cry_internal_wrap(const struct mg_connection *conn,
  3004. struct mg_context *ctx,
  3005. const char *func,
  3006. unsigned line,
  3007. const char *fmt,
  3008. ...)
  3009. {
  3010. va_list ap;
  3011. va_start(ap, fmt);
  3012. if (!conn && ctx) {
  3013. struct mg_connection fc;
  3014. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3015. } else {
  3016. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3017. }
  3018. va_end(ap);
  3019. }
  3020. CIVETWEB_API void
  3021. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3022. {
  3023. va_list ap;
  3024. va_start(ap, fmt);
  3025. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3026. va_end(ap);
  3027. }
  3028. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3029. CIVETWEB_API const char *
  3030. mg_version(void)
  3031. {
  3032. return CIVETWEB_VERSION;
  3033. }
  3034. CIVETWEB_API const struct mg_request_info *
  3035. mg_get_request_info(const struct mg_connection *conn)
  3036. {
  3037. if (!conn) {
  3038. return NULL;
  3039. }
  3040. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3041. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3042. char txt[16];
  3043. struct mg_workerTLS *tls =
  3044. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3045. sprintf(txt, "%03i", conn->response_info.status_code);
  3046. if (strlen(txt) == 3) {
  3047. memcpy(tls->txtbuf, txt, 4);
  3048. } else {
  3049. strcpy(tls->txtbuf, "ERR");
  3050. }
  3051. ((struct mg_connection *)conn)->request_info.local_uri =
  3052. tls->txtbuf; /* use thread safe buffer */
  3053. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3054. tls->txtbuf; /* use the same thread safe buffer */
  3055. ((struct mg_connection *)conn)->request_info.request_uri =
  3056. tls->txtbuf; /* use the same thread safe buffer */
  3057. ((struct mg_connection *)conn)->request_info.num_headers =
  3058. conn->response_info.num_headers;
  3059. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3060. conn->response_info.http_headers,
  3061. sizeof(conn->response_info.http_headers));
  3062. } else
  3063. #endif
  3064. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3065. return NULL;
  3066. }
  3067. return &conn->request_info;
  3068. }
  3069. CIVETWEB_API const struct mg_response_info *
  3070. mg_get_response_info(const struct mg_connection *conn)
  3071. {
  3072. if (!conn) {
  3073. return NULL;
  3074. }
  3075. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3076. return NULL;
  3077. }
  3078. return &conn->response_info;
  3079. }
  3080. static const char *
  3081. get_proto_name(const struct mg_connection *conn)
  3082. {
  3083. #if defined(__clang__)
  3084. #pragma clang diagnostic push
  3085. #pragma clang diagnostic ignored "-Wunreachable-code"
  3086. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3087. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3088. * unreachable, but splitting into four different #ifdef clauses here is
  3089. * more complicated.
  3090. */
  3091. #endif
  3092. const struct mg_request_info *ri = &conn->request_info;
  3093. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3094. ? (ri->is_ssl ? "wss" : "ws")
  3095. : (ri->is_ssl ? "https" : "http"));
  3096. return proto;
  3097. #if defined(__clang__)
  3098. #pragma clang diagnostic pop
  3099. #endif
  3100. }
  3101. static int
  3102. mg_construct_local_link(const struct mg_connection *conn,
  3103. char *buf,
  3104. size_t buflen,
  3105. const char *define_proto,
  3106. int define_port,
  3107. const char *define_uri)
  3108. {
  3109. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3110. return -1;
  3111. } else {
  3112. int i, j;
  3113. int truncated = 0;
  3114. const struct mg_request_info *ri = &conn->request_info;
  3115. const char *proto =
  3116. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3117. const char *uri =
  3118. (define_uri != NULL)
  3119. ? define_uri
  3120. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3121. int port = (define_port > 0) ? define_port : ri->server_port;
  3122. int default_port = 80;
  3123. char *uri_encoded;
  3124. size_t uri_encoded_len;
  3125. if (uri == NULL) {
  3126. return -1;
  3127. }
  3128. uri_encoded_len = strlen(uri) * 3 + 1;
  3129. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3130. if (uri_encoded == NULL) {
  3131. return -1;
  3132. }
  3133. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3134. /* Directory separator should be preserved. */
  3135. for (i = j = 0; uri_encoded[i]; j++) {
  3136. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3137. uri_encoded[j] = '/';
  3138. i += 3;
  3139. } else {
  3140. uri_encoded[j] = uri_encoded[i++];
  3141. }
  3142. }
  3143. uri_encoded[j] = '\0';
  3144. #if defined(USE_X_DOM_SOCKET)
  3145. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3146. /* TODO: Define and document a link for UNIX domain sockets. */
  3147. /* There seems to be no official standard for this.
  3148. * Common uses seem to be "httpunix://", "http.unix://" or
  3149. * "http+unix://" as a protocol definition string, followed by
  3150. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3151. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3152. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3153. * "" (completely skipping the server name part). In any case, the
  3154. * last part is the server local path. */
  3155. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3156. mg_snprintf(conn,
  3157. &truncated,
  3158. buf,
  3159. buflen,
  3160. "%s.unix://%s%s",
  3161. proto,
  3162. server_name,
  3163. ri->local_uri);
  3164. default_port = 0;
  3165. mg_free(uri_encoded);
  3166. return 0;
  3167. }
  3168. #endif
  3169. if (define_proto) {
  3170. /* If we got a protocol name, use the default port accordingly. */
  3171. if ((0 == strcmp(define_proto, "https"))
  3172. || (0 == strcmp(define_proto, "wss"))) {
  3173. default_port = 443;
  3174. }
  3175. } else if (ri->is_ssl) {
  3176. /* If we did not get a protocol name, use TLS as default if it is
  3177. * already used. */
  3178. default_port = 443;
  3179. }
  3180. {
  3181. #if defined(USE_IPV6)
  3182. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3183. #endif
  3184. int auth_domain_check_enabled =
  3185. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3186. && (!mg_strcasecmp(
  3187. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3188. const char *server_domain =
  3189. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3190. char portstr[16];
  3191. char server_ip[48];
  3192. if (port != default_port) {
  3193. sprintf(portstr, ":%u", (unsigned)port);
  3194. } else {
  3195. portstr[0] = 0;
  3196. }
  3197. if (!auth_domain_check_enabled || !server_domain) {
  3198. sockaddr_to_string(server_ip,
  3199. sizeof(server_ip),
  3200. &conn->client.lsa);
  3201. server_domain = server_ip;
  3202. }
  3203. mg_snprintf(conn,
  3204. &truncated,
  3205. buf,
  3206. buflen,
  3207. #if defined(USE_IPV6)
  3208. "%s://%s%s%s%s%s",
  3209. proto,
  3210. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3211. server_domain,
  3212. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3213. #else
  3214. "%s://%s%s%s",
  3215. proto,
  3216. server_domain,
  3217. #endif
  3218. portstr,
  3219. uri_encoded);
  3220. mg_free(uri_encoded);
  3221. if (truncated) {
  3222. return -1;
  3223. }
  3224. return 0;
  3225. }
  3226. }
  3227. }
  3228. CIVETWEB_API int
  3229. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3230. {
  3231. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3232. }
  3233. /* Skip the characters until one of the delimiters characters found.
  3234. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3235. * Advance pointer to buffer to the next word. Return found 0-terminated
  3236. * word.
  3237. * Delimiters can be quoted with quotechar. */
  3238. static char *
  3239. skip_quoted(char **buf,
  3240. const char *delimiters,
  3241. const char *whitespace,
  3242. char quotechar)
  3243. {
  3244. char *p, *begin_word, *end_word, *end_whitespace;
  3245. begin_word = *buf;
  3246. end_word = begin_word + strcspn(begin_word, delimiters);
  3247. /* Check for quotechar */
  3248. if (end_word > begin_word) {
  3249. p = end_word - 1;
  3250. while (*p == quotechar) {
  3251. /* While the delimiter is quoted, look for the next delimiter. */
  3252. /* This happens, e.g., in calls from parse_auth_header,
  3253. * if the user name contains a " character. */
  3254. /* If there is anything beyond end_word, copy it. */
  3255. if (*end_word != '\0') {
  3256. size_t end_off = strcspn(end_word + 1, delimiters);
  3257. memmove(p, end_word, end_off + 1);
  3258. p += end_off; /* p must correspond to end_word - 1 */
  3259. end_word += end_off + 1;
  3260. } else {
  3261. *p = '\0';
  3262. break;
  3263. }
  3264. }
  3265. for (p++; p < end_word; p++) {
  3266. *p = '\0';
  3267. }
  3268. }
  3269. if (*end_word == '\0') {
  3270. *buf = end_word;
  3271. } else {
  3272. #if defined(GCC_DIAGNOSTIC)
  3273. /* Disable spurious conversion warning for GCC */
  3274. #pragma GCC diagnostic push
  3275. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3276. #endif /* defined(GCC_DIAGNOSTIC) */
  3277. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3278. #if defined(GCC_DIAGNOSTIC)
  3279. #pragma GCC diagnostic pop
  3280. #endif /* defined(GCC_DIAGNOSTIC) */
  3281. for (p = end_word; p < end_whitespace; p++) {
  3282. *p = '\0';
  3283. }
  3284. *buf = end_whitespace;
  3285. }
  3286. return begin_word;
  3287. }
  3288. /* Return HTTP header value, or NULL if not found. */
  3289. static const char *
  3290. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3291. {
  3292. int i;
  3293. for (i = 0; i < num_hdr; i++) {
  3294. if (!mg_strcasecmp(name, hdr[i].name)) {
  3295. return hdr[i].value;
  3296. }
  3297. }
  3298. return NULL;
  3299. }
  3300. /* Retrieve requested HTTP header multiple values, and return the number of
  3301. * found occurrences */
  3302. static int
  3303. get_req_headers(const struct mg_request_info *ri,
  3304. const char *name,
  3305. const char **output,
  3306. int output_max_size)
  3307. {
  3308. int i;
  3309. int cnt = 0;
  3310. if (ri) {
  3311. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3312. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3313. output[cnt++] = ri->http_headers[i].value;
  3314. }
  3315. }
  3316. }
  3317. return cnt;
  3318. }
  3319. CIVETWEB_API const char *
  3320. mg_get_header(const struct mg_connection *conn, const char *name)
  3321. {
  3322. if (!conn) {
  3323. return NULL;
  3324. }
  3325. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3326. return get_header(conn->request_info.http_headers,
  3327. conn->request_info.num_headers,
  3328. name);
  3329. }
  3330. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3331. return get_header(conn->response_info.http_headers,
  3332. conn->response_info.num_headers,
  3333. name);
  3334. }
  3335. return NULL;
  3336. }
  3337. static const char *
  3338. get_http_version(const struct mg_connection *conn)
  3339. {
  3340. if (!conn) {
  3341. return NULL;
  3342. }
  3343. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3344. return conn->request_info.http_version;
  3345. }
  3346. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3347. return conn->response_info.http_version;
  3348. }
  3349. return NULL;
  3350. }
  3351. /* A helper function for traversing a comma separated list of values.
  3352. * It returns a list pointer shifted to the next value, or NULL if the end
  3353. * of the list found.
  3354. * Value is stored in val vector. If value has form "x=y", then eq_val
  3355. * vector is initialized to point to the "y" part, and val vector length
  3356. * is adjusted to point only to "x". */
  3357. static const char *
  3358. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3359. {
  3360. int end;
  3361. reparse:
  3362. if (val == NULL || list == NULL || *list == '\0') {
  3363. /* End of the list */
  3364. return NULL;
  3365. }
  3366. /* Skip over leading LWS */
  3367. while (*list == ' ' || *list == '\t')
  3368. list++;
  3369. val->ptr = list;
  3370. if ((list = strchr(val->ptr, ',')) != NULL) {
  3371. /* Comma found. Store length and shift the list ptr */
  3372. val->len = ((size_t)(list - val->ptr));
  3373. list++;
  3374. } else {
  3375. /* This value is the last one */
  3376. list = val->ptr + strlen(val->ptr);
  3377. val->len = ((size_t)(list - val->ptr));
  3378. }
  3379. /* Adjust length for trailing LWS */
  3380. end = (int)val->len - 1;
  3381. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3382. end--;
  3383. val->len = (size_t)(end) + (size_t)(1);
  3384. if (val->len == 0) {
  3385. /* Ignore any empty entries. */
  3386. goto reparse;
  3387. }
  3388. if (eq_val != NULL) {
  3389. /* Value has form "x=y", adjust pointers and lengths
  3390. * so that val points to "x", and eq_val points to "y". */
  3391. eq_val->len = 0;
  3392. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3393. if (eq_val->ptr != NULL) {
  3394. eq_val->ptr++; /* Skip over '=' character */
  3395. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3396. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3397. }
  3398. }
  3399. return list;
  3400. }
  3401. /* A helper function for checking if a comma separated list of values
  3402. * contains
  3403. * the given option (case insensitvely).
  3404. * 'header' can be NULL, in which case false is returned. */
  3405. static int
  3406. header_has_option(const char *header, const char *option)
  3407. {
  3408. struct vec opt_vec;
  3409. struct vec eq_vec;
  3410. DEBUG_ASSERT(option != NULL);
  3411. DEBUG_ASSERT(option[0] != '\0');
  3412. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3413. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3414. return 1;
  3415. }
  3416. return 0;
  3417. }
  3418. /* Sorting function implemented in a separate file */
  3419. #include "sort.inl"
  3420. /* Pattern matching has been reimplemented in a new file */
  3421. #include "match.inl"
  3422. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3423. * This function must tolerate situations when connection info is not
  3424. * set up, for example if request parsing failed. */
  3425. static int
  3426. should_keep_alive(const struct mg_connection *conn)
  3427. {
  3428. const char *http_version;
  3429. const char *header;
  3430. /* First satisfy needs of the server */
  3431. if ((conn == NULL) || conn->must_close) {
  3432. /* Close, if civetweb framework needs to close */
  3433. return 0;
  3434. }
  3435. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3436. /* Close, if keep alive is not enabled */
  3437. return 0;
  3438. }
  3439. /* Check explicit wish of the client */
  3440. header = mg_get_header(conn, "Connection");
  3441. if (header) {
  3442. /* If there is a connection header from the client, obey */
  3443. if (header_has_option(header, "keep-alive")) {
  3444. return 1;
  3445. }
  3446. return 0;
  3447. }
  3448. /* Use default of the standard */
  3449. http_version = get_http_version(conn);
  3450. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3451. /* HTTP 1.1 default is keep alive */
  3452. return 1;
  3453. }
  3454. /* HTTP 1.0 (and earlier) default is to close the connection */
  3455. return 0;
  3456. }
  3457. static int
  3458. should_decode_url(const struct mg_connection *conn)
  3459. {
  3460. if (!conn || !conn->dom_ctx) {
  3461. return 0;
  3462. }
  3463. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3464. }
  3465. static int
  3466. should_decode_query_string(const struct mg_connection *conn)
  3467. {
  3468. if (!conn || !conn->dom_ctx) {
  3469. return 0;
  3470. }
  3471. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3472. == 0);
  3473. }
  3474. static const char *
  3475. suggest_connection_header(const struct mg_connection *conn)
  3476. {
  3477. return should_keep_alive(conn) ? "keep-alive" : "close";
  3478. }
  3479. #include "response.inl"
  3480. static void
  3481. send_no_cache_header(struct mg_connection *conn)
  3482. {
  3483. /* Send all current and obsolete cache opt-out directives. */
  3484. mg_response_header_add(conn,
  3485. "Cache-Control",
  3486. "no-cache, no-store, "
  3487. "must-revalidate, private, max-age=0",
  3488. -1);
  3489. mg_response_header_add(conn, "Expires", "0", -1);
  3490. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3491. /* Obsolete, but still send it for HTTP/1.0 */
  3492. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3493. }
  3494. }
  3495. static void
  3496. send_static_cache_header(struct mg_connection *conn)
  3497. {
  3498. #if !defined(NO_CACHING)
  3499. int max_age;
  3500. char val[64];
  3501. const char *cache_control =
  3502. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3503. /* If there is a full cache-control option configured,0 use it */
  3504. if (cache_control != NULL) {
  3505. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3506. return;
  3507. }
  3508. /* Read the server config to check how long a file may be cached.
  3509. * The configuration is in seconds. */
  3510. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3511. if (max_age <= 0) {
  3512. /* 0 means "do not cache". All values <0 are reserved
  3513. * and may be used differently in the future. */
  3514. /* If a file should not be cached, do not only send
  3515. * max-age=0, but also pragmas and Expires headers. */
  3516. send_no_cache_header(conn);
  3517. return;
  3518. }
  3519. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3520. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3521. /* See also https://www.mnot.net/cache_docs/ */
  3522. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3523. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3524. * leap
  3525. * year to 31622400 seconds. For the moment, we just send whatever has
  3526. * been configured, still the behavior for >1 year should be considered
  3527. * as undefined. */
  3528. mg_snprintf(
  3529. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3530. mg_response_header_add(conn, "Cache-Control", val, -1);
  3531. #else /* NO_CACHING */
  3532. send_no_cache_header(conn);
  3533. #endif /* !NO_CACHING */
  3534. }
  3535. static void
  3536. send_additional_header(struct mg_connection *conn)
  3537. {
  3538. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3539. #if !defined(NO_SSL)
  3540. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3541. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3542. if (max_age >= 0) {
  3543. char val[64];
  3544. mg_snprintf(conn,
  3545. NULL,
  3546. val,
  3547. sizeof(val),
  3548. "max-age=%lu",
  3549. (unsigned long)max_age);
  3550. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3551. }
  3552. }
  3553. #endif
  3554. if (header && header[0]) {
  3555. mg_response_header_add_lines(conn, header);
  3556. }
  3557. }
  3558. static void
  3559. send_cors_header(struct mg_connection *conn)
  3560. {
  3561. const char *origin_hdr = mg_get_header(conn, "Origin");
  3562. const char *cors_orig_cfg =
  3563. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3564. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3565. /* Cross-origin resource sharing (CORS), see
  3566. * http://www.html5rocks.com/en/tutorials/cors/,
  3567. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3568. * CORS preflight is not supported for files. */
  3569. mg_response_header_add(conn,
  3570. "Access-Control-Allow-Origin",
  3571. cors_orig_cfg,
  3572. -1);
  3573. }
  3574. }
  3575. #if !defined(NO_FILESYSTEMS)
  3576. static void handle_file_based_request(struct mg_connection *conn,
  3577. const char *path,
  3578. struct mg_file *filep);
  3579. #endif /* NO_FILESYSTEMS */
  3580. CIVETWEB_API const char *
  3581. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3582. {
  3583. /* See IANA HTTP status code assignment:
  3584. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3585. */
  3586. switch (response_code) {
  3587. /* RFC2616 Section 10.1 - Informational 1xx */
  3588. case 100:
  3589. return "Continue"; /* RFC2616 Section 10.1.1 */
  3590. case 101:
  3591. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3592. case 102:
  3593. return "Processing"; /* RFC2518 Section 10.1 */
  3594. /* RFC2616 Section 10.2 - Successful 2xx */
  3595. case 200:
  3596. return "OK"; /* RFC2616 Section 10.2.1 */
  3597. case 201:
  3598. return "Created"; /* RFC2616 Section 10.2.2 */
  3599. case 202:
  3600. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3601. case 203:
  3602. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3603. case 204:
  3604. return "No Content"; /* RFC2616 Section 10.2.5 */
  3605. case 205:
  3606. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3607. case 206:
  3608. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3609. case 207:
  3610. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3611. */
  3612. case 208:
  3613. return "Already Reported"; /* RFC5842 Section 7.1 */
  3614. case 226:
  3615. return "IM used"; /* RFC3229 Section 10.4.1 */
  3616. /* RFC2616 Section 10.3 - Redirection 3xx */
  3617. case 300:
  3618. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3619. case 301:
  3620. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3621. case 302:
  3622. return "Found"; /* RFC2616 Section 10.3.3 */
  3623. case 303:
  3624. return "See Other"; /* RFC2616 Section 10.3.4 */
  3625. case 304:
  3626. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3627. case 305:
  3628. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3629. case 307:
  3630. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3631. case 308:
  3632. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3633. /* RFC2616 Section 10.4 - Client Error 4xx */
  3634. case 400:
  3635. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3636. case 401:
  3637. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3638. case 402:
  3639. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3640. case 403:
  3641. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3642. case 404:
  3643. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3644. case 405:
  3645. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3646. case 406:
  3647. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3648. case 407:
  3649. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3650. case 408:
  3651. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3652. case 409:
  3653. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3654. case 410:
  3655. return "Gone"; /* RFC2616 Section 10.4.11 */
  3656. case 411:
  3657. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3658. case 412:
  3659. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3660. case 413:
  3661. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3662. case 414:
  3663. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3664. case 415:
  3665. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3666. case 416:
  3667. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3668. */
  3669. case 417:
  3670. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3671. case 421:
  3672. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3673. case 422:
  3674. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3675. * Section 11.2 */
  3676. case 423:
  3677. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3678. case 424:
  3679. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3680. * Section 11.4 */
  3681. case 426:
  3682. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3683. case 428:
  3684. return "Precondition Required"; /* RFC 6585, Section 3 */
  3685. case 429:
  3686. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3687. case 431:
  3688. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3689. case 451:
  3690. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3691. * Section 3 */
  3692. /* RFC2616 Section 10.5 - Server Error 5xx */
  3693. case 500:
  3694. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3695. case 501:
  3696. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3697. case 502:
  3698. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3699. case 503:
  3700. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3701. case 504:
  3702. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3703. case 505:
  3704. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3705. case 506:
  3706. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3707. case 507:
  3708. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3709. * Section 11.5 */
  3710. case 508:
  3711. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3712. case 510:
  3713. return "Not Extended"; /* RFC 2774, Section 7 */
  3714. case 511:
  3715. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3716. /* Other status codes, not shown in the IANA HTTP status code
  3717. * assignment.
  3718. * E.g., "de facto" standards due to common use, ... */
  3719. case 418:
  3720. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3721. case 419:
  3722. return "Authentication Timeout"; /* common use */
  3723. case 420:
  3724. return "Enhance Your Calm"; /* common use */
  3725. case 440:
  3726. return "Login Timeout"; /* common use */
  3727. case 509:
  3728. return "Bandwidth Limit Exceeded"; /* common use */
  3729. default:
  3730. /* This error code is unknown. This should not happen. */
  3731. if (conn) {
  3732. mg_cry_internal(conn,
  3733. "Unknown HTTP response code: %u",
  3734. response_code);
  3735. }
  3736. /* Return at least a category according to RFC 2616 Section 10. */
  3737. if (response_code >= 100 && response_code < 200) {
  3738. /* Unknown informational status code */
  3739. return "Information";
  3740. }
  3741. if (response_code >= 200 && response_code < 300) {
  3742. /* Unknown success code */
  3743. return "Success";
  3744. }
  3745. if (response_code >= 300 && response_code < 400) {
  3746. /* Unknown redirection code */
  3747. return "Redirection";
  3748. }
  3749. if (response_code >= 400 && response_code < 500) {
  3750. /* Unknown request error code */
  3751. return "Client Error";
  3752. }
  3753. if (response_code >= 500 && response_code < 600) {
  3754. /* Unknown server error code */
  3755. return "Server Error";
  3756. }
  3757. /* Response code not even within reasonable range */
  3758. return "";
  3759. }
  3760. }
  3761. static int
  3762. mg_send_http_error_impl(struct mg_connection *conn,
  3763. int status,
  3764. const char *fmt,
  3765. va_list args)
  3766. {
  3767. char errmsg_buf[MG_BUF_LEN];
  3768. va_list ap;
  3769. int has_body;
  3770. #if !defined(NO_FILESYSTEMS)
  3771. char path_buf[UTF8_PATH_MAX];
  3772. int len, i, page_handler_found, scope, truncated;
  3773. const char *error_handler = NULL;
  3774. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3775. const char *error_page_file_ext, *tstr;
  3776. #endif /* NO_FILESYSTEMS */
  3777. int handled_by_callback = 0;
  3778. if ((conn == NULL) || (fmt == NULL)) {
  3779. return -2;
  3780. }
  3781. /* Set status (for log) */
  3782. conn->status_code = status;
  3783. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3784. has_body = ((status > 199) && (status != 204) && (status != 304));
  3785. /* Prepare message in buf, if required */
  3786. if (has_body
  3787. || (!conn->in_error_handler
  3788. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3789. /* Store error message in errmsg_buf */
  3790. va_copy(ap, args);
  3791. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3792. va_end(ap);
  3793. /* In a debug build, print all html errors */
  3794. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3795. }
  3796. /* If there is a http_error callback, call it.
  3797. * But don't do it recursively, if callback calls mg_send_http_error again.
  3798. */
  3799. if (!conn->in_error_handler
  3800. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3801. /* Mark in_error_handler to avoid recursion and call user callback. */
  3802. conn->in_error_handler = 1;
  3803. handled_by_callback =
  3804. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3805. == 0);
  3806. conn->in_error_handler = 0;
  3807. }
  3808. if (!handled_by_callback) {
  3809. /* Check for recursion */
  3810. if (conn->in_error_handler) {
  3811. DEBUG_TRACE(
  3812. "Recursion when handling error %u - fall back to default",
  3813. status);
  3814. #if !defined(NO_FILESYSTEMS)
  3815. } else {
  3816. /* Send user defined error pages, if defined */
  3817. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3818. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3819. page_handler_found = 0;
  3820. if (error_handler != NULL) {
  3821. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3822. switch (scope) {
  3823. case 1: /* Handler for specific error, e.g. 404 error */
  3824. mg_snprintf(conn,
  3825. &truncated,
  3826. path_buf,
  3827. sizeof(path_buf) - 32,
  3828. "%serror%03u.",
  3829. error_handler,
  3830. status);
  3831. break;
  3832. case 2: /* Handler for error group, e.g., 5xx error
  3833. * handler
  3834. * for all server errors (500-599) */
  3835. mg_snprintf(conn,
  3836. &truncated,
  3837. path_buf,
  3838. sizeof(path_buf) - 32,
  3839. "%serror%01uxx.",
  3840. error_handler,
  3841. status / 100);
  3842. break;
  3843. default: /* Handler for all errors */
  3844. mg_snprintf(conn,
  3845. &truncated,
  3846. path_buf,
  3847. sizeof(path_buf) - 32,
  3848. "%serror.",
  3849. error_handler);
  3850. break;
  3851. }
  3852. /* String truncation in buf may only occur if
  3853. * error_handler is too long. This string is
  3854. * from the config, not from a client. */
  3855. (void)truncated;
  3856. /* The following code is redundant, but it should avoid
  3857. * false positives in static source code analyzers and
  3858. * vulnerability scanners.
  3859. */
  3860. path_buf[sizeof(path_buf) - 32] = 0;
  3861. len = (int)strlen(path_buf);
  3862. if (len > (int)sizeof(path_buf) - 32) {
  3863. len = (int)sizeof(path_buf) - 32;
  3864. }
  3865. /* Start with the file extenstion from the configuration. */
  3866. tstr = strchr(error_page_file_ext, '.');
  3867. while (tstr) {
  3868. for (i = 1;
  3869. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3870. i++) {
  3871. /* buffer overrun is not possible here, since
  3872. * (i < 32) && (len < sizeof(path_buf) - 32)
  3873. * ==> (i + len) < sizeof(path_buf) */
  3874. path_buf[len + i - 1] = tstr[i];
  3875. }
  3876. /* buffer overrun is not possible here, since
  3877. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3878. * ==> (i + len) <= sizeof(path_buf) */
  3879. path_buf[len + i - 1] = 0;
  3880. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3881. DEBUG_TRACE("Check error page %s - found",
  3882. path_buf);
  3883. page_handler_found = 1;
  3884. break;
  3885. }
  3886. DEBUG_TRACE("Check error page %s - not found",
  3887. path_buf);
  3888. /* Continue with the next file extenstion from the
  3889. * configuration (if there is a next one). */
  3890. tstr = strchr(tstr + i, '.');
  3891. }
  3892. }
  3893. }
  3894. if (page_handler_found) {
  3895. conn->in_error_handler = 1;
  3896. handle_file_based_request(conn, path_buf, &error_page_file);
  3897. conn->in_error_handler = 0;
  3898. return 0;
  3899. }
  3900. #endif /* NO_FILESYSTEMS */
  3901. }
  3902. /* No custom error page. Send default error page. */
  3903. conn->must_close = 1;
  3904. mg_response_header_start(conn, status);
  3905. send_no_cache_header(conn);
  3906. send_additional_header(conn);
  3907. send_cors_header(conn);
  3908. if (has_body) {
  3909. mg_response_header_add(conn,
  3910. "Content-Type",
  3911. "text/plain; charset=utf-8",
  3912. -1);
  3913. }
  3914. mg_response_header_send(conn);
  3915. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3916. if (has_body) {
  3917. /* For other errors, send a generic error message. */
  3918. const char *status_text = mg_get_response_code_text(conn, status);
  3919. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3920. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3921. } else {
  3922. /* No body allowed. Close the connection. */
  3923. DEBUG_TRACE("Error %i", status);
  3924. }
  3925. }
  3926. return 0;
  3927. }
  3928. CIVETWEB_API int
  3929. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3930. {
  3931. va_list ap;
  3932. int ret;
  3933. va_start(ap, fmt);
  3934. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3935. va_end(ap);
  3936. return ret;
  3937. }
  3938. CIVETWEB_API int
  3939. mg_send_http_ok(struct mg_connection *conn,
  3940. const char *mime_type,
  3941. long long content_length)
  3942. {
  3943. if ((mime_type == NULL) || (*mime_type == 0)) {
  3944. /* No content type defined: default to text/html */
  3945. mime_type = "text/html";
  3946. }
  3947. mg_response_header_start(conn, 200);
  3948. send_no_cache_header(conn);
  3949. send_additional_header(conn);
  3950. send_cors_header(conn);
  3951. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3952. if (content_length < 0) {
  3953. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3954. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3955. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3956. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3957. }
  3958. } else {
  3959. char len[32];
  3960. int trunc = 0;
  3961. mg_snprintf(conn,
  3962. &trunc,
  3963. len,
  3964. sizeof(len),
  3965. "%" UINT64_FMT,
  3966. (uint64_t)content_length);
  3967. if (!trunc) {
  3968. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3969. * !trunc is always true */
  3970. mg_response_header_add(conn, "Content-Length", len, -1);
  3971. }
  3972. }
  3973. mg_response_header_send(conn);
  3974. return 0;
  3975. }
  3976. CIVETWEB_API int
  3977. mg_send_http_redirect(struct mg_connection *conn,
  3978. const char *target_url,
  3979. int redirect_code)
  3980. {
  3981. /* Send a 30x redirect response.
  3982. *
  3983. * Redirect types (status codes):
  3984. *
  3985. * Status | Perm/Temp | Method | Version
  3986. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3987. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3988. * 303 | temporary | always use GET | HTTP/1.1
  3989. * 307 | temporary | always keep method | HTTP/1.1
  3990. * 308 | permanent | always keep method | HTTP/1.1
  3991. */
  3992. #if defined(MG_SEND_REDIRECT_BODY)
  3993. char redirect_body[MG_BUF_LEN];
  3994. size_t content_len = 0;
  3995. char content_len_text[32];
  3996. #endif
  3997. /* In case redirect_code=0, use 307. */
  3998. if (redirect_code == 0) {
  3999. redirect_code = 307;
  4000. }
  4001. /* In case redirect_code is none of the above, return error. */
  4002. if ((redirect_code != 301) && (redirect_code != 302)
  4003. && (redirect_code != 303) && (redirect_code != 307)
  4004. && (redirect_code != 308)) {
  4005. /* Parameter error */
  4006. return -2;
  4007. }
  4008. /* If target_url is not defined, redirect to "/". */
  4009. if ((target_url == NULL) || (*target_url == 0)) {
  4010. target_url = "/";
  4011. }
  4012. #if defined(MG_SEND_REDIRECT_BODY)
  4013. /* TODO: condition name? */
  4014. /* Prepare a response body with a hyperlink.
  4015. *
  4016. * According to RFC2616 (and RFC1945 before):
  4017. * Unless the request method was HEAD, the entity of the
  4018. * response SHOULD contain a short hypertext note with a hyperlink to
  4019. * the new URI(s).
  4020. *
  4021. * However, this response body is not useful in M2M communication.
  4022. * Probably the original reason in the RFC was, clients not supporting
  4023. * a 30x HTTP redirect could still show the HTML page and let the user
  4024. * press the link. Since current browsers support 30x HTTP, the additional
  4025. * HTML body does not seem to make sense anymore.
  4026. *
  4027. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4028. * but it only notes:
  4029. * The server's response payload usually contains a short
  4030. * hypertext note with a hyperlink to the new URI(s).
  4031. *
  4032. * Deactivated by default. If you need the 30x body, set the define.
  4033. */
  4034. mg_snprintf(
  4035. conn,
  4036. NULL /* ignore truncation */,
  4037. redirect_body,
  4038. sizeof(redirect_body),
  4039. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4040. redirect_text,
  4041. target_url,
  4042. target_url);
  4043. content_len = strlen(reply);
  4044. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4045. #endif
  4046. /* Send all required headers */
  4047. mg_response_header_start(conn, redirect_code);
  4048. mg_response_header_add(conn, "Location", target_url, -1);
  4049. if ((redirect_code == 301) || (redirect_code == 308)) {
  4050. /* Permanent redirect */
  4051. send_static_cache_header(conn);
  4052. } else {
  4053. /* Temporary redirect */
  4054. send_no_cache_header(conn);
  4055. }
  4056. send_additional_header(conn);
  4057. send_cors_header(conn);
  4058. #if defined(MG_SEND_REDIRECT_BODY)
  4059. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4060. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4061. #else
  4062. mg_response_header_add(conn, "Content-Length", "0", 1);
  4063. #endif
  4064. mg_response_header_send(conn);
  4065. #if defined(MG_SEND_REDIRECT_BODY)
  4066. /* Send response body */
  4067. /* ... unless it is a HEAD request */
  4068. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4069. ret = mg_write(conn, redirect_body, content_len);
  4070. }
  4071. #endif
  4072. return 1;
  4073. }
  4074. #if defined(_WIN32)
  4075. /* Create substitutes for POSIX functions in Win32. */
  4076. #if defined(GCC_DIAGNOSTIC)
  4077. /* Show no warning in case system functions are not used. */
  4078. #pragma GCC diagnostic push
  4079. #pragma GCC diagnostic ignored "-Wunused-function"
  4080. #endif
  4081. static int
  4082. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4083. {
  4084. (void)unused;
  4085. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4086. InitializeCriticalSection(&mutex->sec);
  4087. return 0;
  4088. }
  4089. static int
  4090. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4091. {
  4092. DeleteCriticalSection(&mutex->sec);
  4093. return 0;
  4094. }
  4095. static int
  4096. pthread_mutex_lock(pthread_mutex_t *mutex)
  4097. {
  4098. EnterCriticalSection(&mutex->sec);
  4099. return 0;
  4100. }
  4101. static int
  4102. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4103. {
  4104. LeaveCriticalSection(&mutex->sec);
  4105. return 0;
  4106. }
  4107. FUNCTION_MAY_BE_UNUSED
  4108. static int
  4109. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4110. {
  4111. (void)unused;
  4112. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4113. cv->waiting_thread = NULL;
  4114. return 0;
  4115. }
  4116. FUNCTION_MAY_BE_UNUSED
  4117. static int
  4118. pthread_cond_timedwait(pthread_cond_t *cv,
  4119. pthread_mutex_t *mutex,
  4120. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4121. {
  4122. struct mg_workerTLS **ptls,
  4123. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4124. int ok;
  4125. uint64_t nsnow, nswaitabs;
  4126. int64_t nswaitrel;
  4127. DWORD mswaitrel;
  4128. pthread_mutex_lock(&cv->threadIdSec);
  4129. /* Add this thread to cv's waiting list */
  4130. ptls = &cv->waiting_thread;
  4131. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4132. ;
  4133. tls->next_waiting_thread = NULL;
  4134. *ptls = tls;
  4135. pthread_mutex_unlock(&cv->threadIdSec);
  4136. if (abstime) {
  4137. nsnow = mg_get_current_time_ns();
  4138. nswaitabs =
  4139. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4140. nswaitrel = nswaitabs - nsnow;
  4141. if (nswaitrel < 0) {
  4142. nswaitrel = 0;
  4143. }
  4144. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4145. } else {
  4146. mswaitrel = (DWORD)INFINITE;
  4147. }
  4148. pthread_mutex_unlock(mutex);
  4149. ok = (WAIT_OBJECT_0
  4150. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4151. if (!ok) {
  4152. ok = 1;
  4153. pthread_mutex_lock(&cv->threadIdSec);
  4154. ptls = &cv->waiting_thread;
  4155. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4156. if (*ptls == tls) {
  4157. *ptls = tls->next_waiting_thread;
  4158. ok = 0;
  4159. break;
  4160. }
  4161. }
  4162. pthread_mutex_unlock(&cv->threadIdSec);
  4163. if (ok) {
  4164. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4165. (DWORD)INFINITE);
  4166. }
  4167. }
  4168. /* This thread has been removed from cv's waiting list */
  4169. pthread_mutex_lock(mutex);
  4170. return ok ? 0 : -1;
  4171. }
  4172. FUNCTION_MAY_BE_UNUSED
  4173. static int
  4174. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4175. {
  4176. return pthread_cond_timedwait(cv, mutex, NULL);
  4177. }
  4178. FUNCTION_MAY_BE_UNUSED
  4179. static int
  4180. pthread_cond_signal(pthread_cond_t *cv)
  4181. {
  4182. HANDLE wkup = NULL;
  4183. BOOL ok = FALSE;
  4184. pthread_mutex_lock(&cv->threadIdSec);
  4185. if (cv->waiting_thread) {
  4186. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4187. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4188. ok = SetEvent(wkup);
  4189. DEBUG_ASSERT(ok);
  4190. }
  4191. pthread_mutex_unlock(&cv->threadIdSec);
  4192. return ok ? 0 : 1;
  4193. }
  4194. FUNCTION_MAY_BE_UNUSED
  4195. static int
  4196. pthread_cond_broadcast(pthread_cond_t *cv)
  4197. {
  4198. pthread_mutex_lock(&cv->threadIdSec);
  4199. while (cv->waiting_thread) {
  4200. pthread_cond_signal(cv);
  4201. }
  4202. pthread_mutex_unlock(&cv->threadIdSec);
  4203. return 0;
  4204. }
  4205. FUNCTION_MAY_BE_UNUSED
  4206. static int
  4207. pthread_cond_destroy(pthread_cond_t *cv)
  4208. {
  4209. pthread_mutex_lock(&cv->threadIdSec);
  4210. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4211. pthread_mutex_unlock(&cv->threadIdSec);
  4212. pthread_mutex_destroy(&cv->threadIdSec);
  4213. return 0;
  4214. }
  4215. #if defined(ALTERNATIVE_QUEUE)
  4216. FUNCTION_MAY_BE_UNUSED
  4217. static void *
  4218. event_create(void)
  4219. {
  4220. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4221. }
  4222. FUNCTION_MAY_BE_UNUSED
  4223. static int
  4224. event_wait(void *eventhdl)
  4225. {
  4226. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4227. return (res == WAIT_OBJECT_0);
  4228. }
  4229. FUNCTION_MAY_BE_UNUSED
  4230. static int
  4231. event_signal(void *eventhdl)
  4232. {
  4233. return (int)SetEvent((HANDLE)eventhdl);
  4234. }
  4235. FUNCTION_MAY_BE_UNUSED
  4236. static void
  4237. event_destroy(void *eventhdl)
  4238. {
  4239. CloseHandle((HANDLE)eventhdl);
  4240. }
  4241. #endif
  4242. #if defined(GCC_DIAGNOSTIC)
  4243. /* Enable unused function warning again */
  4244. #pragma GCC diagnostic pop
  4245. #endif
  4246. /* For Windows, change all slashes to backslashes in path names. */
  4247. static void
  4248. change_slashes_to_backslashes(char *path)
  4249. {
  4250. int i;
  4251. for (i = 0; path[i] != '\0'; i++) {
  4252. if (path[i] == '/') {
  4253. path[i] = '\\';
  4254. }
  4255. /* remove double backslash (check i > 0 to preserve UNC paths,
  4256. * like \\server\file.txt) */
  4257. if ((i > 0) && (path[i] == '\\')) {
  4258. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4259. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4260. }
  4261. }
  4262. }
  4263. }
  4264. static int
  4265. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4266. {
  4267. int diff;
  4268. do {
  4269. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4270. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4271. s1++;
  4272. s2++;
  4273. } while ((diff == 0) && (s1[-1] != L'\0'));
  4274. return diff;
  4275. }
  4276. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4277. * wbuf and wbuf_len is a target buffer and its length. */
  4278. static void
  4279. path_to_unicode(const struct mg_connection *conn,
  4280. const char *path,
  4281. wchar_t *wbuf,
  4282. size_t wbuf_len)
  4283. {
  4284. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4285. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4286. DWORD long_len, err;
  4287. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4288. mg_strlcpy(buf, path, sizeof(buf));
  4289. change_slashes_to_backslashes(buf);
  4290. /* Convert to Unicode and back. If doubly-converted string does not
  4291. * match the original, something is fishy, reject. */
  4292. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4293. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4294. WideCharToMultiByte(
  4295. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4296. if (strcmp(buf, buf2) != 0) {
  4297. wbuf[0] = L'\0';
  4298. }
  4299. /* Windows file systems are not case sensitive, but you can still use
  4300. * uppercase and lowercase letters (on all modern file systems).
  4301. * The server can check if the URI uses the same upper/lowercase
  4302. * letters an the file system, effectively making Windows servers
  4303. * case sensitive (like Linux servers are). It is still not possible
  4304. * to use two files with the same name in different cases on Windows
  4305. * (like /a and /A) - this would be possible in Linux.
  4306. * As a default, Windows is not case sensitive, but the case sensitive
  4307. * file name check can be activated by an additional configuration. */
  4308. if (conn) {
  4309. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4310. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4311. "yes")) {
  4312. /* Use case sensitive compare function */
  4313. fcompare = wcscmp;
  4314. }
  4315. }
  4316. (void)conn; /* conn is currently unused */
  4317. /* Only accept a full file path, not a Windows short (8.3) path. */
  4318. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4319. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4320. if (long_len == 0) {
  4321. err = GetLastError();
  4322. if (err == ERROR_FILE_NOT_FOUND) {
  4323. /* File does not exist. This is not always a problem here. */
  4324. return;
  4325. }
  4326. }
  4327. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4328. /* Short name is used. */
  4329. wbuf[0] = L'\0';
  4330. }
  4331. }
  4332. #if !defined(NO_FILESYSTEMS)
  4333. /* Get file information, return 1 if file exists, 0 if not */
  4334. static int
  4335. mg_stat(const struct mg_connection *conn,
  4336. const char *path,
  4337. struct mg_file_stat *filep)
  4338. {
  4339. wchar_t wbuf[UTF16_PATH_MAX];
  4340. WIN32_FILE_ATTRIBUTE_DATA info;
  4341. time_t creation_time;
  4342. size_t len;
  4343. if (!filep) {
  4344. return 0;
  4345. }
  4346. memset(filep, 0, sizeof(*filep));
  4347. if (mg_path_suspicious(conn, path)) {
  4348. return 0;
  4349. }
  4350. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4351. /* Windows happily opens files with some garbage at the end of file name.
  4352. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4353. * "a.cgi", despite one would expect an error back. */
  4354. len = strlen(path);
  4355. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4356. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4357. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4358. filep->last_modified =
  4359. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4360. info.ftLastWriteTime.dwHighDateTime);
  4361. /* On Windows, the file creation time can be higher than the
  4362. * modification time, e.g. when a file is copied.
  4363. * Since the Last-Modified timestamp is used for caching
  4364. * it should be based on the most recent timestamp. */
  4365. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4366. info.ftCreationTime.dwHighDateTime);
  4367. if (creation_time > filep->last_modified) {
  4368. filep->last_modified = creation_time;
  4369. }
  4370. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4371. return 1;
  4372. }
  4373. return 0;
  4374. }
  4375. #endif
  4376. static int
  4377. mg_remove(const struct mg_connection *conn, const char *path)
  4378. {
  4379. wchar_t wbuf[UTF16_PATH_MAX];
  4380. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4381. return DeleteFileW(wbuf) ? 0 : -1;
  4382. }
  4383. static int
  4384. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4385. {
  4386. wchar_t wbuf[UTF16_PATH_MAX];
  4387. (void)mode;
  4388. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4389. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4390. }
  4391. /* Create substitutes for POSIX functions in Win32. */
  4392. #if defined(GCC_DIAGNOSTIC)
  4393. /* Show no warning in case system functions are not used. */
  4394. #pragma GCC diagnostic push
  4395. #pragma GCC diagnostic ignored "-Wunused-function"
  4396. #endif
  4397. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4398. FUNCTION_MAY_BE_UNUSED
  4399. static DIR *
  4400. mg_opendir(const struct mg_connection *conn, const char *name)
  4401. {
  4402. DIR *dir = NULL;
  4403. wchar_t wpath[UTF16_PATH_MAX];
  4404. DWORD attrs;
  4405. if (name == NULL) {
  4406. SetLastError(ERROR_BAD_ARGUMENTS);
  4407. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4408. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4409. } else {
  4410. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4411. attrs = GetFileAttributesW(wpath);
  4412. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4413. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4414. (void)wcscat(wpath, L"\\*");
  4415. dir->handle = FindFirstFileW(wpath, &dir->info);
  4416. dir->result.d_name[0] = '\0';
  4417. } else {
  4418. mg_free(dir);
  4419. dir = NULL;
  4420. }
  4421. }
  4422. return dir;
  4423. }
  4424. FUNCTION_MAY_BE_UNUSED
  4425. static int
  4426. mg_closedir(DIR *dir)
  4427. {
  4428. int result = 0;
  4429. if (dir != NULL) {
  4430. if (dir->handle != INVALID_HANDLE_VALUE)
  4431. result = FindClose(dir->handle) ? 0 : -1;
  4432. mg_free(dir);
  4433. } else {
  4434. result = -1;
  4435. SetLastError(ERROR_BAD_ARGUMENTS);
  4436. }
  4437. return result;
  4438. }
  4439. FUNCTION_MAY_BE_UNUSED
  4440. static struct dirent *
  4441. mg_readdir(DIR *dir)
  4442. {
  4443. struct dirent *result = 0;
  4444. if (dir) {
  4445. if (dir->handle != INVALID_HANDLE_VALUE) {
  4446. result = &dir->result;
  4447. (void)WideCharToMultiByte(CP_UTF8,
  4448. 0,
  4449. dir->info.cFileName,
  4450. -1,
  4451. result->d_name,
  4452. sizeof(result->d_name),
  4453. NULL,
  4454. NULL);
  4455. if (!FindNextFileW(dir->handle, &dir->info)) {
  4456. (void)FindClose(dir->handle);
  4457. dir->handle = INVALID_HANDLE_VALUE;
  4458. }
  4459. } else {
  4460. SetLastError(ERROR_FILE_NOT_FOUND);
  4461. }
  4462. } else {
  4463. SetLastError(ERROR_BAD_ARGUMENTS);
  4464. }
  4465. return result;
  4466. }
  4467. #if !defined(HAVE_POLL)
  4468. #undef POLLIN
  4469. #undef POLLPRI
  4470. #undef POLLOUT
  4471. #undef POLLERR
  4472. #define POLLIN (1) /* Data ready - read will not block. */
  4473. #define POLLPRI (2) /* Priority data ready. */
  4474. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4475. #define POLLERR (8) /* Error event */
  4476. FUNCTION_MAY_BE_UNUSED
  4477. static int
  4478. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4479. {
  4480. struct timeval tv;
  4481. fd_set rset;
  4482. fd_set wset;
  4483. fd_set eset;
  4484. unsigned int i;
  4485. int result;
  4486. SOCKET maxfd = 0;
  4487. memset(&tv, 0, sizeof(tv));
  4488. tv.tv_sec = milliseconds / 1000;
  4489. tv.tv_usec = (milliseconds % 1000) * 1000;
  4490. FD_ZERO(&rset);
  4491. FD_ZERO(&wset);
  4492. FD_ZERO(&eset);
  4493. for (i = 0; i < n; i++) {
  4494. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4495. if (pfd[i].events & POLLIN) {
  4496. FD_SET(pfd[i].fd, &rset);
  4497. }
  4498. if (pfd[i].events & POLLOUT) {
  4499. FD_SET(pfd[i].fd, &wset);
  4500. }
  4501. /* Check for errors for any FD in the set */
  4502. FD_SET(pfd[i].fd, &eset);
  4503. }
  4504. pfd[i].revents = 0;
  4505. if (pfd[i].fd > maxfd) {
  4506. maxfd = pfd[i].fd;
  4507. }
  4508. }
  4509. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4510. for (i = 0; i < n; i++) {
  4511. if (FD_ISSET(pfd[i].fd, &rset)) {
  4512. pfd[i].revents |= POLLIN;
  4513. }
  4514. if (FD_ISSET(pfd[i].fd, &wset)) {
  4515. pfd[i].revents |= POLLOUT;
  4516. }
  4517. if (FD_ISSET(pfd[i].fd, &eset)) {
  4518. pfd[i].revents |= POLLERR;
  4519. }
  4520. }
  4521. }
  4522. /* We should subtract the time used in select from remaining
  4523. * "milliseconds", in particular if called from mg_poll with a
  4524. * timeout quantum.
  4525. * Unfortunately, the remaining time is not stored in "tv" in all
  4526. * implementations, so the result in "tv" must be considered undefined.
  4527. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4528. return result;
  4529. }
  4530. #endif /* HAVE_POLL */
  4531. #if defined(GCC_DIAGNOSTIC)
  4532. /* Enable unused function warning again */
  4533. #pragma GCC diagnostic pop
  4534. #endif
  4535. static void
  4536. set_close_on_exec(SOCKET sock,
  4537. const struct mg_connection *conn /* may be null */,
  4538. struct mg_context *ctx /* may be null */)
  4539. {
  4540. (void)conn; /* Unused. */
  4541. (void)ctx;
  4542. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4543. }
  4544. CIVETWEB_API int
  4545. mg_start_thread(mg_thread_func_t f, void *p)
  4546. {
  4547. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4548. /* Compile-time option to control stack size, e.g.
  4549. * -DUSE_STACK_SIZE=16384
  4550. */
  4551. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4552. == ((uintptr_t)(-1L)))
  4553. ? -1
  4554. : 0);
  4555. #else
  4556. return (
  4557. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4558. ? -1
  4559. : 0);
  4560. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4561. }
  4562. /* Start a thread storing the thread context. */
  4563. static int
  4564. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4565. void *p,
  4566. pthread_t *threadidptr)
  4567. {
  4568. uintptr_t uip;
  4569. HANDLE threadhandle;
  4570. int result = -1;
  4571. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4572. threadhandle = (HANDLE)uip;
  4573. if ((uip != 0) && (threadidptr != NULL)) {
  4574. *threadidptr = threadhandle;
  4575. result = 0;
  4576. }
  4577. return result;
  4578. }
  4579. /* Wait for a thread to finish. */
  4580. static int
  4581. mg_join_thread(pthread_t threadid)
  4582. {
  4583. int result;
  4584. DWORD dwevent;
  4585. result = -1;
  4586. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4587. if (dwevent == WAIT_FAILED) {
  4588. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4589. } else {
  4590. if (dwevent == WAIT_OBJECT_0) {
  4591. CloseHandle(threadid);
  4592. result = 0;
  4593. }
  4594. }
  4595. return result;
  4596. }
  4597. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4598. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4599. /* Create substitutes for POSIX functions in Win32. */
  4600. #if defined(GCC_DIAGNOSTIC)
  4601. /* Show no warning in case system functions are not used. */
  4602. #pragma GCC diagnostic push
  4603. #pragma GCC diagnostic ignored "-Wunused-function"
  4604. #endif
  4605. FUNCTION_MAY_BE_UNUSED
  4606. static HANDLE
  4607. dlopen(const char *dll_name, int flags)
  4608. {
  4609. wchar_t wbuf[UTF16_PATH_MAX];
  4610. (void)flags;
  4611. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4612. return LoadLibraryW(wbuf);
  4613. }
  4614. FUNCTION_MAY_BE_UNUSED
  4615. static int
  4616. dlclose(void *handle)
  4617. {
  4618. int result;
  4619. if (FreeLibrary((HMODULE)handle) != 0) {
  4620. result = 0;
  4621. } else {
  4622. result = -1;
  4623. }
  4624. return result;
  4625. }
  4626. #if defined(GCC_DIAGNOSTIC)
  4627. /* Enable unused function warning again */
  4628. #pragma GCC diagnostic pop
  4629. #endif
  4630. #endif
  4631. #if !defined(NO_CGI)
  4632. #define SIGKILL (0)
  4633. static int
  4634. kill(pid_t pid, int sig_num)
  4635. {
  4636. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4637. (void)CloseHandle((HANDLE)pid);
  4638. return 0;
  4639. }
  4640. #if !defined(WNOHANG)
  4641. #define WNOHANG (1)
  4642. #endif
  4643. static pid_t
  4644. waitpid(pid_t pid, int *status, int flags)
  4645. {
  4646. DWORD timeout = INFINITE;
  4647. DWORD waitres;
  4648. (void)status; /* Currently not used by any client here */
  4649. if ((flags | WNOHANG) == WNOHANG) {
  4650. timeout = 0;
  4651. }
  4652. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4653. if (waitres == WAIT_OBJECT_0) {
  4654. return pid;
  4655. }
  4656. if (waitres == WAIT_TIMEOUT) {
  4657. return 0;
  4658. }
  4659. return (pid_t)-1;
  4660. }
  4661. static void
  4662. trim_trailing_whitespaces(char *s)
  4663. {
  4664. char *e = s + strlen(s);
  4665. while ((e > s) && isspace((unsigned char)e[-1])) {
  4666. *(--e) = '\0';
  4667. }
  4668. }
  4669. static pid_t
  4670. spawn_process(struct mg_connection *conn,
  4671. const char *prog,
  4672. char *envblk,
  4673. char *envp[],
  4674. int fdin[2],
  4675. int fdout[2],
  4676. int fderr[2],
  4677. const char *dir,
  4678. unsigned char cgi_config_idx)
  4679. {
  4680. HANDLE me;
  4681. char *interp;
  4682. char *interp_arg = 0;
  4683. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4684. int truncated;
  4685. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4686. STARTUPINFOA si;
  4687. PROCESS_INFORMATION pi = {0};
  4688. (void)envp;
  4689. memset(&si, 0, sizeof(si));
  4690. si.cb = sizeof(si);
  4691. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4692. si.wShowWindow = SW_HIDE;
  4693. me = GetCurrentProcess();
  4694. DuplicateHandle(me,
  4695. (HANDLE)_get_osfhandle(fdin[0]),
  4696. me,
  4697. &si.hStdInput,
  4698. 0,
  4699. TRUE,
  4700. DUPLICATE_SAME_ACCESS);
  4701. DuplicateHandle(me,
  4702. (HANDLE)_get_osfhandle(fdout[1]),
  4703. me,
  4704. &si.hStdOutput,
  4705. 0,
  4706. TRUE,
  4707. DUPLICATE_SAME_ACCESS);
  4708. DuplicateHandle(me,
  4709. (HANDLE)_get_osfhandle(fderr[1]),
  4710. me,
  4711. &si.hStdError,
  4712. 0,
  4713. TRUE,
  4714. DUPLICATE_SAME_ACCESS);
  4715. /* Mark handles that should not be inherited. See
  4716. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4717. */
  4718. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4719. HANDLE_FLAG_INHERIT,
  4720. 0);
  4721. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4722. HANDLE_FLAG_INHERIT,
  4723. 0);
  4724. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4725. HANDLE_FLAG_INHERIT,
  4726. 0);
  4727. /* First check, if there is a CGI interpreter configured for all CGI
  4728. * scripts. */
  4729. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4730. if (interp != NULL) {
  4731. /* If there is a configured interpreter, check for additional arguments
  4732. */
  4733. interp_arg =
  4734. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4735. } else {
  4736. /* Otherwise, the interpreter must be stated in the first line of the
  4737. * CGI script file, after a #! (shebang) mark. */
  4738. buf[0] = buf[1] = '\0';
  4739. /* Get the full script path */
  4740. mg_snprintf(
  4741. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4742. if (truncated) {
  4743. pi.hProcess = (pid_t)-1;
  4744. goto spawn_cleanup;
  4745. }
  4746. /* Open the script file, to read the first line */
  4747. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4748. /* Read the first line of the script into the buffer */
  4749. mg_fgets(buf, sizeof(buf), &file);
  4750. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4751. buf[sizeof(buf) - 1] = '\0';
  4752. }
  4753. if ((buf[0] == '#') && (buf[1] == '!')) {
  4754. trim_trailing_whitespaces(buf + 2);
  4755. } else {
  4756. buf[2] = '\0';
  4757. }
  4758. interp = buf + 2;
  4759. }
  4760. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4761. if (interp[0] != '\0') {
  4762. /* This is an interpreted script file. We must call the interpreter. */
  4763. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4764. mg_snprintf(conn,
  4765. &truncated,
  4766. cmdline,
  4767. sizeof(cmdline),
  4768. "\"%s\" %s \"%s\\%s\"",
  4769. interp,
  4770. interp_arg,
  4771. full_dir,
  4772. prog);
  4773. } else {
  4774. mg_snprintf(conn,
  4775. &truncated,
  4776. cmdline,
  4777. sizeof(cmdline),
  4778. "\"%s\" \"%s\\%s\"",
  4779. interp,
  4780. full_dir,
  4781. prog);
  4782. }
  4783. } else {
  4784. /* This is (probably) a compiled program. We call it directly. */
  4785. mg_snprintf(conn,
  4786. &truncated,
  4787. cmdline,
  4788. sizeof(cmdline),
  4789. "\"%s\\%s\"",
  4790. full_dir,
  4791. prog);
  4792. }
  4793. if (truncated) {
  4794. pi.hProcess = (pid_t)-1;
  4795. goto spawn_cleanup;
  4796. }
  4797. DEBUG_TRACE("Running [%s]", cmdline);
  4798. if (CreateProcessA(NULL,
  4799. cmdline,
  4800. NULL,
  4801. NULL,
  4802. TRUE,
  4803. CREATE_NEW_PROCESS_GROUP,
  4804. envblk,
  4805. NULL,
  4806. &si,
  4807. &pi)
  4808. == 0) {
  4809. mg_cry_internal(
  4810. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4811. pi.hProcess = (pid_t)-1;
  4812. /* goto spawn_cleanup; */
  4813. }
  4814. spawn_cleanup:
  4815. (void)CloseHandle(si.hStdOutput);
  4816. (void)CloseHandle(si.hStdError);
  4817. (void)CloseHandle(si.hStdInput);
  4818. if (pi.hThread != NULL) {
  4819. (void)CloseHandle(pi.hThread);
  4820. }
  4821. return (pid_t)pi.hProcess;
  4822. }
  4823. #endif /* !NO_CGI */
  4824. static int
  4825. set_blocking_mode(SOCKET sock)
  4826. {
  4827. unsigned long non_blocking = 0;
  4828. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4829. }
  4830. static int
  4831. set_non_blocking_mode(SOCKET sock)
  4832. {
  4833. unsigned long non_blocking = 1;
  4834. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4835. }
  4836. #else
  4837. #if !defined(NO_FILESYSTEMS)
  4838. static int
  4839. mg_stat(const struct mg_connection *conn,
  4840. const char *path,
  4841. struct mg_file_stat *filep)
  4842. {
  4843. struct stat st;
  4844. if (!filep) {
  4845. return 0;
  4846. }
  4847. memset(filep, 0, sizeof(*filep));
  4848. if (mg_path_suspicious(conn, path)) {
  4849. return 0;
  4850. }
  4851. if (0 == stat(path, &st)) {
  4852. filep->size = (uint64_t)(st.st_size);
  4853. filep->last_modified = st.st_mtime;
  4854. filep->is_directory = S_ISDIR(st.st_mode);
  4855. return 1;
  4856. }
  4857. return 0;
  4858. }
  4859. #endif /* NO_FILESYSTEMS */
  4860. static void
  4861. set_close_on_exec(int fd,
  4862. const struct mg_connection *conn /* may be null */,
  4863. struct mg_context *ctx /* may be null */)
  4864. {
  4865. #if defined(__ZEPHYR__) || defined(ESP_PLATFORM)
  4866. (void)fd;
  4867. (void)conn;
  4868. (void)ctx;
  4869. #else
  4870. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4871. if (conn || ctx) {
  4872. struct mg_connection fc;
  4873. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4874. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4875. __func__,
  4876. strerror(ERRNO));
  4877. }
  4878. }
  4879. #endif
  4880. }
  4881. CIVETWEB_API int
  4882. mg_start_thread(mg_thread_func_t func, void *param)
  4883. {
  4884. cw_thread_handle_t thread_id;
  4885. int result;
  4886. #if defined(ESP_PLATFORM)
  4887. thread_id.stack_size = (HTTP_ESP_STACK + sizeof(StackType_t) - 1) / sizeof(StackType_t);
  4888. thread_id.task_buffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  4889. thread_id.x_stack = (StackType_t*) heap_caps_malloc(thread_id.stack_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  4890. thread_id.param = param;
  4891. thread_id.entry_func = func;
  4892. thread_id.task_handle = xTaskCreateStaticPinnedToCore(freeRTOSTaskEntryFunc, "civetweb", thread_id.stack_size, &thread_id,
  4893. CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT, thread_id.x_stack, thread_id.task_buffer, 1);
  4894. if (thread_id.task_handle != NULL) {
  4895. result = 0;
  4896. } else {
  4897. result = -1;
  4898. }
  4899. #else
  4900. pthread_attr_t attr;
  4901. (void)pthread_attr_init(&attr);
  4902. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4903. #if defined(__ZEPHYR__)
  4904. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4905. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4906. /* Compile-time option to control stack size,
  4907. * e.g. -DUSE_STACK_SIZE=16384 */
  4908. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4909. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4910. result = pthread_create(&thread_id, &attr, func, param);
  4911. pthread_attr_destroy(&attr);
  4912. #endif
  4913. return result;
  4914. }
  4915. /* Start a thread storing the thread context. */
  4916. static int
  4917. mg_start_thread_with_id(mg_thread_func_t func,
  4918. void *param,
  4919. cw_thread_handle_t *threadidptr)
  4920. {
  4921. cw_thread_handle_t thread_id;
  4922. int result;
  4923. #if defined(ESP_PLATFORM)
  4924. result = 0;
  4925. thread_id.stack_size = (HTTP_ESP_STACK + sizeof(StackType_t) - 1) / sizeof(StackType_t);
  4926. thread_id.task_buffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  4927. thread_id.x_stack = (StackType_t*) heap_caps_malloc(thread_id.stack_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  4928. thread_id.param = param;
  4929. thread_id.entry_func = func;
  4930. thread_id.task_handle = xTaskCreateStaticPinnedToCore(freeRTOSTaskEntryFunc, "civetweb", thread_id.stack_size, &thread_id,
  4931. CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT, thread_id.x_stack, thread_id.task_buffer, 1);
  4932. if (thread_id.task_handle != NULL) {
  4933. result = 0;
  4934. *threadidptr = thread_id;
  4935. } else {
  4936. result = -1;
  4937. }
  4938. #else
  4939. #if defined(__ZEPHYR__)
  4940. pthread_attr_setstack(&attr,
  4941. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4942. ZEPHYR_STACK_SIZE);
  4943. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4944. /* Compile-time option to control stack size,
  4945. * e.g. -DUSE_STACK_SIZE=16384 */
  4946. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4947. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4948. result = pthread_create(&thread_id, NULL, func, param);
  4949. if ((result == 0) && (threadidptr != NULL)) {
  4950. *threadidptr = thread_id;
  4951. }
  4952. #endif
  4953. return result;
  4954. }
  4955. /* Wait for a thread to finish. */
  4956. static int
  4957. mg_join_thread(cw_thread_handle_t threadid)
  4958. {
  4959. int result;
  4960. #if defined(ESP_PLATFORM)
  4961. //TODO FREERTOS JOIN, WILL REQUIRE A SEMAPHORE
  4962. result = 0;
  4963. #else
  4964. result = pthread_join(threadid, NULL);
  4965. #endif
  4966. return result;
  4967. }
  4968. #if !defined(NO_CGI)
  4969. static pid_t
  4970. spawn_process(struct mg_connection *conn,
  4971. const char *prog,
  4972. char *envblk,
  4973. char *envp[],
  4974. int fdin[2],
  4975. int fdout[2],
  4976. int fderr[2],
  4977. const char *dir,
  4978. unsigned char cgi_config_idx)
  4979. {
  4980. pid_t pid;
  4981. const char *interp;
  4982. (void)envblk;
  4983. if ((pid = fork()) == -1) {
  4984. /* Parent */
  4985. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4986. } else if (pid != 0) {
  4987. /* Make sure children close parent-side descriptors.
  4988. * The caller will close the child-side immediately. */
  4989. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4990. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4991. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4992. } else {
  4993. /* Child */
  4994. if (chdir(dir) != 0) {
  4995. mg_cry_internal(
  4996. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4997. } else if (dup2(fdin[0], 0) == -1) {
  4998. mg_cry_internal(conn,
  4999. "%s: dup2(%d, 0): %s",
  5000. __func__,
  5001. fdin[0],
  5002. strerror(ERRNO));
  5003. } else if (dup2(fdout[1], 1) == -1) {
  5004. mg_cry_internal(conn,
  5005. "%s: dup2(%d, 1): %s",
  5006. __func__,
  5007. fdout[1],
  5008. strerror(ERRNO));
  5009. } else if (dup2(fderr[1], 2) == -1) {
  5010. mg_cry_internal(conn,
  5011. "%s: dup2(%d, 2): %s",
  5012. __func__,
  5013. fderr[1],
  5014. strerror(ERRNO));
  5015. } else {
  5016. struct sigaction sa;
  5017. /* Keep stderr and stdout in two different pipes.
  5018. * Stdout will be sent back to the client,
  5019. * stderr should go into a server error log. */
  5020. (void)close(fdin[0]);
  5021. (void)close(fdout[1]);
  5022. (void)close(fderr[1]);
  5023. /* Close write end fdin and read end fdout and fderr */
  5024. (void)close(fdin[1]);
  5025. (void)close(fdout[0]);
  5026. (void)close(fderr[0]);
  5027. /* After exec, all signal handlers are restored to their default
  5028. * values, with one exception of SIGCHLD. According to
  5029. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5030. * will leave unchanged after exec if it was set to be ignored.
  5031. * Restore it to default action. */
  5032. memset(&sa, 0, sizeof(sa));
  5033. sa.sa_handler = SIG_DFL;
  5034. sigaction(SIGCHLD, &sa, NULL);
  5035. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  5036. if (interp == NULL) {
  5037. /* no interpreter configured, call the programm directly */
  5038. (void)execle(prog, prog, NULL, envp);
  5039. mg_cry_internal(conn,
  5040. "%s: execle(%s): %s",
  5041. __func__,
  5042. prog,
  5043. strerror(ERRNO));
  5044. } else {
  5045. /* call the configured interpreter */
  5046. const char *interp_args =
  5047. conn->dom_ctx
  5048. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5049. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5050. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5051. } else {
  5052. (void)execle(interp, interp, prog, NULL, envp);
  5053. }
  5054. mg_cry_internal(conn,
  5055. "%s: execle(%s %s): %s",
  5056. __func__,
  5057. interp,
  5058. prog,
  5059. strerror(ERRNO));
  5060. }
  5061. }
  5062. exit(EXIT_FAILURE);
  5063. }
  5064. return pid;
  5065. }
  5066. #endif /* !NO_CGI */
  5067. static int
  5068. set_non_blocking_mode(SOCKET sock)
  5069. {
  5070. int flags = fcntl(sock, F_GETFL, 0);
  5071. if (flags < 0) {
  5072. return -1;
  5073. }
  5074. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5075. return -1;
  5076. }
  5077. return 0;
  5078. }
  5079. static int
  5080. set_blocking_mode(SOCKET sock)
  5081. {
  5082. int flags = fcntl(sock, F_GETFL, 0);
  5083. if (flags < 0) {
  5084. return -1;
  5085. }
  5086. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5087. return -1;
  5088. }
  5089. return 0;
  5090. }
  5091. #endif /* _WIN32 / else */
  5092. /* End of initial operating system specific define block. */
  5093. /* Get a random number (independent of C rand function) */
  5094. static uint64_t
  5095. get_random(void)
  5096. {
  5097. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5098. static uint64_t lcg = 0; /* Linear congruential generator */
  5099. uint64_t now = mg_get_current_time_ns();
  5100. if (lfsr == 0) {
  5101. /* lfsr will be only 0 if has not been initialized,
  5102. * so this code is called only once. */
  5103. lfsr = mg_get_current_time_ns();
  5104. lcg = mg_get_current_time_ns();
  5105. } else {
  5106. /* Get the next step of both random number generators. */
  5107. lfsr = (lfsr >> 1)
  5108. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5109. << 63);
  5110. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5111. }
  5112. /* Combining two pseudo-random number generators and a high resolution
  5113. * part
  5114. * of the current server time will make it hard (impossible?) to guess
  5115. * the
  5116. * next number. */
  5117. return (lfsr ^ lcg ^ now);
  5118. }
  5119. static int
  5120. mg_poll(struct mg_pollfd *pfd,
  5121. unsigned int n,
  5122. int milliseconds,
  5123. const stop_flag_t *stop_flag)
  5124. {
  5125. /* Call poll, but only for a maximum time of a few seconds.
  5126. * This will allow to stop the server after some seconds, instead
  5127. * of having to wait for a long socket timeout. */
  5128. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5129. int check_pollerr = 0;
  5130. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5131. /* If we wait for only one file descriptor, wait on error as well */
  5132. pfd[0].events |= POLLERR;
  5133. check_pollerr = 1;
  5134. }
  5135. do {
  5136. int result;
  5137. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5138. /* Shut down signal */
  5139. return -2;
  5140. }
  5141. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5142. ms_now = milliseconds;
  5143. }
  5144. result = poll(pfd, n, ms_now);
  5145. if (result != 0) {
  5146. /* Poll returned either success (1) or error (-1).
  5147. * Forward both to the caller. */
  5148. if ((check_pollerr)
  5149. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5150. == POLLERR)) {
  5151. /* One and only file descriptor returned error */
  5152. return -1;
  5153. }
  5154. return result;
  5155. }
  5156. /* Poll returned timeout (0). */
  5157. if (milliseconds > 0) {
  5158. milliseconds -= ms_now;
  5159. }
  5160. } while (milliseconds > 0);
  5161. /* timeout: return 0 */
  5162. return 0;
  5163. }
  5164. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5165. * descriptor.
  5166. * Return value:
  5167. * >=0 .. number of bytes successfully written
  5168. * -1 .. timeout
  5169. * -2 .. error
  5170. */
  5171. static int
  5172. push_inner(struct mg_context *ctx,
  5173. FILE *fp,
  5174. SOCKET sock,
  5175. SSL *ssl,
  5176. const char *buf,
  5177. int len,
  5178. double timeout)
  5179. {
  5180. uint64_t start = 0, now = 0, timeout_ns = 0;
  5181. int n, err;
  5182. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5183. #if defined(_WIN32)
  5184. typedef int len_t;
  5185. #else
  5186. typedef size_t len_t;
  5187. #endif
  5188. if (timeout > 0) {
  5189. now = mg_get_current_time_ns();
  5190. start = now;
  5191. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5192. }
  5193. if (ctx == NULL) {
  5194. return -2;
  5195. }
  5196. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5197. if (ssl) {
  5198. return -2;
  5199. }
  5200. #endif
  5201. /* Try to read until it succeeds, fails, times out, or the server
  5202. * shuts down. */
  5203. for (;;) {
  5204. #if defined(USE_MBEDTLS)
  5205. if (ssl != NULL) {
  5206. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5207. if (n <= 0) {
  5208. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5209. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5210. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5211. n = 0;
  5212. } else {
  5213. fprintf(stderr, "SSL write failed, error %d\n", n);
  5214. return -2;
  5215. }
  5216. } else {
  5217. err = 0;
  5218. }
  5219. } else
  5220. #elif !defined(NO_SSL)
  5221. if (ssl != NULL) {
  5222. ERR_clear_error();
  5223. n = SSL_write(ssl, buf, len);
  5224. if (n <= 0) {
  5225. err = SSL_get_error(ssl, n);
  5226. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5227. err = ERRNO;
  5228. } else if ((err == SSL_ERROR_WANT_READ)
  5229. || (err == SSL_ERROR_WANT_WRITE)) {
  5230. n = 0;
  5231. } else {
  5232. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5233. ERR_clear_error();
  5234. return -2;
  5235. }
  5236. ERR_clear_error();
  5237. } else {
  5238. err = 0;
  5239. }
  5240. } else
  5241. #endif
  5242. if (fp != NULL) {
  5243. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5244. if (ferror(fp)) {
  5245. n = -1;
  5246. err = ERRNO;
  5247. } else {
  5248. err = 0;
  5249. }
  5250. } else {
  5251. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5252. err = (n < 0) ? ERRNO : 0;
  5253. #if defined(_WIN32)
  5254. if (err == WSAEWOULDBLOCK) {
  5255. err = 0;
  5256. n = 0;
  5257. }
  5258. #else
  5259. if (ERROR_TRY_AGAIN(err)) {
  5260. err = 0;
  5261. n = 0;
  5262. }
  5263. #endif
  5264. if (n < 0) {
  5265. /* shutdown of the socket at client side */
  5266. return -2;
  5267. }
  5268. }
  5269. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5270. return -2;
  5271. }
  5272. if ((n > 0) || ((n == 0) && (len == 0))) {
  5273. /* some data has been read, or no data was requested */
  5274. return n;
  5275. }
  5276. if (n < 0) {
  5277. /* socket error - check errno */
  5278. DEBUG_TRACE("send() failed, error %d", err);
  5279. /* TODO (mid): error handling depending on the error code.
  5280. * These codes are different between Windows and Linux.
  5281. * Currently there is no problem with failing send calls,
  5282. * if there is a reproducible situation, it should be
  5283. * investigated in detail.
  5284. */
  5285. return -2;
  5286. }
  5287. /* Only in case n=0 (timeout), repeat calling the write function */
  5288. /* If send failed, wait before retry */
  5289. if (fp != NULL) {
  5290. /* For files, just wait a fixed time.
  5291. * Maybe it helps, maybe not. */
  5292. mg_sleep(5);
  5293. } else {
  5294. /* For sockets, wait for the socket using poll */
  5295. struct mg_pollfd pfd[1];
  5296. int pollres;
  5297. pfd[0].fd = sock;
  5298. pfd[0].events = POLLOUT;
  5299. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5300. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5301. return -2;
  5302. }
  5303. if (pollres > 0) {
  5304. continue;
  5305. }
  5306. }
  5307. if (timeout > 0) {
  5308. now = mg_get_current_time_ns();
  5309. if ((now - start) > timeout_ns) {
  5310. /* Timeout */
  5311. break;
  5312. }
  5313. }
  5314. }
  5315. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5316. used */
  5317. return -1;
  5318. }
  5319. static int
  5320. push_all(struct mg_context *ctx,
  5321. FILE *fp,
  5322. SOCKET sock,
  5323. SSL *ssl,
  5324. const char *buf,
  5325. int len)
  5326. {
  5327. double timeout = -1.0;
  5328. int n, nwritten = 0;
  5329. if (ctx == NULL) {
  5330. return -1;
  5331. }
  5332. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5333. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5334. }
  5335. if (timeout <= 0.0) {
  5336. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5337. / 1000.0;
  5338. }
  5339. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5340. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5341. if (n < 0) {
  5342. if (nwritten == 0) {
  5343. nwritten = -1; /* Propagate the error */
  5344. }
  5345. break;
  5346. } else if (n == 0) {
  5347. break; /* No more data to write */
  5348. } else {
  5349. nwritten += n;
  5350. len -= n;
  5351. }
  5352. }
  5353. return nwritten;
  5354. }
  5355. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5356. * Return value:
  5357. * >=0 .. number of bytes successfully read
  5358. * -1 .. timeout
  5359. * -2 .. error
  5360. */
  5361. static int
  5362. pull_inner(FILE *fp,
  5363. struct mg_connection *conn,
  5364. char *buf,
  5365. int len,
  5366. double timeout)
  5367. {
  5368. int nread, err = 0;
  5369. #if defined(_WIN32)
  5370. typedef int len_t;
  5371. #else
  5372. typedef size_t len_t;
  5373. #endif
  5374. /* We need an additional wait loop around this, because in some cases
  5375. * with TLSwe may get data from the socket but not from SSL_read.
  5376. * In this case we need to repeat at least once.
  5377. */
  5378. if (fp != NULL) {
  5379. /* Use read() instead of fread(), because if we're reading from the
  5380. * CGI pipe, fread() may block until IO buffer is filled up. We
  5381. * cannot afford to block and must pass all read bytes immediately
  5382. * to the client. */
  5383. nread = (int)read(fileno(fp), buf, (size_t)len);
  5384. err = (nread < 0) ? ERRNO : 0;
  5385. if ((nread == 0) && (len > 0)) {
  5386. /* Should get data, but got EOL */
  5387. return -2;
  5388. }
  5389. #if defined(USE_MBEDTLS)
  5390. } else if (conn->ssl != NULL) {
  5391. struct mg_pollfd pfd[1];
  5392. int to_read;
  5393. int pollres;
  5394. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5395. if (to_read > 0) {
  5396. /* We already know there is no more data buffered in conn->buf
  5397. * but there is more available in the SSL layer. So don't poll
  5398. * conn->client.sock yet. */
  5399. pollres = 1;
  5400. if (to_read > len)
  5401. to_read = len;
  5402. } else {
  5403. pfd[0].fd = conn->client.sock;
  5404. pfd[0].events = POLLIN;
  5405. to_read = len;
  5406. pollres = mg_poll(pfd,
  5407. 1,
  5408. (int)(timeout * 1000.0),
  5409. &(conn->phys_ctx->stop_flag));
  5410. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5411. return -2;
  5412. }
  5413. }
  5414. if (pollres > 0) {
  5415. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5416. if (nread <= 0) {
  5417. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5418. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5419. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5420. nread = 0;
  5421. } else {
  5422. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5423. return -2;
  5424. }
  5425. } else {
  5426. err = 0;
  5427. }
  5428. } else if (pollres < 0) {
  5429. /* Error */
  5430. return -2;
  5431. } else {
  5432. /* pollres = 0 means timeout */
  5433. nread = 0;
  5434. }
  5435. #elif !defined(NO_SSL)
  5436. } else if (conn->ssl != NULL) {
  5437. int ssl_pending;
  5438. struct mg_pollfd pfd[1];
  5439. int pollres;
  5440. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5441. /* We already know there is no more data buffered in conn->buf
  5442. * but there is more available in the SSL layer. So don't poll
  5443. * conn->client.sock yet. */
  5444. if (ssl_pending > len) {
  5445. ssl_pending = len;
  5446. }
  5447. pollres = 1;
  5448. } else {
  5449. pfd[0].fd = conn->client.sock;
  5450. pfd[0].events = POLLIN;
  5451. pollres = mg_poll(pfd,
  5452. 1,
  5453. (int)(timeout * 1000.0),
  5454. &(conn->phys_ctx->stop_flag));
  5455. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5456. return -2;
  5457. }
  5458. }
  5459. if (pollres > 0) {
  5460. ERR_clear_error();
  5461. nread =
  5462. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5463. if (nread <= 0) {
  5464. err = SSL_get_error(conn->ssl, nread);
  5465. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5466. err = ERRNO;
  5467. } else if ((err == SSL_ERROR_WANT_READ)
  5468. || (err == SSL_ERROR_WANT_WRITE)) {
  5469. nread = 0;
  5470. } else {
  5471. /* All errors should return -2 */
  5472. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5473. ERR_clear_error();
  5474. return -2;
  5475. }
  5476. ERR_clear_error();
  5477. } else {
  5478. err = 0;
  5479. }
  5480. } else if (pollres < 0) {
  5481. /* Error */
  5482. return -2;
  5483. } else {
  5484. /* pollres = 0 means timeout */
  5485. nread = 0;
  5486. }
  5487. #endif
  5488. } else {
  5489. struct mg_pollfd pfd[1];
  5490. int pollres;
  5491. pfd[0].fd = conn->client.sock;
  5492. pfd[0].events = POLLIN;
  5493. pollres = mg_poll(pfd,
  5494. 1,
  5495. (int)(timeout * 1000.0),
  5496. &(conn->phys_ctx->stop_flag));
  5497. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5498. return -2;
  5499. }
  5500. if (pollres > 0) {
  5501. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5502. err = (nread < 0) ? ERRNO : 0;
  5503. if (nread <= 0) {
  5504. /* shutdown of the socket at client side */
  5505. return -2;
  5506. }
  5507. } else if (pollres < 0) {
  5508. /* error callint poll */
  5509. return -2;
  5510. } else {
  5511. /* pollres = 0 means timeout */
  5512. nread = 0;
  5513. }
  5514. }
  5515. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5516. return -2;
  5517. }
  5518. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5519. /* some data has been read, or no data was requested */
  5520. return nread;
  5521. }
  5522. if (nread < 0) {
  5523. /* socket error - check errno */
  5524. #if defined(_WIN32)
  5525. if (err == WSAEWOULDBLOCK) {
  5526. /* TODO (low): check if this is still required */
  5527. /* standard case if called from close_socket_gracefully */
  5528. return -2;
  5529. } else if (err == WSAETIMEDOUT) {
  5530. /* TODO (low): check if this is still required */
  5531. /* timeout is handled by the while loop */
  5532. return 0;
  5533. } else if (err == WSAECONNABORTED) {
  5534. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5535. return -2;
  5536. } else {
  5537. DEBUG_TRACE("recv() failed, error %d", err);
  5538. return -2;
  5539. }
  5540. #else
  5541. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5542. * if the timeout is reached and if the socket was set to non-
  5543. * blocking in close_socket_gracefully, so we can not distinguish
  5544. * here. We have to wait for the timeout in both cases for now.
  5545. */
  5546. if (ERROR_TRY_AGAIN(err)) {
  5547. /* TODO (low): check if this is still required */
  5548. /* EAGAIN/EWOULDBLOCK:
  5549. * standard case if called from close_socket_gracefully
  5550. * => should return -1 */
  5551. /* or timeout occurred
  5552. * => the code must stay in the while loop */
  5553. /* EINTR can be generated on a socket with a timeout set even
  5554. * when SA_RESTART is effective for all relevant signals
  5555. * (see signal(7)).
  5556. * => stay in the while loop */
  5557. } else {
  5558. DEBUG_TRACE("recv() failed, error %d", err);
  5559. return -2;
  5560. }
  5561. #endif
  5562. }
  5563. /* Timeout occurred, but no data available. */
  5564. return -1;
  5565. }
  5566. static int
  5567. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5568. {
  5569. int n, nread = 0;
  5570. double timeout = -1.0;
  5571. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5572. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5573. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5574. }
  5575. if (timeout <= 0.0) {
  5576. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5577. / 1000.0;
  5578. }
  5579. start_time = mg_get_current_time_ns();
  5580. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5581. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5582. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5583. if (n == -2) {
  5584. if (nread == 0) {
  5585. nread = -1; /* Propagate the error */
  5586. }
  5587. break;
  5588. } else if (n == -1) {
  5589. /* timeout */
  5590. if (timeout >= 0.0) {
  5591. now = mg_get_current_time_ns();
  5592. if ((now - start_time) <= timeout_ns) {
  5593. continue;
  5594. }
  5595. }
  5596. break;
  5597. } else if (n == 0) {
  5598. break; /* No more data to read */
  5599. } else {
  5600. nread += n;
  5601. len -= n;
  5602. }
  5603. }
  5604. return nread;
  5605. }
  5606. static void
  5607. discard_unread_request_data(struct mg_connection *conn)
  5608. {
  5609. char buf[MG_BUF_LEN];
  5610. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5611. ;
  5612. }
  5613. static int
  5614. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5615. {
  5616. int64_t content_len, n, buffered_len, nread;
  5617. int64_t len64 =
  5618. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5619. * int, we may not read more
  5620. * bytes */
  5621. const char *body;
  5622. if (conn == NULL) {
  5623. return 0;
  5624. }
  5625. /* If Content-Length is not set for a response with body data,
  5626. * we do not know in advance how much data should be read. */
  5627. content_len = conn->content_len;
  5628. if (content_len < 0) {
  5629. /* The body data is completed when the connection is closed. */
  5630. content_len = INT64_MAX;
  5631. }
  5632. nread = 0;
  5633. if (conn->consumed_content < content_len) {
  5634. /* Adjust number of bytes to read. */
  5635. int64_t left_to_read = content_len - conn->consumed_content;
  5636. if (left_to_read < len64) {
  5637. /* Do not read more than the total content length of the
  5638. * request.
  5639. */
  5640. len64 = left_to_read;
  5641. }
  5642. /* Return buffered data */
  5643. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5644. - conn->consumed_content;
  5645. if (buffered_len > 0) {
  5646. if (len64 < buffered_len) {
  5647. buffered_len = len64;
  5648. }
  5649. body = conn->buf + conn->request_len + conn->consumed_content;
  5650. memcpy(buf, body, (size_t)buffered_len);
  5651. len64 -= buffered_len;
  5652. conn->consumed_content += buffered_len;
  5653. nread += buffered_len;
  5654. buf = (char *)buf + buffered_len;
  5655. }
  5656. /* We have returned all buffered data. Read new data from the remote
  5657. * socket.
  5658. */
  5659. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5660. conn->consumed_content += n;
  5661. nread += n;
  5662. } else {
  5663. nread = ((nread > 0) ? nread : n);
  5664. }
  5665. }
  5666. return (int)nread;
  5667. }
  5668. /* Forward declarations */
  5669. static void handle_request(struct mg_connection *);
  5670. static void log_access(const struct mg_connection *);
  5671. /* Handle request, update statistics and call access log */
  5672. static void
  5673. handle_request_stat_log(struct mg_connection *conn)
  5674. {
  5675. #if defined(USE_SERVER_STATS)
  5676. struct timespec tnow;
  5677. conn->conn_state = 4; /* processing */
  5678. #endif
  5679. handle_request(conn);
  5680. #if defined(USE_SERVER_STATS)
  5681. conn->conn_state = 5; /* processed */
  5682. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5683. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5684. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5685. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5686. conn->num_bytes_sent);
  5687. #endif
  5688. DEBUG_TRACE("%s", "handle_request done");
  5689. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5690. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5691. DEBUG_TRACE("%s", "end_request callback done");
  5692. }
  5693. log_access(conn);
  5694. }
  5695. #if defined(USE_HTTP2)
  5696. #if defined(NO_SSL)
  5697. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5698. #endif
  5699. #define USE_ALPN
  5700. #include "http2.inl"
  5701. /* Not supported with HTTP/2 */
  5702. #define HTTP1_only \
  5703. { \
  5704. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5705. http2_must_use_http1(conn); \
  5706. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5707. return; \
  5708. } \
  5709. }
  5710. #else
  5711. #define HTTP1_only
  5712. #endif
  5713. CIVETWEB_API int
  5714. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5715. {
  5716. if (len > INT_MAX) {
  5717. len = INT_MAX;
  5718. }
  5719. if (conn == NULL) {
  5720. return 0;
  5721. }
  5722. if (conn->is_chunked) {
  5723. size_t all_read = 0;
  5724. while (len > 0) {
  5725. if (conn->is_chunked >= 3) {
  5726. /* No more data left to read */
  5727. return 0;
  5728. }
  5729. if (conn->is_chunked != 1) {
  5730. /* Has error */
  5731. return -1;
  5732. }
  5733. if (conn->consumed_content != conn->content_len) {
  5734. /* copy from the current chunk */
  5735. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5736. if (read_ret < 1) {
  5737. /* read error */
  5738. conn->is_chunked = 2;
  5739. return -1;
  5740. }
  5741. all_read += (size_t)read_ret;
  5742. len -= (size_t)read_ret;
  5743. if (conn->consumed_content == conn->content_len) {
  5744. /* Add data bytes in the current chunk have been read,
  5745. * so we are expecting \r\n now. */
  5746. char x[2];
  5747. conn->content_len += 2;
  5748. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5749. || (x[1] != '\n')) {
  5750. /* Protocol violation */
  5751. conn->is_chunked = 2;
  5752. return -1;
  5753. }
  5754. }
  5755. } else {
  5756. /* fetch a new chunk */
  5757. size_t i;
  5758. char lenbuf[64];
  5759. char *end = NULL;
  5760. unsigned long chunkSize = 0;
  5761. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5762. conn->content_len++;
  5763. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5764. lenbuf[i] = 0;
  5765. }
  5766. if ((i > 0) && (lenbuf[i] == '\r')
  5767. && (lenbuf[i - 1] != '\r')) {
  5768. continue;
  5769. }
  5770. if ((i > 1) && (lenbuf[i] == '\n')
  5771. && (lenbuf[i - 1] == '\r')) {
  5772. lenbuf[i + 1] = 0;
  5773. chunkSize = strtoul(lenbuf, &end, 16);
  5774. if (chunkSize == 0) {
  5775. /* regular end of content */
  5776. conn->is_chunked = 3;
  5777. }
  5778. break;
  5779. }
  5780. if (!isxdigit((unsigned char)lenbuf[i])) {
  5781. /* illegal character for chunk length */
  5782. conn->is_chunked = 2;
  5783. return -1;
  5784. }
  5785. }
  5786. if ((end == NULL) || (*end != '\r')) {
  5787. /* chunksize not set correctly */
  5788. conn->is_chunked = 2;
  5789. return -1;
  5790. }
  5791. if (chunkSize == 0) {
  5792. /* try discarding trailer for keep-alive */
  5793. conn->content_len += 2;
  5794. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5795. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5796. conn->is_chunked = 4;
  5797. }
  5798. break;
  5799. }
  5800. /* append a new chunk */
  5801. conn->content_len += (int64_t)chunkSize;
  5802. }
  5803. }
  5804. return (int)all_read;
  5805. }
  5806. return mg_read_inner(conn, buf, len);
  5807. }
  5808. CIVETWEB_API int
  5809. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5810. {
  5811. time_t now;
  5812. int n, total, allowed;
  5813. if (conn == NULL) {
  5814. return 0;
  5815. }
  5816. if (len > INT_MAX) {
  5817. return -1;
  5818. }
  5819. /* Mark connection as "data sent" */
  5820. conn->request_state = 10;
  5821. #if defined(USE_HTTP2)
  5822. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5823. http2_data_frame_head(conn, len, 0);
  5824. }
  5825. #endif
  5826. if (conn->throttle > 0) {
  5827. if ((now = time(NULL)) != conn->last_throttle_time) {
  5828. conn->last_throttle_time = now;
  5829. conn->last_throttle_bytes = 0;
  5830. }
  5831. allowed = conn->throttle - conn->last_throttle_bytes;
  5832. if (allowed > (int)len) {
  5833. allowed = (int)len;
  5834. }
  5835. total = push_all(conn->phys_ctx,
  5836. NULL,
  5837. conn->client.sock,
  5838. conn->ssl,
  5839. (const char *)buf,
  5840. allowed);
  5841. if (total == allowed) {
  5842. buf = (const char *)buf + total;
  5843. conn->last_throttle_bytes += total;
  5844. while ((total < (int)len)
  5845. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5846. allowed = (conn->throttle > ((int)len - total))
  5847. ? (int)len - total
  5848. : conn->throttle;
  5849. n = push_all(conn->phys_ctx,
  5850. NULL,
  5851. conn->client.sock,
  5852. conn->ssl,
  5853. (const char *)buf,
  5854. allowed);
  5855. if (n != allowed) {
  5856. break;
  5857. }
  5858. sleep(1);
  5859. conn->last_throttle_bytes = allowed;
  5860. conn->last_throttle_time = time(NULL);
  5861. buf = (const char *)buf + n;
  5862. total += n;
  5863. }
  5864. }
  5865. } else {
  5866. total = push_all(conn->phys_ctx,
  5867. NULL,
  5868. conn->client.sock,
  5869. conn->ssl,
  5870. (const char *)buf,
  5871. (int)len);
  5872. }
  5873. if (total > 0) {
  5874. conn->num_bytes_sent += total;
  5875. }
  5876. return total;
  5877. }
  5878. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5879. CIVETWEB_API int
  5880. mg_send_chunk(struct mg_connection *conn,
  5881. const char *chunk,
  5882. unsigned int chunk_len)
  5883. {
  5884. char lenbuf[16];
  5885. size_t lenbuf_len;
  5886. int ret;
  5887. int t;
  5888. /* First store the length information in a text buffer. */
  5889. sprintf(lenbuf, "%x\r\n", chunk_len);
  5890. lenbuf_len = strlen(lenbuf);
  5891. /* Then send length information, chunk and terminating \r\n. */
  5892. ret = mg_write(conn, lenbuf, lenbuf_len);
  5893. if (ret != (int)lenbuf_len) {
  5894. return -1;
  5895. }
  5896. t = ret;
  5897. ret = mg_write(conn, chunk, chunk_len);
  5898. if (ret != (int)chunk_len) {
  5899. return -1;
  5900. }
  5901. t += ret;
  5902. ret = mg_write(conn, "\r\n", 2);
  5903. if (ret != 2) {
  5904. return -1;
  5905. }
  5906. t += ret;
  5907. return t;
  5908. }
  5909. #if defined(GCC_DIAGNOSTIC)
  5910. /* This block forwards format strings to printf implementations,
  5911. * so we need to disable the format-nonliteral warning. */
  5912. #pragma GCC diagnostic push
  5913. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5914. #endif
  5915. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5916. static int
  5917. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5918. {
  5919. va_list ap_copy;
  5920. size_t size = MG_BUF_LEN / 4;
  5921. int len = -1;
  5922. *buf = NULL;
  5923. while (len < 0) {
  5924. if (*buf) {
  5925. mg_free(*buf);
  5926. }
  5927. size *= 4;
  5928. *buf = (char *)mg_malloc(size);
  5929. if (!*buf) {
  5930. break;
  5931. }
  5932. va_copy(ap_copy, ap);
  5933. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5934. va_end(ap_copy);
  5935. (*buf)[size - 1] = 0;
  5936. }
  5937. return len;
  5938. }
  5939. /* Print message to buffer. If buffer is large enough to hold the message,
  5940. * return buffer. If buffer is to small, allocate large enough buffer on
  5941. * heap,
  5942. * and return allocated buffer. */
  5943. static int
  5944. alloc_vprintf(char **out_buf,
  5945. char *prealloc_buf,
  5946. size_t prealloc_size,
  5947. const char *fmt,
  5948. va_list ap)
  5949. {
  5950. va_list ap_copy;
  5951. int len;
  5952. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5953. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5954. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5955. * Therefore, we make two passes: on first pass, get required message
  5956. * length.
  5957. * On second pass, actually print the message. */
  5958. va_copy(ap_copy, ap);
  5959. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5960. va_end(ap_copy);
  5961. if (len < 0) {
  5962. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5963. * Switch to alternative code path that uses incremental
  5964. * allocations.
  5965. */
  5966. va_copy(ap_copy, ap);
  5967. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5968. va_end(ap_copy);
  5969. } else if ((size_t)(len) >= prealloc_size) {
  5970. /* The pre-allocated buffer not large enough. */
  5971. /* Allocate a new buffer. */
  5972. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5973. if (!*out_buf) {
  5974. /* Allocation failed. Return -1 as "out of memory" error. */
  5975. return -1;
  5976. }
  5977. /* Buffer allocation successful. Store the string there. */
  5978. va_copy(ap_copy, ap);
  5979. IGNORE_UNUSED_RESULT(
  5980. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5981. va_end(ap_copy);
  5982. } else {
  5983. /* The pre-allocated buffer is large enough.
  5984. * Use it to store the string and return the address. */
  5985. va_copy(ap_copy, ap);
  5986. IGNORE_UNUSED_RESULT(
  5987. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5988. va_end(ap_copy);
  5989. *out_buf = prealloc_buf;
  5990. }
  5991. return len;
  5992. }
  5993. static int
  5994. alloc_printf(char **out_buf, const char *fmt, ...)
  5995. {
  5996. va_list ap;
  5997. int result;
  5998. va_start(ap, fmt);
  5999. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6000. va_end(ap);
  6001. return result;
  6002. }
  6003. #if defined(GCC_DIAGNOSTIC)
  6004. /* Enable format-nonliteral warning again. */
  6005. #pragma GCC diagnostic pop
  6006. #endif
  6007. static int
  6008. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6009. {
  6010. char mem[MG_BUF_LEN];
  6011. char *buf = NULL;
  6012. int len;
  6013. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6014. len = mg_write(conn, buf, (size_t)len);
  6015. }
  6016. if (buf != mem) {
  6017. mg_free(buf);
  6018. }
  6019. return len;
  6020. }
  6021. CIVETWEB_API int
  6022. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6023. {
  6024. va_list ap;
  6025. int result;
  6026. va_start(ap, fmt);
  6027. result = mg_vprintf(conn, fmt, ap);
  6028. va_end(ap);
  6029. return result;
  6030. }
  6031. CIVETWEB_API int
  6032. mg_url_decode(const char *src,
  6033. int src_len,
  6034. char *dst,
  6035. int dst_len,
  6036. int is_form_url_encoded)
  6037. {
  6038. int i, j, a, b;
  6039. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6040. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6041. if ((i < src_len - 2) && (src[i] == '%')
  6042. && isxdigit((unsigned char)src[i + 1])
  6043. && isxdigit((unsigned char)src[i + 2])) {
  6044. a = tolower((unsigned char)src[i + 1]);
  6045. b = tolower((unsigned char)src[i + 2]);
  6046. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6047. i += 2;
  6048. } else if (is_form_url_encoded && (src[i] == '+')) {
  6049. dst[j] = ' ';
  6050. } else {
  6051. dst[j] = src[i];
  6052. }
  6053. }
  6054. dst[j] = '\0'; /* Null-terminate the destination */
  6055. return (i >= src_len) ? j : -1;
  6056. }
  6057. /* form url decoding of an entire string */
  6058. static void
  6059. url_decode_in_place(char *buf)
  6060. {
  6061. int len = (int)strlen(buf);
  6062. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6063. }
  6064. CIVETWEB_API int
  6065. mg_get_var(const char *data,
  6066. size_t data_len,
  6067. const char *name,
  6068. char *dst,
  6069. size_t dst_len)
  6070. {
  6071. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6072. }
  6073. CIVETWEB_API int
  6074. mg_get_var2(const char *data,
  6075. size_t data_len,
  6076. const char *name,
  6077. char *dst,
  6078. size_t dst_len,
  6079. size_t occurrence)
  6080. {
  6081. const char *p, *e, *s;
  6082. size_t name_len;
  6083. int len;
  6084. if ((dst == NULL) || (dst_len == 0)) {
  6085. len = -2;
  6086. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6087. len = -1;
  6088. dst[0] = '\0';
  6089. } else {
  6090. name_len = strlen(name);
  6091. e = data + data_len;
  6092. len = -1;
  6093. dst[0] = '\0';
  6094. /* data is "var1=val1&var2=val2...". Find variable first */
  6095. for (p = data; p + name_len < e; p++) {
  6096. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6097. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6098. /* Point p to variable value */
  6099. p += name_len + 1;
  6100. /* Point s to the end of the value */
  6101. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6102. if (s == NULL) {
  6103. s = e;
  6104. }
  6105. DEBUG_ASSERT(s >= p);
  6106. if (s < p) {
  6107. return -3;
  6108. }
  6109. /* Decode variable into destination buffer */
  6110. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6111. /* Redirect error code from -1 to -2 (destination buffer too
  6112. * small). */
  6113. if (len == -1) {
  6114. len = -2;
  6115. }
  6116. break;
  6117. }
  6118. }
  6119. }
  6120. return len;
  6121. }
  6122. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6123. CIVETWEB_API int
  6124. mg_split_form_urlencoded(char *data,
  6125. struct mg_header *form_fields,
  6126. unsigned num_form_fields)
  6127. {
  6128. char *b;
  6129. int i;
  6130. int num = 0;
  6131. if (data == NULL) {
  6132. /* parameter error */
  6133. return -1;
  6134. }
  6135. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6136. /* determine the number of expected fields */
  6137. if (data[0] == 0) {
  6138. return 0;
  6139. }
  6140. /* count number of & to return the number of key-value-pairs */
  6141. num = 1;
  6142. while (*data) {
  6143. if (*data == '&') {
  6144. num++;
  6145. }
  6146. data++;
  6147. }
  6148. return num;
  6149. }
  6150. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6151. /* parameter error */
  6152. return -1;
  6153. }
  6154. for (i = 0; i < (int)num_form_fields; i++) {
  6155. /* extract key-value pairs from input data */
  6156. while ((*data == ' ') || (*data == '\t')) {
  6157. /* skip initial spaces */
  6158. data++;
  6159. }
  6160. if (*data == 0) {
  6161. /* end of string reached */
  6162. break;
  6163. }
  6164. form_fields[num].name = data;
  6165. /* find & or = */
  6166. b = data;
  6167. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6168. b++;
  6169. }
  6170. if (*b == 0) {
  6171. /* last key without value */
  6172. form_fields[num].value = NULL;
  6173. } else if (*b == '&') {
  6174. /* mid key without value */
  6175. form_fields[num].value = NULL;
  6176. } else {
  6177. /* terminate string */
  6178. *b = 0;
  6179. /* value starts after '=' */
  6180. data = b + 1;
  6181. form_fields[num].value = data;
  6182. }
  6183. /* new field is stored */
  6184. num++;
  6185. /* find a next key */
  6186. b = strchr(data, '&');
  6187. if (b == 0) {
  6188. /* no more data */
  6189. break;
  6190. } else {
  6191. /* terminate value of last field at '&' */
  6192. *b = 0;
  6193. /* next key-value-pairs starts after '&' */
  6194. data = b + 1;
  6195. }
  6196. }
  6197. /* Decode all values */
  6198. for (i = 0; i < num; i++) {
  6199. if (form_fields[i].name) {
  6200. url_decode_in_place((char *)form_fields[i].name);
  6201. }
  6202. if (form_fields[i].value) {
  6203. url_decode_in_place((char *)form_fields[i].value);
  6204. }
  6205. }
  6206. /* return number of fields found */
  6207. return num;
  6208. }
  6209. /* HCP24: some changes to compare whole var_name */
  6210. CIVETWEB_API int
  6211. mg_get_cookie(const char *cookie_header,
  6212. const char *var_name,
  6213. char *dst,
  6214. size_t dst_size)
  6215. {
  6216. const char *s, *p, *end;
  6217. int name_len, len = -1;
  6218. if ((dst == NULL) || (dst_size == 0)) {
  6219. return -2;
  6220. }
  6221. dst[0] = '\0';
  6222. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6223. return -1;
  6224. }
  6225. name_len = (int)strlen(var_name);
  6226. end = s + strlen(s);
  6227. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6228. if (s[name_len] == '=') {
  6229. /* HCP24: now check is it a substring or a full cookie name */
  6230. if ((s == cookie_header) || (s[-1] == ' ')) {
  6231. s += name_len + 1;
  6232. if ((p = strchr(s, ' ')) == NULL) {
  6233. p = end;
  6234. }
  6235. if (p[-1] == ';') {
  6236. p--;
  6237. }
  6238. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6239. s++;
  6240. p--;
  6241. }
  6242. if ((size_t)(p - s) < dst_size) {
  6243. len = (int)(p - s);
  6244. mg_strlcpy(dst, s, (size_t)len + 1);
  6245. } else {
  6246. len = -3;
  6247. }
  6248. break;
  6249. }
  6250. }
  6251. }
  6252. return len;
  6253. }
  6254. CIVETWEB_API int
  6255. mg_base64_encode(const unsigned char *src,
  6256. size_t src_len,
  6257. char *dst,
  6258. size_t *dst_len)
  6259. {
  6260. static const char *b64 =
  6261. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6262. size_t i, j;
  6263. int a, b, c;
  6264. if (dst_len != NULL) {
  6265. /* Expected length including 0 termination: */
  6266. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6267. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6268. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6269. if (*dst_len < expected_len) {
  6270. if (*dst_len > 0) {
  6271. dst[0] = '\0';
  6272. }
  6273. *dst_len = expected_len;
  6274. return 0;
  6275. }
  6276. }
  6277. for (i = j = 0; i < src_len; i += 3) {
  6278. a = src[i];
  6279. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6280. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6281. dst[j++] = b64[a >> 2];
  6282. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6283. if (i + 1 < src_len) {
  6284. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6285. }
  6286. if (i + 2 < src_len) {
  6287. dst[j++] = b64[c & 63];
  6288. }
  6289. }
  6290. while (j % 4 != 0) {
  6291. dst[j++] = '=';
  6292. }
  6293. dst[j++] = '\0';
  6294. if (dst_len != NULL) {
  6295. *dst_len = (size_t)j;
  6296. }
  6297. /* Return -1 for "OK" */
  6298. return -1;
  6299. }
  6300. static unsigned char
  6301. b64reverse(char letter)
  6302. {
  6303. if ((letter >= 'A') && (letter <= 'Z')) {
  6304. return letter - 'A';
  6305. }
  6306. if ((letter >= 'a') && (letter <= 'z')) {
  6307. return letter - 'a' + 26;
  6308. }
  6309. if ((letter >= '0') && (letter <= '9')) {
  6310. return letter - '0' + 52;
  6311. }
  6312. if (letter == '+') {
  6313. return 62;
  6314. }
  6315. if (letter == '/') {
  6316. return 63;
  6317. }
  6318. if (letter == '=') {
  6319. return 255; /* normal end */
  6320. }
  6321. return 254; /* error */
  6322. }
  6323. CIVETWEB_API int
  6324. mg_base64_decode(const char *src,
  6325. size_t src_len,
  6326. unsigned char *dst,
  6327. size_t *dst_len)
  6328. {
  6329. size_t i;
  6330. unsigned char a, b, c, d;
  6331. size_t dst_len_limit = (size_t)-1;
  6332. size_t dst_len_used = 0;
  6333. if (dst_len != NULL) {
  6334. dst_len_limit = *dst_len;
  6335. *dst_len = 0;
  6336. }
  6337. for (i = 0; i < src_len; i += 4) {
  6338. /* Read 4 characters from BASE64 string */
  6339. a = b64reverse(src[i]);
  6340. if (a >= 254) {
  6341. return (int)i;
  6342. }
  6343. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6344. if (b >= 254) {
  6345. return (int)i + 1;
  6346. }
  6347. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6348. if (c == 254) {
  6349. return (int)i + 2;
  6350. }
  6351. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6352. if (d == 254) {
  6353. return (int)i + 3;
  6354. }
  6355. /* Add first (of 3) decoded character */
  6356. if (dst_len_used < dst_len_limit) {
  6357. dst[dst_len_used] = (a << 2) + (b >> 4);
  6358. }
  6359. dst_len_used++;
  6360. if (c != 255) {
  6361. if (dst_len_used < dst_len_limit) {
  6362. dst[dst_len_used] = (b << 4) + (c >> 2);
  6363. }
  6364. dst_len_used++;
  6365. if (d != 255) {
  6366. if (dst_len_used < dst_len_limit) {
  6367. dst[dst_len_used] = (c << 6) + d;
  6368. }
  6369. dst_len_used++;
  6370. }
  6371. }
  6372. }
  6373. /* Add terminating zero */
  6374. if (dst_len_used < dst_len_limit) {
  6375. dst[dst_len_used] = '\0';
  6376. }
  6377. dst_len_used++;
  6378. if (dst_len != NULL) {
  6379. *dst_len = dst_len_used;
  6380. }
  6381. if (dst_len_used > dst_len_limit) {
  6382. /* Out of memory */
  6383. return 0;
  6384. }
  6385. /* Return -1 for "OK" */
  6386. return -1;
  6387. }
  6388. static int
  6389. is_put_or_delete_method(const struct mg_connection *conn)
  6390. {
  6391. if (conn) {
  6392. const char *s = conn->request_info.request_method;
  6393. if (s != NULL) {
  6394. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6395. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6396. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6397. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6398. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6399. || !strcmp(s, "COPY"));
  6400. }
  6401. }
  6402. return 0;
  6403. }
  6404. static int
  6405. is_civetweb_webdav_method(const struct mg_connection *conn)
  6406. {
  6407. /* Note: Here we only have to identify the WebDav methods that need special
  6408. * handling in the CivetWeb code - not all methods used in WebDav. In
  6409. * particular, methods used on directories (when using Windows Explorer as
  6410. * WebDav client).
  6411. */
  6412. if (conn) {
  6413. const char *s = conn->request_info.request_method;
  6414. if (s != NULL) {
  6415. /* These are the civetweb builtin DAV methods */
  6416. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6417. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6418. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6419. }
  6420. }
  6421. return 0;
  6422. }
  6423. #if !defined(NO_FILES)
  6424. static int
  6425. extention_matches_script(
  6426. struct mg_connection *conn, /* in: request (must be valid) */
  6427. const char *filename /* in: filename (must be valid) */
  6428. )
  6429. {
  6430. #if !defined(NO_CGI)
  6431. unsigned char cgi_config_idx, inc, max;
  6432. #endif
  6433. #if defined(USE_LUA)
  6434. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6435. filename)
  6436. > 0) {
  6437. return 1;
  6438. }
  6439. #endif
  6440. #if defined(USE_DUKTAPE)
  6441. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6442. filename)
  6443. > 0) {
  6444. return 1;
  6445. }
  6446. #endif
  6447. #if !defined(NO_CGI)
  6448. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6449. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6450. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6451. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6452. && (match_prefix_strlen(
  6453. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6454. filename)
  6455. > 0)) {
  6456. return 1;
  6457. }
  6458. }
  6459. #endif
  6460. /* filename and conn could be unused, if all preocessor conditions
  6461. * are false (no script language supported). */
  6462. (void)filename;
  6463. (void)conn;
  6464. return 0;
  6465. }
  6466. static int
  6467. extention_matches_template_text(
  6468. struct mg_connection *conn, /* in: request (must be valid) */
  6469. const char *filename /* in: filename (must be valid) */
  6470. )
  6471. {
  6472. #if defined(USE_LUA)
  6473. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6474. filename)
  6475. > 0) {
  6476. return 1;
  6477. }
  6478. #endif
  6479. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6480. > 0) {
  6481. return 1;
  6482. }
  6483. return 0;
  6484. }
  6485. /* For given directory path, substitute it to valid index file.
  6486. * Return 1 if index file has been found, 0 if not found.
  6487. * If the file is found, it's stats is returned in stp. */
  6488. static int
  6489. substitute_index_file(struct mg_connection *conn,
  6490. char *path,
  6491. size_t path_len,
  6492. struct mg_file_stat *filestat)
  6493. {
  6494. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6495. struct vec filename_vec;
  6496. size_t n = strlen(path);
  6497. int found = 0;
  6498. /* The 'path' given to us points to the directory. Remove all trailing
  6499. * directory separator characters from the end of the path, and
  6500. * then append single directory separator character. */
  6501. while ((n > 0) && (path[n - 1] == '/')) {
  6502. n--;
  6503. }
  6504. path[n] = '/';
  6505. /* Traverse index files list. For each entry, append it to the given
  6506. * path and see if the file exists. If it exists, break the loop */
  6507. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6508. /* Ignore too long entries that may overflow path buffer */
  6509. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6510. continue;
  6511. }
  6512. /* Prepare full path to the index file */
  6513. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6514. /* Does it exist? */
  6515. if (mg_stat(conn, path, filestat)) {
  6516. /* Yes it does, break the loop */
  6517. found = 1;
  6518. break;
  6519. }
  6520. }
  6521. /* If no index file exists, restore directory path */
  6522. if (!found) {
  6523. path[n] = '\0';
  6524. }
  6525. return found;
  6526. }
  6527. #endif
  6528. static void
  6529. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6530. char *filename, /* out: filename */
  6531. size_t filename_buf_len, /* in: size of filename buffer */
  6532. struct mg_file_stat *filestat, /* out: file status structure */
  6533. int *is_found, /* out: file found (directly) */
  6534. int *is_script_resource, /* out: handled by a script? */
  6535. int *is_websocket_request, /* out: websocket connetion? */
  6536. int *is_put_or_delete_request, /* out: put/delete a file? */
  6537. int *is_webdav_request, /* out: webdav request? */
  6538. int *is_template_text /* out: SSI file or LSP file? */
  6539. )
  6540. {
  6541. char const *accept_encoding;
  6542. #if !defined(NO_FILES)
  6543. const char *uri = conn->request_info.local_uri;
  6544. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6545. const char *rewrite;
  6546. struct vec a, b;
  6547. ptrdiff_t match_len;
  6548. char gz_path[UTF8_PATH_MAX];
  6549. int truncated;
  6550. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6551. char *tmp_str;
  6552. size_t tmp_str_len, sep_pos;
  6553. int allow_substitute_script_subresources;
  6554. #endif
  6555. #else
  6556. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6557. #endif
  6558. /* Step 1: Set all initially unknown outputs to zero */
  6559. memset(filestat, 0, sizeof(*filestat));
  6560. *filename = 0;
  6561. *is_found = 0;
  6562. *is_script_resource = 0;
  6563. *is_template_text = 0;
  6564. /* Step 2: Classify the request method */
  6565. /* Step 2a: Check if the request attempts to modify the file system */
  6566. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6567. /* Step 2b: Check if the request uses WebDav method that requires special
  6568. * handling */
  6569. *is_webdav_request = is_civetweb_webdav_method(conn);
  6570. /* Step 3: Check if it is a websocket request, and modify the document
  6571. * root if required */
  6572. #if defined(USE_WEBSOCKET)
  6573. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6574. #if !defined(NO_FILES)
  6575. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6576. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6577. }
  6578. #endif /* !NO_FILES */
  6579. #else /* USE_WEBSOCKET */
  6580. *is_websocket_request = 0;
  6581. #endif /* USE_WEBSOCKET */
  6582. /* Step 4: Check if gzip encoded response is allowed */
  6583. conn->accept_gzip = 0;
  6584. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6585. if (strstr(accept_encoding, "gzip") != NULL) {
  6586. conn->accept_gzip = 1;
  6587. }
  6588. }
  6589. #if !defined(NO_FILES)
  6590. /* Step 5: If there is no root directory, don't look for files. */
  6591. /* Note that root == NULL is a regular use case here. This occurs,
  6592. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6593. * config is not required. */
  6594. if (root == NULL) {
  6595. /* all file related outputs have already been set to 0, just return
  6596. */
  6597. return;
  6598. }
  6599. /* Step 6: Determine the local file path from the root path and the
  6600. * request uri. */
  6601. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6602. * part of the path one byte on the right. */
  6603. truncated = 0;
  6604. mg_snprintf(
  6605. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6606. if (truncated) {
  6607. goto interpret_cleanup;
  6608. }
  6609. /* Step 7: URI rewriting */
  6610. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6611. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6612. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6613. mg_snprintf(conn,
  6614. &truncated,
  6615. filename,
  6616. filename_buf_len - 1,
  6617. "%.*s%s",
  6618. (int)b.len,
  6619. b.ptr,
  6620. uri + match_len);
  6621. break;
  6622. }
  6623. }
  6624. if (truncated) {
  6625. goto interpret_cleanup;
  6626. }
  6627. /* Step 8: Check if the file exists at the server */
  6628. /* Local file path and name, corresponding to requested URI
  6629. * is now stored in "filename" variable. */
  6630. if (mg_stat(conn, filename, filestat)) {
  6631. int uri_len = (int)strlen(uri);
  6632. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6633. /* 8.1: File exists. */
  6634. *is_found = 1;
  6635. /* 8.2: Check if it is a script type. */
  6636. if (extention_matches_script(conn, filename)) {
  6637. /* The request addresses a CGI resource, Lua script or
  6638. * server-side javascript.
  6639. * The URI corresponds to the script itself (like
  6640. * /path/script.cgi), and there is no additional resource
  6641. * path (like /path/script.cgi/something).
  6642. * Requests that modify (replace or delete) a resource, like
  6643. * PUT and DELETE requests, should replace/delete the script
  6644. * file.
  6645. * Requests that read or write from/to a resource, like GET and
  6646. * POST requests, should call the script and return the
  6647. * generated response. */
  6648. *is_script_resource = (!*is_put_or_delete_request);
  6649. }
  6650. /* 8.3: Check for SSI and LSP files */
  6651. if (extention_matches_template_text(conn, filename)) {
  6652. /* Same as above, but for *.lsp and *.shtml files. */
  6653. /* A "template text" is a file delivered directly to the client,
  6654. * but with some text tags replaced by dynamic content.
  6655. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6656. * (LP, LSP) file. */
  6657. *is_template_text = (!*is_put_or_delete_request);
  6658. }
  6659. /* 8.4: If the request target is a directory, there could be
  6660. * a substitute file (index.html, index.cgi, ...). */
  6661. /* But do not substitute a directory for a WebDav request */
  6662. if (filestat->is_directory && is_uri_end_slash
  6663. && (!*is_webdav_request)) {
  6664. /* Use a local copy here, since substitute_index_file will
  6665. * change the content of the file status */
  6666. struct mg_file_stat tmp_filestat;
  6667. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6668. if (substitute_index_file(
  6669. conn, filename, filename_buf_len, &tmp_filestat)) {
  6670. /* Substitute file found. Copy stat to the output, then
  6671. * check if the file is a script file */
  6672. *filestat = tmp_filestat;
  6673. if (extention_matches_script(conn, filename)) {
  6674. /* Substitute file is a script file */
  6675. *is_script_resource = 1;
  6676. } else if (extention_matches_template_text(conn, filename)) {
  6677. /* Substitute file is a LSP or SSI file */
  6678. *is_template_text = 1;
  6679. } else {
  6680. /* Substitute file is a regular file */
  6681. *is_script_resource = 0;
  6682. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6683. }
  6684. }
  6685. /* If there is no substitute file, the server could return
  6686. * a directory listing in a later step */
  6687. }
  6688. return;
  6689. }
  6690. /* Step 9: Check for zipped files: */
  6691. /* If we can't find the actual file, look for the file
  6692. * with the same name but a .gz extension. If we find it,
  6693. * use that and set the gzipped flag in the file struct
  6694. * to indicate that the response need to have the content-
  6695. * encoding: gzip header.
  6696. * We can only do this if the browser declares support. */
  6697. if (conn->accept_gzip) {
  6698. mg_snprintf(
  6699. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6700. if (truncated) {
  6701. goto interpret_cleanup;
  6702. }
  6703. if (mg_stat(conn, gz_path, filestat)) {
  6704. if (filestat) {
  6705. filestat->is_gzipped = 1;
  6706. *is_found = 1;
  6707. }
  6708. /* Currently gz files can not be scripts. */
  6709. return;
  6710. }
  6711. }
  6712. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6713. /* Step 10: Script resources may handle sub-resources */
  6714. /* Support PATH_INFO for CGI scripts. */
  6715. tmp_str_len = strlen(filename);
  6716. tmp_str =
  6717. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6718. if (!tmp_str) {
  6719. /* Out of memory */
  6720. goto interpret_cleanup;
  6721. }
  6722. memcpy(tmp_str, filename, tmp_str_len + 1);
  6723. /* Check config, if index scripts may have sub-resources */
  6724. allow_substitute_script_subresources =
  6725. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6726. "yes");
  6727. if (*is_webdav_request) {
  6728. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6729. * PROPFIND fo their subresources? */
  6730. /* allow_substitute_script_subresources = 0; */
  6731. }
  6732. sep_pos = tmp_str_len;
  6733. while (sep_pos > 0) {
  6734. sep_pos--;
  6735. if (tmp_str[sep_pos] == '/') {
  6736. int is_script = 0, does_exist = 0;
  6737. tmp_str[sep_pos] = 0;
  6738. if (tmp_str[0]) {
  6739. is_script = extention_matches_script(conn, tmp_str);
  6740. does_exist = mg_stat(conn, tmp_str, filestat);
  6741. }
  6742. if (does_exist && is_script) {
  6743. filename[sep_pos] = 0;
  6744. memmove(filename + sep_pos + 2,
  6745. filename + sep_pos + 1,
  6746. strlen(filename + sep_pos + 1) + 1);
  6747. conn->path_info = filename + sep_pos + 1;
  6748. filename[sep_pos + 1] = '/';
  6749. *is_script_resource = 1;
  6750. *is_found = 1;
  6751. break;
  6752. }
  6753. if (allow_substitute_script_subresources) {
  6754. if (substitute_index_file(
  6755. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6756. /* some intermediate directory has an index file */
  6757. if (extention_matches_script(conn, tmp_str)) {
  6758. size_t script_name_len = strlen(tmp_str);
  6759. /* subres_name read before this memory locatio will be
  6760. overwritten */
  6761. char *subres_name = filename + sep_pos;
  6762. size_t subres_name_len = strlen(subres_name);
  6763. DEBUG_TRACE("Substitute script %s serving path %s",
  6764. tmp_str,
  6765. filename);
  6766. /* this index file is a script */
  6767. if ((script_name_len + subres_name_len + 2)
  6768. >= filename_buf_len) {
  6769. mg_free(tmp_str);
  6770. goto interpret_cleanup;
  6771. }
  6772. conn->path_info =
  6773. filename + script_name_len + 1; /* new target */
  6774. memmove(conn->path_info, subres_name, subres_name_len);
  6775. conn->path_info[subres_name_len] = 0;
  6776. memcpy(filename, tmp_str, script_name_len + 1);
  6777. *is_script_resource = 1;
  6778. *is_found = 1;
  6779. break;
  6780. } else {
  6781. DEBUG_TRACE("Substitute file %s serving path %s",
  6782. tmp_str,
  6783. filename);
  6784. /* non-script files will not have sub-resources */
  6785. filename[sep_pos] = 0;
  6786. conn->path_info = 0;
  6787. *is_script_resource = 0;
  6788. *is_found = 0;
  6789. break;
  6790. }
  6791. }
  6792. }
  6793. tmp_str[sep_pos] = '/';
  6794. }
  6795. }
  6796. mg_free(tmp_str);
  6797. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6798. #endif /* !defined(NO_FILES) */
  6799. return;
  6800. #if !defined(NO_FILES)
  6801. /* Reset all outputs */
  6802. interpret_cleanup:
  6803. memset(filestat, 0, sizeof(*filestat));
  6804. *filename = 0;
  6805. *is_found = 0;
  6806. *is_script_resource = 0;
  6807. *is_websocket_request = 0;
  6808. *is_put_or_delete_request = 0;
  6809. #endif /* !defined(NO_FILES) */
  6810. }
  6811. /* Check whether full request is buffered. Return:
  6812. * -1 if request or response is malformed
  6813. * 0 if request or response is not yet fully buffered
  6814. * >0 actual request length, including last \r\n\r\n */
  6815. static int
  6816. get_http_header_len(const char *buf, int buflen)
  6817. {
  6818. int i;
  6819. for (i = 0; i < buflen; i++) {
  6820. /* Do an unsigned comparison in some conditions below */
  6821. const unsigned char c = (unsigned char)buf[i];
  6822. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6823. && !isprint(c)) {
  6824. /* abort scan as soon as one malformed character is found */
  6825. return -1;
  6826. }
  6827. if (i < buflen - 1) {
  6828. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6829. /* Two newline, no carriage return - not standard compliant,
  6830. * but it should be accepted */
  6831. return i + 2;
  6832. }
  6833. }
  6834. if (i < buflen - 3) {
  6835. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6836. && (buf[i + 3] == '\n')) {
  6837. /* Two \r\n - standard compliant */
  6838. return i + 4;
  6839. }
  6840. }
  6841. }
  6842. return 0;
  6843. }
  6844. #if !defined(NO_CACHING)
  6845. /* Convert month to the month number. Return -1 on error, or month number */
  6846. static int
  6847. get_month_index(const char *s)
  6848. {
  6849. size_t i;
  6850. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6851. if (!strcmp(s, month_names[i])) {
  6852. return (int)i;
  6853. }
  6854. }
  6855. return -1;
  6856. }
  6857. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6858. static time_t
  6859. parse_date_string(const char *datetime)
  6860. {
  6861. char month_str[32] = {0};
  6862. int second, minute, hour, day, month, year;
  6863. time_t result = (time_t)0;
  6864. struct tm tm;
  6865. if ((sscanf(datetime,
  6866. "%d/%3s/%d %d:%d:%d",
  6867. &day,
  6868. month_str,
  6869. &year,
  6870. &hour,
  6871. &minute,
  6872. &second)
  6873. == 6)
  6874. || (sscanf(datetime,
  6875. "%d %3s %d %d:%d:%d",
  6876. &day,
  6877. month_str,
  6878. &year,
  6879. &hour,
  6880. &minute,
  6881. &second)
  6882. == 6)
  6883. || (sscanf(datetime,
  6884. "%*3s, %d %3s %d %d:%d:%d",
  6885. &day,
  6886. month_str,
  6887. &year,
  6888. &hour,
  6889. &minute,
  6890. &second)
  6891. == 6)
  6892. || (sscanf(datetime,
  6893. "%d-%3s-%d %d:%d:%d",
  6894. &day,
  6895. month_str,
  6896. &year,
  6897. &hour,
  6898. &minute,
  6899. &second)
  6900. == 6)) {
  6901. month = get_month_index(month_str);
  6902. if ((month >= 0) && (year >= 1970)) {
  6903. memset(&tm, 0, sizeof(tm));
  6904. tm.tm_year = year - 1900;
  6905. tm.tm_mon = month;
  6906. tm.tm_mday = day;
  6907. tm.tm_hour = hour;
  6908. tm.tm_min = minute;
  6909. tm.tm_sec = second;
  6910. result = timegm(&tm);
  6911. }
  6912. }
  6913. return result;
  6914. }
  6915. #endif /* !NO_CACHING */
  6916. /* Pre-process URIs according to RFC + protect against directory disclosure
  6917. * attacks by removing '..', excessive '/' and '\' characters */
  6918. static void
  6919. remove_dot_segments(char *inout)
  6920. {
  6921. /* Windows backend protection
  6922. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6923. * in URI by slash */
  6924. char *out_end = inout;
  6925. char *in = inout;
  6926. if (!in) {
  6927. /* Param error. */
  6928. return;
  6929. }
  6930. while (*in) {
  6931. if (*in == '\\') {
  6932. *in = '/';
  6933. }
  6934. in++;
  6935. }
  6936. /* Algorithm "remove_dot_segments" from
  6937. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6938. /* Step 1:
  6939. * The input buffer is initialized.
  6940. * The output buffer is initialized to the empty string.
  6941. */
  6942. in = inout;
  6943. /* Step 2:
  6944. * While the input buffer is not empty, loop as follows:
  6945. */
  6946. /* Less than out_end of the inout buffer is used as output, so keep
  6947. * condition: out_end <= in */
  6948. while (*in) {
  6949. /* Step 2a:
  6950. * If the input buffer begins with a prefix of "../" or "./",
  6951. * then remove that prefix from the input buffer;
  6952. */
  6953. if (!strncmp(in, "../", 3)) {
  6954. in += 3;
  6955. } else if (!strncmp(in, "./", 2)) {
  6956. in += 2;
  6957. }
  6958. /* otherwise */
  6959. /* Step 2b:
  6960. * if the input buffer begins with a prefix of "/./" or "/.",
  6961. * where "." is a complete path segment, then replace that
  6962. * prefix with "/" in the input buffer;
  6963. */
  6964. else if (!strncmp(in, "/./", 3)) {
  6965. in += 2;
  6966. } else if (!strcmp(in, "/.")) {
  6967. in[1] = 0;
  6968. }
  6969. /* otherwise */
  6970. /* Step 2c:
  6971. * if the input buffer begins with a prefix of "/../" or "/..",
  6972. * where ".." is a complete path segment, then replace that
  6973. * prefix with "/" in the input buffer and remove the last
  6974. * segment and its preceding "/" (if any) from the output
  6975. * buffer;
  6976. */
  6977. else if (!strncmp(in, "/../", 4)) {
  6978. in += 3;
  6979. if (inout != out_end) {
  6980. /* remove last segment */
  6981. do {
  6982. out_end--;
  6983. } while ((inout != out_end) && (*out_end != '/'));
  6984. }
  6985. } else if (!strcmp(in, "/..")) {
  6986. in[1] = 0;
  6987. if (inout != out_end) {
  6988. /* remove last segment */
  6989. do {
  6990. out_end--;
  6991. } while ((inout != out_end) && (*out_end != '/'));
  6992. }
  6993. }
  6994. /* otherwise */
  6995. /* Step 2d:
  6996. * if the input buffer consists only of "." or "..", then remove
  6997. * that from the input buffer;
  6998. */
  6999. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7000. *in = 0;
  7001. }
  7002. /* otherwise */
  7003. /* Step 2e:
  7004. * move the first path segment in the input buffer to the end of
  7005. * the output buffer, including the initial "/" character (if
  7006. * any) and any subsequent characters up to, but not including,
  7007. * the next "/" character or the end of the input buffer.
  7008. */
  7009. else {
  7010. do {
  7011. *out_end = *in;
  7012. out_end++;
  7013. in++;
  7014. } while ((*in != 0) && (*in != '/'));
  7015. }
  7016. }
  7017. /* Step 3:
  7018. * Finally, the output buffer is returned as the result of
  7019. * remove_dot_segments.
  7020. */
  7021. /* Terminate output */
  7022. *out_end = 0;
  7023. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7024. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7025. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7026. * or "//" anymore.
  7027. */
  7028. out_end = in = inout;
  7029. while (*in) {
  7030. if (*in == '.') {
  7031. /* remove . at the end or preceding of / */
  7032. char *in_ahead = in;
  7033. do {
  7034. in_ahead++;
  7035. } while (*in_ahead == '.');
  7036. if (*in_ahead == '/') {
  7037. in = in_ahead;
  7038. if ((out_end != inout) && (out_end[-1] == '/')) {
  7039. /* remove generated // */
  7040. out_end--;
  7041. }
  7042. } else if (*in_ahead == 0) {
  7043. in = in_ahead;
  7044. } else {
  7045. do {
  7046. *out_end++ = '.';
  7047. in++;
  7048. } while (in != in_ahead);
  7049. }
  7050. } else if (*in == '/') {
  7051. /* replace // by / */
  7052. *out_end++ = '/';
  7053. do {
  7054. in++;
  7055. } while (*in == '/');
  7056. } else {
  7057. *out_end++ = *in;
  7058. in++;
  7059. }
  7060. }
  7061. *out_end = 0;
  7062. }
  7063. static const struct {
  7064. const char *extension;
  7065. size_t ext_len;
  7066. const char *mime_type;
  7067. } builtin_mime_types[] = {
  7068. /* IANA registered MIME types
  7069. * (http://www.iana.org/assignments/media-types)
  7070. * application types */
  7071. {".bin", 4, "application/octet-stream"},
  7072. {".deb", 4, "application/octet-stream"},
  7073. {".dmg", 4, "application/octet-stream"},
  7074. {".dll", 4, "application/octet-stream"},
  7075. {".doc", 4, "application/msword"},
  7076. {".eps", 4, "application/postscript"},
  7077. {".exe", 4, "application/octet-stream"},
  7078. {".iso", 4, "application/octet-stream"},
  7079. {".js", 3, "application/javascript"},
  7080. {".json", 5, "application/json"},
  7081. {".msi", 4, "application/octet-stream"},
  7082. {".pdf", 4, "application/pdf"},
  7083. {".ps", 3, "application/postscript"},
  7084. {".rtf", 4, "application/rtf"},
  7085. {".xhtml", 6, "application/xhtml+xml"},
  7086. {".xsl", 4, "application/xml"},
  7087. {".xslt", 5, "application/xml"},
  7088. /* fonts */
  7089. {".ttf", 4, "application/font-sfnt"},
  7090. {".cff", 4, "application/font-sfnt"},
  7091. {".otf", 4, "application/font-sfnt"},
  7092. {".aat", 4, "application/font-sfnt"},
  7093. {".sil", 4, "application/font-sfnt"},
  7094. {".pfr", 4, "application/font-tdpfr"},
  7095. {".woff", 5, "application/font-woff"},
  7096. {".woff2", 6, "application/font-woff2"},
  7097. /* audio */
  7098. {".mp3", 4, "audio/mpeg"},
  7099. {".oga", 4, "audio/ogg"},
  7100. {".ogg", 4, "audio/ogg"},
  7101. /* image */
  7102. {".gif", 4, "image/gif"},
  7103. {".ief", 4, "image/ief"},
  7104. {".jpeg", 5, "image/jpeg"},
  7105. {".jpg", 4, "image/jpeg"},
  7106. {".jpm", 4, "image/jpm"},
  7107. {".jpx", 4, "image/jpx"},
  7108. {".png", 4, "image/png"},
  7109. {".svg", 4, "image/svg+xml"},
  7110. {".tif", 4, "image/tiff"},
  7111. {".tiff", 5, "image/tiff"},
  7112. /* model */
  7113. {".wrl", 4, "model/vrml"},
  7114. /* text */
  7115. {".css", 4, "text/css"},
  7116. {".csv", 4, "text/csv"},
  7117. {".htm", 4, "text/html"},
  7118. {".html", 5, "text/html"},
  7119. {".sgm", 4, "text/sgml"},
  7120. {".shtm", 5, "text/html"},
  7121. {".shtml", 6, "text/html"},
  7122. {".txt", 4, "text/plain"},
  7123. {".xml", 4, "text/xml"},
  7124. /* video */
  7125. {".mov", 4, "video/quicktime"},
  7126. {".mp4", 4, "video/mp4"},
  7127. {".mpeg", 5, "video/mpeg"},
  7128. {".mpg", 4, "video/mpeg"},
  7129. {".ogv", 4, "video/ogg"},
  7130. {".qt", 3, "video/quicktime"},
  7131. /* not registered types
  7132. * (http://reference.sitepoint.com/html/mime-types-full,
  7133. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7134. {".arj", 4, "application/x-arj-compressed"},
  7135. {".gz", 3, "application/x-gunzip"},
  7136. {".rar", 4, "application/x-arj-compressed"},
  7137. {".swf", 4, "application/x-shockwave-flash"},
  7138. {".tar", 4, "application/x-tar"},
  7139. {".tgz", 4, "application/x-tar-gz"},
  7140. {".torrent", 8, "application/x-bittorrent"},
  7141. {".ppt", 4, "application/x-mspowerpoint"},
  7142. {".xls", 4, "application/x-msexcel"},
  7143. {".zip", 4, "application/x-zip-compressed"},
  7144. {".aac",
  7145. 4,
  7146. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7147. {".flac", 5, "audio/flac"},
  7148. {".aif", 4, "audio/x-aif"},
  7149. {".m3u", 4, "audio/x-mpegurl"},
  7150. {".mid", 4, "audio/x-midi"},
  7151. {".ra", 3, "audio/x-pn-realaudio"},
  7152. {".ram", 4, "audio/x-pn-realaudio"},
  7153. {".wav", 4, "audio/x-wav"},
  7154. {".bmp", 4, "image/bmp"},
  7155. {".ico", 4, "image/x-icon"},
  7156. {".pct", 4, "image/x-pct"},
  7157. {".pict", 5, "image/pict"},
  7158. {".rgb", 4, "image/x-rgb"},
  7159. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7160. {".asf", 4, "video/x-ms-asf"},
  7161. {".avi", 4, "video/x-msvideo"},
  7162. {".m4v", 4, "video/x-m4v"},
  7163. {NULL, 0, NULL}};
  7164. CIVETWEB_API const char *
  7165. mg_get_builtin_mime_type(const char *path)
  7166. {
  7167. const char *ext;
  7168. size_t i, path_len;
  7169. path_len = strlen(path);
  7170. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7171. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7172. if ((path_len > builtin_mime_types[i].ext_len)
  7173. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7174. return builtin_mime_types[i].mime_type;
  7175. }
  7176. }
  7177. return "text/plain";
  7178. }
  7179. /* Look at the "path" extension and figure what mime type it has.
  7180. * Store mime type in the vector. */
  7181. static void
  7182. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7183. {
  7184. struct vec ext_vec, mime_vec;
  7185. const char *list, *ext;
  7186. size_t path_len;
  7187. path_len = strlen(path);
  7188. if ((conn == NULL) || (vec == NULL)) {
  7189. if (vec != NULL) {
  7190. memset(vec, '\0', sizeof(struct vec));
  7191. }
  7192. return;
  7193. }
  7194. /* Scan user-defined mime types first, in case user wants to
  7195. * override default mime types. */
  7196. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7197. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7198. /* ext now points to the path suffix */
  7199. ext = path + path_len - ext_vec.len;
  7200. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7201. *vec = mime_vec;
  7202. return;
  7203. }
  7204. }
  7205. vec->ptr = mg_get_builtin_mime_type(path);
  7206. vec->len = strlen(vec->ptr);
  7207. }
  7208. /* Stringify binary data. Output buffer must be twice as big as input,
  7209. * because each byte takes 2 bytes in string representation */
  7210. static void
  7211. bin2str(char *to, const unsigned char *p, size_t len)
  7212. {
  7213. static const char *hex = "0123456789abcdef";
  7214. for (; len--; p++) {
  7215. *to++ = hex[p[0] >> 4];
  7216. *to++ = hex[p[0] & 0x0f];
  7217. }
  7218. *to = '\0';
  7219. }
  7220. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7221. */
  7222. CIVETWEB_API char *
  7223. mg_md5(char buf[33], ...)
  7224. {
  7225. md5_byte_t hash[16];
  7226. const char *p;
  7227. va_list ap;
  7228. md5_state_t ctx;
  7229. md5_init(&ctx);
  7230. va_start(ap, buf);
  7231. while ((p = va_arg(ap, const char *)) != NULL) {
  7232. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7233. }
  7234. va_end(ap);
  7235. md5_finish(&ctx, hash);
  7236. bin2str(buf, hash, sizeof(hash));
  7237. return buf;
  7238. }
  7239. /* Check the user's password, return 1 if OK */
  7240. static int
  7241. check_password_digest(const char *method,
  7242. const char *ha1,
  7243. const char *uri,
  7244. const char *nonce,
  7245. const char *nc,
  7246. const char *cnonce,
  7247. const char *qop,
  7248. const char *response)
  7249. {
  7250. char ha2[32 + 1], expected_response[32 + 1];
  7251. /* Some of the parameters may be NULL */
  7252. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7253. || (qop == NULL) || (response == NULL)) {
  7254. return 0;
  7255. }
  7256. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7257. if (strlen(response) != 32) {
  7258. return 0;
  7259. }
  7260. mg_md5(ha2, method, ":", uri, NULL);
  7261. mg_md5(expected_response,
  7262. ha1,
  7263. ":",
  7264. nonce,
  7265. ":",
  7266. nc,
  7267. ":",
  7268. cnonce,
  7269. ":",
  7270. qop,
  7271. ":",
  7272. ha2,
  7273. NULL);
  7274. return mg_strcasecmp(response, expected_response) == 0;
  7275. }
  7276. #if !defined(NO_FILESYSTEMS)
  7277. /* Use the global passwords file, if specified by auth_gpass option,
  7278. * or search for .htpasswd in the requested directory. */
  7279. static void
  7280. open_auth_file(struct mg_connection *conn,
  7281. const char *path,
  7282. struct mg_file *filep)
  7283. {
  7284. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7285. char name[UTF8_PATH_MAX];
  7286. const char *p, *e,
  7287. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7288. int truncated;
  7289. if (gpass != NULL) {
  7290. /* Use global passwords file */
  7291. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7292. #if defined(DEBUG)
  7293. /* Use mg_cry_internal here, since gpass has been
  7294. * configured. */
  7295. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7296. #endif
  7297. }
  7298. /* Important: using local struct mg_file to test path for
  7299. * is_directory flag. If filep is used, mg_stat() makes it
  7300. * appear as if auth file was opened.
  7301. * TODO(mid): Check if this is still required after rewriting
  7302. * mg_stat */
  7303. } else if (mg_stat(conn, path, &filep->stat)
  7304. && filep->stat.is_directory) {
  7305. mg_snprintf(conn,
  7306. &truncated,
  7307. name,
  7308. sizeof(name),
  7309. "%s/%s",
  7310. path,
  7311. PASSWORDS_FILE_NAME);
  7312. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7313. #if defined(DEBUG)
  7314. /* Don't use mg_cry_internal here, but only a trace, since
  7315. * this is a typical case. It will occur for every directory
  7316. * without a password file. */
  7317. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7318. #endif
  7319. }
  7320. } else {
  7321. /* Try to find .htpasswd in requested directory. */
  7322. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7323. if (e[0] == '/') {
  7324. break;
  7325. }
  7326. }
  7327. mg_snprintf(conn,
  7328. &truncated,
  7329. name,
  7330. sizeof(name),
  7331. "%.*s/%s",
  7332. (int)(e - p),
  7333. p,
  7334. PASSWORDS_FILE_NAME);
  7335. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7336. #if defined(DEBUG)
  7337. /* Don't use mg_cry_internal here, but only a trace, since
  7338. * this is a typical case. It will occur for every directory
  7339. * without a password file. */
  7340. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7341. #endif
  7342. }
  7343. }
  7344. }
  7345. }
  7346. #endif /* NO_FILESYSTEMS */
  7347. /* Parsed Authorization header */
  7348. struct ah {
  7349. char *user;
  7350. int type; /* 1 = basic, 2 = digest */
  7351. char *plain_password; /* Basic only */
  7352. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7353. };
  7354. /* Return 1 on success. Always initializes the ah structure. */
  7355. static int
  7356. parse_auth_header(struct mg_connection *conn,
  7357. char *buf,
  7358. size_t buf_size,
  7359. struct ah *ah)
  7360. {
  7361. char *name, *value, *s;
  7362. const char *auth_header;
  7363. uint64_t nonce;
  7364. if (!ah || !conn) {
  7365. return 0;
  7366. }
  7367. (void)memset(ah, 0, sizeof(*ah));
  7368. auth_header = mg_get_header(conn, "Authorization");
  7369. if (auth_header == NULL) {
  7370. /* No Authorization header at all */
  7371. return 0;
  7372. }
  7373. if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
  7374. /* Basic Auth (we never asked for this, but some client may send it) */
  7375. char *split;
  7376. const char *userpw_b64 = auth_header + 6;
  7377. size_t userpw_b64_len = strlen(userpw_b64);
  7378. size_t buf_len_r = buf_size;
  7379. if (mg_base64_decode(
  7380. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7381. != -1) {
  7382. return 0; /* decode error */
  7383. }
  7384. split = strchr(buf, ':');
  7385. if (!split) {
  7386. return 0; /* Format error */
  7387. }
  7388. /* Separate string at ':' */
  7389. *split = 0;
  7390. /* User name is before ':', Password is after ':' */
  7391. ah->user = buf;
  7392. ah->type = 1;
  7393. ah->plain_password = split + 1;
  7394. return 1;
  7395. } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
  7396. /* Digest Auth ... implemented below */
  7397. ah->type = 2;
  7398. } else {
  7399. /* Unknown or invalid Auth method */
  7400. return 0;
  7401. }
  7402. /* Make modifiable copy of the auth header */
  7403. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7404. s = buf;
  7405. /* Parse authorization header */
  7406. for (;;) {
  7407. /* Gobble initial spaces */
  7408. while (isspace((unsigned char)*s)) {
  7409. s++;
  7410. }
  7411. name = skip_quoted(&s, "=", " ", 0);
  7412. /* Value is either quote-delimited, or ends at first comma or space.
  7413. */
  7414. if (s[0] == '\"') {
  7415. s++;
  7416. value = skip_quoted(&s, "\"", " ", '\\');
  7417. if (s[0] == ',') {
  7418. s++;
  7419. }
  7420. } else {
  7421. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7422. * uses spaces */
  7423. }
  7424. if (*name == '\0') {
  7425. break;
  7426. }
  7427. if (!strcmp(name, "username")) {
  7428. ah->user = value;
  7429. } else if (!strcmp(name, "cnonce")) {
  7430. ah->cnonce = value;
  7431. } else if (!strcmp(name, "response")) {
  7432. ah->response = value;
  7433. } else if (!strcmp(name, "uri")) {
  7434. ah->uri = value;
  7435. } else if (!strcmp(name, "qop")) {
  7436. ah->qop = value;
  7437. } else if (!strcmp(name, "nc")) {
  7438. ah->nc = value;
  7439. } else if (!strcmp(name, "nonce")) {
  7440. ah->nonce = value;
  7441. }
  7442. }
  7443. #if !defined(NO_NONCE_CHECK)
  7444. /* Read the nonce from the response. */
  7445. if (ah->nonce == NULL) {
  7446. return 0;
  7447. }
  7448. s = NULL;
  7449. nonce = strtoull(ah->nonce, &s, 10);
  7450. if ((s == NULL) || (*s != 0)) {
  7451. return 0;
  7452. }
  7453. /* Convert the nonce from the client to a number. */
  7454. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7455. /* The converted number corresponds to the time the nounce has been
  7456. * created. This should not be earlier than the server start. */
  7457. /* Server side nonce check is valuable in all situations but one:
  7458. * if the server restarts frequently, but the client should not see
  7459. * that, so the server should accept nonces from previous starts. */
  7460. /* However, the reasonable default is to not accept a nonce from a
  7461. * previous start, so if anyone changed the access rights between
  7462. * two restarts, a new login is required. */
  7463. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7464. /* nonce is from a previous start of the server and no longer valid
  7465. * (replay attack?) */
  7466. return 0;
  7467. }
  7468. /* Check if the nonce is too high, so it has not (yet) been used by the
  7469. * server. */
  7470. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7471. + conn->dom_ctx->nonce_count)) {
  7472. return 0;
  7473. }
  7474. #else
  7475. (void)nonce;
  7476. #endif
  7477. return (ah->user != NULL);
  7478. }
  7479. static const char *
  7480. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7481. {
  7482. if (!filep) {
  7483. return NULL;
  7484. }
  7485. if (filep->access.fp != NULL) {
  7486. return fgets(buf, (int)size, filep->access.fp);
  7487. } else {
  7488. return NULL;
  7489. }
  7490. }
  7491. /* Define the initial recursion depth for procesesing htpasswd files that
  7492. * include other htpasswd
  7493. * (or even the same) files. It is not difficult to provide a file or files
  7494. * s.t. they force civetweb
  7495. * to infinitely recurse and then crash.
  7496. */
  7497. #define INITIAL_DEPTH 9
  7498. #if INITIAL_DEPTH <= 0
  7499. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7500. #endif
  7501. #if !defined(NO_FILESYSTEMS)
  7502. struct read_auth_file_struct {
  7503. struct mg_connection *conn;
  7504. struct ah ah;
  7505. const char *domain;
  7506. char buf[256 + 256 + 40];
  7507. const char *f_user;
  7508. const char *f_domain;
  7509. const char *f_ha1;
  7510. };
  7511. static int
  7512. read_auth_file(struct mg_file *filep,
  7513. struct read_auth_file_struct *workdata,
  7514. int depth)
  7515. {
  7516. int is_authorized = 0;
  7517. struct mg_file fp;
  7518. size_t l;
  7519. if (!filep || !workdata || (0 == depth)) {
  7520. return 0;
  7521. }
  7522. /* Loop over passwords file */
  7523. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7524. l = strlen(workdata->buf);
  7525. while (l > 0) {
  7526. if (isspace((unsigned char)workdata->buf[l - 1])
  7527. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7528. l--;
  7529. workdata->buf[l] = 0;
  7530. } else
  7531. break;
  7532. }
  7533. if (l < 1) {
  7534. continue;
  7535. }
  7536. workdata->f_user = workdata->buf;
  7537. if (workdata->f_user[0] == ':') {
  7538. /* user names may not contain a ':' and may not be empty,
  7539. * so lines starting with ':' may be used for a special purpose
  7540. */
  7541. if (workdata->f_user[1] == '#') {
  7542. /* :# is a comment */
  7543. continue;
  7544. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7545. if (mg_fopen(workdata->conn,
  7546. workdata->f_user + 9,
  7547. MG_FOPEN_MODE_READ,
  7548. &fp)) {
  7549. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7550. (void)mg_fclose(
  7551. &fp.access); /* ignore error on read only file */
  7552. /* No need to continue processing files once we have a
  7553. * match, since nothing will reset it back
  7554. * to 0.
  7555. */
  7556. if (is_authorized) {
  7557. return is_authorized;
  7558. }
  7559. } else {
  7560. mg_cry_internal(workdata->conn,
  7561. "%s: cannot open authorization file: %s",
  7562. __func__,
  7563. workdata->buf);
  7564. }
  7565. continue;
  7566. }
  7567. /* everything is invalid for the moment (might change in the
  7568. * future) */
  7569. mg_cry_internal(workdata->conn,
  7570. "%s: syntax error in authorization file: %s",
  7571. __func__,
  7572. workdata->buf);
  7573. continue;
  7574. }
  7575. workdata->f_domain = strchr(workdata->f_user, ':');
  7576. if (workdata->f_domain == NULL) {
  7577. mg_cry_internal(workdata->conn,
  7578. "%s: syntax error in authorization file: %s",
  7579. __func__,
  7580. workdata->buf);
  7581. continue;
  7582. }
  7583. *(char *)(workdata->f_domain) = 0;
  7584. (workdata->f_domain)++;
  7585. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7586. if (workdata->f_ha1 == NULL) {
  7587. mg_cry_internal(workdata->conn,
  7588. "%s: syntax error in authorization file: %s",
  7589. __func__,
  7590. workdata->buf);
  7591. continue;
  7592. }
  7593. *(char *)(workdata->f_ha1) = 0;
  7594. (workdata->f_ha1)++;
  7595. if (!strcmp(workdata->ah.user, workdata->f_user)
  7596. && !strcmp(workdata->domain, workdata->f_domain)) {
  7597. switch (workdata->ah.type) {
  7598. case 1: /* Basic */
  7599. {
  7600. size_t mlen = strlen(workdata->f_user)
  7601. + strlen(workdata->domain)
  7602. + strlen(workdata->ah.plain_password) + 3;
  7603. char md5[33];
  7604. mg_md5(md5,
  7605. workdata->f_user,
  7606. ":",
  7607. workdata->domain,
  7608. ":",
  7609. workdata->ah.plain_password,
  7610. NULL);
  7611. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7612. }
  7613. case 2: /* Digest */
  7614. return check_password_digest(
  7615. workdata->conn->request_info.request_method,
  7616. workdata->f_ha1,
  7617. workdata->ah.uri,
  7618. workdata->ah.nonce,
  7619. workdata->ah.nc,
  7620. workdata->ah.cnonce,
  7621. workdata->ah.qop,
  7622. workdata->ah.response);
  7623. default: /* None/Other/Unknown */
  7624. return 0;
  7625. }
  7626. }
  7627. }
  7628. return is_authorized;
  7629. }
  7630. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7631. static int
  7632. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7633. {
  7634. struct read_auth_file_struct workdata;
  7635. char buf[MG_BUF_LEN];
  7636. if (!conn || !conn->dom_ctx) {
  7637. return 0;
  7638. }
  7639. memset(&workdata, 0, sizeof(workdata));
  7640. workdata.conn = conn;
  7641. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7642. return 0;
  7643. }
  7644. /* CGI needs it as REMOTE_USER */
  7645. conn->request_info.remote_user =
  7646. mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
  7647. if (realm) {
  7648. workdata.domain = realm;
  7649. } else {
  7650. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7651. }
  7652. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7653. }
  7654. /* Public function to check http digest authentication header */
  7655. CIVETWEB_API int
  7656. mg_check_digest_access_authentication(struct mg_connection *conn,
  7657. const char *realm,
  7658. const char *filename)
  7659. {
  7660. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7661. int auth;
  7662. if (!conn || !filename) {
  7663. return -1;
  7664. }
  7665. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7666. return -2;
  7667. }
  7668. auth = authorize(conn, &file, realm);
  7669. mg_fclose(&file.access);
  7670. return auth;
  7671. }
  7672. #endif /* NO_FILESYSTEMS */
  7673. /* Return 1 if request is authorised, 0 otherwise. */
  7674. static int
  7675. check_authorization(struct mg_connection *conn, const char *path)
  7676. {
  7677. #if !defined(NO_FILESYSTEMS)
  7678. char fname[UTF8_PATH_MAX];
  7679. struct vec uri_vec, filename_vec;
  7680. const char *list;
  7681. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7682. int authorized = 1, truncated;
  7683. if (!conn || !conn->dom_ctx) {
  7684. return 0;
  7685. }
  7686. list = conn->dom_ctx->config[PROTECT_URI];
  7687. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7688. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7689. mg_snprintf(conn,
  7690. &truncated,
  7691. fname,
  7692. sizeof(fname),
  7693. "%.*s",
  7694. (int)filename_vec.len,
  7695. filename_vec.ptr);
  7696. if (truncated
  7697. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7698. mg_cry_internal(conn,
  7699. "%s: cannot open %s: %s",
  7700. __func__,
  7701. fname,
  7702. strerror(errno));
  7703. }
  7704. break;
  7705. }
  7706. }
  7707. if (!is_file_opened(&file.access)) {
  7708. open_auth_file(conn, path, &file);
  7709. }
  7710. if (is_file_opened(&file.access)) {
  7711. authorized = authorize(conn, &file, NULL);
  7712. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7713. }
  7714. return authorized;
  7715. #else
  7716. (void)conn;
  7717. (void)path;
  7718. return 1;
  7719. #endif /* NO_FILESYSTEMS */
  7720. }
  7721. /* Internal function. Assumes conn is valid */
  7722. static void
  7723. send_authorization_request(struct mg_connection *conn, const char *realm)
  7724. {
  7725. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7726. int trunc = 0;
  7727. char buf[128];
  7728. if (!realm) {
  7729. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7730. }
  7731. mg_lock_context(conn->phys_ctx);
  7732. nonce += conn->dom_ctx->nonce_count;
  7733. ++conn->dom_ctx->nonce_count;
  7734. mg_unlock_context(conn->phys_ctx);
  7735. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7736. conn->must_close = 1;
  7737. /* Create 401 response */
  7738. mg_response_header_start(conn, 401);
  7739. send_no_cache_header(conn);
  7740. send_additional_header(conn);
  7741. mg_response_header_add(conn, "Content-Length", "0", -1);
  7742. /* Content for "WWW-Authenticate" header */
  7743. mg_snprintf(conn,
  7744. &trunc,
  7745. buf,
  7746. sizeof(buf),
  7747. "Digest qop=\"auth\", realm=\"%s\", "
  7748. "nonce=\"%" UINT64_FMT "\"",
  7749. realm,
  7750. nonce);
  7751. if (!trunc) {
  7752. /* !trunc should always be true */
  7753. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7754. }
  7755. /* Send all headers */
  7756. mg_response_header_send(conn);
  7757. }
  7758. /* Interface function. Parameters are provided by the user, so do
  7759. * at least some basic checks.
  7760. */
  7761. CIVETWEB_API int
  7762. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7763. const char *realm)
  7764. {
  7765. if (conn && conn->dom_ctx) {
  7766. send_authorization_request(conn, realm);
  7767. return 0;
  7768. }
  7769. return -1;
  7770. }
  7771. #if !defined(NO_FILES)
  7772. static int
  7773. is_authorized_for_put(struct mg_connection *conn)
  7774. {
  7775. int ret = 0;
  7776. if (conn) {
  7777. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7778. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7779. if (passfile != NULL
  7780. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7781. ret = authorize(conn, &file, NULL);
  7782. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7783. }
  7784. }
  7785. DEBUG_TRACE("file write autorization: %i", ret);
  7786. return ret;
  7787. }
  7788. #endif
  7789. CIVETWEB_API int
  7790. mg_modify_passwords_file_ha1(const char *fname,
  7791. const char *domain,
  7792. const char *user,
  7793. const char *ha1)
  7794. {
  7795. int found = 0, i, result = 1;
  7796. char line[512], u[256], d[256], h[256];
  7797. struct stat st = {0};
  7798. FILE *fp = NULL;
  7799. char *temp_file = NULL;
  7800. int temp_file_offs = 0;
  7801. /* Regard empty password as no password - remove user record. */
  7802. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7803. ha1 = NULL;
  7804. }
  7805. /* Other arguments must not be empty */
  7806. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7807. return 0;
  7808. }
  7809. /* Using the given file format, user name and domain must not contain
  7810. * the ':' character */
  7811. if (strchr(user, ':') != NULL) {
  7812. return 0;
  7813. }
  7814. if (strchr(domain, ':') != NULL) {
  7815. return 0;
  7816. }
  7817. /* Do not allow control characters like newline in user name and domain.
  7818. * Do not allow excessively long names either. */
  7819. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7820. if (iscntrl((unsigned char)user[i])) {
  7821. return 0;
  7822. }
  7823. }
  7824. if (user[i]) {
  7825. return 0; /* user name too long */
  7826. }
  7827. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7828. if (iscntrl((unsigned char)domain[i])) {
  7829. return 0;
  7830. }
  7831. }
  7832. if (domain[i]) {
  7833. return 0; /* domain name too long */
  7834. }
  7835. /* The maximum length of the path to the password file is limited */
  7836. if (strlen(fname) >= UTF8_PATH_MAX) {
  7837. return 0;
  7838. }
  7839. /* Check if the file exists, and get file size */
  7840. if (0 == stat(fname, &st)) {
  7841. int temp_buf_len = (int)st.st_size + 1024;
  7842. /* Allocate memory (instead of using a temporary file) */
  7843. temp_file = (char *)mg_calloc(temp_buf_len, 1);
  7844. if (!temp_file) {
  7845. /* Out of memory */
  7846. return 0;
  7847. }
  7848. /* File exists. Read it into a memory buffer. */
  7849. fp = fopen(fname, "r");
  7850. if (fp == NULL) {
  7851. /* Cannot read file. No permission? */
  7852. mg_free(temp_file);
  7853. return 0;
  7854. }
  7855. /* Read content and store in memory */
  7856. while ((fgets(line, sizeof(line), fp) != NULL)
  7857. && ((temp_file_offs + 600) < temp_buf_len)) {
  7858. /* file format is "user:domain:hash\n" */
  7859. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7860. continue;
  7861. }
  7862. u[255] = 0;
  7863. d[255] = 0;
  7864. h[255] = 0;
  7865. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7866. /* Found the user: change the password hash or drop the user
  7867. */
  7868. if ((ha1 != NULL) && (!found)) {
  7869. i = sprintf(temp_file + temp_file_offs,
  7870. "%s:%s:%s\n",
  7871. user,
  7872. domain,
  7873. ha1);
  7874. if (i < 1) {
  7875. fclose(fp);
  7876. mg_free(temp_file);
  7877. return 0;
  7878. }
  7879. temp_file_offs += i;
  7880. }
  7881. found = 1;
  7882. } else {
  7883. /* Copy existing user, including password hash */
  7884. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7885. if (i < 1) {
  7886. fclose(fp);
  7887. mg_free(temp_file);
  7888. return 0;
  7889. }
  7890. temp_file_offs += i;
  7891. }
  7892. }
  7893. fclose(fp);
  7894. }
  7895. /* Create new file */
  7896. fp = fopen(fname, "w");
  7897. if (!fp) {
  7898. mg_free(temp_file);
  7899. return 0;
  7900. }
  7901. #if !defined(_WIN32)
  7902. /* On Linux & co., restrict file read/write permissions to the owner */
  7903. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7904. result = 0;
  7905. }
  7906. #endif
  7907. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7908. /* Store buffered content of old file */
  7909. if (fwrite(temp_file, 1, temp_file_offs, fp)
  7910. != (size_t)temp_file_offs) {
  7911. result = 0;
  7912. }
  7913. }
  7914. /* If new user, just add it */
  7915. if ((ha1 != NULL) && (!found)) {
  7916. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7917. result = 0;
  7918. }
  7919. }
  7920. /* All data written */
  7921. if (fclose(fp) != 0) {
  7922. result = 0;
  7923. }
  7924. mg_free(temp_file);
  7925. return result;
  7926. }
  7927. CIVETWEB_API int
  7928. mg_modify_passwords_file(const char *fname,
  7929. const char *domain,
  7930. const char *user,
  7931. const char *pass)
  7932. {
  7933. char ha1buf[33];
  7934. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7935. return 0;
  7936. }
  7937. if ((pass == NULL) || (pass[0] == 0)) {
  7938. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7939. }
  7940. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7941. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7942. }
  7943. static int
  7944. is_valid_port(unsigned long port)
  7945. {
  7946. return (port <= 0xffff);
  7947. }
  7948. static int
  7949. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7950. {
  7951. struct addrinfo hints, *res, *ressave;
  7952. int func_ret = 0;
  7953. int gai_ret;
  7954. memset(&hints, 0, sizeof(struct addrinfo));
  7955. hints.ai_family = af;
  7956. if (!resolve_src) {
  7957. hints.ai_flags = AI_NUMERICHOST;
  7958. }
  7959. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7960. if (gai_ret != 0) {
  7961. /* gai_strerror could be used to convert gai_ret to a string */
  7962. /* POSIX return values: see
  7963. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7964. */
  7965. /* Windows return values: see
  7966. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7967. */
  7968. return 0;
  7969. }
  7970. ressave = res;
  7971. while (res) {
  7972. if ((dstlen >= (size_t)res->ai_addrlen)
  7973. && (res->ai_addr->sa_family == af)) {
  7974. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7975. func_ret = 1;
  7976. }
  7977. res = res->ai_next;
  7978. }
  7979. freeaddrinfo(ressave);
  7980. return func_ret;
  7981. }
  7982. static int
  7983. connect_socket(
  7984. struct mg_context *ctx /* may be NULL */,
  7985. const char *host,
  7986. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7987. int use_ssl, /* 0 or 1 */
  7988. struct mg_error_data *error,
  7989. SOCKET *sock /* output: socket, must not be NULL */,
  7990. union usa *sa /* output: socket address, must not be NULL */
  7991. )
  7992. {
  7993. int ip_ver = 0;
  7994. int conn_ret = -1;
  7995. int sockerr = 0;
  7996. *sock = INVALID_SOCKET;
  7997. memset(sa, 0, sizeof(*sa));
  7998. if (host == NULL) {
  7999. if (error != NULL) {
  8000. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8001. mg_snprintf(NULL,
  8002. NULL, /* No truncation check for ebuf */
  8003. error->text,
  8004. error->text_buffer_size,
  8005. "%s",
  8006. "NULL host");
  8007. }
  8008. return 0;
  8009. }
  8010. #if defined(USE_X_DOM_SOCKET)
  8011. if (port == -99) {
  8012. /* Unix domain socket */
  8013. size_t hostlen = strlen(host);
  8014. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8015. if (error != NULL) {
  8016. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8017. mg_snprintf(NULL,
  8018. NULL, /* No truncation check for ebuf */
  8019. error->text,
  8020. error->text_buffer_size,
  8021. "%s",
  8022. "host length exceeds limit");
  8023. }
  8024. return 0;
  8025. }
  8026. } else
  8027. #endif
  8028. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8029. if (error != NULL) {
  8030. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8031. mg_snprintf(NULL,
  8032. NULL, /* No truncation check for ebuf */
  8033. error->text,
  8034. error->text_buffer_size,
  8035. "%s",
  8036. "invalid port");
  8037. }
  8038. return 0;
  8039. }
  8040. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  8041. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8042. if (use_ssl && (TLS_client_method == NULL)) {
  8043. if (error != NULL) {
  8044. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8045. mg_snprintf(NULL,
  8046. NULL, /* No truncation check for ebuf */
  8047. error->text,
  8048. error->text_buffer_size,
  8049. "%s",
  8050. "SSL is not initialized");
  8051. }
  8052. return 0;
  8053. }
  8054. #else
  8055. if (use_ssl && (SSLv23_client_method == NULL)) {
  8056. if (error != 0) {
  8057. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8058. mg_snprintf(NULL,
  8059. NULL, /* No truncation check for ebuf */
  8060. error->text,
  8061. error->text_buffer_size,
  8062. "%s",
  8063. "SSL is not initialized");
  8064. }
  8065. return 0;
  8066. }
  8067. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8068. #else
  8069. (void)use_ssl;
  8070. #endif /* NO SSL */
  8071. #if defined(USE_X_DOM_SOCKET)
  8072. if (port == -99) {
  8073. size_t hostlen = strlen(host);
  8074. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8075. ip_ver = -99;
  8076. sa->sun.sun_family = AF_UNIX;
  8077. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8078. memcpy(sa->sun.sun_path, host, hostlen);
  8079. } else
  8080. #endif
  8081. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8082. sa->sin.sin_port = htons((uint16_t)port);
  8083. ip_ver = 4;
  8084. #if defined(USE_IPV6)
  8085. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8086. sa->sin6.sin6_port = htons((uint16_t)port);
  8087. ip_ver = 6;
  8088. } else if (host[0] == '[') {
  8089. /* While getaddrinfo on Windows will work with [::1],
  8090. * getaddrinfo on Linux only works with ::1 (without []). */
  8091. size_t l = strlen(host + 1);
  8092. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8093. if (h) {
  8094. h[l - 1] = 0;
  8095. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8096. sa->sin6.sin6_port = htons((uint16_t)port);
  8097. ip_ver = 6;
  8098. }
  8099. mg_free(h);
  8100. }
  8101. #endif
  8102. }
  8103. if (ip_ver == 0) {
  8104. if (error != NULL) {
  8105. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8106. mg_snprintf(NULL,
  8107. NULL, /* No truncation check for ebuf */
  8108. error->text,
  8109. error->text_buffer_size,
  8110. "%s",
  8111. "host not found");
  8112. }
  8113. return 0;
  8114. }
  8115. if (ip_ver == 4) {
  8116. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8117. }
  8118. #if defined(USE_IPV6)
  8119. else if (ip_ver == 6) {
  8120. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8121. }
  8122. #endif
  8123. #if defined(USE_X_DOM_SOCKET)
  8124. else if (ip_ver == -99) {
  8125. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8126. }
  8127. #endif
  8128. if (*sock == INVALID_SOCKET) {
  8129. if (error != NULL) {
  8130. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8131. error->code_sub = ERRNO;
  8132. mg_snprintf(NULL,
  8133. NULL, /* No truncation check for ebuf */
  8134. error->text,
  8135. error->text_buffer_size,
  8136. "socket(): %s",
  8137. strerror(ERRNO));
  8138. }
  8139. return 0;
  8140. }
  8141. if (0 != set_non_blocking_mode(*sock)) {
  8142. if (error != NULL) {
  8143. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8144. error->code_sub = ERRNO;
  8145. mg_snprintf(NULL,
  8146. NULL, /* No truncation check for ebuf */
  8147. error->text,
  8148. error->text_buffer_size,
  8149. "Cannot set socket to non-blocking: %s",
  8150. strerror(ERRNO));
  8151. }
  8152. closesocket(*sock);
  8153. *sock = INVALID_SOCKET;
  8154. return 0;
  8155. }
  8156. set_close_on_exec(*sock, NULL, ctx);
  8157. if (ip_ver == 4) {
  8158. /* connected with IPv4 */
  8159. conn_ret = connect(*sock,
  8160. (struct sockaddr *)((void *)&sa->sin),
  8161. sizeof(sa->sin));
  8162. }
  8163. #if defined(USE_IPV6)
  8164. else if (ip_ver == 6) {
  8165. /* connected with IPv6 */
  8166. conn_ret = connect(*sock,
  8167. (struct sockaddr *)((void *)&sa->sin6),
  8168. sizeof(sa->sin6));
  8169. }
  8170. #endif
  8171. #if defined(USE_X_DOM_SOCKET)
  8172. else if (ip_ver == -99) {
  8173. /* connected to domain socket */
  8174. conn_ret = connect(*sock,
  8175. (struct sockaddr *)((void *)&sa->sun),
  8176. sizeof(sa->sun));
  8177. }
  8178. #endif
  8179. if (conn_ret != 0) {
  8180. sockerr = ERRNO;
  8181. }
  8182. #if defined(_WIN32)
  8183. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8184. #else
  8185. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8186. #endif
  8187. /* Data for getsockopt */
  8188. void *psockerr = &sockerr;
  8189. int ret;
  8190. #if defined(_WIN32)
  8191. int len = (int)sizeof(sockerr);
  8192. #else
  8193. socklen_t len = (socklen_t)sizeof(sockerr);
  8194. #endif
  8195. /* Data for poll */
  8196. struct mg_pollfd pfd[1];
  8197. int pollres;
  8198. int ms_wait = 10000; /* 10 second timeout */
  8199. stop_flag_t nonstop;
  8200. STOP_FLAG_ASSIGN(&nonstop, 0);
  8201. /* For a non-blocking socket, the connect sequence is:
  8202. * 1) call connect (will not block)
  8203. * 2) wait until the socket is ready for writing (select or poll)
  8204. * 3) check connection state with getsockopt
  8205. */
  8206. pfd[0].fd = *sock;
  8207. pfd[0].events = POLLOUT;
  8208. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8209. if (pollres != 1) {
  8210. /* Not connected */
  8211. if (error != NULL) {
  8212. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8213. mg_snprintf(NULL,
  8214. NULL, /* No truncation check for ebuf */
  8215. error->text,
  8216. error->text_buffer_size,
  8217. "connect(%s:%d): timeout",
  8218. host,
  8219. port);
  8220. }
  8221. closesocket(*sock);
  8222. *sock = INVALID_SOCKET;
  8223. return 0;
  8224. }
  8225. #if defined(_WIN32)
  8226. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8227. #else
  8228. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8229. #endif
  8230. if ((ret == 0) && (sockerr == 0)) {
  8231. conn_ret = 0;
  8232. }
  8233. }
  8234. if (conn_ret != 0) {
  8235. /* Not connected */
  8236. if (error != NULL) {
  8237. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8238. error->code_sub = ERRNO;
  8239. mg_snprintf(NULL,
  8240. NULL, /* No truncation check for ebuf */
  8241. error->text,
  8242. error->text_buffer_size,
  8243. "connect(%s:%d): error %s",
  8244. host,
  8245. port,
  8246. strerror(sockerr));
  8247. }
  8248. closesocket(*sock);
  8249. *sock = INVALID_SOCKET;
  8250. return 0;
  8251. }
  8252. return 1;
  8253. }
  8254. CIVETWEB_API int
  8255. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8256. {
  8257. static const char *dont_escape = "._-$,;~()";
  8258. static const char *hex = "0123456789abcdef";
  8259. char *pos = dst;
  8260. const char *end = dst + dst_len - 1;
  8261. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8262. if (isalnum((unsigned char)*src)
  8263. || (strchr(dont_escape, *src) != NULL)) {
  8264. *pos = *src;
  8265. } else if (pos + 2 < end) {
  8266. pos[0] = '%';
  8267. pos[1] = hex[(unsigned char)*src >> 4];
  8268. pos[2] = hex[(unsigned char)*src & 0xf];
  8269. pos += 2;
  8270. } else {
  8271. break;
  8272. }
  8273. }
  8274. *pos = '\0';
  8275. return (*src == '\0') ? (int)(pos - dst) : -1;
  8276. }
  8277. /* Return 0 on success, non-zero if an error occurs. */
  8278. static int
  8279. print_dir_entry(struct mg_connection *conn, struct de *de)
  8280. {
  8281. size_t namesize, escsize, i;
  8282. char *href, *esc, *p;
  8283. char size[64], mod[64];
  8284. #if defined(REENTRANT_TIME)
  8285. struct tm _tm;
  8286. struct tm *tm = &_tm;
  8287. #else
  8288. struct tm *tm;
  8289. #endif
  8290. /* Estimate worst case size for encoding and escaping */
  8291. namesize = strlen(de->file_name) + 1;
  8292. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8293. href = (char *)mg_malloc(namesize * 3 + escsize);
  8294. if (href == NULL) {
  8295. return -1;
  8296. }
  8297. mg_url_encode(de->file_name, href, namesize * 3);
  8298. esc = NULL;
  8299. if (escsize > 0) {
  8300. /* HTML escaping needed */
  8301. esc = href + namesize * 3;
  8302. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8303. mg_strlcpy(p, de->file_name + i, 2);
  8304. if (*p == '&') {
  8305. strcpy(p, "&amp;");
  8306. } else if (*p == '<') {
  8307. strcpy(p, "&lt;");
  8308. } else if (*p == '>') {
  8309. strcpy(p, "&gt;");
  8310. }
  8311. }
  8312. }
  8313. if (de->file.is_directory) {
  8314. mg_snprintf(conn,
  8315. NULL, /* Buffer is big enough */
  8316. size,
  8317. sizeof(size),
  8318. "%s",
  8319. "[DIRECTORY]");
  8320. } else {
  8321. /* We use (signed) cast below because MSVC 6 compiler cannot
  8322. * convert unsigned __int64 to double. Sigh. */
  8323. if (de->file.size < 1024) {
  8324. mg_snprintf(conn,
  8325. NULL, /* Buffer is big enough */
  8326. size,
  8327. sizeof(size),
  8328. "%d",
  8329. (int)de->file.size);
  8330. } else if (de->file.size < 0x100000) {
  8331. mg_snprintf(conn,
  8332. NULL, /* Buffer is big enough */
  8333. size,
  8334. sizeof(size),
  8335. "%.1fk",
  8336. (double)de->file.size / 1024.0);
  8337. } else if (de->file.size < 0x40000000) {
  8338. mg_snprintf(conn,
  8339. NULL, /* Buffer is big enough */
  8340. size,
  8341. sizeof(size),
  8342. "%.1fM",
  8343. (double)de->file.size / 1048576);
  8344. } else {
  8345. mg_snprintf(conn,
  8346. NULL, /* Buffer is big enough */
  8347. size,
  8348. sizeof(size),
  8349. "%.1fG",
  8350. (double)de->file.size / 1073741824);
  8351. }
  8352. }
  8353. /* Note: mg_snprintf will not cause a buffer overflow above.
  8354. * So, string truncation checks are not required here. */
  8355. #if defined(REENTRANT_TIME)
  8356. localtime_r(&de->file.last_modified, tm);
  8357. #else
  8358. tm = localtime(&de->file.last_modified);
  8359. #endif
  8360. if (tm != NULL) {
  8361. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8362. } else {
  8363. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8364. mod[sizeof(mod) - 1] = '\0';
  8365. }
  8366. mg_printf(conn,
  8367. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8368. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8369. href,
  8370. de->file.is_directory ? "/" : "",
  8371. esc ? esc : de->file_name,
  8372. de->file.is_directory ? "/" : "",
  8373. mod,
  8374. size);
  8375. mg_free(href);
  8376. return 0;
  8377. }
  8378. /* This function is called from send_directory() and used for
  8379. * sorting directory entries by size, name, or modification time. */
  8380. static int
  8381. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8382. {
  8383. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8384. if (p1 && p2) {
  8385. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8386. int cmp_result = 0;
  8387. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8388. query_string = "n";
  8389. }
  8390. /* Sort Directories vs Files */
  8391. if (a->file.is_directory && !b->file.is_directory) {
  8392. return -1; /* Always put directories on top */
  8393. } else if (!a->file.is_directory && b->file.is_directory) {
  8394. return 1; /* Always put directories on top */
  8395. }
  8396. /* Sort by size or date */
  8397. if (*query_string == 's') {
  8398. cmp_result = (a->file.size == b->file.size)
  8399. ? 0
  8400. : ((a->file.size > b->file.size) ? 1 : -1);
  8401. } else if (*query_string == 'd') {
  8402. cmp_result =
  8403. (a->file.last_modified == b->file.last_modified)
  8404. ? 0
  8405. : ((a->file.last_modified > b->file.last_modified) ? 1
  8406. : -1);
  8407. }
  8408. /* Sort by name:
  8409. * if (*query_string == 'n') ...
  8410. * but also sort files of same size/date by name as secondary criterion.
  8411. */
  8412. if (cmp_result == 0) {
  8413. cmp_result = strcmp(a->file_name, b->file_name);
  8414. }
  8415. /* For descending order, invert result */
  8416. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8417. }
  8418. return 0;
  8419. }
  8420. static int
  8421. must_hide_file(struct mg_connection *conn, const char *path)
  8422. {
  8423. if (conn && conn->dom_ctx) {
  8424. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8425. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8426. return (match_prefix_strlen(pw_pattern, path) > 0)
  8427. || (match_prefix_strlen(pattern, path) > 0);
  8428. }
  8429. return 0;
  8430. }
  8431. #if !defined(NO_FILESYSTEMS)
  8432. static int
  8433. scan_directory(struct mg_connection *conn,
  8434. const char *dir,
  8435. void *data,
  8436. int (*cb)(struct de *, void *))
  8437. {
  8438. char path[UTF8_PATH_MAX];
  8439. struct dirent *dp;
  8440. DIR *dirp;
  8441. struct de de;
  8442. int truncated;
  8443. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8444. return 0;
  8445. } else {
  8446. while ((dp = mg_readdir(dirp)) != NULL) {
  8447. /* Do not show current dir and hidden files */
  8448. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8449. || must_hide_file(conn, dp->d_name)) {
  8450. continue;
  8451. }
  8452. mg_snprintf(
  8453. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8454. /* If we don't memset stat structure to zero, mtime will have
  8455. * garbage and strftime() will segfault later on in
  8456. * print_dir_entry(). memset is required only if mg_stat()
  8457. * fails. For more details, see
  8458. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8459. memset(&de.file, 0, sizeof(de.file));
  8460. if (truncated) {
  8461. /* If the path is not complete, skip processing. */
  8462. continue;
  8463. }
  8464. if (!mg_stat(conn, path, &de.file)) {
  8465. mg_cry_internal(conn,
  8466. "%s: mg_stat(%s) failed: %s",
  8467. __func__,
  8468. path,
  8469. strerror(ERRNO));
  8470. }
  8471. de.file_name = dp->d_name;
  8472. if (cb(&de, data)) {
  8473. /* stopped */
  8474. break;
  8475. }
  8476. }
  8477. (void)mg_closedir(dirp);
  8478. }
  8479. return 1;
  8480. }
  8481. #endif /* NO_FILESYSTEMS */
  8482. #if !defined(NO_FILES)
  8483. static int
  8484. remove_directory(struct mg_connection *conn, const char *dir)
  8485. {
  8486. char path[UTF8_PATH_MAX];
  8487. struct dirent *dp;
  8488. DIR *dirp;
  8489. struct de de;
  8490. int truncated;
  8491. int ok = 1;
  8492. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8493. return 0;
  8494. } else {
  8495. while ((dp = mg_readdir(dirp)) != NULL) {
  8496. /* Do not show current dir (but show hidden files as they will
  8497. * also be removed) */
  8498. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8499. continue;
  8500. }
  8501. mg_snprintf(
  8502. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8503. /* If we don't memset stat structure to zero, mtime will have
  8504. * garbage and strftime() will segfault later on in
  8505. * print_dir_entry(). memset is required only if mg_stat()
  8506. * fails. For more details, see
  8507. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8508. memset(&de.file, 0, sizeof(de.file));
  8509. if (truncated) {
  8510. /* Do not delete anything shorter */
  8511. ok = 0;
  8512. continue;
  8513. }
  8514. if (!mg_stat(conn, path, &de.file)) {
  8515. mg_cry_internal(conn,
  8516. "%s: mg_stat(%s) failed: %s",
  8517. __func__,
  8518. path,
  8519. strerror(ERRNO));
  8520. ok = 0;
  8521. }
  8522. if (de.file.is_directory) {
  8523. if (remove_directory(conn, path) == 0) {
  8524. ok = 0;
  8525. }
  8526. } else {
  8527. /* This will fail file is the file is in memory */
  8528. if (mg_remove(conn, path) == 0) {
  8529. ok = 0;
  8530. }
  8531. }
  8532. }
  8533. (void)mg_closedir(dirp);
  8534. IGNORE_UNUSED_RESULT(rmdir(dir));
  8535. }
  8536. return ok;
  8537. }
  8538. #endif
  8539. struct dir_scan_data {
  8540. struct de *entries;
  8541. size_t num_entries;
  8542. size_t arr_size;
  8543. };
  8544. #if !defined(NO_FILESYSTEMS)
  8545. static int
  8546. dir_scan_callback(struct de *de, void *data)
  8547. {
  8548. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8549. struct de *entries = dsd->entries;
  8550. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8551. /* Here "entries" is a temporary pointer and can be replaced,
  8552. * "dsd->entries" is the original pointer */
  8553. entries =
  8554. (struct de *)mg_realloc(entries,
  8555. dsd->arr_size * 2 * sizeof(entries[0]));
  8556. if (entries == NULL) {
  8557. /* stop scan */
  8558. return 1;
  8559. }
  8560. dsd->entries = entries;
  8561. dsd->arr_size *= 2;
  8562. }
  8563. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8564. if (entries[dsd->num_entries].file_name == NULL) {
  8565. /* stop scan */
  8566. return 1;
  8567. }
  8568. entries[dsd->num_entries].file = de->file;
  8569. dsd->num_entries++;
  8570. return 0;
  8571. }
  8572. static void
  8573. handle_directory_request(struct mg_connection *conn, const char *dir)
  8574. {
  8575. size_t i;
  8576. int sort_direction;
  8577. struct dir_scan_data data = {NULL, 0, 128};
  8578. char date[64], *esc, *p;
  8579. const char *title;
  8580. time_t curtime = time(NULL);
  8581. if (!conn) {
  8582. return;
  8583. }
  8584. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8585. mg_send_http_error(conn,
  8586. 500,
  8587. "Error: Cannot open directory\nopendir(%s): %s",
  8588. dir,
  8589. strerror(ERRNO));
  8590. return;
  8591. }
  8592. gmt_time_string(date, sizeof(date), &curtime);
  8593. esc = NULL;
  8594. title = conn->request_info.local_uri;
  8595. if (title[strcspn(title, "&<>")]) {
  8596. /* HTML escaping needed */
  8597. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8598. if (esc) {
  8599. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8600. mg_strlcpy(p, title + i, 2);
  8601. if (*p == '&') {
  8602. strcpy(p, "&amp;");
  8603. } else if (*p == '<') {
  8604. strcpy(p, "&lt;");
  8605. } else if (*p == '>') {
  8606. strcpy(p, "&gt;");
  8607. }
  8608. }
  8609. } else {
  8610. title = "";
  8611. }
  8612. }
  8613. sort_direction = ((conn->request_info.query_string != NULL)
  8614. && (conn->request_info.query_string[0] != '\0')
  8615. && (conn->request_info.query_string[1] == 'd'))
  8616. ? 'a'
  8617. : 'd';
  8618. conn->must_close = 1;
  8619. /* Create 200 OK response */
  8620. mg_response_header_start(conn, 200);
  8621. send_static_cache_header(conn);
  8622. send_additional_header(conn);
  8623. mg_response_header_add(conn,
  8624. "Content-Type",
  8625. "text/html; charset=utf-8",
  8626. -1);
  8627. /* Send all headers */
  8628. mg_response_header_send(conn);
  8629. /* Body */
  8630. mg_printf(conn,
  8631. "<html><head><title>Index of %s</title>"
  8632. "<style>th {text-align: left;}</style></head>"
  8633. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8634. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8635. "<th><a href=\"?d%c\">Modified</a></th>"
  8636. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8637. "<tr><td colspan=\"3\"><hr></td></tr>",
  8638. esc ? esc : title,
  8639. esc ? esc : title,
  8640. sort_direction,
  8641. sort_direction,
  8642. sort_direction);
  8643. mg_free(esc);
  8644. /* Print first entry - link to a parent directory */
  8645. mg_printf(conn,
  8646. "<tr><td><a href=\"%s\">%s</a></td>"
  8647. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8648. "..",
  8649. "Parent directory",
  8650. "-",
  8651. "-");
  8652. /* Sort and print directory entries */
  8653. if (data.entries != NULL) {
  8654. mg_sort(data.entries,
  8655. data.num_entries,
  8656. sizeof(data.entries[0]),
  8657. compare_dir_entries,
  8658. (void *)conn->request_info.query_string);
  8659. for (i = 0; i < data.num_entries; i++) {
  8660. print_dir_entry(conn, &data.entries[i]);
  8661. mg_free(data.entries[i].file_name);
  8662. }
  8663. mg_free(data.entries);
  8664. }
  8665. mg_printf(conn, "%s", "</table></pre></body></html>");
  8666. conn->status_code = 200;
  8667. }
  8668. #endif /* NO_FILESYSTEMS */
  8669. /* Send len bytes from the opened file to the client. */
  8670. static void
  8671. send_file_data(struct mg_connection *conn,
  8672. struct mg_file *filep,
  8673. int64_t offset,
  8674. int64_t len,
  8675. int no_buffering)
  8676. {
  8677. char buf[MG_BUF_LEN];
  8678. int to_read, num_read, num_written;
  8679. int64_t size;
  8680. if (!filep || !conn) {
  8681. return;
  8682. }
  8683. /* Sanity check the offset */
  8684. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8685. : (int64_t)(filep->stat.size);
  8686. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8687. if (len > 0 && filep->access.fp != NULL) {
  8688. /* file stored on disk */
  8689. #if defined(__linux__)
  8690. /* sendfile is only available for Linux */
  8691. if ((conn->ssl == 0) && (conn->throttle == 0)
  8692. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8693. "yes"))) {
  8694. off_t sf_offs = (off_t)offset;
  8695. ssize_t sf_sent;
  8696. int sf_file = fileno(filep->access.fp);
  8697. int loop_cnt = 0;
  8698. do {
  8699. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8700. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8701. size_t sf_tosend =
  8702. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8703. sf_sent =
  8704. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8705. if (sf_sent > 0) {
  8706. len -= sf_sent;
  8707. offset += sf_sent;
  8708. } else if (loop_cnt == 0) {
  8709. /* This file can not be sent using sendfile.
  8710. * This might be the case for pseudo-files in the
  8711. * /sys/ and /proc/ file system.
  8712. * Use the regular user mode copy code instead. */
  8713. break;
  8714. } else if (sf_sent == 0) {
  8715. /* No error, but 0 bytes sent. May be EOF? */
  8716. return;
  8717. }
  8718. loop_cnt++;
  8719. } while ((len > 0) && (sf_sent >= 0));
  8720. if (sf_sent > 0) {
  8721. return; /* OK */
  8722. }
  8723. /* sf_sent<0 means error, thus fall back to the classic way */
  8724. /* This is always the case, if sf_file is not a "normal" file,
  8725. * e.g., for sending data from the output of a CGI process. */
  8726. offset = (int64_t)sf_offs;
  8727. }
  8728. #endif
  8729. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8730. mg_cry_internal(conn,
  8731. "%s: fseeko() failed: %s",
  8732. __func__,
  8733. strerror(ERRNO));
  8734. mg_send_http_error(
  8735. conn,
  8736. 500,
  8737. "%s",
  8738. "Error: Unable to access file at requested position.");
  8739. } else {
  8740. while (len > 0) {
  8741. /* Calculate how much to read from the file into the buffer. */
  8742. /* If no_buffering is set, we should not wait until the
  8743. * CGI->Server buffer is filled, but send everything
  8744. * immediately. In theory buffering could be turned off using
  8745. * setbuf(filep->access.fp, NULL);
  8746. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8747. * but in practice this does not work. A "Linux only" solution
  8748. * may be to use select(). The only portable way is to read byte
  8749. * by byte, but this is quite inefficient from a performance
  8750. * point of view. */
  8751. to_read = no_buffering ? 1 : sizeof(buf);
  8752. if ((int64_t)to_read > len) {
  8753. to_read = (int)len;
  8754. }
  8755. /* Read from file, exit the loop on error */
  8756. if ((num_read =
  8757. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8758. <= 0) {
  8759. break;
  8760. }
  8761. /* Send read bytes to the client, exit the loop on error */
  8762. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8763. != num_read) {
  8764. break;
  8765. }
  8766. /* Both read and were successful, adjust counters */
  8767. len -= num_written;
  8768. }
  8769. }
  8770. }
  8771. }
  8772. static int
  8773. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8774. {
  8775. return sscanf(header,
  8776. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8777. a,
  8778. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8779. // to an integer value, but function will not report
  8780. // conversion errors; consider using 'strtol' instead
  8781. }
  8782. static void
  8783. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8784. {
  8785. if ((filestat != NULL) && (buf != NULL)) {
  8786. mg_snprintf(NULL,
  8787. NULL, /* All calls to construct_etag use 64 byte buffer */
  8788. buf,
  8789. buf_len,
  8790. "\"%lx.%" INT64_FMT "\"",
  8791. (unsigned long)filestat->last_modified,
  8792. filestat->size);
  8793. }
  8794. }
  8795. static void
  8796. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8797. {
  8798. if (filep != NULL && filep->fp != NULL) {
  8799. #if defined(_WIN32)
  8800. (void)conn; /* Unused. */
  8801. #else
  8802. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8803. mg_cry_internal(conn,
  8804. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8805. __func__,
  8806. strerror(ERRNO));
  8807. }
  8808. #endif
  8809. }
  8810. }
  8811. #if defined(USE_ZLIB)
  8812. #include "mod_zlib.inl"
  8813. #endif
  8814. #if !defined(NO_FILESYSTEMS)
  8815. static void
  8816. handle_static_file_request(struct mg_connection *conn,
  8817. const char *path,
  8818. struct mg_file *filep,
  8819. const char *mime_type,
  8820. const char *additional_headers)
  8821. {
  8822. char lm[64], etag[64];
  8823. char range[128]; /* large enough, so there will be no overflow */
  8824. const char *range_hdr;
  8825. int64_t cl, r1, r2;
  8826. struct vec mime_vec;
  8827. int n, truncated;
  8828. char gz_path[UTF8_PATH_MAX];
  8829. const char *encoding = 0;
  8830. int is_head_request;
  8831. #if defined(USE_ZLIB)
  8832. /* Compression is allowed, unless there is a reason not to use
  8833. * compression. If the file is already compressed, too small or a
  8834. * "range" request was made, on the fly compression is not possible. */
  8835. int allow_on_the_fly_compression = 1;
  8836. #endif
  8837. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8838. return;
  8839. }
  8840. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8841. if (mime_type == NULL) {
  8842. get_mime_type(conn, path, &mime_vec);
  8843. } else {
  8844. mime_vec.ptr = mime_type;
  8845. mime_vec.len = strlen(mime_type);
  8846. }
  8847. if (filep->stat.size > INT64_MAX) {
  8848. mg_send_http_error(conn,
  8849. 500,
  8850. "Error: File size is too large to send\n%" INT64_FMT,
  8851. filep->stat.size);
  8852. return;
  8853. }
  8854. cl = (int64_t)filep->stat.size;
  8855. conn->status_code = 200;
  8856. range[0] = '\0';
  8857. #if defined(USE_ZLIB)
  8858. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8859. * it's important to rewrite the filename after resolving
  8860. * the mime type from it, to preserve the actual file's type */
  8861. if (!conn->accept_gzip) {
  8862. allow_on_the_fly_compression = 0;
  8863. }
  8864. #endif
  8865. /* Check if there is a range header */
  8866. range_hdr = mg_get_header(conn, "Range");
  8867. /* For gzipped files, add *.gz */
  8868. if (filep->stat.is_gzipped) {
  8869. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8870. if (truncated) {
  8871. mg_send_http_error(conn,
  8872. 500,
  8873. "Error: Path of zipped file too long (%s)",
  8874. path);
  8875. return;
  8876. }
  8877. path = gz_path;
  8878. encoding = "gzip";
  8879. #if defined(USE_ZLIB)
  8880. /* File is already compressed. No "on the fly" compression. */
  8881. allow_on_the_fly_compression = 0;
  8882. #endif
  8883. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8884. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8885. struct mg_file_stat file_stat;
  8886. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8887. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8888. && !file_stat.is_directory) {
  8889. file_stat.is_gzipped = 1;
  8890. filep->stat = file_stat;
  8891. cl = (int64_t)filep->stat.size;
  8892. path = gz_path;
  8893. encoding = "gzip";
  8894. #if defined(USE_ZLIB)
  8895. /* File is already compressed. No "on the fly" compression. */
  8896. allow_on_the_fly_compression = 0;
  8897. #endif
  8898. }
  8899. }
  8900. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8901. mg_send_http_error(conn,
  8902. 500,
  8903. "Error: Cannot open file\nfopen(%s): %s",
  8904. path,
  8905. strerror(ERRNO));
  8906. return;
  8907. }
  8908. fclose_on_exec(&filep->access, conn);
  8909. /* If "Range" request was made: parse header, send only selected part
  8910. * of the file. */
  8911. r1 = r2 = 0;
  8912. if ((range_hdr != NULL)
  8913. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8914. && (r2 >= 0)) {
  8915. /* actually, range requests don't play well with a pre-gzipped
  8916. * file (since the range is specified in the uncompressed space) */
  8917. if (filep->stat.is_gzipped) {
  8918. mg_send_http_error(
  8919. conn,
  8920. 416, /* 416 = Range Not Satisfiable */
  8921. "%s",
  8922. "Error: Range requests in gzipped files are not supported");
  8923. (void)mg_fclose(
  8924. &filep->access); /* ignore error on read only file */
  8925. return;
  8926. }
  8927. conn->status_code = 206;
  8928. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8929. mg_snprintf(conn,
  8930. NULL, /* range buffer is big enough */
  8931. range,
  8932. sizeof(range),
  8933. "bytes "
  8934. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8935. r1,
  8936. r1 + cl - 1,
  8937. filep->stat.size);
  8938. #if defined(USE_ZLIB)
  8939. /* Do not compress ranges. */
  8940. allow_on_the_fly_compression = 0;
  8941. #endif
  8942. }
  8943. /* Do not compress small files. Small files do not benefit from file
  8944. * compression, but there is still some overhead. */
  8945. #if defined(USE_ZLIB)
  8946. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8947. /* File is below the size limit. */
  8948. allow_on_the_fly_compression = 0;
  8949. }
  8950. #endif
  8951. /* Prepare Etag, and Last-Modified headers. */
  8952. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8953. construct_etag(etag, sizeof(etag), &filep->stat);
  8954. /* Create 2xx (200, 206) response */
  8955. mg_response_header_start(conn, conn->status_code);
  8956. send_static_cache_header(conn);
  8957. send_additional_header(conn);
  8958. send_cors_header(conn);
  8959. mg_response_header_add(conn,
  8960. "Content-Type",
  8961. mime_vec.ptr,
  8962. (int)mime_vec.len);
  8963. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8964. mg_response_header_add(conn, "Etag", etag, -1);
  8965. #if defined(USE_ZLIB)
  8966. /* On the fly compression allowed */
  8967. if (allow_on_the_fly_compression) {
  8968. /* For on the fly compression, we don't know the content size in
  8969. * advance, so we have to use chunked encoding */
  8970. encoding = "gzip";
  8971. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8972. /* HTTP/2 is always using "chunks" (frames) */
  8973. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8974. }
  8975. } else
  8976. #endif
  8977. {
  8978. /* Without on-the-fly compression, we know the content-length
  8979. * and we can use ranges (with on-the-fly compression we cannot).
  8980. * So we send these response headers only in this case. */
  8981. char len[32];
  8982. int trunc = 0;
  8983. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8984. if (!trunc) {
  8985. mg_response_header_add(conn, "Content-Length", len, -1);
  8986. }
  8987. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8988. }
  8989. if (encoding) {
  8990. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8991. }
  8992. if (range[0] != 0) {
  8993. mg_response_header_add(conn, "Content-Range", range, -1);
  8994. }
  8995. /* The code above does not add any header starting with X- to make
  8996. * sure no one of the additional_headers is included twice */
  8997. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8998. mg_response_header_add_lines(conn, additional_headers);
  8999. }
  9000. /* Send all headers */
  9001. mg_response_header_send(conn);
  9002. if (!is_head_request) {
  9003. #if defined(USE_ZLIB)
  9004. if (allow_on_the_fly_compression) {
  9005. /* Compress and send */
  9006. send_compressed_data(conn, filep);
  9007. } else
  9008. #endif
  9009. {
  9010. /* Send file directly */
  9011. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9012. }
  9013. }
  9014. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9015. }
  9016. CIVETWEB_API int
  9017. mg_send_file_body(struct mg_connection *conn, const char *path)
  9018. {
  9019. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9020. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9021. return -1;
  9022. }
  9023. fclose_on_exec(&file.access, conn);
  9024. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9025. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9026. return 0; /* >= 0 for OK */
  9027. }
  9028. #endif /* NO_FILESYSTEMS */
  9029. #if !defined(NO_CACHING)
  9030. /* Return True if we should reply 304 Not Modified. */
  9031. static int
  9032. is_not_modified(const struct mg_connection *conn,
  9033. const struct mg_file_stat *filestat)
  9034. {
  9035. char etag[64];
  9036. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9037. const char *inm = mg_get_header(conn, "If-None-Match");
  9038. construct_etag(etag, sizeof(etag), filestat);
  9039. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9040. || ((ims != NULL)
  9041. && (filestat->last_modified <= parse_date_string(ims)));
  9042. }
  9043. static void
  9044. handle_not_modified_static_file_request(struct mg_connection *conn,
  9045. struct mg_file *filep)
  9046. {
  9047. char lm[64], etag[64];
  9048. if ((conn == NULL) || (filep == NULL)) {
  9049. return;
  9050. }
  9051. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9052. construct_etag(etag, sizeof(etag), &filep->stat);
  9053. /* Create 304 "not modified" response */
  9054. mg_response_header_start(conn, 304);
  9055. send_static_cache_header(conn);
  9056. send_additional_header(conn);
  9057. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9058. mg_response_header_add(conn, "Etag", etag, -1);
  9059. /* Send all headers */
  9060. mg_response_header_send(conn);
  9061. }
  9062. #endif
  9063. #if !defined(NO_FILESYSTEMS)
  9064. CIVETWEB_API void
  9065. mg_send_file(struct mg_connection *conn, const char *path)
  9066. {
  9067. mg_send_mime_file2(conn, path, NULL, NULL);
  9068. }
  9069. CIVETWEB_API void
  9070. mg_send_mime_file(struct mg_connection *conn,
  9071. const char *path,
  9072. const char *mime_type)
  9073. {
  9074. mg_send_mime_file2(conn, path, mime_type, NULL);
  9075. }
  9076. CIVETWEB_API void
  9077. mg_send_mime_file2(struct mg_connection *conn,
  9078. const char *path,
  9079. const char *mime_type,
  9080. const char *additional_headers)
  9081. {
  9082. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9083. if (!conn) {
  9084. /* No conn */
  9085. return;
  9086. }
  9087. if (mg_stat(conn, path, &file.stat)) {
  9088. #if !defined(NO_CACHING)
  9089. if (is_not_modified(conn, &file.stat)) {
  9090. /* Send 304 "Not Modified" - this must not send any body data */
  9091. handle_not_modified_static_file_request(conn, &file);
  9092. } else
  9093. #endif /* NO_CACHING */
  9094. if (file.stat.is_directory) {
  9095. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9096. "yes")) {
  9097. handle_directory_request(conn, path);
  9098. } else {
  9099. mg_send_http_error(conn,
  9100. 403,
  9101. "%s",
  9102. "Error: Directory listing denied");
  9103. }
  9104. } else {
  9105. handle_static_file_request(
  9106. conn, path, &file, mime_type, additional_headers);
  9107. }
  9108. } else {
  9109. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9110. }
  9111. }
  9112. /* For a given PUT path, create all intermediate subdirectories.
  9113. * Return 0 if the path itself is a directory.
  9114. * Return 1 if the path leads to a file.
  9115. * Return -1 for if the path is too long.
  9116. * Return -2 if path can not be created.
  9117. */
  9118. static int
  9119. put_dir(struct mg_connection *conn, const char *path)
  9120. {
  9121. char buf[UTF8_PATH_MAX];
  9122. const char *s, *p;
  9123. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9124. size_t len;
  9125. int res = 1;
  9126. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9127. len = (size_t)(p - path);
  9128. if (len >= sizeof(buf)) {
  9129. /* path too long */
  9130. res = -1;
  9131. break;
  9132. }
  9133. memcpy(buf, path, len);
  9134. buf[len] = '\0';
  9135. /* Try to create intermediate directory */
  9136. DEBUG_TRACE("mkdir(%s)", buf);
  9137. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9138. /* path does not exixt and can not be created */
  9139. res = -2;
  9140. break;
  9141. }
  9142. /* Is path itself a directory? */
  9143. if (p[1] == '\0') {
  9144. res = 0;
  9145. }
  9146. }
  9147. return res;
  9148. }
  9149. static void
  9150. remove_bad_file(const struct mg_connection *conn, const char *path)
  9151. {
  9152. int r = mg_remove(conn, path);
  9153. if (r != 0) {
  9154. mg_cry_internal(conn,
  9155. "%s: Cannot remove invalid file %s",
  9156. __func__,
  9157. path);
  9158. }
  9159. }
  9160. CIVETWEB_API long long
  9161. mg_store_body(struct mg_connection *conn, const char *path)
  9162. {
  9163. char buf[MG_BUF_LEN];
  9164. long long len = 0;
  9165. int ret, n;
  9166. struct mg_file fi;
  9167. if (conn->consumed_content != 0) {
  9168. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9169. return -11;
  9170. }
  9171. ret = put_dir(conn, path);
  9172. if (ret < 0) {
  9173. /* -1 for path too long,
  9174. * -2 for path can not be created. */
  9175. return ret;
  9176. }
  9177. if (ret != 1) {
  9178. /* Return 0 means, path itself is a directory. */
  9179. return 0;
  9180. }
  9181. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9182. return -12;
  9183. }
  9184. ret = mg_read(conn, buf, sizeof(buf));
  9185. while (ret > 0) {
  9186. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9187. if (n != ret) {
  9188. (void)mg_fclose(
  9189. &fi.access); /* File is bad and will be removed anyway. */
  9190. remove_bad_file(conn, path);
  9191. return -13;
  9192. }
  9193. len += ret;
  9194. ret = mg_read(conn, buf, sizeof(buf));
  9195. }
  9196. /* File is open for writing. If fclose fails, there was probably an
  9197. * error flushing the buffer to disk, so the file on disk might be
  9198. * broken. Delete it and return an error to the caller. */
  9199. if (mg_fclose(&fi.access) != 0) {
  9200. remove_bad_file(conn, path);
  9201. return -14;
  9202. }
  9203. return len;
  9204. }
  9205. #endif /* NO_FILESYSTEMS */
  9206. /* Parse a buffer:
  9207. * Forward the string pointer till the end of a word, then
  9208. * terminate it and forward till the begin of the next word.
  9209. */
  9210. static int
  9211. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9212. {
  9213. /* Forward until a space is found - use isgraph here */
  9214. /* See http://www.cplusplus.com/reference/cctype/ */
  9215. while (isgraph((unsigned char)**ppw)) {
  9216. (*ppw)++;
  9217. }
  9218. /* Check end of word */
  9219. if (eol) {
  9220. /* must be a end of line */
  9221. if ((**ppw != '\r') && (**ppw != '\n')) {
  9222. return -1;
  9223. }
  9224. } else {
  9225. /* must be a end of a word, but not a line */
  9226. if (**ppw != ' ') {
  9227. return -1;
  9228. }
  9229. }
  9230. /* Terminate and forward to the next word */
  9231. do {
  9232. **ppw = 0;
  9233. (*ppw)++;
  9234. } while (isspace((unsigned char)**ppw));
  9235. /* Check after term */
  9236. if (!eol) {
  9237. /* if it's not the end of line, there must be a next word */
  9238. if (!isgraph((unsigned char)**ppw)) {
  9239. return -1;
  9240. }
  9241. }
  9242. /* ok */
  9243. return 1;
  9244. }
  9245. /* Parse HTTP headers from the given buffer, advance buf pointer
  9246. * to the point where parsing stopped.
  9247. * All parameters must be valid pointers (not NULL).
  9248. * Return <0 on error. */
  9249. static int
  9250. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9251. {
  9252. int i;
  9253. int num_headers = 0;
  9254. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9255. char *dp = *buf;
  9256. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9257. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9258. dp++;
  9259. }
  9260. if (dp == *buf) {
  9261. /* End of headers reached. */
  9262. break;
  9263. }
  9264. /* Drop all spaces after header name before : */
  9265. while (*dp == ' ') {
  9266. *dp = 0;
  9267. dp++;
  9268. }
  9269. if (*dp != ':') {
  9270. /* This is not a valid field. */
  9271. return -1;
  9272. }
  9273. /* End of header key (*dp == ':') */
  9274. /* Truncate here and set the key name */
  9275. *dp = 0;
  9276. hdr[i].name = *buf;
  9277. /* Skip all spaces */
  9278. do {
  9279. dp++;
  9280. } while ((*dp == ' ') || (*dp == '\t'));
  9281. /* The rest of the line is the value */
  9282. hdr[i].value = dp;
  9283. /* Find end of line */
  9284. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9285. dp++;
  9286. };
  9287. /* eliminate \r */
  9288. if (*dp == '\r') {
  9289. *dp = 0;
  9290. dp++;
  9291. if (*dp != '\n') {
  9292. /* This is not a valid line. */
  9293. return -1;
  9294. }
  9295. }
  9296. /* here *dp is either 0 or '\n' */
  9297. /* in any case, we have a new header */
  9298. num_headers = i + 1;
  9299. if (*dp) {
  9300. *dp = 0;
  9301. dp++;
  9302. *buf = dp;
  9303. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9304. /* This is the end of the header */
  9305. break;
  9306. }
  9307. } else {
  9308. *buf = dp;
  9309. break;
  9310. }
  9311. }
  9312. return num_headers;
  9313. }
  9314. struct mg_http_method_info {
  9315. const char *name;
  9316. int request_has_body;
  9317. int response_has_body;
  9318. int is_safe;
  9319. int is_idempotent;
  9320. int is_cacheable;
  9321. };
  9322. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9323. static const struct mg_http_method_info http_methods[] = {
  9324. /* HTTP (RFC 2616) */
  9325. {"GET", 0, 1, 1, 1, 1},
  9326. {"POST", 1, 1, 0, 0, 0},
  9327. {"PUT", 1, 0, 0, 1, 0},
  9328. {"DELETE", 0, 0, 0, 1, 0},
  9329. {"HEAD", 0, 0, 1, 1, 1},
  9330. {"OPTIONS", 0, 0, 1, 1, 0},
  9331. {"CONNECT", 1, 1, 0, 0, 0},
  9332. /* TRACE method (RFC 2616) is not supported for security reasons */
  9333. /* PATCH method (RFC 5789) */
  9334. {"PATCH", 1, 0, 0, 0, 0},
  9335. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9336. /* WEBDAV (RFC 2518) */
  9337. {"PROPFIND", 0, 1, 1, 1, 0},
  9338. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9339. * Some PROPFIND results MAY be cached, with care,
  9340. * as there is no cache validation mechanism for
  9341. * most properties. This method is both safe and
  9342. * idempotent (see Section 9.1 of [RFC2616]). */
  9343. {"MKCOL", 0, 0, 0, 1, 0},
  9344. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9345. * When MKCOL is invoked without a request body,
  9346. * the newly created collection SHOULD have no
  9347. * members. A MKCOL request message may contain
  9348. * a message body. The precise behavior of a MKCOL
  9349. * request when the body is present is undefined,
  9350. * ... ==> We do not support MKCOL with body data.
  9351. * This method is idempotent, but not safe (see
  9352. * Section 9.1 of [RFC2616]). Responses to this
  9353. * method MUST NOT be cached. */
  9354. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9355. {"LOCK", 1, 1, 0, 0, 0},
  9356. {"UNLOCK", 1, 0, 0, 0, 0},
  9357. {"PROPPATCH", 1, 1, 0, 0, 0},
  9358. {"COPY", 1, 0, 0, 0, 0},
  9359. {"MOVE", 1, 1, 0, 0, 0},
  9360. /* Unsupported WEBDAV Methods: */
  9361. /* + 11 methods from RFC 3253 */
  9362. /* ORDERPATCH (RFC 3648) */
  9363. /* ACL (RFC 3744) */
  9364. /* SEARCH (RFC 5323) */
  9365. /* + MicroSoft extensions
  9366. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9367. /* REPORT method (RFC 3253) */
  9368. {"REPORT", 1, 1, 1, 1, 1},
  9369. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9370. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9371. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9372. * to be useful for REST in case a "GET request with body" is
  9373. * required. */
  9374. {NULL, 0, 0, 0, 0, 0}
  9375. /* end of list */
  9376. };
  9377. /* All method names */
  9378. static char *all_methods = NULL; /* Built by mg_init_library */
  9379. static const struct mg_http_method_info *
  9380. get_http_method_info(const char *method)
  9381. {
  9382. /* Check if the method is known to the server. The list of all known
  9383. * HTTP methods can be found here at
  9384. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9385. */
  9386. const struct mg_http_method_info *m = http_methods;
  9387. while (m->name) {
  9388. if (!strcmp(m->name, method)) {
  9389. return m;
  9390. }
  9391. m++;
  9392. }
  9393. return NULL;
  9394. }
  9395. static int
  9396. is_valid_http_method(const char *method)
  9397. {
  9398. return (get_http_method_info(method) != NULL);
  9399. }
  9400. /* Parse HTTP request, fill in mg_request_info structure.
  9401. * This function modifies the buffer by NUL-terminating
  9402. * HTTP request components, header names and header values.
  9403. * Parameters:
  9404. * buf (in/out): pointer to the HTTP header to parse and split
  9405. * len (in): length of HTTP header buffer
  9406. * re (out): parsed header as mg_request_info
  9407. * buf and ri must be valid pointers (not NULL), len>0.
  9408. * Returns <0 on error. */
  9409. static int
  9410. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9411. {
  9412. int request_length;
  9413. int init_skip = 0;
  9414. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9415. * remote_port */
  9416. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9417. NULL;
  9418. ri->num_headers = 0;
  9419. /* RFC says that all initial whitespaces should be ignored */
  9420. /* This included all leading \r and \n (isspace) */
  9421. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9422. while ((len > 0) && isspace((unsigned char)*buf)) {
  9423. buf++;
  9424. len--;
  9425. init_skip++;
  9426. }
  9427. if (len == 0) {
  9428. /* Incomplete request */
  9429. return 0;
  9430. }
  9431. /* Control characters are not allowed, including zero */
  9432. if (iscntrl((unsigned char)*buf)) {
  9433. return -1;
  9434. }
  9435. /* Find end of HTTP header */
  9436. request_length = get_http_header_len(buf, len);
  9437. if (request_length <= 0) {
  9438. return request_length;
  9439. }
  9440. buf[request_length - 1] = '\0';
  9441. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9442. return -1;
  9443. }
  9444. /* The first word has to be the HTTP method */
  9445. ri->request_method = buf;
  9446. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9447. return -1;
  9448. }
  9449. /* The second word is the URI */
  9450. ri->request_uri = buf;
  9451. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9452. return -1;
  9453. }
  9454. /* Next would be the HTTP version */
  9455. ri->http_version = buf;
  9456. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9457. return -1;
  9458. }
  9459. /* Check for a valid HTTP version key */
  9460. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9461. /* Invalid request */
  9462. return -1;
  9463. }
  9464. ri->http_version += 5;
  9465. /* Check for a valid http method */
  9466. if (!is_valid_http_method(ri->request_method)) {
  9467. return -1;
  9468. }
  9469. /* Parse all HTTP headers */
  9470. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9471. if (ri->num_headers < 0) {
  9472. /* Error while parsing headers */
  9473. return -1;
  9474. }
  9475. return request_length + init_skip;
  9476. }
  9477. static int
  9478. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9479. {
  9480. int response_length;
  9481. int init_skip = 0;
  9482. char *tmp, *tmp2;
  9483. long l;
  9484. /* Initialize elements. */
  9485. ri->http_version = ri->status_text = NULL;
  9486. ri->num_headers = ri->status_code = 0;
  9487. /* RFC says that all initial whitespaces should be ingored */
  9488. /* This included all leading \r and \n (isspace) */
  9489. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9490. while ((len > 0) && isspace((unsigned char)*buf)) {
  9491. buf++;
  9492. len--;
  9493. init_skip++;
  9494. }
  9495. if (len == 0) {
  9496. /* Incomplete request */
  9497. return 0;
  9498. }
  9499. /* Control characters are not allowed, including zero */
  9500. if (iscntrl((unsigned char)*buf)) {
  9501. return -1;
  9502. }
  9503. /* Find end of HTTP header */
  9504. response_length = get_http_header_len(buf, len);
  9505. if (response_length <= 0) {
  9506. return response_length;
  9507. }
  9508. buf[response_length - 1] = '\0';
  9509. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9510. return -1;
  9511. }
  9512. /* The first word is the HTTP version */
  9513. /* Check for a valid HTTP version key */
  9514. if (strncmp(buf, "HTTP/", 5) != 0) {
  9515. /* Invalid request */
  9516. return -1;
  9517. }
  9518. buf += 5;
  9519. if (!isgraph((unsigned char)buf[0])) {
  9520. /* Invalid request */
  9521. return -1;
  9522. }
  9523. ri->http_version = buf;
  9524. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9525. return -1;
  9526. }
  9527. /* The second word is the status as a number */
  9528. tmp = buf;
  9529. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9530. return -1;
  9531. }
  9532. l = strtol(tmp, &tmp2, 10);
  9533. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9534. /* Everything else but a 3 digit code is invalid */
  9535. return -1;
  9536. }
  9537. ri->status_code = (int)l;
  9538. /* The rest of the line is the status text */
  9539. ri->status_text = buf;
  9540. /* Find end of status text */
  9541. /* isgraph or isspace = isprint */
  9542. while (isprint((unsigned char)*buf)) {
  9543. buf++;
  9544. }
  9545. if ((*buf != '\r') && (*buf != '\n')) {
  9546. return -1;
  9547. }
  9548. /* Terminate string and forward buf to next line */
  9549. do {
  9550. *buf = 0;
  9551. buf++;
  9552. } while (isspace((unsigned char)*buf));
  9553. /* Parse all HTTP headers */
  9554. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9555. if (ri->num_headers < 0) {
  9556. /* Error while parsing headers */
  9557. return -1;
  9558. }
  9559. return response_length + init_skip;
  9560. }
  9561. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9562. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9563. * buffer (which marks the end of HTTP request). Buffer buf may already
  9564. * have some data. The length of the data is stored in nread.
  9565. * Upon every read operation, increase nread by the number of bytes read. */
  9566. static int
  9567. read_message(FILE *fp,
  9568. struct mg_connection *conn,
  9569. char *buf,
  9570. int bufsiz,
  9571. int *nread)
  9572. {
  9573. int request_len, n = 0;
  9574. struct timespec last_action_time;
  9575. double request_timeout;
  9576. if (!conn) {
  9577. return 0;
  9578. }
  9579. memset(&last_action_time, 0, sizeof(last_action_time));
  9580. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9581. /* value of request_timeout is in seconds, config in milliseconds */
  9582. request_timeout =
  9583. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9584. } else {
  9585. request_timeout =
  9586. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9587. / 1000.0;
  9588. }
  9589. if (conn->handled_requests > 0) {
  9590. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9591. request_timeout =
  9592. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9593. / 1000.0;
  9594. }
  9595. }
  9596. request_len = get_http_header_len(buf, *nread);
  9597. while (request_len == 0) {
  9598. /* Full request not yet received */
  9599. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9600. /* Server is to be stopped. */
  9601. return -1;
  9602. }
  9603. if (*nread >= bufsiz) {
  9604. /* Request too long */
  9605. return -2;
  9606. }
  9607. n = pull_inner(
  9608. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9609. if (n == -2) {
  9610. /* Receive error */
  9611. return -1;
  9612. }
  9613. /* update clock after every read request */
  9614. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9615. if (n > 0) {
  9616. *nread += n;
  9617. request_len = get_http_header_len(buf, *nread);
  9618. }
  9619. if ((request_len == 0) && (request_timeout >= 0)) {
  9620. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9621. > request_timeout) {
  9622. /* Timeout */
  9623. return -1;
  9624. }
  9625. }
  9626. }
  9627. return request_len;
  9628. }
  9629. #if !defined(NO_CGI) || !defined(NO_FILES)
  9630. static int
  9631. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9632. {
  9633. const char *expect;
  9634. char buf[MG_BUF_LEN];
  9635. int success = 0;
  9636. if (!conn) {
  9637. return 0;
  9638. }
  9639. expect = mg_get_header(conn, "Expect");
  9640. DEBUG_ASSERT(fp != NULL);
  9641. if (!fp) {
  9642. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9643. return 0;
  9644. }
  9645. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9646. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9647. */
  9648. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9649. } else {
  9650. if (expect != NULL) {
  9651. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9652. conn->status_code = 100;
  9653. } else {
  9654. conn->status_code = 200;
  9655. }
  9656. DEBUG_ASSERT(conn->consumed_content == 0);
  9657. if (conn->consumed_content != 0) {
  9658. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9659. return 0;
  9660. }
  9661. for (;;) {
  9662. int nread = mg_read(conn, buf, sizeof(buf));
  9663. if (nread <= 0) {
  9664. success = (nread == 0);
  9665. break;
  9666. }
  9667. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9668. break;
  9669. }
  9670. }
  9671. /* Each error code path in this function must send an error */
  9672. if (!success) {
  9673. /* NOTE: Maybe some data has already been sent. */
  9674. /* TODO (low): If some data has been sent, a correct error
  9675. * reply can no longer be sent, so just close the connection */
  9676. mg_send_http_error(conn, 500, "%s", "");
  9677. }
  9678. }
  9679. return success;
  9680. }
  9681. #endif
  9682. #if defined(USE_TIMERS)
  9683. #define TIMER_API static
  9684. #include "timer.inl"
  9685. #endif /* USE_TIMERS */
  9686. #if !defined(NO_CGI)
  9687. /* This structure helps to create an environment for the spawned CGI
  9688. * program.
  9689. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9690. * last element must be NULL.
  9691. * However, on Windows there is a requirement that all these
  9692. * VARIABLE=VALUE\0
  9693. * strings must reside in a contiguous buffer. The end of the buffer is
  9694. * marked by two '\0' characters.
  9695. * We satisfy both worlds: we create an envp array (which is vars), all
  9696. * entries are actually pointers inside buf. */
  9697. struct cgi_environment {
  9698. struct mg_connection *conn;
  9699. /* Data block */
  9700. char *buf; /* Environment buffer */
  9701. size_t buflen; /* Space available in buf */
  9702. size_t bufused; /* Space taken in buf */
  9703. /* Index block */
  9704. char **var; /* char **envp */
  9705. size_t varlen; /* Number of variables available in var */
  9706. size_t varused; /* Number of variables stored in var */
  9707. };
  9708. static void addenv(struct cgi_environment *env,
  9709. PRINTF_FORMAT_STRING(const char *fmt),
  9710. ...) PRINTF_ARGS(2, 3);
  9711. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9712. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9713. static void
  9714. addenv(struct cgi_environment *env, const char *fmt, ...)
  9715. {
  9716. size_t i, n, space;
  9717. int truncated = 0;
  9718. char *added;
  9719. va_list ap;
  9720. if ((env->varlen - env->varused) < 2) {
  9721. mg_cry_internal(env->conn,
  9722. "%s: Cannot register CGI variable [%s]",
  9723. __func__,
  9724. fmt);
  9725. return;
  9726. }
  9727. /* Calculate how much space is left in the buffer */
  9728. space = (env->buflen - env->bufused);
  9729. do {
  9730. /* Space for "\0\0" is always needed. */
  9731. if (space <= 2) {
  9732. /* Allocate new buffer */
  9733. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9734. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9735. if (!added) {
  9736. /* Out of memory */
  9737. mg_cry_internal(
  9738. env->conn,
  9739. "%s: Cannot allocate memory for CGI variable [%s]",
  9740. __func__,
  9741. fmt);
  9742. return;
  9743. }
  9744. /* Retarget pointers */
  9745. env->buf = added;
  9746. env->buflen = n;
  9747. for (i = 0, n = 0; i < env->varused; i++) {
  9748. env->var[i] = added + n;
  9749. n += strlen(added + n) + 1;
  9750. }
  9751. space = (env->buflen - env->bufused);
  9752. }
  9753. /* Make a pointer to the free space int the buffer */
  9754. added = env->buf + env->bufused;
  9755. /* Copy VARIABLE=VALUE\0 string into the free space */
  9756. va_start(ap, fmt);
  9757. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9758. va_end(ap);
  9759. /* Do not add truncated strings to the environment */
  9760. if (truncated) {
  9761. /* Reallocate the buffer */
  9762. space = 0;
  9763. }
  9764. } while (truncated);
  9765. /* Calculate number of bytes added to the environment */
  9766. n = strlen(added) + 1;
  9767. env->bufused += n;
  9768. /* Append a pointer to the added string into the envp array */
  9769. env->var[env->varused] = added;
  9770. env->varused++;
  9771. }
  9772. /* Return 0 on success, non-zero if an error occurs. */
  9773. static int
  9774. prepare_cgi_environment(struct mg_connection *conn,
  9775. const char *prog,
  9776. struct cgi_environment *env,
  9777. unsigned char cgi_config_idx)
  9778. {
  9779. const char *s;
  9780. struct vec var_vec;
  9781. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9782. int i, truncated, uri_len;
  9783. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9784. return -1;
  9785. }
  9786. env->conn = conn;
  9787. env->buflen = CGI_ENVIRONMENT_SIZE;
  9788. env->bufused = 0;
  9789. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9790. if (env->buf == NULL) {
  9791. mg_cry_internal(conn,
  9792. "%s: Not enough memory for environmental buffer",
  9793. __func__);
  9794. return -1;
  9795. }
  9796. env->varlen = MAX_CGI_ENVIR_VARS;
  9797. env->varused = 0;
  9798. env->var =
  9799. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9800. if (env->var == NULL) {
  9801. mg_cry_internal(conn,
  9802. "%s: Not enough memory for environmental variables",
  9803. __func__);
  9804. mg_free(env->buf);
  9805. return -1;
  9806. }
  9807. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9808. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9809. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9810. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9811. /* Prepare the environment block */
  9812. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9813. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9814. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9815. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9816. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9817. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9818. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9819. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9820. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9821. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9822. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9823. /* SCRIPT_NAME */
  9824. uri_len = (int)strlen(conn->request_info.local_uri);
  9825. if (conn->path_info == NULL) {
  9826. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9827. /* URI: /path_to_script/script.cgi */
  9828. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9829. } else {
  9830. /* URI: /path_to_script/ ... using index.cgi */
  9831. const char *index_file = strrchr(prog, '/');
  9832. if (index_file) {
  9833. addenv(env,
  9834. "SCRIPT_NAME=%s%s",
  9835. conn->request_info.local_uri,
  9836. index_file + 1);
  9837. }
  9838. }
  9839. } else {
  9840. /* URI: /path_to_script/script.cgi/path_info */
  9841. addenv(env,
  9842. "SCRIPT_NAME=%.*s",
  9843. uri_len - (int)strlen(conn->path_info),
  9844. conn->request_info.local_uri);
  9845. }
  9846. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9847. if (conn->path_info == NULL) {
  9848. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9849. } else {
  9850. addenv(env,
  9851. "PATH_TRANSLATED=%s%s",
  9852. conn->dom_ctx->config[DOCUMENT_ROOT],
  9853. conn->path_info);
  9854. }
  9855. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9856. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9857. addenv(env, "CONTENT_TYPE=%s", s);
  9858. }
  9859. if (conn->request_info.query_string != NULL) {
  9860. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9861. }
  9862. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9863. addenv(env, "CONTENT_LENGTH=%s", s);
  9864. }
  9865. if ((s = getenv("PATH")) != NULL) {
  9866. addenv(env, "PATH=%s", s);
  9867. }
  9868. if (conn->path_info != NULL) {
  9869. addenv(env, "PATH_INFO=%s", conn->path_info);
  9870. }
  9871. if (conn->status_code > 0) {
  9872. /* CGI error handler should show the status code */
  9873. addenv(env, "STATUS=%d", conn->status_code);
  9874. }
  9875. #if defined(_WIN32)
  9876. if ((s = getenv("COMSPEC")) != NULL) {
  9877. addenv(env, "COMSPEC=%s", s);
  9878. }
  9879. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9880. addenv(env, "SYSTEMROOT=%s", s);
  9881. }
  9882. if ((s = getenv("SystemDrive")) != NULL) {
  9883. addenv(env, "SystemDrive=%s", s);
  9884. }
  9885. if ((s = getenv("ProgramFiles")) != NULL) {
  9886. addenv(env, "ProgramFiles=%s", s);
  9887. }
  9888. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9889. addenv(env, "ProgramFiles(x86)=%s", s);
  9890. }
  9891. #else
  9892. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9893. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9894. }
  9895. #endif /* _WIN32 */
  9896. if ((s = getenv("PERLLIB")) != NULL) {
  9897. addenv(env, "PERLLIB=%s", s);
  9898. }
  9899. if (conn->request_info.remote_user != NULL) {
  9900. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9901. addenv(env, "%s", "AUTH_TYPE=Digest");
  9902. }
  9903. /* Add all headers as HTTP_* variables */
  9904. for (i = 0; i < conn->request_info.num_headers; i++) {
  9905. (void)mg_snprintf(conn,
  9906. &truncated,
  9907. http_var_name,
  9908. sizeof(http_var_name),
  9909. "HTTP_%s",
  9910. conn->request_info.http_headers[i].name);
  9911. if (truncated) {
  9912. mg_cry_internal(conn,
  9913. "%s: HTTP header variable too long [%s]",
  9914. __func__,
  9915. conn->request_info.http_headers[i].name);
  9916. continue;
  9917. }
  9918. /* Convert variable name into uppercase, and change - to _ */
  9919. for (p = http_var_name; *p != '\0'; p++) {
  9920. if (*p == '-') {
  9921. *p = '_';
  9922. }
  9923. *p = (char)toupper((unsigned char)*p);
  9924. }
  9925. addenv(env,
  9926. "%s=%s",
  9927. http_var_name,
  9928. conn->request_info.http_headers[i].value);
  9929. }
  9930. /* Add user-specified variables */
  9931. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9932. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9933. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9934. }
  9935. env->var[env->varused] = NULL;
  9936. env->buf[env->bufused] = '\0';
  9937. return 0;
  9938. }
  9939. /* Data for CGI process control: PID and number of references */
  9940. struct process_control_data {
  9941. pid_t pid;
  9942. ptrdiff_t references;
  9943. };
  9944. static int
  9945. abort_cgi_process(void *data)
  9946. {
  9947. /* Waitpid checks for child status and won't work for a pid that does
  9948. * not identify a child of the current process. Thus, if the pid is
  9949. * reused, we will not affect a different process. */
  9950. struct process_control_data *proc = (struct process_control_data *)data;
  9951. int status = 0;
  9952. ptrdiff_t refs;
  9953. pid_t ret_pid;
  9954. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9955. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9956. /* Stop child process */
  9957. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9958. kill(proc->pid, SIGABRT);
  9959. /* Wait until process is terminated (don't leave zombies) */
  9960. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9961. ;
  9962. } else {
  9963. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9964. }
  9965. /* Dec reference counter */
  9966. refs = mg_atomic_dec(&proc->references);
  9967. if (refs == 0) {
  9968. /* no more references - free data */
  9969. mg_free(data);
  9970. }
  9971. return 0;
  9972. }
  9973. /* Local (static) function assumes all arguments are valid. */
  9974. static void
  9975. handle_cgi_request(struct mg_connection *conn,
  9976. const char *prog,
  9977. unsigned char cgi_config_idx)
  9978. {
  9979. char *buf;
  9980. size_t buflen;
  9981. int headers_len, data_len, i, truncated;
  9982. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9983. const char *status, *status_text;
  9984. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9985. struct mg_request_info ri;
  9986. struct cgi_environment blk;
  9987. FILE *in = NULL, *out = NULL, *err = NULL;
  9988. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9989. pid_t pid = (pid_t)-1;
  9990. struct process_control_data *proc = NULL;
  9991. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  9992. int no_buffering = 0;
  9993. #if defined(USE_TIMERS)
  9994. double cgi_timeout;
  9995. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9996. /* Get timeout in seconds */
  9997. cgi_timeout =
  9998. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9999. } else {
  10000. cgi_timeout =
  10001. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10002. }
  10003. #endif
  10004. if (cfg_buffering != NULL) {
  10005. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10006. no_buffering = 1;
  10007. }
  10008. }
  10009. buf = NULL;
  10010. buflen = conn->phys_ctx->max_request_size;
  10011. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10012. if (i != 0) {
  10013. blk.buf = NULL;
  10014. blk.var = NULL;
  10015. goto done;
  10016. }
  10017. /* CGI must be executed in its own directory. 'dir' must point to the
  10018. * directory containing executable program, 'p' must point to the
  10019. * executable program name relative to 'dir'. */
  10020. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10021. if (truncated) {
  10022. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10023. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10024. goto done;
  10025. }
  10026. if ((p = strrchr(dir, '/')) != NULL) {
  10027. *p++ = '\0';
  10028. } else {
  10029. dir[0] = '.';
  10030. dir[1] = '\0';
  10031. p = (char *)prog;
  10032. }
  10033. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10034. status = strerror(ERRNO);
  10035. mg_cry_internal(
  10036. conn,
  10037. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10038. prog,
  10039. status);
  10040. mg_send_http_error(conn,
  10041. 500,
  10042. "Error: Cannot create CGI pipe: %s",
  10043. status);
  10044. goto done;
  10045. }
  10046. proc = (struct process_control_data *)
  10047. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10048. if (proc == NULL) {
  10049. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10050. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10051. goto done;
  10052. }
  10053. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10054. pid = spawn_process(
  10055. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10056. if (pid == (pid_t)-1) {
  10057. status = strerror(ERRNO);
  10058. mg_cry_internal(
  10059. conn,
  10060. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10061. prog,
  10062. status);
  10063. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10064. mg_free(proc);
  10065. proc = NULL;
  10066. goto done;
  10067. }
  10068. /* Store data in shared process_control_data */
  10069. proc->pid = pid;
  10070. proc->references = 1;
  10071. #if defined(USE_TIMERS)
  10072. if (cgi_timeout > 0.0) {
  10073. proc->references = 2;
  10074. // Start a timer for CGI
  10075. timer_add(conn->phys_ctx,
  10076. cgi_timeout /* in seconds */,
  10077. 0.0,
  10078. 1,
  10079. abort_cgi_process,
  10080. (void *)proc,
  10081. NULL);
  10082. }
  10083. #endif
  10084. /* Parent closes only one side of the pipes.
  10085. * If we don't mark them as closed, close() attempt before
  10086. * return from this function throws an exception on Windows.
  10087. * Windows does not like when closed descriptor is closed again. */
  10088. (void)close(fdin[0]);
  10089. (void)close(fdout[1]);
  10090. (void)close(fderr[1]);
  10091. fdin[0] = fdout[1] = fderr[1] = -1;
  10092. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10093. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10094. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10095. status = strerror(ERRNO);
  10096. mg_cry_internal(conn,
  10097. "Error: CGI program \"%s\": Can not open fd: %s",
  10098. prog,
  10099. status);
  10100. mg_send_http_error(conn,
  10101. 500,
  10102. "Error: CGI can not open fd\nfdopen: %s",
  10103. status);
  10104. goto done;
  10105. }
  10106. setbuf(in, NULL);
  10107. setbuf(out, NULL);
  10108. setbuf(err, NULL);
  10109. fout.access.fp = out;
  10110. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10111. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10112. conn->content_len);
  10113. /* This is a POST/PUT request, or another request with body data. */
  10114. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10115. /* Error sending the body data */
  10116. mg_cry_internal(
  10117. conn,
  10118. "Error: CGI program \"%s\": Forward body data failed",
  10119. prog);
  10120. goto done;
  10121. }
  10122. }
  10123. /* Close so child gets an EOF. */
  10124. fclose(in);
  10125. in = NULL;
  10126. fdin[1] = -1;
  10127. /* Now read CGI reply into a buffer. We need to set correct
  10128. * status code, thus we need to see all HTTP headers first.
  10129. * Do not send anything back to client, until we buffer in all
  10130. * HTTP headers. */
  10131. data_len = 0;
  10132. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10133. if (buf == NULL) {
  10134. mg_send_http_error(conn,
  10135. 500,
  10136. "Error: Not enough memory for CGI buffer (%u bytes)",
  10137. (unsigned int)buflen);
  10138. mg_cry_internal(
  10139. conn,
  10140. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10141. "bytes)",
  10142. prog,
  10143. (unsigned int)buflen);
  10144. goto done;
  10145. }
  10146. DEBUG_TRACE("CGI: %s", "wait for response");
  10147. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10148. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10149. if (headers_len <= 0) {
  10150. /* Could not parse the CGI response. Check if some error message on
  10151. * stderr. */
  10152. i = pull_all(err, conn, buf, (int)buflen);
  10153. if (i > 0) {
  10154. /* CGI program explicitly sent an error */
  10155. /* Write the error message to the internal log */
  10156. mg_cry_internal(conn,
  10157. "Error: CGI program \"%s\" sent error "
  10158. "message: [%.*s]",
  10159. prog,
  10160. i,
  10161. buf);
  10162. /* Don't send the error message back to the client */
  10163. mg_send_http_error(conn,
  10164. 500,
  10165. "Error: CGI program \"%s\" failed.",
  10166. prog);
  10167. } else {
  10168. /* CGI program did not explicitly send an error, but a broken
  10169. * respon header */
  10170. mg_cry_internal(conn,
  10171. "Error: CGI program sent malformed or too big "
  10172. "(>%u bytes) HTTP headers: [%.*s]",
  10173. (unsigned)buflen,
  10174. data_len,
  10175. buf);
  10176. mg_send_http_error(conn,
  10177. 500,
  10178. "Error: CGI program sent malformed or too big "
  10179. "(>%u bytes) HTTP headers: [%.*s]",
  10180. (unsigned)buflen,
  10181. data_len,
  10182. buf);
  10183. }
  10184. /* in both cases, abort processing CGI */
  10185. goto done;
  10186. }
  10187. pbuf = buf;
  10188. buf[headers_len - 1] = '\0';
  10189. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10190. /* Make up and send the status line */
  10191. status_text = "OK";
  10192. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10193. != NULL) {
  10194. conn->status_code = atoi(status);
  10195. status_text = status;
  10196. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10197. status_text++;
  10198. }
  10199. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10200. != NULL) {
  10201. conn->status_code = 307;
  10202. } else {
  10203. conn->status_code = 200;
  10204. }
  10205. if (!should_keep_alive(conn)) {
  10206. conn->must_close = 1;
  10207. }
  10208. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10209. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10210. /* Send headers */
  10211. for (i = 0; i < ri.num_headers; i++) {
  10212. DEBUG_TRACE("CGI header: %s: %s",
  10213. ri.http_headers[i].name,
  10214. ri.http_headers[i].value);
  10215. mg_printf(conn,
  10216. "%s: %s\r\n",
  10217. ri.http_headers[i].name,
  10218. ri.http_headers[i].value);
  10219. }
  10220. mg_write(conn, "\r\n", 2);
  10221. /* Send chunk of data that may have been read after the headers */
  10222. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10223. /* Read the rest of CGI output and send to the client */
  10224. DEBUG_TRACE("CGI: %s", "forward all data");
  10225. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10226. DEBUG_TRACE("CGI: %s", "all data sent");
  10227. done:
  10228. mg_free(blk.var);
  10229. mg_free(blk.buf);
  10230. if (pid != (pid_t)-1) {
  10231. abort_cgi_process((void *)proc);
  10232. }
  10233. if (fdin[0] != -1) {
  10234. close(fdin[0]);
  10235. }
  10236. if (fdout[1] != -1) {
  10237. close(fdout[1]);
  10238. }
  10239. if (fderr[1] != -1) {
  10240. close(fderr[1]);
  10241. }
  10242. if (in != NULL) {
  10243. fclose(in);
  10244. } else if (fdin[1] != -1) {
  10245. close(fdin[1]);
  10246. }
  10247. if (out != NULL) {
  10248. fclose(out);
  10249. } else if (fdout[0] != -1) {
  10250. close(fdout[0]);
  10251. }
  10252. if (err != NULL) {
  10253. fclose(err);
  10254. } else if (fderr[0] != -1) {
  10255. close(fderr[0]);
  10256. }
  10257. mg_free(buf);
  10258. }
  10259. #endif /* !NO_CGI */
  10260. #if !defined(NO_FILES)
  10261. static void
  10262. dav_mkcol(struct mg_connection *conn, const char *path)
  10263. {
  10264. int rc, body_len;
  10265. struct de de;
  10266. if (conn == NULL) {
  10267. return;
  10268. }
  10269. /* TODO (mid): Check the mg_send_http_error situations in this function
  10270. */
  10271. memset(&de.file, 0, sizeof(de.file));
  10272. if (!mg_stat(conn, path, &de.file)) {
  10273. mg_cry_internal(conn,
  10274. "%s: mg_stat(%s) failed: %s",
  10275. __func__,
  10276. path,
  10277. strerror(ERRNO));
  10278. }
  10279. if (de.file.last_modified) {
  10280. /* TODO (mid): This check does not seem to make any sense ! */
  10281. /* TODO (mid): Add a webdav unit test first, before changing
  10282. * anything here. */
  10283. mg_send_http_error(
  10284. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10285. return;
  10286. }
  10287. body_len = conn->data_len - conn->request_len;
  10288. if (body_len > 0) {
  10289. mg_send_http_error(
  10290. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10291. return;
  10292. }
  10293. rc = mg_mkdir(conn, path, 0755);
  10294. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10295. if (rc == 0) {
  10296. /* Create 201 "Created" response */
  10297. mg_response_header_start(conn, 201);
  10298. send_static_cache_header(conn);
  10299. send_additional_header(conn);
  10300. mg_response_header_add(conn, "Content-Length", "0", -1);
  10301. /* Send all headers - there is no body */
  10302. mg_response_header_send(conn);
  10303. } else {
  10304. int http_status = 500;
  10305. switch (errno) {
  10306. case EEXIST:
  10307. http_status = 405;
  10308. break;
  10309. case EACCES:
  10310. http_status = 403;
  10311. break;
  10312. case ENOENT:
  10313. http_status = 409;
  10314. break;
  10315. }
  10316. mg_send_http_error(conn,
  10317. http_status,
  10318. "Error processing %s: %s",
  10319. path,
  10320. strerror(ERRNO));
  10321. }
  10322. }
  10323. /* Forward decrlaration */
  10324. static int get_uri_type(const char *uri);
  10325. static const char *
  10326. get_rel_url_at_current_server(const char *uri,
  10327. const struct mg_connection *conn);
  10328. static void
  10329. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10330. {
  10331. const char *overwrite_hdr;
  10332. const char *destination_hdr;
  10333. const char *root;
  10334. int rc, dest_uri_type;
  10335. int http_status = 400;
  10336. int do_overwrite = 0;
  10337. int destination_ok = 0;
  10338. char dest_path[UTF8_PATH_MAX];
  10339. struct mg_file_stat ignored;
  10340. if (conn == NULL) {
  10341. return;
  10342. }
  10343. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10344. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10345. destination_hdr = mg_get_header(conn, "Destination");
  10346. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10347. do_overwrite = 1;
  10348. }
  10349. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10350. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10351. return;
  10352. }
  10353. if (root != NULL) {
  10354. char *local_dest = NULL;
  10355. dest_uri_type = get_uri_type(destination_hdr);
  10356. if (dest_uri_type == 2) {
  10357. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10358. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10359. const char *h =
  10360. get_rel_url_at_current_server(destination_hdr, conn);
  10361. if (h) {
  10362. int len = (int)strlen(h);
  10363. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10364. mg_url_decode(h, len, local_dest, len + 1, 0);
  10365. }
  10366. }
  10367. if (local_dest != NULL) {
  10368. remove_dot_segments(local_dest);
  10369. if (local_dest[0] == '/') {
  10370. int trunc_check = 0;
  10371. mg_snprintf(conn,
  10372. &trunc_check,
  10373. dest_path,
  10374. sizeof(dest_path),
  10375. "%s/%s",
  10376. root,
  10377. local_dest);
  10378. if (trunc_check == 0) {
  10379. destination_ok = 1;
  10380. }
  10381. }
  10382. mg_free(local_dest);
  10383. }
  10384. }
  10385. if (!destination_ok) {
  10386. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10387. return;
  10388. }
  10389. /* Check now if this file exists */
  10390. if (mg_stat(conn, dest_path, &ignored)) {
  10391. /* File exists */
  10392. if (do_overwrite) {
  10393. /* Overwrite allowed: delete the file first */
  10394. if (0 != remove(dest_path)) {
  10395. /* No overwrite: return error */
  10396. mg_send_http_error(conn,
  10397. 403,
  10398. "Cannot overwrite file: %s",
  10399. dest_path);
  10400. return;
  10401. }
  10402. } else {
  10403. /* No overwrite: return error */
  10404. mg_send_http_error(conn,
  10405. 412,
  10406. "Destination already exists: %s",
  10407. dest_path);
  10408. return;
  10409. }
  10410. }
  10411. /* Copy / Move / Rename operation. */
  10412. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10413. #if defined(_WIN32)
  10414. {
  10415. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10416. wchar_t wSource[UTF16_PATH_MAX];
  10417. wchar_t wDest[UTF16_PATH_MAX];
  10418. BOOL ok;
  10419. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10420. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10421. if (do_copy) {
  10422. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10423. } else {
  10424. ok = MoveFileExW(wSource,
  10425. wDest,
  10426. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10427. }
  10428. if (ok) {
  10429. rc = 0;
  10430. } else {
  10431. DWORD lastErr = GetLastError();
  10432. if (lastErr == ERROR_ALREADY_EXISTS) {
  10433. mg_send_http_error(conn,
  10434. 412,
  10435. "Destination already exists: %s",
  10436. dest_path);
  10437. return;
  10438. }
  10439. rc = -1;
  10440. http_status = 400;
  10441. }
  10442. }
  10443. #else
  10444. {
  10445. /* Linux uses already UTF-8, we don't need to convert file names. */
  10446. if (do_copy) {
  10447. /* TODO: COPY for Linux. */
  10448. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10449. return;
  10450. }
  10451. rc = rename(path, dest_path);
  10452. if (rc) {
  10453. switch (errno) {
  10454. case EEXIST:
  10455. http_status = 412;
  10456. break;
  10457. case EACCES:
  10458. http_status = 403;
  10459. break;
  10460. case ENOENT:
  10461. http_status = 409;
  10462. break;
  10463. }
  10464. }
  10465. }
  10466. #endif
  10467. if (rc == 0) {
  10468. /* Create 204 "No Content" response */
  10469. mg_response_header_start(conn, 204);
  10470. mg_response_header_add(conn, "Content-Length", "0", -1);
  10471. /* Send all headers - there is no body */
  10472. mg_response_header_send(conn);
  10473. } else {
  10474. mg_send_http_error(conn, http_status, "Operation failed");
  10475. }
  10476. }
  10477. static void
  10478. put_file(struct mg_connection *conn, const char *path)
  10479. {
  10480. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10481. const char *range;
  10482. int64_t r1, r2;
  10483. int rc;
  10484. if (conn == NULL) {
  10485. return;
  10486. }
  10487. DEBUG_TRACE("store %s", path);
  10488. if (mg_stat(conn, path, &file.stat)) {
  10489. /* File already exists */
  10490. conn->status_code = 200;
  10491. if (file.stat.is_directory) {
  10492. /* This is an already existing directory,
  10493. * so there is nothing to do for the server. */
  10494. rc = 0;
  10495. } else {
  10496. /* File exists and is not a directory. */
  10497. /* Can it be replaced? */
  10498. /* Check if the server may write this file */
  10499. if (access(path, W_OK) == 0) {
  10500. /* Access granted */
  10501. rc = 1;
  10502. } else {
  10503. mg_send_http_error(
  10504. conn,
  10505. 403,
  10506. "Error: Put not possible\nReplacing %s is not allowed",
  10507. path);
  10508. return;
  10509. }
  10510. }
  10511. } else {
  10512. /* File should be created */
  10513. conn->status_code = 201;
  10514. rc = put_dir(conn, path);
  10515. }
  10516. if (rc == 0) {
  10517. /* put_dir returns 0 if path is a directory */
  10518. /* Create response */
  10519. mg_response_header_start(conn, conn->status_code);
  10520. send_no_cache_header(conn);
  10521. send_additional_header(conn);
  10522. mg_response_header_add(conn, "Content-Length", "0", -1);
  10523. /* Send all headers - there is no body */
  10524. mg_response_header_send(conn);
  10525. /* Request to create a directory has been fulfilled successfully.
  10526. * No need to put a file. */
  10527. return;
  10528. }
  10529. if (rc == -1) {
  10530. /* put_dir returns -1 if the path is too long */
  10531. mg_send_http_error(conn,
  10532. 414,
  10533. "Error: Path too long\nput_dir(%s): %s",
  10534. path,
  10535. strerror(ERRNO));
  10536. return;
  10537. }
  10538. if (rc == -2) {
  10539. /* put_dir returns -2 if the directory can not be created */
  10540. mg_send_http_error(conn,
  10541. 500,
  10542. "Error: Can not create directory\nput_dir(%s): %s",
  10543. path,
  10544. strerror(ERRNO));
  10545. return;
  10546. }
  10547. /* A file should be created or overwritten. */
  10548. /* Currently CivetWeb does not nead read+write access. */
  10549. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10550. || file.access.fp == NULL) {
  10551. (void)mg_fclose(&file.access);
  10552. mg_send_http_error(conn,
  10553. 500,
  10554. "Error: Can not create file\nfopen(%s): %s",
  10555. path,
  10556. strerror(ERRNO));
  10557. return;
  10558. }
  10559. fclose_on_exec(&file.access, conn);
  10560. range = mg_get_header(conn, "Content-Range");
  10561. r1 = r2 = 0;
  10562. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10563. conn->status_code = 206; /* Partial content */
  10564. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10565. mg_send_http_error(conn,
  10566. 500,
  10567. "Error: Internal error processing file %s",
  10568. path);
  10569. return;
  10570. }
  10571. }
  10572. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10573. /* forward_body_data failed.
  10574. * The error code has already been sent to the client,
  10575. * and conn->status_code is already set. */
  10576. (void)mg_fclose(&file.access);
  10577. return;
  10578. }
  10579. if (mg_fclose(&file.access) != 0) {
  10580. /* fclose failed. This might have different reasons, but a likely
  10581. * one is "no space on disk", http 507. */
  10582. conn->status_code = 507;
  10583. }
  10584. /* Create response (status_code has been set before) */
  10585. mg_response_header_start(conn, conn->status_code);
  10586. send_no_cache_header(conn);
  10587. send_additional_header(conn);
  10588. mg_response_header_add(conn, "Content-Length", "0", -1);
  10589. /* Send all headers - there is no body */
  10590. mg_response_header_send(conn);
  10591. }
  10592. static void
  10593. delete_file(struct mg_connection *conn, const char *path)
  10594. {
  10595. struct de de;
  10596. memset(&de.file, 0, sizeof(de.file));
  10597. if (!mg_stat(conn, path, &de.file)) {
  10598. /* mg_stat returns 0 if the file does not exist */
  10599. mg_send_http_error(conn,
  10600. 404,
  10601. "Error: Cannot delete file\nFile %s not found",
  10602. path);
  10603. return;
  10604. }
  10605. DEBUG_TRACE("delete %s", path);
  10606. if (de.file.is_directory) {
  10607. if (remove_directory(conn, path)) {
  10608. /* Delete is successful: Return 204 without content. */
  10609. mg_send_http_error(conn, 204, "%s", "");
  10610. } else {
  10611. /* Delete is not successful: Return 500 (Server error). */
  10612. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10613. }
  10614. return;
  10615. }
  10616. /* This is an existing file (not a directory).
  10617. * Check if write permission is granted. */
  10618. if (access(path, W_OK) != 0) {
  10619. /* File is read only */
  10620. mg_send_http_error(
  10621. conn,
  10622. 403,
  10623. "Error: Delete not possible\nDeleting %s is not allowed",
  10624. path);
  10625. return;
  10626. }
  10627. /* Try to delete it. */
  10628. if (mg_remove(conn, path) == 0) {
  10629. /* Delete was successful: Return 204 without content. */
  10630. mg_response_header_start(conn, 204);
  10631. send_no_cache_header(conn);
  10632. send_additional_header(conn);
  10633. mg_response_header_add(conn, "Content-Length", "0", -1);
  10634. mg_response_header_send(conn);
  10635. } else {
  10636. /* Delete not successful (file locked). */
  10637. mg_send_http_error(conn,
  10638. 423,
  10639. "Error: Cannot delete file\nremove(%s): %s",
  10640. path,
  10641. strerror(ERRNO));
  10642. }
  10643. }
  10644. #endif /* !NO_FILES */
  10645. #if !defined(NO_FILESYSTEMS)
  10646. static void
  10647. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10648. static void
  10649. do_ssi_include(struct mg_connection *conn,
  10650. const char *ssi,
  10651. char *tag,
  10652. int include_level)
  10653. {
  10654. char file_name[MG_BUF_LEN], path[512], *p;
  10655. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10656. size_t len;
  10657. int truncated = 0;
  10658. if (conn == NULL) {
  10659. return;
  10660. }
  10661. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10662. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10663. * always < MG_BUF_LEN. */
  10664. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10665. /* File name is relative to the webserver root */
  10666. file_name[511] = 0;
  10667. (void)mg_snprintf(conn,
  10668. &truncated,
  10669. path,
  10670. sizeof(path),
  10671. "%s/%s",
  10672. conn->dom_ctx->config[DOCUMENT_ROOT],
  10673. file_name);
  10674. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10675. /* File name is relative to the webserver working directory
  10676. * or it is absolute system path */
  10677. file_name[511] = 0;
  10678. (void)
  10679. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10680. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10681. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10682. /* File name is relative to the currect document */
  10683. file_name[511] = 0;
  10684. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10685. if (!truncated) {
  10686. if ((p = strrchr(path, '/')) != NULL) {
  10687. p[1] = '\0';
  10688. }
  10689. len = strlen(path);
  10690. (void)mg_snprintf(conn,
  10691. &truncated,
  10692. path + len,
  10693. sizeof(path) - len,
  10694. "%s",
  10695. file_name);
  10696. }
  10697. } else {
  10698. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10699. return;
  10700. }
  10701. if (truncated) {
  10702. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10703. return;
  10704. }
  10705. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10706. mg_cry_internal(conn,
  10707. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10708. tag,
  10709. path,
  10710. strerror(ERRNO));
  10711. } else {
  10712. fclose_on_exec(&file.access, conn);
  10713. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10714. > 0) {
  10715. send_ssi_file(conn, path, &file, include_level + 1);
  10716. } else {
  10717. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10718. }
  10719. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10720. }
  10721. }
  10722. #if !defined(NO_POPEN)
  10723. static void
  10724. do_ssi_exec(struct mg_connection *conn, char *tag)
  10725. {
  10726. char cmd[1024] = "";
  10727. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10728. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10729. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10730. } else {
  10731. cmd[1023] = 0;
  10732. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10733. mg_cry_internal(conn,
  10734. "Cannot SSI #exec: [%s]: %s",
  10735. cmd,
  10736. strerror(ERRNO));
  10737. } else {
  10738. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10739. pclose(file.access.fp);
  10740. }
  10741. }
  10742. }
  10743. #endif /* !NO_POPEN */
  10744. static int
  10745. mg_fgetc(struct mg_file *filep)
  10746. {
  10747. if (filep == NULL) {
  10748. return EOF;
  10749. }
  10750. if (filep->access.fp != NULL) {
  10751. return fgetc(filep->access.fp);
  10752. } else {
  10753. return EOF;
  10754. }
  10755. }
  10756. static void
  10757. send_ssi_file(struct mg_connection *conn,
  10758. const char *path,
  10759. struct mg_file *filep,
  10760. int include_level)
  10761. {
  10762. char buf[MG_BUF_LEN];
  10763. int ch, len, in_tag, in_ssi_tag;
  10764. if (include_level > 10) {
  10765. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10766. return;
  10767. }
  10768. in_tag = in_ssi_tag = len = 0;
  10769. /* Read file, byte by byte, and look for SSI include tags */
  10770. while ((ch = mg_fgetc(filep)) != EOF) {
  10771. if (in_tag) {
  10772. /* We are in a tag, either SSI tag or html tag */
  10773. if (ch == '>') {
  10774. /* Tag is closing */
  10775. buf[len++] = '>';
  10776. if (in_ssi_tag) {
  10777. /* Handle SSI tag */
  10778. buf[len] = 0;
  10779. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10780. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10781. #if !defined(NO_POPEN)
  10782. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10783. do_ssi_exec(conn, buf + 9);
  10784. #endif /* !NO_POPEN */
  10785. } else {
  10786. mg_cry_internal(conn,
  10787. "%s: unknown SSI "
  10788. "command: \"%s\"",
  10789. path,
  10790. buf);
  10791. }
  10792. len = 0;
  10793. in_ssi_tag = in_tag = 0;
  10794. } else {
  10795. /* Not an SSI tag */
  10796. /* Flush buffer */
  10797. (void)mg_write(conn, buf, (size_t)len);
  10798. len = 0;
  10799. in_tag = 0;
  10800. }
  10801. } else {
  10802. /* Tag is still open */
  10803. buf[len++] = (char)(ch & 0xff);
  10804. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10805. /* All SSI tags start with <!--# */
  10806. in_ssi_tag = 1;
  10807. }
  10808. if ((len + 2) > (int)sizeof(buf)) {
  10809. /* Tag to long for buffer */
  10810. mg_cry_internal(conn, "%s: tag is too large", path);
  10811. return;
  10812. }
  10813. }
  10814. } else {
  10815. /* We are not in a tag yet. */
  10816. if (ch == '<') {
  10817. /* Tag is opening */
  10818. in_tag = 1;
  10819. if (len > 0) {
  10820. /* Flush current buffer.
  10821. * Buffer is filled with "len" bytes. */
  10822. (void)mg_write(conn, buf, (size_t)len);
  10823. }
  10824. /* Store the < */
  10825. len = 1;
  10826. buf[0] = '<';
  10827. } else {
  10828. /* No Tag */
  10829. /* Add data to buffer */
  10830. buf[len++] = (char)(ch & 0xff);
  10831. /* Flush if buffer is full */
  10832. if (len == (int)sizeof(buf)) {
  10833. mg_write(conn, buf, (size_t)len);
  10834. len = 0;
  10835. }
  10836. }
  10837. }
  10838. }
  10839. /* Send the rest of buffered data */
  10840. if (len > 0) {
  10841. mg_write(conn, buf, (size_t)len);
  10842. }
  10843. }
  10844. static void
  10845. handle_ssi_file_request(struct mg_connection *conn,
  10846. const char *path,
  10847. struct mg_file *filep)
  10848. {
  10849. char date[64];
  10850. time_t curtime = time(NULL);
  10851. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10852. return;
  10853. }
  10854. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10855. /* File exists (precondition for calling this function),
  10856. * but can not be opened by the server. */
  10857. mg_send_http_error(conn,
  10858. 500,
  10859. "Error: Cannot read file\nfopen(%s): %s",
  10860. path,
  10861. strerror(ERRNO));
  10862. } else {
  10863. /* Set "must_close" for HTTP/1.x, since we do not know the
  10864. * content length */
  10865. conn->must_close = 1;
  10866. gmt_time_string(date, sizeof(date), &curtime);
  10867. fclose_on_exec(&filep->access, conn);
  10868. /* 200 OK response */
  10869. mg_response_header_start(conn, 200);
  10870. send_no_cache_header(conn);
  10871. send_additional_header(conn);
  10872. send_cors_header(conn);
  10873. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10874. mg_response_header_send(conn);
  10875. /* Header sent, now send body */
  10876. send_ssi_file(conn, path, filep, 0);
  10877. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10878. }
  10879. }
  10880. #endif /* NO_FILESYSTEMS */
  10881. #if !defined(NO_FILES)
  10882. static void
  10883. send_options(struct mg_connection *conn)
  10884. {
  10885. if (!conn || !all_methods) {
  10886. return;
  10887. }
  10888. /* We do not set a "Cache-Control" header here, but leave the default.
  10889. * Since browsers do not send an OPTIONS request, we can not test the
  10890. * effect anyway. */
  10891. mg_response_header_start(conn, 200);
  10892. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10893. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10894. /* Use the same as before */
  10895. mg_response_header_add(conn, "Allow", all_methods, -1);
  10896. mg_response_header_add(conn, "DAV", "1", -1);
  10897. } else {
  10898. /* TODO: Check this later for HTTP/2 */
  10899. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10900. }
  10901. send_additional_header(conn);
  10902. mg_response_header_send(conn);
  10903. }
  10904. /* Writes PROPFIND properties for a collection element */
  10905. static int
  10906. print_props(struct mg_connection *conn,
  10907. const char *uri,
  10908. const char *name,
  10909. struct mg_file_stat *filep)
  10910. {
  10911. size_t i;
  10912. char mtime[64];
  10913. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10914. char *link_concat;
  10915. size_t link_concat_len;
  10916. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10917. return 0;
  10918. }
  10919. link_concat_len = strlen(uri) + strlen(name) + 1;
  10920. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  10921. if (!link_concat) {
  10922. return 0;
  10923. }
  10924. strcpy(link_concat, uri);
  10925. strcat(link_concat, name);
  10926. /* Get full link used in request */
  10927. mg_construct_local_link(
  10928. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  10929. /*
  10930. OutputDebugStringA("print_props:\n uri: ");
  10931. OutputDebugStringA(uri);
  10932. OutputDebugStringA("\n name: ");
  10933. OutputDebugStringA(name);
  10934. OutputDebugStringA("\n link: ");
  10935. OutputDebugStringA(link_buf);
  10936. OutputDebugStringA("\n");
  10937. */
  10938. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10939. mg_printf(conn,
  10940. "<d:response>"
  10941. "<d:href>%s</d:href>"
  10942. "<d:propstat>"
  10943. "<d:prop>"
  10944. "<d:resourcetype>%s</d:resourcetype>"
  10945. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10946. "<d:getlastmodified>%s</d:getlastmodified>"
  10947. "<d:lockdiscovery>",
  10948. link_buf,
  10949. filep->is_directory ? "<d:collection/>" : "",
  10950. filep->size,
  10951. mtime);
  10952. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10953. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10954. if (!strcmp(dav_lock[i].path, link_buf)) {
  10955. mg_printf(conn,
  10956. "<d:activelock>"
  10957. "<d:locktype><d:write/></d:locktype>"
  10958. "<d:lockscope><d:exclusive/></d:lockscope>"
  10959. "<d:depth>0</d:depth>"
  10960. "<d:owner>%s</d:owner>"
  10961. "<d:timeout>Second-%u</d:timeout>"
  10962. "<d:locktoken>"
  10963. "<d:href>%s</d:href>"
  10964. "</d:locktoken>"
  10965. "</d:activelock>\n",
  10966. dav_lock[i].user,
  10967. (unsigned)LOCK_DURATION_S,
  10968. dav_lock[i].token);
  10969. }
  10970. }
  10971. mg_printf(conn,
  10972. "</d:lockdiscovery>"
  10973. "</d:prop>"
  10974. "<d:status>HTTP/1.1 200 OK</d:status>"
  10975. "</d:propstat>"
  10976. "</d:response>\n");
  10977. mg_free(link_concat);
  10978. return 1;
  10979. }
  10980. static int
  10981. print_dav_dir_entry(struct de *de, void *data)
  10982. {
  10983. struct mg_connection *conn = (struct mg_connection *)data;
  10984. if (!de || !conn
  10985. || !print_props(
  10986. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10987. /* stop scan */
  10988. return 1;
  10989. }
  10990. return 0;
  10991. }
  10992. static void
  10993. handle_propfind(struct mg_connection *conn,
  10994. const char *path,
  10995. struct mg_file_stat *filep)
  10996. {
  10997. const char *depth = mg_get_header(conn, "Depth");
  10998. if (!conn || !path || !filep || !conn->dom_ctx) {
  10999. return;
  11000. }
  11001. /* return 207 "Multi-Status" */
  11002. conn->must_close = 1;
  11003. mg_response_header_start(conn, 207);
  11004. send_static_cache_header(conn);
  11005. send_additional_header(conn);
  11006. mg_response_header_add(conn,
  11007. "Content-Type",
  11008. "application/xml; charset=utf-8",
  11009. -1);
  11010. mg_response_header_send(conn);
  11011. /* Content */
  11012. mg_printf(conn,
  11013. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11014. "<d:multistatus xmlns:d='DAV:'>\n");
  11015. /* Print properties for the requested resource itself */
  11016. print_props(conn, conn->request_info.local_uri, "", filep);
  11017. /* If it is a directory, print directory entries too if Depth is not 0
  11018. */
  11019. if (filep->is_directory
  11020. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11021. "yes")
  11022. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11023. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11024. }
  11025. mg_printf(conn, "%s\n", "</d:multistatus>");
  11026. }
  11027. static void
  11028. dav_lock_file(struct mg_connection *conn, const char *path)
  11029. {
  11030. /* internal function - therefore conn is assumed to be valid */
  11031. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11032. uint64_t new_locktime;
  11033. int lock_index = -1;
  11034. int i;
  11035. uint64_t LOCK_DURATION_NS =
  11036. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11037. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11038. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11039. return;
  11040. }
  11041. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11042. /* const char *refresh = mg_get_header(conn, "If"); */
  11043. /* Link refresh should have an "If" header:
  11044. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11045. * But it seems Windows Explorer does not send them.
  11046. */
  11047. mg_lock_context(conn->phys_ctx);
  11048. new_locktime = mg_get_current_time_ns();
  11049. /* Find a slot for a lock */
  11050. while (lock_index < 0) {
  11051. /* find existing lock */
  11052. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11053. if (!strcmp(dav_lock[i].path, link_buf)) {
  11054. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11055. /* locked by the same user */
  11056. dav_lock[i].locktime = new_locktime;
  11057. lock_index = i;
  11058. break;
  11059. } else {
  11060. /* already locked by someone else */
  11061. if (new_locktime
  11062. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11063. /* Lock expired */
  11064. dav_lock[i].path[0] = 0;
  11065. } else {
  11066. /* Lock still valid */
  11067. mg_unlock_context(conn->phys_ctx);
  11068. mg_send_http_error(conn, 423, "%s", "Already locked");
  11069. return;
  11070. }
  11071. }
  11072. }
  11073. }
  11074. /* create new lock token */
  11075. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11076. if (dav_lock[i].path[0] == 0) {
  11077. char s[32];
  11078. dav_lock[i].locktime = mg_get_current_time_ns();
  11079. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11080. mg_md5(dav_lock[i].token,
  11081. link_buf,
  11082. "\x01",
  11083. s,
  11084. "\x01",
  11085. conn->request_info.remote_user,
  11086. NULL);
  11087. strncpy(dav_lock[i].path,
  11088. link_buf,
  11089. sizeof(dav_lock[i].path) - 1);
  11090. strncpy(dav_lock[i].user,
  11091. conn->request_info.remote_user,
  11092. sizeof(dav_lock[i].user) - 1);
  11093. lock_index = i;
  11094. break;
  11095. }
  11096. }
  11097. if (lock_index < 0) {
  11098. /* too many locks. Find oldest lock */
  11099. uint64_t oldest_locktime = dav_lock[0].locktime;
  11100. lock_index = 0;
  11101. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11102. if (dav_lock[i].locktime < oldest_locktime) {
  11103. oldest_locktime = dav_lock[i].locktime;
  11104. lock_index = i;
  11105. }
  11106. }
  11107. /* invalidate oldest lock */
  11108. dav_lock[lock_index].path[0] = 0;
  11109. }
  11110. }
  11111. mg_unlock_context(conn->phys_ctx);
  11112. /* return 200 "OK" */
  11113. conn->must_close = 1;
  11114. mg_response_header_start(conn, 200);
  11115. send_static_cache_header(conn);
  11116. send_additional_header(conn);
  11117. mg_response_header_add(conn,
  11118. "Content-Type",
  11119. "application/xml; charset=utf-8",
  11120. -1);
  11121. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11122. mg_response_header_send(conn);
  11123. /* Content */
  11124. mg_printf(conn,
  11125. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11126. "<d:prop xmlns:d=\"DAV:\">\n"
  11127. " <d:lockdiscovery>\n"
  11128. " <d:activelock>\n"
  11129. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11130. " <d:locktype><d:write/></d:locktype>\n"
  11131. " <d:owner>\n"
  11132. " <d:href>%s</d:href>\n"
  11133. " </d:owner>\n"
  11134. " <d:timeout>Second-%u</d:timeout>\n"
  11135. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11136. " <d:lockroot>\n"
  11137. " <d:href>%s</d:href>\n"
  11138. " </d:lockroot>\n"
  11139. " </d:activelock>\n"
  11140. " </d:lockdiscovery>\n"
  11141. " </d:prop>\n",
  11142. dav_lock[lock_index].user,
  11143. (LOCK_DURATION_S),
  11144. dav_lock[lock_index].token,
  11145. dav_lock[lock_index].path);
  11146. }
  11147. static void
  11148. dav_unlock_file(struct mg_connection *conn, const char *path)
  11149. {
  11150. /* internal function - therefore conn is assumed to be valid */
  11151. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11152. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11153. int lock_index;
  11154. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11155. return;
  11156. }
  11157. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11158. mg_lock_context(conn->phys_ctx);
  11159. /* find existing lock */
  11160. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11161. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11162. /* Success: return 204 "No Content" */
  11163. mg_unlock_context(conn->phys_ctx);
  11164. conn->must_close = 1;
  11165. mg_response_header_start(conn, 204);
  11166. mg_response_header_send(conn);
  11167. return;
  11168. }
  11169. }
  11170. mg_unlock_context(conn->phys_ctx);
  11171. /* Error: Cannot unlock a resource that is not locked */
  11172. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11173. }
  11174. static void
  11175. dav_proppatch(struct mg_connection *conn, const char *path)
  11176. {
  11177. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11178. if (!conn || !path || !conn->dom_ctx) {
  11179. return;
  11180. }
  11181. /* return 207 "Multi-Status" */
  11182. conn->must_close = 1;
  11183. mg_response_header_start(conn, 207);
  11184. send_static_cache_header(conn);
  11185. send_additional_header(conn);
  11186. mg_response_header_add(conn,
  11187. "Content-Type",
  11188. "application/xml; charset=utf-8",
  11189. -1);
  11190. mg_response_header_send(conn);
  11191. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11192. /* Content */
  11193. mg_printf(conn,
  11194. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11195. "<d:multistatus xmlns:d='DAV:'>\n"
  11196. "<d:response>\n<d:href>%s</d:href>\n",
  11197. link_buf);
  11198. mg_printf(conn,
  11199. "<d:propstat><d:status>HTTP/1.1 403 "
  11200. "Forbidden</d:status></d:propstat>\n");
  11201. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11202. }
  11203. #endif
  11204. CIVETWEB_API void
  11205. mg_lock_connection(struct mg_connection *conn)
  11206. {
  11207. if (conn) {
  11208. (void)pthread_mutex_lock(&conn->mutex);
  11209. }
  11210. }
  11211. CIVETWEB_API void
  11212. mg_unlock_connection(struct mg_connection *conn)
  11213. {
  11214. if (conn) {
  11215. (void)pthread_mutex_unlock(&conn->mutex);
  11216. }
  11217. }
  11218. CIVETWEB_API void
  11219. mg_lock_context(struct mg_context *ctx)
  11220. {
  11221. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11222. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11223. }
  11224. }
  11225. CIVETWEB_API void
  11226. mg_unlock_context(struct mg_context *ctx)
  11227. {
  11228. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11229. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11230. }
  11231. }
  11232. #if defined(USE_LUA)
  11233. #include "mod_lua.inl"
  11234. #endif /* USE_LUA */
  11235. #if defined(USE_DUKTAPE)
  11236. #include "mod_duktape.inl"
  11237. #endif /* USE_DUKTAPE */
  11238. #if defined(USE_WEBSOCKET)
  11239. #if !defined(NO_SSL_DL)
  11240. #if !defined(OPENSSL_API_3_0)
  11241. #define SHA_API static
  11242. #include "sha1.inl"
  11243. #endif
  11244. #endif
  11245. static int
  11246. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11247. {
  11248. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11249. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11250. size_t dst_len = sizeof(b64_sha);
  11251. #if !defined(OPENSSL_API_3_0)
  11252. SHA_CTX sha_ctx;
  11253. #endif
  11254. int truncated;
  11255. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11256. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11257. if (truncated) {
  11258. conn->must_close = 1;
  11259. return 0;
  11260. }
  11261. DEBUG_TRACE("%s", "Send websocket handshake");
  11262. #if defined(OPENSSL_API_3_0)
  11263. EVP_Digest((unsigned char *)buf,
  11264. (uint32_t)strlen(buf),
  11265. (unsigned char *)sha,
  11266. NULL,
  11267. EVP_get_digestbyname("sha1"),
  11268. NULL);
  11269. #else
  11270. SHA1_Init(&sha_ctx);
  11271. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11272. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11273. #endif
  11274. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11275. mg_printf(conn,
  11276. "HTTP/1.1 101 Switching Protocols\r\n"
  11277. "Upgrade: websocket\r\n"
  11278. "Connection: Upgrade\r\n"
  11279. "Sec-WebSocket-Accept: %s\r\n",
  11280. b64_sha);
  11281. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11282. // Send negotiated compression extension parameters
  11283. websocket_deflate_response(conn);
  11284. #endif
  11285. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11286. mg_printf(conn,
  11287. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11288. conn->request_info.acceptedWebSocketSubprotocol);
  11289. } else {
  11290. mg_printf(conn, "%s", "\r\n");
  11291. }
  11292. return 1;
  11293. }
  11294. #if !defined(MG_MAX_UNANSWERED_PING)
  11295. /* Configuration of the maximum number of websocket PINGs that might
  11296. * stay unanswered before the connection is considered broken.
  11297. * Note: The name of this define may still change (until it is
  11298. * defined as a compile parameter in a documentation).
  11299. */
  11300. #define MG_MAX_UNANSWERED_PING (5)
  11301. #endif
  11302. static void
  11303. read_websocket(struct mg_connection *conn,
  11304. mg_websocket_data_handler ws_data_handler,
  11305. void *callback_data)
  11306. {
  11307. /* Pointer to the beginning of the portion of the incoming websocket
  11308. * message queue.
  11309. * The original websocket upgrade request is never removed, so the queue
  11310. * begins after it. */
  11311. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11312. int n, error, exit_by_callback;
  11313. int ret;
  11314. /* body_len is the length of the entire queue in bytes
  11315. * len is the length of the current message
  11316. * data_len is the length of the current message's data payload
  11317. * header_len is the length of the current message's header */
  11318. size_t i, len, mask_len = 0, header_len, body_len;
  11319. uint64_t data_len = 0;
  11320. /* "The masking key is a 32-bit value chosen at random by the client."
  11321. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11322. */
  11323. unsigned char mask[4];
  11324. /* data points to the place where the message is stored when passed to
  11325. * the websocket_data callback. This is either mem on the stack, or a
  11326. * dynamically allocated buffer if it is too large. */
  11327. unsigned char mem[4096];
  11328. unsigned char mop; /* mask flag and opcode */
  11329. /* Variables used for connection monitoring */
  11330. double timeout = -1.0;
  11331. int enable_ping_pong = 0;
  11332. int ping_count = 0;
  11333. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11334. enable_ping_pong =
  11335. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11336. "yes");
  11337. }
  11338. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11339. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11340. }
  11341. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11342. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11343. }
  11344. if (timeout <= 0.0) {
  11345. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11346. }
  11347. /* Enter data processing loop */
  11348. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11349. conn->request_info.remote_addr,
  11350. conn->request_info.remote_port);
  11351. conn->in_websocket_handling = 1;
  11352. mg_set_thread_name("wsock");
  11353. /* Loop continuously, reading messages from the socket, invoking the
  11354. * callback, and waiting repeatedly until an error occurs. */
  11355. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11356. && (!conn->must_close)) {
  11357. header_len = 0;
  11358. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11359. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11360. len = buf[1] & 127;
  11361. mask_len = (buf[1] & 128) ? 4 : 0;
  11362. if ((len < 126) && (body_len >= mask_len)) {
  11363. /* inline 7-bit length field */
  11364. data_len = len;
  11365. header_len = 2 + mask_len;
  11366. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11367. /* 16-bit length field */
  11368. header_len = 4 + mask_len;
  11369. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11370. } else if (body_len >= (10 + mask_len)) {
  11371. /* 64-bit length field */
  11372. uint32_t l1, l2;
  11373. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11374. memcpy(&l2, &buf[6], 4);
  11375. header_len = 10 + mask_len;
  11376. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11377. if (data_len > (uint64_t)0x7FFF0000ul) {
  11378. /* no can do */
  11379. mg_cry_internal(
  11380. conn,
  11381. "%s",
  11382. "websocket out of memory; closing connection");
  11383. break;
  11384. }
  11385. }
  11386. }
  11387. if ((header_len > 0) && (body_len >= header_len)) {
  11388. /* Allocate space to hold websocket payload */
  11389. unsigned char *data = mem;
  11390. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11391. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11392. conn->phys_ctx);
  11393. if (data == NULL) {
  11394. /* Allocation failed, exit the loop and then close the
  11395. * connection */
  11396. mg_cry_internal(
  11397. conn,
  11398. "%s",
  11399. "websocket out of memory; closing connection");
  11400. break;
  11401. }
  11402. }
  11403. /* Copy the mask before we shift the queue and destroy it */
  11404. if (mask_len > 0) {
  11405. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11406. } else {
  11407. memset(mask, 0, sizeof(mask));
  11408. }
  11409. /* Read frame payload from the first message in the queue into
  11410. * data and advance the queue by moving the memory in place. */
  11411. DEBUG_ASSERT(body_len >= header_len);
  11412. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11413. mop = buf[0]; /* current mask and opcode */
  11414. /* Overflow case */
  11415. len = body_len - header_len;
  11416. memcpy(data, buf + header_len, len);
  11417. error = 0;
  11418. while ((uint64_t)len < data_len) {
  11419. n = pull_inner(NULL,
  11420. conn,
  11421. (char *)(data + len),
  11422. (int)(data_len - len),
  11423. timeout);
  11424. if (n <= -2) {
  11425. error = 1;
  11426. break;
  11427. } else if (n > 0) {
  11428. len += (size_t)n;
  11429. } else {
  11430. /* Timeout: should retry */
  11431. /* TODO: retry condition */
  11432. }
  11433. }
  11434. if (error) {
  11435. mg_cry_internal(
  11436. conn,
  11437. "%s",
  11438. "Websocket pull failed; closing connection");
  11439. if (data != mem) {
  11440. mg_free(data);
  11441. }
  11442. break;
  11443. }
  11444. conn->data_len = conn->request_len;
  11445. } else {
  11446. mop = buf[0]; /* current mask and opcode, overwritten by
  11447. * memmove() */
  11448. /* Length of the message being read at the front of the
  11449. * queue. Cast to 31 bit is OK, since we limited
  11450. * data_len before. */
  11451. len = (size_t)data_len + header_len;
  11452. /* Copy the data payload into the data pointer for the
  11453. * callback. Cast to 31 bit is OK, since we
  11454. * limited data_len */
  11455. memcpy(data, buf + header_len, (size_t)data_len);
  11456. /* Move the queue forward len bytes */
  11457. memmove(buf, buf + len, body_len - len);
  11458. /* Mark the queue as advanced */
  11459. conn->data_len -= (int)len;
  11460. }
  11461. /* Apply mask if necessary */
  11462. if (mask_len > 0) {
  11463. for (i = 0; i < (size_t)data_len; i++) {
  11464. data[i] ^= mask[i & 3];
  11465. }
  11466. }
  11467. exit_by_callback = 0;
  11468. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11469. /* filter PONG messages */
  11470. DEBUG_TRACE("PONG from %s:%u",
  11471. conn->request_info.remote_addr,
  11472. conn->request_info.remote_port);
  11473. /* No unanwered PINGs left */
  11474. ping_count = 0;
  11475. } else if (enable_ping_pong
  11476. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11477. /* reply PING messages */
  11478. DEBUG_TRACE("Reply PING from %s:%u",
  11479. conn->request_info.remote_addr,
  11480. conn->request_info.remote_port);
  11481. ret = mg_websocket_write(conn,
  11482. MG_WEBSOCKET_OPCODE_PONG,
  11483. (char *)data,
  11484. (size_t)data_len);
  11485. if (ret <= 0) {
  11486. /* Error: send failed */
  11487. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11488. break;
  11489. }
  11490. } else {
  11491. /* Exit the loop if callback signals to exit (server side),
  11492. * or "connection close" opcode received (client side). */
  11493. if (ws_data_handler != NULL) {
  11494. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11495. if (mop & 0x40) {
  11496. /* Inflate the data received if bit RSV1 is set. */
  11497. if (!conn->websocket_deflate_initialized) {
  11498. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11499. exit_by_callback = 1;
  11500. }
  11501. if (!exit_by_callback) {
  11502. size_t inflate_buf_size_old = 0;
  11503. size_t inflate_buf_size =
  11504. data_len
  11505. * 4; // Initial guess of the inflated message
  11506. // size. We double the memory when needed.
  11507. Bytef *inflated = NULL;
  11508. Bytef *new_mem = NULL;
  11509. conn->websocket_inflate_state.avail_in =
  11510. (uInt)(data_len + 4);
  11511. conn->websocket_inflate_state.next_in = data;
  11512. // Add trailing 0x00 0x00 0xff 0xff bytes
  11513. data[data_len] = '\x00';
  11514. data[data_len + 1] = '\x00';
  11515. data[data_len + 2] = '\xff';
  11516. data[data_len + 3] = '\xff';
  11517. do {
  11518. if (inflate_buf_size_old == 0) {
  11519. new_mem =
  11520. (Bytef *)mg_calloc(inflate_buf_size,
  11521. sizeof(Bytef));
  11522. } else {
  11523. inflate_buf_size *= 2;
  11524. new_mem =
  11525. (Bytef *)mg_realloc(inflated,
  11526. inflate_buf_size);
  11527. }
  11528. if (new_mem == NULL) {
  11529. mg_cry_internal(
  11530. conn,
  11531. "Out of memory: Cannot allocate "
  11532. "inflate buffer of %lu bytes",
  11533. (unsigned long)inflate_buf_size);
  11534. exit_by_callback = 1;
  11535. break;
  11536. }
  11537. inflated = new_mem;
  11538. conn->websocket_inflate_state.avail_out =
  11539. (uInt)(inflate_buf_size
  11540. - inflate_buf_size_old);
  11541. conn->websocket_inflate_state.next_out =
  11542. inflated + inflate_buf_size_old;
  11543. ret = inflate(&conn->websocket_inflate_state,
  11544. Z_SYNC_FLUSH);
  11545. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11546. || ret == Z_MEM_ERROR) {
  11547. mg_cry_internal(
  11548. conn,
  11549. "ZLIB inflate error: %i %s",
  11550. ret,
  11551. (conn->websocket_inflate_state.msg
  11552. ? conn->websocket_inflate_state.msg
  11553. : "<no error message>"));
  11554. exit_by_callback = 1;
  11555. break;
  11556. }
  11557. inflate_buf_size_old = inflate_buf_size;
  11558. } while (conn->websocket_inflate_state.avail_out
  11559. == 0);
  11560. inflate_buf_size -=
  11561. conn->websocket_inflate_state.avail_out;
  11562. if (!ws_data_handler(conn,
  11563. mop,
  11564. (char *)inflated,
  11565. inflate_buf_size,
  11566. callback_data)) {
  11567. exit_by_callback = 1;
  11568. }
  11569. mg_free(inflated);
  11570. }
  11571. } else
  11572. #endif
  11573. if (!ws_data_handler(conn,
  11574. mop,
  11575. (char *)data,
  11576. (size_t)data_len,
  11577. callback_data)) {
  11578. exit_by_callback = 1;
  11579. }
  11580. }
  11581. }
  11582. /* It a buffer has been allocated, free it again */
  11583. if (data != mem) {
  11584. mg_free(data);
  11585. }
  11586. if (exit_by_callback) {
  11587. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11588. conn->request_info.remote_addr,
  11589. conn->request_info.remote_port);
  11590. break;
  11591. }
  11592. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11593. /* Opcode == 8, connection close */
  11594. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11595. conn->request_info.remote_addr,
  11596. conn->request_info.remote_port);
  11597. break;
  11598. }
  11599. /* Not breaking the loop, process next websocket frame. */
  11600. } else {
  11601. /* Read from the socket into the next available location in the
  11602. * message queue. */
  11603. n = pull_inner(NULL,
  11604. conn,
  11605. conn->buf + conn->data_len,
  11606. conn->buf_size - conn->data_len,
  11607. timeout);
  11608. if (n <= -2) {
  11609. /* Error, no bytes read */
  11610. DEBUG_TRACE("PULL from %s:%u failed",
  11611. conn->request_info.remote_addr,
  11612. conn->request_info.remote_port);
  11613. break;
  11614. }
  11615. if (n > 0) {
  11616. conn->data_len += n;
  11617. /* Reset open PING count */
  11618. ping_count = 0;
  11619. } else {
  11620. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11621. && (!conn->must_close)) {
  11622. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11623. /* Stop sending PING */
  11624. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11625. "- closing connection",
  11626. ping_count,
  11627. conn->request_info.remote_addr,
  11628. conn->request_info.remote_port);
  11629. break;
  11630. }
  11631. if (enable_ping_pong) {
  11632. /* Send Websocket PING message */
  11633. DEBUG_TRACE("PING to %s:%u",
  11634. conn->request_info.remote_addr,
  11635. conn->request_info.remote_port);
  11636. ret = mg_websocket_write(conn,
  11637. MG_WEBSOCKET_OPCODE_PING,
  11638. NULL,
  11639. 0);
  11640. if (ret <= 0) {
  11641. /* Error: send failed */
  11642. DEBUG_TRACE("Send PING failed (%i)", ret);
  11643. break;
  11644. }
  11645. ping_count++;
  11646. }
  11647. }
  11648. /* Timeout: should retry */
  11649. /* TODO: get timeout def */
  11650. }
  11651. }
  11652. }
  11653. /* Leave data processing loop */
  11654. mg_set_thread_name("worker");
  11655. conn->in_websocket_handling = 0;
  11656. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11657. conn->request_info.remote_addr,
  11658. conn->request_info.remote_port);
  11659. }
  11660. static int
  11661. mg_websocket_write_exec(struct mg_connection *conn,
  11662. int opcode,
  11663. const char *data,
  11664. size_t dataLen,
  11665. uint32_t masking_key)
  11666. {
  11667. unsigned char header[14];
  11668. size_t headerLen;
  11669. int retval;
  11670. #if defined(GCC_DIAGNOSTIC)
  11671. /* Disable spurious conversion warning for GCC */
  11672. #pragma GCC diagnostic push
  11673. #pragma GCC diagnostic ignored "-Wconversion"
  11674. #endif
  11675. /* Note that POSIX/Winsock's send() is threadsafe
  11676. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11677. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11678. * push(), although that is only a problem if the packet is large or
  11679. * outgoing buffer is full). */
  11680. /* TODO: Check if this lock should be moved to user land.
  11681. * Currently the server sets this lock for websockets, but
  11682. * not for any other connection. It must be set for every
  11683. * conn read/written by more than one thread, no matter if
  11684. * it is a websocket or regular connection. */
  11685. (void)mg_lock_connection(conn);
  11686. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11687. size_t deflated_size = 0;
  11688. Bytef *deflated = 0;
  11689. // Deflate websocket messages over 100kb
  11690. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11691. if (use_deflate) {
  11692. if (!conn->websocket_deflate_initialized) {
  11693. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11694. return 0;
  11695. }
  11696. // Deflating the message
  11697. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11698. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11699. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11700. deflated_size = (size_t)compressBound((uLong)dataLen);
  11701. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11702. if (deflated == NULL) {
  11703. mg_cry_internal(
  11704. conn,
  11705. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11706. (unsigned long)deflated_size);
  11707. mg_unlock_connection(conn);
  11708. return -1;
  11709. }
  11710. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11711. conn->websocket_deflate_state.next_out = deflated;
  11712. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11713. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11714. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11715. } else
  11716. #endif
  11717. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11718. #if defined(GCC_DIAGNOSTIC)
  11719. #pragma GCC diagnostic pop
  11720. #endif
  11721. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11722. if (dataLen < 126) {
  11723. /* inline 7-bit length field */
  11724. header[1] = (unsigned char)dataLen;
  11725. headerLen = 2;
  11726. } else if (dataLen <= 0xFFFF) {
  11727. /* 16-bit length field */
  11728. uint16_t len = htons((uint16_t)dataLen);
  11729. header[1] = 126;
  11730. memcpy(header + 2, &len, 2);
  11731. headerLen = 4;
  11732. } else {
  11733. /* 64-bit length field */
  11734. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11735. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11736. header[1] = 127;
  11737. memcpy(header + 2, &len1, 4);
  11738. memcpy(header + 6, &len2, 4);
  11739. headerLen = 10;
  11740. }
  11741. if (masking_key) {
  11742. /* add mask */
  11743. header[1] |= 0x80;
  11744. memcpy(header + headerLen, &masking_key, 4);
  11745. headerLen += 4;
  11746. }
  11747. retval = mg_write(conn, header, headerLen);
  11748. if (retval != (int)headerLen) {
  11749. /* Did not send complete header */
  11750. retval = -1;
  11751. } else {
  11752. if (dataLen > 0) {
  11753. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11754. if (use_deflate) {
  11755. retval = mg_write(conn, deflated, dataLen);
  11756. mg_free(deflated);
  11757. } else
  11758. #endif
  11759. retval = mg_write(conn, data, dataLen);
  11760. }
  11761. /* if dataLen == 0, the header length (2) is returned */
  11762. }
  11763. /* TODO: Remove this unlock as well, when lock is removed. */
  11764. mg_unlock_connection(conn);
  11765. return retval;
  11766. }
  11767. CIVETWEB_API int
  11768. mg_websocket_write(struct mg_connection *conn,
  11769. int opcode,
  11770. const char *data,
  11771. size_t dataLen)
  11772. {
  11773. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11774. }
  11775. static void
  11776. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11777. {
  11778. size_t i = 0;
  11779. i = 0;
  11780. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11781. /* Convert in 32 bit words, if data is 4 byte aligned */
  11782. while (i < (in_len - 3)) {
  11783. *(uint32_t *)(void *)(out + i) =
  11784. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11785. i += 4;
  11786. }
  11787. }
  11788. if (i != in_len) {
  11789. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11790. while (i < in_len) {
  11791. *(uint8_t *)(void *)(out + i) =
  11792. *(uint8_t *)(void *)(in + i)
  11793. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11794. i++;
  11795. }
  11796. }
  11797. }
  11798. CIVETWEB_API int
  11799. mg_websocket_client_write(struct mg_connection *conn,
  11800. int opcode,
  11801. const char *data,
  11802. size_t dataLen)
  11803. {
  11804. int retval = -1;
  11805. char *masked_data =
  11806. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11807. uint32_t masking_key = 0;
  11808. if (masked_data == NULL) {
  11809. /* Return -1 in an error case */
  11810. mg_cry_internal(conn,
  11811. "%s",
  11812. "Cannot allocate buffer for masked websocket response: "
  11813. "Out of memory");
  11814. return -1;
  11815. }
  11816. do {
  11817. /* Get a masking key - but not 0 */
  11818. masking_key = (uint32_t)get_random();
  11819. } while (masking_key == 0);
  11820. mask_data(data, dataLen, masking_key, masked_data);
  11821. retval = mg_websocket_write_exec(
  11822. conn, opcode, masked_data, dataLen, masking_key);
  11823. mg_free(masked_data);
  11824. return retval;
  11825. }
  11826. static void
  11827. handle_websocket_request(struct mg_connection *conn,
  11828. const char *path,
  11829. int is_callback_resource,
  11830. struct mg_websocket_subprotocols *subprotocols,
  11831. mg_websocket_connect_handler ws_connect_handler,
  11832. mg_websocket_ready_handler ws_ready_handler,
  11833. mg_websocket_data_handler ws_data_handler,
  11834. mg_websocket_close_handler ws_close_handler,
  11835. void *cbData)
  11836. {
  11837. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11838. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11839. ptrdiff_t lua_websock = 0;
  11840. #if !defined(USE_LUA)
  11841. (void)path;
  11842. #endif
  11843. /* Step 1: Check websocket protocol version. */
  11844. /* Step 1.1: Check Sec-WebSocket-Key. */
  11845. if (!websock_key) {
  11846. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11847. * requires a Sec-WebSocket-Key header.
  11848. */
  11849. /* It could be the hixie draft version
  11850. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11851. */
  11852. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11853. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11854. char key3[8];
  11855. if ((key1 != NULL) && (key2 != NULL)) {
  11856. /* This version uses 8 byte body data in a GET request */
  11857. conn->content_len = 8;
  11858. if (8 == mg_read(conn, key3, 8)) {
  11859. /* This is the hixie version */
  11860. mg_send_http_error(conn,
  11861. 426,
  11862. "%s",
  11863. "Protocol upgrade to RFC 6455 required");
  11864. return;
  11865. }
  11866. }
  11867. /* This is an unknown version */
  11868. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11869. return;
  11870. }
  11871. /* Step 1.2: Check websocket protocol version. */
  11872. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11873. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11874. /* Reject wrong versions */
  11875. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11876. return;
  11877. }
  11878. /* Step 1.3: Could check for "Host", but we do not really nead this
  11879. * value for anything, so just ignore it. */
  11880. /* Step 2: If a callback is responsible, call it. */
  11881. if (is_callback_resource) {
  11882. /* Step 2.1 check and select subprotocol */
  11883. const char *protocols[64]; // max 64 headers
  11884. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11885. "Sec-WebSocket-Protocol",
  11886. protocols,
  11887. 64);
  11888. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11889. int headerNo, idx;
  11890. size_t len;
  11891. const char *sep, *curSubProtocol,
  11892. *acceptedWebSocketSubprotocol = NULL;
  11893. /* look for matching subprotocol */
  11894. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11895. /* There might be multiple headers ... */
  11896. const char *protocol = protocols[headerNo];
  11897. curSubProtocol = protocol;
  11898. /* ... and in every header there might be a , separated list */
  11899. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11900. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11901. curSubProtocol++;
  11902. sep = strchr(curSubProtocol, ',');
  11903. if (sep) {
  11904. len = (size_t)(sep - curSubProtocol);
  11905. } else {
  11906. len = strlen(curSubProtocol);
  11907. }
  11908. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11909. // COMPARE: curSubProtocol ==
  11910. // subprotocols->subprotocols[idx]
  11911. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11912. && (strncmp(curSubProtocol,
  11913. subprotocols->subprotocols[idx],
  11914. len)
  11915. == 0)) {
  11916. acceptedWebSocketSubprotocol =
  11917. subprotocols->subprotocols[idx];
  11918. break;
  11919. }
  11920. }
  11921. curSubProtocol += len;
  11922. }
  11923. }
  11924. conn->request_info.acceptedWebSocketSubprotocol =
  11925. acceptedWebSocketSubprotocol;
  11926. }
  11927. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11928. websocket_deflate_negotiate(conn);
  11929. #endif
  11930. if ((ws_connect_handler != NULL)
  11931. && (ws_connect_handler(conn, cbData) != 0)) {
  11932. /* C callback has returned non-zero, do not proceed with
  11933. * handshake.
  11934. */
  11935. /* Note that C callbacks are no longer called when Lua is
  11936. * responsible, so C can no longer filter callbacks for Lua. */
  11937. return;
  11938. }
  11939. }
  11940. #if defined(USE_LUA)
  11941. /* Step 3: No callback. Check if Lua is responsible. */
  11942. else {
  11943. /* Step 3.1: Check if Lua is responsible. */
  11944. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11945. lua_websock = match_prefix_strlen(
  11946. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11947. }
  11948. if (lua_websock > 0) {
  11949. /* Step 3.2: Lua is responsible: call it. */
  11950. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11951. if (!conn->lua_websocket_state) {
  11952. /* Lua rejected the new client */
  11953. return;
  11954. }
  11955. }
  11956. }
  11957. #endif
  11958. /* Step 4: Check if there is a responsible websocket handler. */
  11959. if (!is_callback_resource && !lua_websock) {
  11960. /* There is no callback, and Lua is not responsible either. */
  11961. /* Reply with a 404 Not Found. We are still at a standard
  11962. * HTTP request here, before the websocket handshake, so
  11963. * we can still send standard HTTP error replies. */
  11964. mg_send_http_error(conn, 404, "%s", "Not found");
  11965. return;
  11966. }
  11967. /* Step 5: The websocket connection has been accepted */
  11968. if (!send_websocket_handshake(conn, websock_key)) {
  11969. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11970. return;
  11971. }
  11972. /* Step 6: Call the ready handler */
  11973. if (is_callback_resource) {
  11974. if (ws_ready_handler != NULL) {
  11975. ws_ready_handler(conn, cbData);
  11976. }
  11977. #if defined(USE_LUA)
  11978. } else if (lua_websock) {
  11979. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11980. /* the ready handler returned false */
  11981. return;
  11982. }
  11983. #endif
  11984. }
  11985. /* Step 7: Enter the read loop */
  11986. if (is_callback_resource) {
  11987. read_websocket(conn, ws_data_handler, cbData);
  11988. #if defined(USE_LUA)
  11989. } else if (lua_websock) {
  11990. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11991. #endif
  11992. }
  11993. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11994. /* Step 8: Close the deflate & inflate buffers */
  11995. if (conn->websocket_deflate_initialized) {
  11996. deflateEnd(&conn->websocket_deflate_state);
  11997. inflateEnd(&conn->websocket_inflate_state);
  11998. }
  11999. #endif
  12000. /* Step 9: Call the close handler */
  12001. if (ws_close_handler) {
  12002. ws_close_handler(conn, cbData);
  12003. }
  12004. }
  12005. #endif /* !USE_WEBSOCKET */
  12006. /* Is upgrade request:
  12007. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12008. * 1 = upgrade to websocket
  12009. * 2 = upgrade to HTTP/2
  12010. * -1 = upgrade to unknown protocol
  12011. */
  12012. static int
  12013. should_switch_to_protocol(const struct mg_connection *conn)
  12014. {
  12015. const char *connection_headers[8];
  12016. const char *upgrade_to;
  12017. int connection_header_count, i, should_upgrade;
  12018. /* A websocket protocoll has the following HTTP headers:
  12019. *
  12020. * Connection: Upgrade
  12021. * Upgrade: Websocket
  12022. *
  12023. * It seems some clients use multiple headers:
  12024. * see https://github.com/civetweb/civetweb/issues/1083
  12025. */
  12026. connection_header_count = get_req_headers(&conn->request_info,
  12027. "Connection",
  12028. connection_headers,
  12029. 8);
  12030. should_upgrade = 0;
  12031. for (i = 0; i < connection_header_count; i++) {
  12032. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12033. should_upgrade = 1;
  12034. }
  12035. }
  12036. if (!should_upgrade) {
  12037. return PROTOCOL_TYPE_HTTP1;
  12038. }
  12039. upgrade_to = mg_get_header(conn, "Upgrade");
  12040. if (upgrade_to == NULL) {
  12041. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12042. return -1;
  12043. }
  12044. /* Upgrade to ... */
  12045. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12046. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12047. * "Sec-WebSocket-Version" are also required.
  12048. * Don't check them here, since even an unsupported websocket protocol
  12049. * request still IS a websocket request (in contrast to a standard HTTP
  12050. * request). It will fail later in handle_websocket_request.
  12051. */
  12052. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12053. }
  12054. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12055. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12056. }
  12057. /* Upgrade to another protocol */
  12058. return -1;
  12059. }
  12060. static int
  12061. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12062. {
  12063. int n;
  12064. unsigned int a, b, c, d, slash;
  12065. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12066. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12067. // integer value, but function will not report conversion
  12068. // errors; consider using 'strtol' instead
  12069. slash = 32;
  12070. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12071. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12072. // an integer value, but function will not report conversion
  12073. // errors; consider using 'strtol' instead
  12074. n = 0;
  12075. }
  12076. }
  12077. if ((n > 0) && ((size_t)n == vec->len)) {
  12078. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12079. /* IPv4 format */
  12080. if (sa->sa.sa_family == AF_INET) {
  12081. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12082. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12083. | ((uint32_t)c << 8) | (uint32_t)d;
  12084. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12085. return (ip & mask) == net;
  12086. }
  12087. return 0;
  12088. }
  12089. }
  12090. #if defined(USE_IPV6)
  12091. else {
  12092. char ad[50];
  12093. const char *p;
  12094. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12095. slash = 128;
  12096. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12097. n = 0;
  12098. }
  12099. }
  12100. if ((n <= 0) && no_strict) {
  12101. /* no square brackets? */
  12102. p = strchr(vec->ptr, '/');
  12103. if (p && (p < (vec->ptr + vec->len))) {
  12104. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12105. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12106. n += (int)(p - vec->ptr);
  12107. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12108. } else {
  12109. n = 0;
  12110. }
  12111. } else if (vec->len < sizeof(ad)) {
  12112. n = (int)vec->len;
  12113. slash = 128;
  12114. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12115. }
  12116. }
  12117. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12118. p = ad;
  12119. c = 0;
  12120. /* zone indexes are unsupported, at least two colons are needed */
  12121. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12122. if (*(p++) == ':') {
  12123. c++;
  12124. }
  12125. }
  12126. if ((*p == '\0') && (c >= 2)) {
  12127. struct sockaddr_in6 sin6;
  12128. unsigned int i;
  12129. /* for strict validation, an actual IPv6 argument is needed */
  12130. if (sa->sa.sa_family != AF_INET6) {
  12131. return 0;
  12132. }
  12133. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12134. /* IPv6 format */
  12135. for (i = 0; i < 16; i++) {
  12136. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12137. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12138. uint8_t mask = 0;
  12139. if (8 * i + 8 < slash) {
  12140. mask = 0xFFu;
  12141. } else if (8 * i < slash) {
  12142. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12143. }
  12144. if ((ip & mask) != net) {
  12145. return 0;
  12146. }
  12147. }
  12148. return 1;
  12149. }
  12150. }
  12151. }
  12152. }
  12153. #else
  12154. (void)no_strict;
  12155. #endif
  12156. /* malformed */
  12157. return -1;
  12158. }
  12159. static int
  12160. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12161. {
  12162. int throttle = 0;
  12163. struct vec vec, val;
  12164. char mult;
  12165. double v;
  12166. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12167. mult = ',';
  12168. if ((val.ptr == NULL)
  12169. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12170. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12171. // to an integer value, but function will not report
  12172. // conversion errors; consider using 'strtol' instead
  12173. || (v < 0)
  12174. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12175. && (mult != ','))) {
  12176. continue;
  12177. }
  12178. v *= (lowercase(&mult) == 'k')
  12179. ? 1024
  12180. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12181. if (vec.len == 1 && vec.ptr[0] == '*') {
  12182. throttle = (int)v;
  12183. } else {
  12184. int matched = parse_match_net(&vec, rsa, 0);
  12185. if (matched >= 0) {
  12186. /* a valid IP subnet */
  12187. if (matched) {
  12188. throttle = (int)v;
  12189. }
  12190. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12191. throttle = (int)v;
  12192. }
  12193. }
  12194. }
  12195. return throttle;
  12196. }
  12197. /* The mg_upload function is superseeded by mg_handle_form_request. */
  12198. #include "handle_form.inl"
  12199. static int
  12200. get_first_ssl_listener_index(const struct mg_context *ctx)
  12201. {
  12202. unsigned int i;
  12203. int idx = -1;
  12204. if (ctx) {
  12205. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12206. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12207. }
  12208. }
  12209. return idx;
  12210. }
  12211. /* Return host (without port) */
  12212. static void
  12213. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12214. {
  12215. const char *host_header =
  12216. get_header(ri->http_headers, ri->num_headers, "Host");
  12217. host->ptr = NULL;
  12218. host->len = 0;
  12219. if (host_header != NULL) {
  12220. const char *pos;
  12221. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12222. * is found. */
  12223. if (*host_header == '[') {
  12224. pos = strchr(host_header, ']');
  12225. if (!pos) {
  12226. /* Malformed hostname starts with '[', but no ']' found */
  12227. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12228. return;
  12229. }
  12230. /* terminate after ']' */
  12231. host->ptr = host_header;
  12232. host->len = (size_t)(pos + 1 - host_header);
  12233. } else {
  12234. /* Otherwise, a ':' separates hostname and port number */
  12235. pos = strchr(host_header, ':');
  12236. if (pos != NULL) {
  12237. host->len = (size_t)(pos - host_header);
  12238. } else {
  12239. host->len = strlen(host_header);
  12240. }
  12241. host->ptr = host_header;
  12242. }
  12243. }
  12244. }
  12245. static int
  12246. switch_domain_context(struct mg_connection *conn)
  12247. {
  12248. struct vec host;
  12249. get_host_from_request_info(&host, &conn->request_info);
  12250. if (host.ptr) {
  12251. if (conn->ssl) {
  12252. /* This is a HTTPS connection, maybe we have a hostname
  12253. * from SNI (set in ssl_servername_callback). */
  12254. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12255. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12256. /* We are not using the default domain */
  12257. if ((strlen(sslhost) != host.len)
  12258. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12259. /* Mismatch between SNI domain and HTTP domain */
  12260. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12261. sslhost,
  12262. (int)host.len,
  12263. host.ptr);
  12264. return 0;
  12265. }
  12266. }
  12267. } else {
  12268. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12269. while (dom) {
  12270. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12271. size_t domNameLen = strlen(domName);
  12272. if ((domNameLen == host.len)
  12273. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12274. /* Found matching domain */
  12275. DEBUG_TRACE("HTTP domain %s found",
  12276. dom->config[AUTHENTICATION_DOMAIN]);
  12277. /* TODO: Check if this is a HTTP or HTTPS domain */
  12278. conn->dom_ctx = dom;
  12279. break;
  12280. }
  12281. mg_lock_context(conn->phys_ctx);
  12282. dom = dom->next;
  12283. mg_unlock_context(conn->phys_ctx);
  12284. }
  12285. }
  12286. DEBUG_TRACE("HTTP%s Host: %.*s",
  12287. conn->ssl ? "S" : "",
  12288. (int)host.len,
  12289. host.ptr);
  12290. } else {
  12291. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12292. return 1;
  12293. }
  12294. return 1;
  12295. }
  12296. static void
  12297. redirect_to_https_port(struct mg_connection *conn, int port)
  12298. {
  12299. char target_url[MG_BUF_LEN];
  12300. int truncated = 0;
  12301. const char *expect_proto =
  12302. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12303. /* Use "308 Permanent Redirect" */
  12304. int redirect_code = 308;
  12305. /* In any case, close the current connection */
  12306. conn->must_close = 1;
  12307. /* Send host, port, uri and (if it exists) ?query_string */
  12308. if (mg_construct_local_link(
  12309. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12310. < 0) {
  12311. truncated = 1;
  12312. } else if (conn->request_info.query_string != NULL) {
  12313. size_t slen1 = strlen(target_url);
  12314. size_t slen2 = strlen(conn->request_info.query_string);
  12315. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12316. target_url[slen1] = '?';
  12317. memcpy(target_url + slen1 + 1,
  12318. conn->request_info.query_string,
  12319. slen2);
  12320. target_url[slen1 + slen2 + 1] = 0;
  12321. } else {
  12322. truncated = 1;
  12323. }
  12324. }
  12325. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12326. * is used as buffer size) */
  12327. if (truncated) {
  12328. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12329. return;
  12330. }
  12331. /* Use redirect helper function */
  12332. mg_send_http_redirect(conn, target_url, redirect_code);
  12333. }
  12334. static void
  12335. mg_set_handler_type(struct mg_context *phys_ctx,
  12336. struct mg_domain_context *dom_ctx,
  12337. const char *uri,
  12338. int handler_type,
  12339. int is_delete_request,
  12340. mg_request_handler handler,
  12341. struct mg_websocket_subprotocols *subprotocols,
  12342. mg_websocket_connect_handler connect_handler,
  12343. mg_websocket_ready_handler ready_handler,
  12344. mg_websocket_data_handler data_handler,
  12345. mg_websocket_close_handler close_handler,
  12346. mg_authorization_handler auth_handler,
  12347. void *cbdata)
  12348. {
  12349. struct mg_handler_info *tmp_rh, **lastref;
  12350. size_t urilen = strlen(uri);
  12351. if (handler_type == WEBSOCKET_HANDLER) {
  12352. DEBUG_ASSERT(handler == NULL);
  12353. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12354. || ready_handler != NULL || data_handler != NULL
  12355. || close_handler != NULL);
  12356. DEBUG_ASSERT(auth_handler == NULL);
  12357. if (handler != NULL) {
  12358. return;
  12359. }
  12360. if (!is_delete_request && (connect_handler == NULL)
  12361. && (ready_handler == NULL) && (data_handler == NULL)
  12362. && (close_handler == NULL)) {
  12363. return;
  12364. }
  12365. if (auth_handler != NULL) {
  12366. return;
  12367. }
  12368. } else if (handler_type == REQUEST_HANDLER) {
  12369. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12370. && data_handler == NULL && close_handler == NULL);
  12371. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12372. DEBUG_ASSERT(auth_handler == NULL);
  12373. if ((connect_handler != NULL) || (ready_handler != NULL)
  12374. || (data_handler != NULL) || (close_handler != NULL)) {
  12375. return;
  12376. }
  12377. if (!is_delete_request && (handler == NULL)) {
  12378. return;
  12379. }
  12380. if (auth_handler != NULL) {
  12381. return;
  12382. }
  12383. } else if (handler_type == AUTH_HANDLER) {
  12384. DEBUG_ASSERT(handler == NULL);
  12385. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12386. && data_handler == NULL && close_handler == NULL);
  12387. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12388. if (handler != NULL) {
  12389. return;
  12390. }
  12391. if ((connect_handler != NULL) || (ready_handler != NULL)
  12392. || (data_handler != NULL) || (close_handler != NULL)) {
  12393. return;
  12394. }
  12395. if (!is_delete_request && (auth_handler == NULL)) {
  12396. return;
  12397. }
  12398. } else {
  12399. /* Unknown handler type. */
  12400. return;
  12401. }
  12402. if (!phys_ctx || !dom_ctx) {
  12403. /* no context available */
  12404. return;
  12405. }
  12406. mg_lock_context(phys_ctx);
  12407. /* first try to find an existing handler */
  12408. do {
  12409. lastref = &(dom_ctx->handlers);
  12410. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12411. tmp_rh = tmp_rh->next) {
  12412. if (tmp_rh->handler_type == handler_type
  12413. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12414. if (!is_delete_request) {
  12415. /* update existing handler */
  12416. if (handler_type == REQUEST_HANDLER) {
  12417. /* Wait for end of use before updating */
  12418. if (tmp_rh->refcount) {
  12419. mg_unlock_context(phys_ctx);
  12420. mg_sleep(1);
  12421. mg_lock_context(phys_ctx);
  12422. /* tmp_rh might have been freed, search again. */
  12423. break;
  12424. }
  12425. /* Ok, the handler is no more use -> Update it */
  12426. tmp_rh->handler = handler;
  12427. } else if (handler_type == WEBSOCKET_HANDLER) {
  12428. tmp_rh->subprotocols = subprotocols;
  12429. tmp_rh->connect_handler = connect_handler;
  12430. tmp_rh->ready_handler = ready_handler;
  12431. tmp_rh->data_handler = data_handler;
  12432. tmp_rh->close_handler = close_handler;
  12433. } else { /* AUTH_HANDLER */
  12434. tmp_rh->auth_handler = auth_handler;
  12435. }
  12436. tmp_rh->cbdata = cbdata;
  12437. } else {
  12438. /* remove existing handler */
  12439. if (handler_type == REQUEST_HANDLER) {
  12440. /* Wait for end of use before removing */
  12441. if (tmp_rh->refcount) {
  12442. tmp_rh->removing = 1;
  12443. mg_unlock_context(phys_ctx);
  12444. mg_sleep(1);
  12445. mg_lock_context(phys_ctx);
  12446. /* tmp_rh might have been freed, search again. */
  12447. break;
  12448. }
  12449. /* Ok, the handler is no more used */
  12450. }
  12451. *lastref = tmp_rh->next;
  12452. mg_free(tmp_rh->uri);
  12453. mg_free(tmp_rh);
  12454. }
  12455. mg_unlock_context(phys_ctx);
  12456. return;
  12457. }
  12458. lastref = &(tmp_rh->next);
  12459. }
  12460. } while (tmp_rh != NULL);
  12461. if (is_delete_request) {
  12462. /* no handler to set, this was a remove request to a non-existing
  12463. * handler */
  12464. mg_unlock_context(phys_ctx);
  12465. return;
  12466. }
  12467. tmp_rh =
  12468. (struct mg_handler_info *)mg_calloc_ctx(1,
  12469. sizeof(struct mg_handler_info),
  12470. phys_ctx);
  12471. if (tmp_rh == NULL) {
  12472. mg_unlock_context(phys_ctx);
  12473. mg_cry_ctx_internal(phys_ctx,
  12474. "%s",
  12475. "Cannot create new request handler struct, OOM");
  12476. return;
  12477. }
  12478. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12479. if (!tmp_rh->uri) {
  12480. mg_unlock_context(phys_ctx);
  12481. mg_free(tmp_rh);
  12482. mg_cry_ctx_internal(phys_ctx,
  12483. "%s",
  12484. "Cannot create new request handler struct, OOM");
  12485. return;
  12486. }
  12487. tmp_rh->uri_len = urilen;
  12488. if (handler_type == REQUEST_HANDLER) {
  12489. tmp_rh->refcount = 0;
  12490. tmp_rh->removing = 0;
  12491. tmp_rh->handler = handler;
  12492. } else if (handler_type == WEBSOCKET_HANDLER) {
  12493. tmp_rh->subprotocols = subprotocols;
  12494. tmp_rh->connect_handler = connect_handler;
  12495. tmp_rh->ready_handler = ready_handler;
  12496. tmp_rh->data_handler = data_handler;
  12497. tmp_rh->close_handler = close_handler;
  12498. } else { /* AUTH_HANDLER */
  12499. tmp_rh->auth_handler = auth_handler;
  12500. }
  12501. tmp_rh->cbdata = cbdata;
  12502. tmp_rh->handler_type = handler_type;
  12503. tmp_rh->next = NULL;
  12504. *lastref = tmp_rh;
  12505. mg_unlock_context(phys_ctx);
  12506. }
  12507. CIVETWEB_API void
  12508. mg_set_request_handler(struct mg_context *ctx,
  12509. const char *uri,
  12510. mg_request_handler handler,
  12511. void *cbdata)
  12512. {
  12513. mg_set_handler_type(ctx,
  12514. &(ctx->dd),
  12515. uri,
  12516. REQUEST_HANDLER,
  12517. handler == NULL,
  12518. handler,
  12519. NULL,
  12520. NULL,
  12521. NULL,
  12522. NULL,
  12523. NULL,
  12524. NULL,
  12525. cbdata);
  12526. }
  12527. CIVETWEB_API void
  12528. mg_set_websocket_handler(struct mg_context *ctx,
  12529. const char *uri,
  12530. mg_websocket_connect_handler connect_handler,
  12531. mg_websocket_ready_handler ready_handler,
  12532. mg_websocket_data_handler data_handler,
  12533. mg_websocket_close_handler close_handler,
  12534. void *cbdata)
  12535. {
  12536. mg_set_websocket_handler_with_subprotocols(ctx,
  12537. uri,
  12538. NULL,
  12539. connect_handler,
  12540. ready_handler,
  12541. data_handler,
  12542. close_handler,
  12543. cbdata);
  12544. }
  12545. CIVETWEB_API void
  12546. mg_set_websocket_handler_with_subprotocols(
  12547. struct mg_context *ctx,
  12548. const char *uri,
  12549. struct mg_websocket_subprotocols *subprotocols,
  12550. mg_websocket_connect_handler connect_handler,
  12551. mg_websocket_ready_handler ready_handler,
  12552. mg_websocket_data_handler data_handler,
  12553. mg_websocket_close_handler close_handler,
  12554. void *cbdata)
  12555. {
  12556. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12557. && (data_handler == NULL)
  12558. && (close_handler == NULL);
  12559. mg_set_handler_type(ctx,
  12560. &(ctx->dd),
  12561. uri,
  12562. WEBSOCKET_HANDLER,
  12563. is_delete_request,
  12564. NULL,
  12565. subprotocols,
  12566. connect_handler,
  12567. ready_handler,
  12568. data_handler,
  12569. close_handler,
  12570. NULL,
  12571. cbdata);
  12572. }
  12573. CIVETWEB_API void
  12574. mg_set_auth_handler(struct mg_context *ctx,
  12575. const char *uri,
  12576. mg_authorization_handler handler,
  12577. void *cbdata)
  12578. {
  12579. mg_set_handler_type(ctx,
  12580. &(ctx->dd),
  12581. uri,
  12582. AUTH_HANDLER,
  12583. handler == NULL,
  12584. NULL,
  12585. NULL,
  12586. NULL,
  12587. NULL,
  12588. NULL,
  12589. NULL,
  12590. handler,
  12591. cbdata);
  12592. }
  12593. static int
  12594. get_request_handler(struct mg_connection *conn,
  12595. int handler_type,
  12596. mg_request_handler *handler,
  12597. struct mg_websocket_subprotocols **subprotocols,
  12598. mg_websocket_connect_handler *connect_handler,
  12599. mg_websocket_ready_handler *ready_handler,
  12600. mg_websocket_data_handler *data_handler,
  12601. mg_websocket_close_handler *close_handler,
  12602. mg_authorization_handler *auth_handler,
  12603. void **cbdata,
  12604. struct mg_handler_info **handler_info)
  12605. {
  12606. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12607. if (request_info) {
  12608. const char *uri = request_info->local_uri;
  12609. size_t urilen = strlen(uri);
  12610. struct mg_handler_info *tmp_rh;
  12611. int step, matched;
  12612. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12613. return 0;
  12614. }
  12615. mg_lock_context(conn->phys_ctx);
  12616. for (step = 0; step < 3; step++) {
  12617. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12618. tmp_rh = tmp_rh->next) {
  12619. if (tmp_rh->handler_type != handler_type) {
  12620. continue;
  12621. }
  12622. if (step == 0) {
  12623. /* first try for an exact match */
  12624. matched = (tmp_rh->uri_len == urilen)
  12625. && (strcmp(tmp_rh->uri, uri) == 0);
  12626. } else if (step == 1) {
  12627. /* next try for a partial match, we will accept
  12628. uri/something */
  12629. matched =
  12630. (tmp_rh->uri_len < urilen)
  12631. && (uri[tmp_rh->uri_len] == '/')
  12632. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12633. } else {
  12634. /* finally try for pattern match */
  12635. matched =
  12636. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12637. }
  12638. if (matched) {
  12639. if (handler_type == WEBSOCKET_HANDLER) {
  12640. *subprotocols = tmp_rh->subprotocols;
  12641. *connect_handler = tmp_rh->connect_handler;
  12642. *ready_handler = tmp_rh->ready_handler;
  12643. *data_handler = tmp_rh->data_handler;
  12644. *close_handler = tmp_rh->close_handler;
  12645. } else if (handler_type == REQUEST_HANDLER) {
  12646. if (tmp_rh->removing) {
  12647. /* Treat as none found */
  12648. step = 2;
  12649. break;
  12650. }
  12651. *handler = tmp_rh->handler;
  12652. /* Acquire handler and give it back */
  12653. tmp_rh->refcount++;
  12654. *handler_info = tmp_rh;
  12655. } else { /* AUTH_HANDLER */
  12656. *auth_handler = tmp_rh->auth_handler;
  12657. }
  12658. *cbdata = tmp_rh->cbdata;
  12659. mg_unlock_context(conn->phys_ctx);
  12660. return 1;
  12661. }
  12662. }
  12663. }
  12664. mg_unlock_context(conn->phys_ctx);
  12665. }
  12666. return 0; /* none found */
  12667. }
  12668. /* Check if the script file is in a path, allowed for script files.
  12669. * This can be used if uploading files is possible not only for the server
  12670. * admin, and the upload mechanism does not check the file extension.
  12671. */
  12672. static int
  12673. is_in_script_path(const struct mg_connection *conn, const char *path)
  12674. {
  12675. /* TODO (Feature): Add config value for allowed script path.
  12676. * Default: All allowed. */
  12677. (void)conn;
  12678. (void)path;
  12679. return 1;
  12680. }
  12681. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12682. static int
  12683. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12684. int bits,
  12685. char *data,
  12686. size_t len,
  12687. void *cbdata)
  12688. {
  12689. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12690. if (pcallbacks->websocket_data) {
  12691. return pcallbacks->websocket_data(conn, bits, data, len);
  12692. }
  12693. /* No handler set - assume "OK" */
  12694. return 1;
  12695. }
  12696. static void
  12697. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12698. void *cbdata)
  12699. {
  12700. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12701. if (pcallbacks->connection_close) {
  12702. pcallbacks->connection_close(conn);
  12703. }
  12704. }
  12705. #endif
  12706. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12707. */
  12708. static void
  12709. release_handler_ref(struct mg_connection *conn,
  12710. struct mg_handler_info *handler_info)
  12711. {
  12712. if (handler_info != NULL) {
  12713. /* Use context lock for ref counter */
  12714. mg_lock_context(conn->phys_ctx);
  12715. handler_info->refcount--;
  12716. mg_unlock_context(conn->phys_ctx);
  12717. }
  12718. }
  12719. /* This is the heart of the Civetweb's logic.
  12720. * This function is called when the request is read, parsed and validated,
  12721. * and Civetweb must decide what action to take: serve a file, or
  12722. * a directory, or call embedded function, etcetera. */
  12723. static void
  12724. handle_request(struct mg_connection *conn)
  12725. {
  12726. struct mg_request_info *ri = &conn->request_info;
  12727. char path[UTF8_PATH_MAX];
  12728. int uri_len, ssl_index;
  12729. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12730. is_put_or_delete_request = 0, is_callback_resource = 0,
  12731. is_template_text_file = 0, is_webdav_request = 0;
  12732. int i;
  12733. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12734. mg_request_handler callback_handler = NULL;
  12735. struct mg_handler_info *handler_info = NULL;
  12736. struct mg_websocket_subprotocols *subprotocols;
  12737. mg_websocket_connect_handler ws_connect_handler = NULL;
  12738. mg_websocket_ready_handler ws_ready_handler = NULL;
  12739. mg_websocket_data_handler ws_data_handler = NULL;
  12740. mg_websocket_close_handler ws_close_handler = NULL;
  12741. void *callback_data = NULL;
  12742. mg_authorization_handler auth_handler = NULL;
  12743. void *auth_callback_data = NULL;
  12744. int handler_type;
  12745. time_t curtime = time(NULL);
  12746. char date[64];
  12747. char *tmp;
  12748. path[0] = 0;
  12749. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12750. conn->request_state = 0;
  12751. /* 1. get the request url */
  12752. /* 1.1. split into url and query string */
  12753. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12754. != NULL) {
  12755. *((char *)conn->request_info.query_string++) = '\0';
  12756. }
  12757. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12758. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12759. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12760. if (ssl_index >= 0) {
  12761. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12762. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12763. redirect_to_https_port(conn, port);
  12764. } else {
  12765. /* A http to https forward port has been specified,
  12766. * but no https port to forward to. */
  12767. mg_send_http_error(conn,
  12768. 503,
  12769. "%s",
  12770. "Error: SSL forward not configured properly");
  12771. mg_cry_internal(conn,
  12772. "%s",
  12773. "Can not redirect to SSL, no SSL port available");
  12774. }
  12775. return;
  12776. }
  12777. uri_len = (int)strlen(ri->local_uri);
  12778. /* 1.3. decode url (if config says so) */
  12779. if (should_decode_url(conn)) {
  12780. url_decode_in_place((char *)ri->local_uri);
  12781. }
  12782. /* URL decode the query-string only if explicity set in the configuration */
  12783. if (conn->request_info.query_string) {
  12784. if (should_decode_query_string(conn)) {
  12785. url_decode_in_place((char *)conn->request_info.query_string);
  12786. }
  12787. }
  12788. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12789. * possible. The fact that we cleaned the URI is stored in that the
  12790. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12791. * ri->local_uri_raw still points to memory allocated in
  12792. * worker_thread_run(). ri->local_uri is private to the request so we
  12793. * don't have to use preallocated memory here. */
  12794. tmp = mg_strdup(ri->local_uri_raw);
  12795. if (!tmp) {
  12796. /* Out of memory. We cannot do anything reasonable here. */
  12797. return;
  12798. }
  12799. remove_dot_segments(tmp);
  12800. ri->local_uri = tmp;
  12801. /* step 1. completed, the url is known now */
  12802. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12803. /* 2. if this ip has limited speed, set it for this connection */
  12804. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12805. &conn->client.rsa,
  12806. ri->local_uri);
  12807. /* 3. call a "handle everything" callback, if registered */
  12808. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12809. /* Note that since V1.7 the "begin_request" function is called
  12810. * before an authorization check. If an authorization check is
  12811. * required, use a request_handler instead. */
  12812. i = conn->phys_ctx->callbacks.begin_request(conn);
  12813. if (i > 0) {
  12814. /* callback already processed the request. Store the
  12815. return value as a status code for the access log. */
  12816. conn->status_code = i;
  12817. if (!conn->must_close) {
  12818. discard_unread_request_data(conn);
  12819. }
  12820. DEBUG_TRACE("%s", "begin_request handled request");
  12821. return;
  12822. } else if (i == 0) {
  12823. /* civetweb should process the request */
  12824. } else {
  12825. /* unspecified - may change with the next version */
  12826. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12827. return;
  12828. }
  12829. }
  12830. /* request not yet handled by a handler or redirect, so the request
  12831. * is processed here */
  12832. /* 4. Check for CORS preflight requests and handle them (if configured).
  12833. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12834. */
  12835. if (!strcmp(ri->request_method, "OPTIONS")) {
  12836. /* Send a response to CORS preflights only if
  12837. * access_control_allow_methods is not NULL and not an empty string.
  12838. * In this case, scripts can still handle CORS. */
  12839. const char *cors_meth_cfg =
  12840. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12841. const char *cors_orig_cfg =
  12842. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12843. const char *cors_origin =
  12844. get_header(ri->http_headers, ri->num_headers, "Origin");
  12845. const char *cors_acrm = get_header(ri->http_headers,
  12846. ri->num_headers,
  12847. "Access-Control-Request-Method");
  12848. /* Todo: check if cors_origin is in cors_orig_cfg.
  12849. * Or, let the client check this. */
  12850. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12851. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12852. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12853. /* This is a valid CORS preflight, and the server is configured
  12854. * to handle it automatically. */
  12855. const char *cors_acrh =
  12856. get_header(ri->http_headers,
  12857. ri->num_headers,
  12858. "Access-Control-Request-Headers");
  12859. gmt_time_string(date, sizeof(date), &curtime);
  12860. mg_printf(conn,
  12861. "HTTP/1.1 200 OK\r\n"
  12862. "Date: %s\r\n"
  12863. "Access-Control-Allow-Origin: %s\r\n"
  12864. "Access-Control-Allow-Methods: %s\r\n"
  12865. "Content-Length: 0\r\n"
  12866. "Connection: %s\r\n",
  12867. date,
  12868. cors_orig_cfg,
  12869. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12870. suggest_connection_header(conn));
  12871. if (cors_acrh != NULL) {
  12872. /* CORS request is asking for additional headers */
  12873. const char *cors_hdr_cfg =
  12874. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12875. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12876. /* Allow only if access_control_allow_headers is
  12877. * not NULL and not an empty string. If this
  12878. * configuration is set to *, allow everything.
  12879. * Otherwise this configuration must be a list
  12880. * of allowed HTTP header names. */
  12881. mg_printf(conn,
  12882. "Access-Control-Allow-Headers: %s\r\n",
  12883. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12884. : cors_hdr_cfg));
  12885. }
  12886. }
  12887. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12888. mg_printf(conn, "\r\n");
  12889. DEBUG_TRACE("%s", "OPTIONS done");
  12890. return;
  12891. }
  12892. }
  12893. /* 5. interpret the url to find out how the request must be handled
  12894. */
  12895. /* 5.1. first test, if the request targets the regular http(s)://
  12896. * protocol namespace or the websocket ws(s):// protocol namespace.
  12897. */
  12898. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12899. #if defined(USE_WEBSOCKET)
  12900. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12901. #else
  12902. handler_type = REQUEST_HANDLER;
  12903. #endif /* defined(USE_WEBSOCKET) */
  12904. if (is_websocket_request) {
  12905. HTTP1_only;
  12906. }
  12907. /* 5.2. check if the request will be handled by a callback */
  12908. if (get_request_handler(conn,
  12909. handler_type,
  12910. &callback_handler,
  12911. &subprotocols,
  12912. &ws_connect_handler,
  12913. &ws_ready_handler,
  12914. &ws_data_handler,
  12915. &ws_close_handler,
  12916. NULL,
  12917. &callback_data,
  12918. &handler_info)) {
  12919. /* 5.2.1. A callback will handle this request. All requests
  12920. * handled by a callback have to be considered as requests
  12921. * to a script resource. */
  12922. is_callback_resource = 1;
  12923. is_script_resource = 1;
  12924. is_put_or_delete_request = is_put_or_delete_method(conn);
  12925. /* Never handle a C callback according to File WebDav rules,
  12926. * even if it is a webdav method */
  12927. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12928. } else {
  12929. no_callback_resource:
  12930. /* 5.2.2. No callback is responsible for this request. The URI
  12931. * addresses a file based resource (static content or Lua/cgi
  12932. * scripts in the file system). */
  12933. is_callback_resource = 0;
  12934. interpret_uri(conn,
  12935. path,
  12936. sizeof(path),
  12937. &file.stat,
  12938. &is_found,
  12939. &is_script_resource,
  12940. &is_websocket_request,
  12941. &is_put_or_delete_request,
  12942. &is_webdav_request,
  12943. &is_template_text_file);
  12944. }
  12945. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12946. if (is_webdav_request) {
  12947. /* TODO: Do we need a config option? */
  12948. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  12949. if (webdav_enable[0] != 'y') {
  12950. mg_send_http_error(conn,
  12951. 405,
  12952. "%s method not allowed",
  12953. conn->request_info.request_method);
  12954. DEBUG_TRACE("%s", "webdav rejected");
  12955. return;
  12956. }
  12957. }
  12958. /* 6. authorization check */
  12959. /* 6.1. a custom authorization handler is installed */
  12960. if (get_request_handler(conn,
  12961. AUTH_HANDLER,
  12962. NULL,
  12963. NULL,
  12964. NULL,
  12965. NULL,
  12966. NULL,
  12967. NULL,
  12968. &auth_handler,
  12969. &auth_callback_data,
  12970. NULL)) {
  12971. if (!auth_handler(conn, auth_callback_data)) {
  12972. /* Callback handler will not be used anymore. Release it */
  12973. release_handler_ref(conn, handler_info);
  12974. DEBUG_TRACE("%s", "auth handler rejected request");
  12975. return;
  12976. }
  12977. } else if (is_put_or_delete_request && !is_script_resource
  12978. && !is_callback_resource) {
  12979. HTTP1_only;
  12980. /* 6.2. this request is a PUT/DELETE to a real file */
  12981. /* 6.2.1. thus, the server must have real files */
  12982. #if defined(NO_FILES)
  12983. if (1) {
  12984. #else
  12985. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  12986. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  12987. #endif
  12988. /* This code path will not be called for request handlers */
  12989. DEBUG_ASSERT(handler_info == NULL);
  12990. /* This server does not have any real files, thus the
  12991. * PUT/DELETE methods are not valid. */
  12992. mg_send_http_error(conn,
  12993. 405,
  12994. "%s method not allowed",
  12995. conn->request_info.request_method);
  12996. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  12997. return;
  12998. }
  12999. #if !defined(NO_FILES)
  13000. /* 6.2.2. Check if put authorization for static files is
  13001. * available.
  13002. */
  13003. if (!is_authorized_for_put(conn)) {
  13004. send_authorization_request(conn, NULL);
  13005. DEBUG_TRACE("%s", "file write needs authorization");
  13006. return;
  13007. }
  13008. #endif
  13009. } else {
  13010. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13011. * or it is a PUT or DELETE request to a resource that does not
  13012. * correspond to a file. Check authorization. */
  13013. if (!check_authorization(conn, path)) {
  13014. send_authorization_request(conn, NULL);
  13015. /* Callback handler will not be used anymore. Release it */
  13016. release_handler_ref(conn, handler_info);
  13017. DEBUG_TRACE("%s", "access authorization required");
  13018. return;
  13019. }
  13020. }
  13021. /* request is authorized or does not need authorization */
  13022. /* 7. check if there are request handlers for this uri */
  13023. if (is_callback_resource) {
  13024. HTTP1_only;
  13025. if (!is_websocket_request) {
  13026. i = callback_handler(conn, callback_data);
  13027. /* Callback handler will not be used anymore. Release it */
  13028. release_handler_ref(conn, handler_info);
  13029. if (i > 0) {
  13030. /* Do nothing, callback has served the request. Store
  13031. * then return value as status code for the log and discard
  13032. * all data from the client not used by the callback. */
  13033. conn->status_code = i;
  13034. if (!conn->must_close) {
  13035. discard_unread_request_data(conn);
  13036. }
  13037. } else {
  13038. /* The handler did NOT handle the request. */
  13039. /* Some proper reactions would be:
  13040. * a) close the connections without sending anything
  13041. * b) send a 404 not found
  13042. * c) try if there is a file matching the URI
  13043. * It would be possible to do a, b or c in the callback
  13044. * implementation, and return 1 - we cannot do anything
  13045. * here, that is not possible in the callback.
  13046. *
  13047. * TODO: What would be the best reaction here?
  13048. * (Note: The reaction may change, if there is a better
  13049. * idea.)
  13050. */
  13051. /* For the moment, use option c: We look for a proper file,
  13052. * but since a file request is not always a script resource,
  13053. * the authorization check might be different. */
  13054. callback_handler = NULL;
  13055. /* Here we are at a dead end:
  13056. * According to URI matching, a callback should be
  13057. * responsible for handling the request,
  13058. * we called it, but the callback declared itself
  13059. * not responsible.
  13060. * We use a goto here, to get out of this dead end,
  13061. * and continue with the default handling.
  13062. * A goto here is simpler and better to understand
  13063. * than some curious loop. */
  13064. goto no_callback_resource;
  13065. }
  13066. } else {
  13067. #if defined(USE_WEBSOCKET)
  13068. handle_websocket_request(conn,
  13069. path,
  13070. is_callback_resource,
  13071. subprotocols,
  13072. ws_connect_handler,
  13073. ws_ready_handler,
  13074. ws_data_handler,
  13075. ws_close_handler,
  13076. callback_data);
  13077. #endif
  13078. }
  13079. DEBUG_TRACE("%s", "websocket handling done");
  13080. return;
  13081. }
  13082. /* 8. handle websocket requests */
  13083. #if defined(USE_WEBSOCKET)
  13084. if (is_websocket_request) {
  13085. HTTP1_only;
  13086. if (is_script_resource) {
  13087. if (is_in_script_path(conn, path)) {
  13088. /* Websocket Lua script */
  13089. handle_websocket_request(conn,
  13090. path,
  13091. 0 /* Lua Script */,
  13092. NULL,
  13093. NULL,
  13094. NULL,
  13095. NULL,
  13096. NULL,
  13097. conn->phys_ctx->user_data);
  13098. } else {
  13099. /* Script was in an illegal path */
  13100. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13101. }
  13102. } else {
  13103. mg_send_http_error(conn, 404, "%s", "Not found");
  13104. }
  13105. DEBUG_TRACE("%s", "websocket script done");
  13106. return;
  13107. } else
  13108. #endif
  13109. #if defined(NO_FILES)
  13110. /* 9a. In case the server uses only callbacks, this uri is
  13111. * unknown.
  13112. * Then, all request handling ends here. */
  13113. mg_send_http_error(conn, 404, "%s", "Not Found");
  13114. #else
  13115. /* 9b. This request is either for a static file or resource handled
  13116. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13117. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13118. mg_send_http_error(conn, 404, "%s", "Not Found");
  13119. DEBUG_TRACE("%s", "no document root available");
  13120. return;
  13121. }
  13122. /* 10. Request is handled by a script */
  13123. if (is_script_resource) {
  13124. HTTP1_only;
  13125. handle_file_based_request(conn, path, &file);
  13126. DEBUG_TRACE("%s", "script handling done");
  13127. return;
  13128. }
  13129. /* Request was not handled by a callback or script. It will be
  13130. * handled by a server internal method. */
  13131. /* 11. Handle put/delete/mkcol requests */
  13132. if (is_put_or_delete_request) {
  13133. HTTP1_only;
  13134. /* 11.1. PUT method */
  13135. if (!strcmp(ri->request_method, "PUT")) {
  13136. put_file(conn, path);
  13137. DEBUG_TRACE("handling %s request to %s done",
  13138. ri->request_method,
  13139. path);
  13140. return;
  13141. }
  13142. /* 11.2. DELETE method */
  13143. if (!strcmp(ri->request_method, "DELETE")) {
  13144. delete_file(conn, path);
  13145. DEBUG_TRACE("handling %s request to %s done",
  13146. ri->request_method,
  13147. path);
  13148. return;
  13149. }
  13150. /* 11.3. MKCOL method */
  13151. if (!strcmp(ri->request_method, "MKCOL")) {
  13152. dav_mkcol(conn, path);
  13153. DEBUG_TRACE("handling %s request to %s done",
  13154. ri->request_method,
  13155. path);
  13156. return;
  13157. }
  13158. /* 11.4. MOVE method */
  13159. if (!strcmp(ri->request_method, "MOVE")) {
  13160. dav_move_file(conn, path, 0);
  13161. DEBUG_TRACE("handling %s request to %s done",
  13162. ri->request_method,
  13163. path);
  13164. return;
  13165. }
  13166. if (!strcmp(ri->request_method, "COPY")) {
  13167. dav_move_file(conn, path, 1);
  13168. DEBUG_TRACE("handling %s request to %s done",
  13169. ri->request_method,
  13170. path);
  13171. return;
  13172. }
  13173. /* 11.5. LOCK method */
  13174. if (!strcmp(ri->request_method, "LOCK")) {
  13175. dav_lock_file(conn, path);
  13176. DEBUG_TRACE("handling %s request to %s done",
  13177. ri->request_method,
  13178. path);
  13179. return;
  13180. }
  13181. /* 11.6. UNLOCK method */
  13182. if (!strcmp(ri->request_method, "UNLOCK")) {
  13183. dav_unlock_file(conn, path);
  13184. DEBUG_TRACE("handling %s request to %s done",
  13185. ri->request_method,
  13186. path);
  13187. return;
  13188. }
  13189. /* 11.7. PROPPATCH method */
  13190. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13191. dav_proppatch(conn, path);
  13192. DEBUG_TRACE("handling %s request to %s done",
  13193. ri->request_method,
  13194. path);
  13195. return;
  13196. }
  13197. /* 11.8. Other methods, e.g.: PATCH
  13198. * This method is not supported for static resources,
  13199. * only for scripts (Lua, CGI) and callbacks. */
  13200. mg_send_http_error(conn,
  13201. 405,
  13202. "%s method not allowed",
  13203. conn->request_info.request_method);
  13204. DEBUG_TRACE("method %s on %s is not supported",
  13205. ri->request_method,
  13206. path);
  13207. return;
  13208. }
  13209. /* 11. File does not exist, or it was configured that it should be
  13210. * hidden */
  13211. if (!is_found || (must_hide_file(conn, path))) {
  13212. mg_send_http_error(conn, 404, "%s", "Not found");
  13213. DEBUG_TRACE("handling %s request to %s: file not found",
  13214. ri->request_method,
  13215. path);
  13216. return;
  13217. }
  13218. /* 12. Directory uris should end with a slash */
  13219. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13220. && (ri->local_uri[uri_len - 1] != '/')) {
  13221. /* Path + server root */
  13222. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13223. char *new_path;
  13224. if (ri->query_string) {
  13225. buflen += strlen(ri->query_string);
  13226. }
  13227. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13228. if (!new_path) {
  13229. mg_send_http_error(conn, 500, "out or memory");
  13230. } else {
  13231. mg_get_request_link(conn, new_path, buflen - 1);
  13232. strcat(new_path, "/");
  13233. if (ri->query_string) {
  13234. /* Append ? and query string */
  13235. strcat(new_path, "?");
  13236. strcat(new_path, ri->query_string);
  13237. }
  13238. mg_send_http_redirect(conn, new_path, 301);
  13239. mg_free(new_path);
  13240. }
  13241. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13242. ri->request_method,
  13243. path);
  13244. return;
  13245. }
  13246. /* 13. Handle other methods than GET/HEAD */
  13247. /* 13.1. Handle PROPFIND */
  13248. if (!strcmp(ri->request_method, "PROPFIND")) {
  13249. handle_propfind(conn, path, &file.stat);
  13250. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13251. return;
  13252. }
  13253. /* 13.2. Handle OPTIONS for files */
  13254. if (!strcmp(ri->request_method, "OPTIONS")) {
  13255. /* This standard handler is only used for real files.
  13256. * Scripts should support the OPTIONS method themselves, to allow a
  13257. * maximum flexibility.
  13258. * Lua and CGI scripts may fully support CORS this way (including
  13259. * preflights). */
  13260. send_options(conn);
  13261. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13262. return;
  13263. }
  13264. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13265. if ((0 != strcmp(ri->request_method, "GET"))
  13266. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13267. mg_send_http_error(conn,
  13268. 405,
  13269. "%s method not allowed",
  13270. conn->request_info.request_method);
  13271. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13272. return;
  13273. }
  13274. /* 14. directories */
  13275. if (file.stat.is_directory) {
  13276. /* Substitute files have already been handled above. */
  13277. /* Here we can either generate and send a directory listing,
  13278. * or send an "access denied" error. */
  13279. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13280. "yes")) {
  13281. handle_directory_request(conn, path);
  13282. } else {
  13283. mg_send_http_error(conn,
  13284. 403,
  13285. "%s",
  13286. "Error: Directory listing denied");
  13287. }
  13288. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13289. return;
  13290. }
  13291. /* 15. Files with search/replace patterns: LSP and SSI */
  13292. if (is_template_text_file) {
  13293. HTTP1_only;
  13294. handle_file_based_request(conn, path, &file);
  13295. DEBUG_TRACE("handling %s request to %s done (template)",
  13296. ri->request_method,
  13297. path);
  13298. return;
  13299. }
  13300. /* 16. Static file - maybe cached */
  13301. #if !defined(NO_CACHING)
  13302. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13303. /* Send 304 "Not Modified" - this must not send any body data */
  13304. handle_not_modified_static_file_request(conn, &file);
  13305. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13306. ri->request_method,
  13307. path);
  13308. return;
  13309. }
  13310. #endif /* !NO_CACHING */
  13311. /* 17. Static file - not cached */
  13312. handle_static_file_request(conn, path, &file, NULL, NULL);
  13313. DEBUG_TRACE("handling %s request to %s done (static)",
  13314. ri->request_method,
  13315. path);
  13316. #endif /* !defined(NO_FILES) */
  13317. }
  13318. #if !defined(NO_FILESYSTEMS)
  13319. static void
  13320. handle_file_based_request(struct mg_connection *conn,
  13321. const char *path,
  13322. struct mg_file *file)
  13323. {
  13324. #if !defined(NO_CGI)
  13325. unsigned char cgi_config_idx, inc, max;
  13326. #endif
  13327. if (!conn || !conn->dom_ctx) {
  13328. return;
  13329. }
  13330. #if defined(USE_LUA)
  13331. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13332. path)
  13333. > 0) {
  13334. if (is_in_script_path(conn, path)) {
  13335. /* Lua server page: an SSI like page containing mostly plain
  13336. * html code plus some tags with server generated contents. */
  13337. handle_lsp_request(conn, path, file, NULL);
  13338. } else {
  13339. /* Script was in an illegal path */
  13340. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13341. }
  13342. return;
  13343. }
  13344. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13345. > 0) {
  13346. if (is_in_script_path(conn, path)) {
  13347. /* Lua in-server module script: a CGI like script used to
  13348. * generate the entire reply. */
  13349. mg_exec_lua_script(conn, path, NULL);
  13350. } else {
  13351. /* Script was in an illegal path */
  13352. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13353. }
  13354. return;
  13355. }
  13356. #endif
  13357. #if defined(USE_DUKTAPE)
  13358. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13359. path)
  13360. > 0) {
  13361. if (is_in_script_path(conn, path)) {
  13362. /* Call duktape to generate the page */
  13363. mg_exec_duktape_script(conn, path);
  13364. } else {
  13365. /* Script was in an illegal path */
  13366. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13367. }
  13368. return;
  13369. }
  13370. #endif
  13371. #if !defined(NO_CGI)
  13372. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13373. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13374. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13375. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13376. if (match_prefix_strlen(
  13377. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13378. path)
  13379. > 0) {
  13380. if (is_in_script_path(conn, path)) {
  13381. /* CGI scripts may support all HTTP methods */
  13382. handle_cgi_request(conn, path, cgi_config_idx);
  13383. } else {
  13384. /* Script was in an illegal path */
  13385. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13386. }
  13387. return;
  13388. }
  13389. }
  13390. }
  13391. #endif /* !NO_CGI */
  13392. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13393. if (is_in_script_path(conn, path)) {
  13394. handle_ssi_file_request(conn, path, file);
  13395. } else {
  13396. /* Script was in an illegal path */
  13397. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13398. }
  13399. return;
  13400. }
  13401. #if !defined(NO_CACHING)
  13402. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13403. /* Send 304 "Not Modified" - this must not send any body data */
  13404. handle_not_modified_static_file_request(conn, file);
  13405. return;
  13406. }
  13407. #endif /* !NO_CACHING */
  13408. handle_static_file_request(conn, path, file, NULL, NULL);
  13409. }
  13410. #endif /* NO_FILESYSTEMS */
  13411. static void
  13412. close_all_listening_sockets(struct mg_context *ctx)
  13413. {
  13414. unsigned int i;
  13415. if (!ctx) {
  13416. return;
  13417. }
  13418. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13419. closesocket(ctx->listening_sockets[i].sock);
  13420. #if defined(USE_X_DOM_SOCKET)
  13421. /* For unix domain sockets, the socket name represents a file that has
  13422. * to be deleted. */
  13423. /* See
  13424. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13425. */
  13426. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13427. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13428. IGNORE_UNUSED_RESULT(
  13429. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13430. }
  13431. #endif
  13432. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13433. }
  13434. mg_free(ctx->listening_sockets);
  13435. ctx->listening_sockets = NULL;
  13436. mg_free(ctx->listening_socket_fds);
  13437. ctx->listening_socket_fds = NULL;
  13438. }
  13439. /* Valid listening port specification is: [ip_address:]port[s]
  13440. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13441. * Examples for IPv6: [::]:80, [::1]:80,
  13442. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13443. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13444. * In order to bind to both, IPv4 and IPv6, you can either add
  13445. * both ports using 8080,[::]:8080, or the short form +8080.
  13446. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13447. * one only accepting IPv4 the other only IPv6. +8080 creates
  13448. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13449. * environment, they might work differently, or might not work
  13450. * at all - it must be tested what options work best in the
  13451. * relevant network environment.
  13452. */
  13453. static int
  13454. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13455. {
  13456. unsigned int a, b, c, d;
  13457. unsigned port;
  13458. unsigned long portUL;
  13459. int ch, len;
  13460. const char *cb;
  13461. char *endptr;
  13462. #if defined(USE_IPV6)
  13463. char buf[100] = {0};
  13464. #endif
  13465. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13466. * Also, all-zeroes in the socket address means binding to all addresses
  13467. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13468. memset(so, 0, sizeof(*so));
  13469. so->lsa.sin.sin_family = AF_INET;
  13470. *ip_version = 0;
  13471. /* Initialize len as invalid. */
  13472. port = 0;
  13473. len = 0;
  13474. /* Test for different ways to format this string */
  13475. if (sscanf(vec->ptr,
  13476. "%u.%u.%u.%u:%u%n",
  13477. &a,
  13478. &b,
  13479. &c,
  13480. &d,
  13481. &port,
  13482. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13483. // to an integer value, but function will not report
  13484. // conversion errors; consider using 'strtol' instead
  13485. == 5) {
  13486. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13487. so->lsa.sin.sin_addr.s_addr =
  13488. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13489. so->lsa.sin.sin_port = htons((uint16_t)port);
  13490. *ip_version = 4;
  13491. #if defined(USE_IPV6)
  13492. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13493. && ((size_t)len <= vec->len)
  13494. && mg_inet_pton(
  13495. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13496. /* IPv6 address, examples: see above */
  13497. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13498. */
  13499. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13500. *ip_version = 6;
  13501. #endif
  13502. } else if ((vec->ptr[0] == '+')
  13503. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13504. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13505. // string to an integer value, but function will not
  13506. // report conversion errors; consider using 'strtol'
  13507. // instead
  13508. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13509. /* Add 1 to len for the + character we skipped before */
  13510. len++;
  13511. #if defined(USE_IPV6)
  13512. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13513. so->lsa.sin6.sin6_family = AF_INET6;
  13514. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13515. *ip_version = 4 + 6;
  13516. #else
  13517. /* Bind to IPv4 only, since IPv6 is not built in. */
  13518. so->lsa.sin.sin_port = htons((uint16_t)port);
  13519. *ip_version = 4;
  13520. #endif
  13521. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13522. && (vec->ptr != endptr)) {
  13523. len = (int)(endptr - vec->ptr);
  13524. port = (uint16_t)portUL;
  13525. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13526. so->lsa.sin.sin_port = htons((uint16_t)port);
  13527. *ip_version = 4;
  13528. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13529. /* String could be a hostname. This check algotithm
  13530. * will only work for RFC 952 compliant hostnames,
  13531. * starting with a letter, containing only letters,
  13532. * digits and hyphen ('-'). Newer specs may allow
  13533. * more, but this is not guaranteed here, since it
  13534. * may interfere with rules for port option lists. */
  13535. /* According to RFC 1035, hostnames are restricted to 255 characters
  13536. * in total (63 between two dots). */
  13537. char hostname[256];
  13538. size_t hostnlen = (size_t)(cb - vec->ptr);
  13539. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13540. /* This would be invalid in any case */
  13541. *ip_version = 0;
  13542. return 0;
  13543. }
  13544. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13545. if (mg_inet_pton(
  13546. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13547. if (sscanf(cb + 1, "%u%n", &port, &len)
  13548. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13549. // string to an integer value, but function will not
  13550. // report conversion errors; consider using 'strtol'
  13551. // instead
  13552. *ip_version = 4;
  13553. so->lsa.sin.sin_port = htons((uint16_t)port);
  13554. len += (int)(hostnlen + 1);
  13555. } else {
  13556. len = 0;
  13557. }
  13558. #if defined(USE_IPV6)
  13559. } else if (mg_inet_pton(AF_INET6,
  13560. hostname,
  13561. &so->lsa.sin6,
  13562. sizeof(so->lsa.sin6),
  13563. 1)) {
  13564. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13565. *ip_version = 6;
  13566. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13567. len += (int)(hostnlen + 1);
  13568. } else {
  13569. len = 0;
  13570. }
  13571. #endif
  13572. } else {
  13573. len = 0;
  13574. }
  13575. #if defined(USE_X_DOM_SOCKET)
  13576. } else if (vec->ptr[0] == 'x') {
  13577. /* unix (linux) domain socket */
  13578. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13579. len = vec->len;
  13580. so->lsa.sun.sun_family = AF_UNIX;
  13581. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13582. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13583. port = 0;
  13584. *ip_version = 99;
  13585. } else {
  13586. /* String too long */
  13587. len = 0;
  13588. }
  13589. #endif
  13590. } else {
  13591. /* Parsing failure. */
  13592. len = 0;
  13593. }
  13594. /* sscanf and the option splitting code ensure the following condition
  13595. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13596. if ((len > 0) && is_valid_port(port)
  13597. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13598. /* Next character after the port number */
  13599. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13600. so->is_ssl = (ch == 's');
  13601. so->ssl_redir = (ch == 'r');
  13602. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13603. return 1;
  13604. }
  13605. }
  13606. /* Reset ip_version to 0 if there is an error */
  13607. *ip_version = 0;
  13608. return 0;
  13609. }
  13610. /* Is there any SSL port in use? */
  13611. static int
  13612. is_ssl_port_used(const char *ports)
  13613. {
  13614. if (ports) {
  13615. /* There are several different allowed syntax variants:
  13616. * - "80" for a single port using every network interface
  13617. * - "localhost:80" for a single port using only localhost
  13618. * - "80,localhost:8080" for two ports, one bound to localhost
  13619. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13620. * to IPv4 localhost, one to IPv6 localhost
  13621. * - "+80" use port 80 for IPv4 and IPv6
  13622. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13623. * for both: IPv4 and IPv4
  13624. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13625. * additionally port 8080 bound to localhost connections
  13626. *
  13627. * If we just look for 's' anywhere in the string, "localhost:80"
  13628. * will be detected as SSL (false positive).
  13629. * Looking for 's' after a digit may cause false positives in
  13630. * "my24service:8080".
  13631. * Looking from 's' backward if there are only ':' and numbers
  13632. * before will not work for "24service:8080" (non SSL, port 8080)
  13633. * or "24s" (SSL, port 24).
  13634. *
  13635. * Remark: Initially hostnames were not allowed to start with a
  13636. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13637. * Section 2.1).
  13638. *
  13639. * To get this correct, the entire string must be parsed as a whole,
  13640. * reading it as a list element for element and parsing with an
  13641. * algorithm equivalent to parse_port_string.
  13642. *
  13643. * In fact, we use local interface names here, not arbitrary
  13644. * hostnames, so in most cases the only name will be "localhost".
  13645. *
  13646. * So, for now, we use this simple algorithm, that may still return
  13647. * a false positive in bizarre cases.
  13648. */
  13649. int i;
  13650. int portslen = (int)strlen(ports);
  13651. char prevIsNumber = 0;
  13652. for (i = 0; i < portslen; i++) {
  13653. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13654. return 1;
  13655. }
  13656. if (ports[i] >= '0' && ports[i] <= '9') {
  13657. prevIsNumber = 1;
  13658. } else {
  13659. prevIsNumber = 0;
  13660. }
  13661. }
  13662. }
  13663. return 0;
  13664. }
  13665. static int
  13666. set_ports_option(struct mg_context *phys_ctx)
  13667. {
  13668. const char *list;
  13669. int on = 1;
  13670. #if defined(USE_IPV6)
  13671. int off = 0;
  13672. #endif
  13673. struct vec vec;
  13674. struct socket so, *ptr;
  13675. struct mg_pollfd *pfd;
  13676. union usa usa;
  13677. socklen_t len;
  13678. int ip_version;
  13679. int portsTotal = 0;
  13680. int portsOk = 0;
  13681. const char *opt_txt;
  13682. long opt_listen_backlog;
  13683. if (!phys_ctx) {
  13684. return 0;
  13685. }
  13686. memset(&so, 0, sizeof(so));
  13687. memset(&usa, 0, sizeof(usa));
  13688. len = sizeof(usa);
  13689. list = phys_ctx->dd.config[LISTENING_PORTS];
  13690. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13691. portsTotal++;
  13692. if (!parse_port_string(&vec, &so, &ip_version)) {
  13693. mg_cry_ctx_internal(
  13694. phys_ctx,
  13695. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13696. (int)vec.len,
  13697. vec.ptr,
  13698. portsTotal,
  13699. "[IP_ADDRESS:]PORT[s|r]");
  13700. continue;
  13701. }
  13702. #if !defined(NO_SSL)
  13703. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13704. mg_cry_ctx_internal(phys_ctx,
  13705. "Cannot add SSL socket (entry %i)",
  13706. portsTotal);
  13707. continue;
  13708. }
  13709. #endif
  13710. /* Create socket. */
  13711. /* For a list of protocol numbers (e.g., TCP==6) see:
  13712. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13713. */
  13714. if ((so.sock =
  13715. socket(so.lsa.sa.sa_family,
  13716. SOCK_STREAM,
  13717. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13718. == INVALID_SOCKET) {
  13719. mg_cry_ctx_internal(phys_ctx,
  13720. "cannot create socket (entry %i)",
  13721. portsTotal);
  13722. continue;
  13723. }
  13724. #if defined(_WIN32)
  13725. /* Windows SO_REUSEADDR lets many procs binds to a
  13726. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13727. * if someone already has the socket -- DTL */
  13728. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13729. * Windows might need a few seconds before
  13730. * the same port can be used again in the
  13731. * same process, so a short Sleep may be
  13732. * required between mg_stop and mg_start.
  13733. */
  13734. if (setsockopt(so.sock,
  13735. SOL_SOCKET,
  13736. SO_EXCLUSIVEADDRUSE,
  13737. (SOCK_OPT_TYPE)&on,
  13738. sizeof(on))
  13739. != 0) {
  13740. /* Set reuse option, but don't abort on errors. */
  13741. mg_cry_ctx_internal(
  13742. phys_ctx,
  13743. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13744. portsTotal);
  13745. }
  13746. #else
  13747. if (setsockopt(so.sock,
  13748. SOL_SOCKET,
  13749. SO_REUSEADDR,
  13750. (SOCK_OPT_TYPE)&on,
  13751. sizeof(on))
  13752. != 0) {
  13753. /* Set reuse option, but don't abort on errors. */
  13754. mg_cry_ctx_internal(
  13755. phys_ctx,
  13756. "cannot set socket option SO_REUSEADDR (entry %i)",
  13757. portsTotal);
  13758. }
  13759. #endif
  13760. #if defined(USE_X_DOM_SOCKET)
  13761. if (ip_version == 99) {
  13762. /* Unix domain socket */
  13763. } else
  13764. #endif
  13765. if (ip_version > 4) {
  13766. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13767. #if defined(USE_IPV6)
  13768. if (ip_version > 6) {
  13769. if (so.lsa.sa.sa_family == AF_INET6
  13770. && setsockopt(so.sock,
  13771. IPPROTO_IPV6,
  13772. IPV6_V6ONLY,
  13773. (void *)&off,
  13774. sizeof(off))
  13775. != 0) {
  13776. /* Set IPv6 only option, but don't abort on errors. */
  13777. mg_cry_ctx_internal(phys_ctx,
  13778. "cannot set socket option "
  13779. "IPV6_V6ONLY=off (entry %i)",
  13780. portsTotal);
  13781. }
  13782. } else {
  13783. if (so.lsa.sa.sa_family == AF_INET6
  13784. && setsockopt(so.sock,
  13785. IPPROTO_IPV6,
  13786. IPV6_V6ONLY,
  13787. (void *)&on,
  13788. sizeof(on))
  13789. != 0) {
  13790. /* Set IPv6 only option, but don't abort on errors. */
  13791. mg_cry_ctx_internal(phys_ctx,
  13792. "cannot set socket option "
  13793. "IPV6_V6ONLY=on (entry %i)",
  13794. portsTotal);
  13795. }
  13796. }
  13797. #else
  13798. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13799. closesocket(so.sock);
  13800. so.sock = INVALID_SOCKET;
  13801. continue;
  13802. #endif
  13803. }
  13804. if (so.lsa.sa.sa_family == AF_INET) {
  13805. len = sizeof(so.lsa.sin);
  13806. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13807. mg_cry_ctx_internal(phys_ctx,
  13808. "cannot bind to %.*s: %d (%s)",
  13809. (int)vec.len,
  13810. vec.ptr,
  13811. (int)ERRNO,
  13812. strerror(errno));
  13813. closesocket(so.sock);
  13814. so.sock = INVALID_SOCKET;
  13815. continue;
  13816. }
  13817. }
  13818. #if defined(USE_IPV6)
  13819. else if (so.lsa.sa.sa_family == AF_INET6) {
  13820. len = sizeof(so.lsa.sin6);
  13821. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13822. mg_cry_ctx_internal(phys_ctx,
  13823. "cannot bind to IPv6 %.*s: %d (%s)",
  13824. (int)vec.len,
  13825. vec.ptr,
  13826. (int)ERRNO,
  13827. strerror(errno));
  13828. closesocket(so.sock);
  13829. so.sock = INVALID_SOCKET;
  13830. continue;
  13831. }
  13832. }
  13833. #endif
  13834. #if defined(USE_X_DOM_SOCKET)
  13835. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13836. len = sizeof(so.lsa.sun);
  13837. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13838. mg_cry_ctx_internal(phys_ctx,
  13839. "cannot bind to unix socket %s: %d (%s)",
  13840. so.lsa.sun.sun_path,
  13841. (int)ERRNO,
  13842. strerror(errno));
  13843. closesocket(so.sock);
  13844. so.sock = INVALID_SOCKET;
  13845. continue;
  13846. }
  13847. }
  13848. #endif
  13849. else {
  13850. mg_cry_ctx_internal(
  13851. phys_ctx,
  13852. "cannot bind: address family not supported (entry %i)",
  13853. portsTotal);
  13854. closesocket(so.sock);
  13855. so.sock = INVALID_SOCKET;
  13856. continue;
  13857. }
  13858. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13859. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13860. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13861. mg_cry_ctx_internal(phys_ctx,
  13862. "%s value \"%s\" is invalid",
  13863. config_options[LISTEN_BACKLOG_SIZE].name,
  13864. opt_txt);
  13865. closesocket(so.sock);
  13866. so.sock = INVALID_SOCKET;
  13867. continue;
  13868. }
  13869. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13870. mg_cry_ctx_internal(phys_ctx,
  13871. "cannot listen to %.*s: %d (%s)",
  13872. (int)vec.len,
  13873. vec.ptr,
  13874. (int)ERRNO,
  13875. strerror(errno));
  13876. closesocket(so.sock);
  13877. so.sock = INVALID_SOCKET;
  13878. continue;
  13879. }
  13880. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13881. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13882. int err = (int)ERRNO;
  13883. mg_cry_ctx_internal(phys_ctx,
  13884. "call to getsockname failed %.*s: %d (%s)",
  13885. (int)vec.len,
  13886. vec.ptr,
  13887. err,
  13888. strerror(errno));
  13889. closesocket(so.sock);
  13890. so.sock = INVALID_SOCKET;
  13891. continue;
  13892. }
  13893. /* Update lsa port in case of random free ports */
  13894. #if defined(USE_IPV6)
  13895. if (so.lsa.sa.sa_family == AF_INET6) {
  13896. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13897. } else
  13898. #endif
  13899. {
  13900. so.lsa.sin.sin_port = usa.sin.sin_port;
  13901. }
  13902. if ((ptr = (struct socket *)
  13903. mg_realloc_ctx(phys_ctx->listening_sockets,
  13904. (phys_ctx->num_listening_sockets + 1)
  13905. * sizeof(phys_ctx->listening_sockets[0]),
  13906. phys_ctx))
  13907. == NULL) {
  13908. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13909. closesocket(so.sock);
  13910. so.sock = INVALID_SOCKET;
  13911. continue;
  13912. }
  13913. if ((pfd = (struct mg_pollfd *)
  13914. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13915. (phys_ctx->num_listening_sockets + 1)
  13916. * sizeof(phys_ctx->listening_socket_fds[0]),
  13917. phys_ctx))
  13918. == NULL) {
  13919. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13920. closesocket(so.sock);
  13921. so.sock = INVALID_SOCKET;
  13922. mg_free(ptr);
  13923. continue;
  13924. }
  13925. set_close_on_exec(so.sock, NULL, phys_ctx);
  13926. phys_ctx->listening_sockets = ptr;
  13927. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13928. phys_ctx->listening_socket_fds = pfd;
  13929. phys_ctx->num_listening_sockets++;
  13930. portsOk++;
  13931. }
  13932. if (portsOk != portsTotal) {
  13933. close_all_listening_sockets(phys_ctx);
  13934. portsOk = 0;
  13935. }
  13936. return portsOk;
  13937. }
  13938. static const char *
  13939. header_val(const struct mg_connection *conn, const char *header)
  13940. {
  13941. const char *header_value;
  13942. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13943. return "-";
  13944. } else {
  13945. return header_value;
  13946. }
  13947. }
  13948. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13949. #include "external_log_access.inl"
  13950. #elif !defined(NO_FILESYSTEMS)
  13951. static void
  13952. log_access(const struct mg_connection *conn)
  13953. {
  13954. const struct mg_request_info *ri;
  13955. struct mg_file fi;
  13956. char date[64], src_addr[IP_ADDR_STR_LEN];
  13957. #if defined(REENTRANT_TIME)
  13958. struct tm _tm;
  13959. struct tm *tm = &_tm;
  13960. #else
  13961. struct tm *tm;
  13962. #endif
  13963. const char *referer;
  13964. const char *user_agent;
  13965. char log_buf[4096];
  13966. if (!conn || !conn->dom_ctx) {
  13967. return;
  13968. }
  13969. /* Set log message to "empty" */
  13970. log_buf[0] = 0;
  13971. #if defined(USE_LUA)
  13972. if (conn->phys_ctx->lua_bg_log_available) {
  13973. int ret;
  13974. struct mg_context *ctx = conn->phys_ctx;
  13975. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13976. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13977. /* call "log()" in Lua */
  13978. lua_getglobal(lstate, "log");
  13979. prepare_lua_request_info_inner(conn, lstate);
  13980. push_lua_response_log_data(conn, lstate);
  13981. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13982. if (ret == 0) {
  13983. int t = lua_type(lstate, -1);
  13984. if (t == LUA_TBOOLEAN) {
  13985. if (lua_toboolean(lstate, -1) == 0) {
  13986. /* log() returned false: do not log */
  13987. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13988. return;
  13989. }
  13990. /* log returned true: continue logging */
  13991. } else if (t == LUA_TSTRING) {
  13992. size_t len;
  13993. const char *txt = lua_tolstring(lstate, -1, &len);
  13994. if ((len == 0) || (*txt == 0)) {
  13995. /* log() returned empty string: do not log */
  13996. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13997. return;
  13998. }
  13999. /* Copy test from Lua into log_buf */
  14000. if (len >= sizeof(log_buf)) {
  14001. len = sizeof(log_buf) - 1;
  14002. }
  14003. memcpy(log_buf, txt, len);
  14004. log_buf[len] = 0;
  14005. }
  14006. } else {
  14007. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14008. }
  14009. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14010. }
  14011. #endif
  14012. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14013. if (mg_fopen(conn,
  14014. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14015. MG_FOPEN_MODE_APPEND,
  14016. &fi)
  14017. == 0) {
  14018. fi.access.fp = NULL;
  14019. }
  14020. } else {
  14021. fi.access.fp = NULL;
  14022. }
  14023. /* Log is written to a file and/or a callback. If both are not set,
  14024. * executing the rest of the function is pointless. */
  14025. if ((fi.access.fp == NULL)
  14026. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14027. return;
  14028. }
  14029. /* If we did not get a log message from Lua, create it here. */
  14030. if (!log_buf[0]) {
  14031. #if defined(REENTRANT_TIME)
  14032. localtime_r(&conn->conn_birth_time, tm);
  14033. #else
  14034. tm = localtime(&conn->conn_birth_time);
  14035. #endif
  14036. if (tm != NULL) {
  14037. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14038. } else {
  14039. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14040. date[sizeof(date) - 1] = '\0';
  14041. }
  14042. ri = &conn->request_info;
  14043. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14044. referer = header_val(conn, "Referer");
  14045. user_agent = header_val(conn, "User-Agent");
  14046. mg_snprintf(conn,
  14047. NULL, /* Ignore truncation in access log */
  14048. log_buf,
  14049. sizeof(log_buf),
  14050. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14051. " %s %s",
  14052. src_addr,
  14053. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14054. date,
  14055. ri->request_method ? ri->request_method : "-",
  14056. ri->request_uri ? ri->request_uri : "-",
  14057. ri->query_string ? "?" : "",
  14058. ri->query_string ? ri->query_string : "",
  14059. ri->http_version,
  14060. conn->status_code,
  14061. conn->num_bytes_sent,
  14062. referer,
  14063. user_agent);
  14064. }
  14065. /* Here we have a log message in log_buf. Call the callback */
  14066. if (conn->phys_ctx->callbacks.log_access) {
  14067. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14068. /* do not log if callack returns non-zero */
  14069. if (fi.access.fp) {
  14070. mg_fclose(&fi.access);
  14071. }
  14072. return;
  14073. }
  14074. }
  14075. /* Store in file */
  14076. if (fi.access.fp) {
  14077. int ok = 1;
  14078. flockfile(fi.access.fp);
  14079. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14080. ok = 0;
  14081. }
  14082. if (fflush(fi.access.fp) != 0) {
  14083. ok = 0;
  14084. }
  14085. funlockfile(fi.access.fp);
  14086. if (mg_fclose(&fi.access) != 0) {
  14087. ok = 0;
  14088. }
  14089. if (!ok) {
  14090. mg_cry_internal(conn,
  14091. "Error writing log file %s",
  14092. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14093. }
  14094. }
  14095. }
  14096. #else
  14097. #error "Either enable filesystems or provide a custom log_access implementation"
  14098. #endif /* Externally provided function */
  14099. /* Verify given socket address against the ACL.
  14100. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14101. */
  14102. static int
  14103. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14104. {
  14105. int allowed, flag, matched;
  14106. struct vec vec;
  14107. if (phys_ctx) {
  14108. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14109. /* If any ACL is set, deny by default */
  14110. allowed = (list == NULL) ? '+' : '-';
  14111. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14112. flag = vec.ptr[0];
  14113. matched = -1;
  14114. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14115. vec.ptr++;
  14116. vec.len--;
  14117. matched = parse_match_net(&vec, sa, 1);
  14118. }
  14119. if (matched < 0) {
  14120. mg_cry_ctx_internal(phys_ctx,
  14121. "%s: subnet must be [+|-]IP-addr[/x]",
  14122. __func__);
  14123. return -1;
  14124. }
  14125. if (matched) {
  14126. allowed = flag;
  14127. }
  14128. }
  14129. return allowed == '+';
  14130. }
  14131. return -1;
  14132. }
  14133. #if !defined(_WIN32) && !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  14134. static int
  14135. set_uid_option(struct mg_context *phys_ctx)
  14136. {
  14137. int success = 0;
  14138. if (phys_ctx) {
  14139. /* We are currently running as curr_uid. */
  14140. const uid_t curr_uid = getuid();
  14141. /* If set, we want to run as run_as_user. */
  14142. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14143. const struct passwd *to_pw = NULL;
  14144. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14145. /* run_as_user does not exist on the system. We can't proceed
  14146. * further. */
  14147. mg_cry_ctx_internal(phys_ctx,
  14148. "%s: unknown user [%s]",
  14149. __func__,
  14150. run_as_user);
  14151. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14152. /* There was either no request to change user, or we're already
  14153. * running as run_as_user. Nothing else to do.
  14154. */
  14155. success = 1;
  14156. } else {
  14157. /* Valid change request. */
  14158. if (setgid(to_pw->pw_gid) == -1) {
  14159. mg_cry_ctx_internal(phys_ctx,
  14160. "%s: setgid(%s): %s",
  14161. __func__,
  14162. run_as_user,
  14163. strerror(errno));
  14164. } else if (setgroups(0, NULL) == -1) {
  14165. mg_cry_ctx_internal(phys_ctx,
  14166. "%s: setgroups(): %s",
  14167. __func__,
  14168. strerror(errno));
  14169. } else if (setuid(to_pw->pw_uid) == -1) {
  14170. mg_cry_ctx_internal(phys_ctx,
  14171. "%s: setuid(%s): %s",
  14172. __func__,
  14173. run_as_user,
  14174. strerror(errno));
  14175. } else {
  14176. success = 1;
  14177. }
  14178. }
  14179. }
  14180. return success;
  14181. }
  14182. #endif /* !_WIN32 */
  14183. static void
  14184. tls_dtor(void *key)
  14185. {
  14186. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14187. /* key == pthread_getspecific(sTlsKey); */
  14188. if (tls) {
  14189. if (tls->is_master == 2) {
  14190. tls->is_master = -3; /* Mark memory as dead */
  14191. mg_free(tls);
  14192. }
  14193. }
  14194. pthread_setspecific(sTlsKey, NULL);
  14195. }
  14196. #if defined(USE_MBEDTLS)
  14197. /* Check if SSL is required.
  14198. * If so, set up ctx->ssl_ctx pointer. */
  14199. static int
  14200. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14201. {
  14202. if (!phys_ctx) {
  14203. return 0;
  14204. }
  14205. if (!dom_ctx) {
  14206. dom_ctx = &(phys_ctx->dd);
  14207. }
  14208. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14209. /* No SSL port is set. No need to setup SSL. */
  14210. return 1;
  14211. }
  14212. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14213. if (dom_ctx->ssl_ctx == NULL) {
  14214. fprintf(stderr, "ssl_ctx malloc failed\n");
  14215. return 0;
  14216. }
  14217. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14218. == 0
  14219. ? 1
  14220. : 0;
  14221. }
  14222. #elif !defined(NO_SSL)
  14223. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14224. struct mg_domain_context *dom_ctx,
  14225. const char *pem,
  14226. const char *chain);
  14227. static const char *ssl_error(void);
  14228. static int
  14229. refresh_trust(struct mg_connection *conn)
  14230. {
  14231. struct stat cert_buf;
  14232. int64_t t = 0;
  14233. const char *pem;
  14234. const char *chain;
  14235. int should_verify_peer;
  14236. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14237. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14238. * refresh_trust still can not work. */
  14239. return 0;
  14240. }
  14241. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14242. if (chain == NULL) {
  14243. /* pem is not NULL here */
  14244. chain = pem;
  14245. }
  14246. if (*chain == 0) {
  14247. chain = NULL;
  14248. }
  14249. if (stat(pem, &cert_buf) != -1) {
  14250. t = (int64_t)cert_buf.st_mtime;
  14251. }
  14252. mg_lock_context(conn->phys_ctx);
  14253. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14254. conn->dom_ctx->ssl_cert_last_mtime = t;
  14255. should_verify_peer = 0;
  14256. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14257. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14258. == 0) {
  14259. should_verify_peer = 1;
  14260. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14261. "optional")
  14262. == 0) {
  14263. should_verify_peer = 1;
  14264. }
  14265. }
  14266. if (should_verify_peer) {
  14267. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14268. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14269. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14270. ca_file,
  14271. ca_path)
  14272. != 1) {
  14273. mg_unlock_context(conn->phys_ctx);
  14274. mg_cry_ctx_internal(
  14275. conn->phys_ctx,
  14276. "SSL_CTX_load_verify_locations error: %s "
  14277. "ssl_verify_peer requires setting "
  14278. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14279. "present in "
  14280. "the .conf file?",
  14281. ssl_error());
  14282. return 0;
  14283. }
  14284. }
  14285. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14286. mg_unlock_context(conn->phys_ctx);
  14287. return 0;
  14288. }
  14289. }
  14290. mg_unlock_context(conn->phys_ctx);
  14291. return 1;
  14292. }
  14293. #if defined(OPENSSL_API_1_1)
  14294. #else
  14295. static pthread_mutex_t *ssl_mutexes;
  14296. #endif /* OPENSSL_API_1_1 */
  14297. static int
  14298. sslize(struct mg_connection *conn,
  14299. int (*func)(SSL *),
  14300. const struct mg_client_options *client_options)
  14301. {
  14302. int ret, err;
  14303. int short_trust;
  14304. unsigned timeout = 1024;
  14305. unsigned i;
  14306. if (!conn) {
  14307. return 0;
  14308. }
  14309. short_trust =
  14310. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14311. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14312. if (short_trust) {
  14313. int trust_ret = refresh_trust(conn);
  14314. if (!trust_ret) {
  14315. return trust_ret;
  14316. }
  14317. }
  14318. mg_lock_context(conn->phys_ctx);
  14319. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14320. mg_unlock_context(conn->phys_ctx);
  14321. if (conn->ssl == NULL) {
  14322. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14323. OPENSSL_REMOVE_THREAD_STATE();
  14324. return 0;
  14325. }
  14326. SSL_set_app_data(conn->ssl, (char *)conn);
  14327. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14328. if (ret != 1) {
  14329. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14330. SSL_free(conn->ssl);
  14331. conn->ssl = NULL;
  14332. OPENSSL_REMOVE_THREAD_STATE();
  14333. return 0;
  14334. }
  14335. if (client_options) {
  14336. if (client_options->host_name) {
  14337. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14338. }
  14339. }
  14340. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14341. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14342. /* NOTE: The loop below acts as a back-off, so we can end
  14343. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14344. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14345. if (to >= 0) {
  14346. timeout = (unsigned)to;
  14347. }
  14348. }
  14349. /* SSL functions may fail and require to be called again:
  14350. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14351. * Here "func" could be SSL_connect or SSL_accept. */
  14352. for (i = 0; i <= timeout; i += 50) {
  14353. ERR_clear_error();
  14354. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14355. ret = func(conn->ssl);
  14356. if (ret != 1) {
  14357. err = SSL_get_error(conn->ssl, ret);
  14358. if ((err == SSL_ERROR_WANT_CONNECT)
  14359. || (err == SSL_ERROR_WANT_ACCEPT)
  14360. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14361. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14362. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14363. /* Don't wait if the server is going to be stopped. */
  14364. break;
  14365. }
  14366. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14367. /* Simply retry the function call. */
  14368. mg_sleep(50);
  14369. } else {
  14370. /* Need to retry the function call "later".
  14371. * See https://linux.die.net/man/3/ssl_get_error
  14372. * This is typical for non-blocking sockets. */
  14373. struct mg_pollfd pfd;
  14374. int pollres;
  14375. pfd.fd = conn->client.sock;
  14376. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14377. || (err == SSL_ERROR_WANT_WRITE))
  14378. ? POLLOUT
  14379. : POLLIN;
  14380. pollres =
  14381. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14382. if (pollres < 0) {
  14383. /* Break if error occured (-1)
  14384. * or server shutdown (-2) */
  14385. break;
  14386. }
  14387. }
  14388. } else if (err == SSL_ERROR_SYSCALL) {
  14389. /* This is an IO error. Look at errno. */
  14390. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14391. break;
  14392. } else {
  14393. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14394. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14395. break;
  14396. }
  14397. } else {
  14398. /* success */
  14399. break;
  14400. }
  14401. }
  14402. ERR_clear_error();
  14403. if (ret != 1) {
  14404. SSL_free(conn->ssl);
  14405. conn->ssl = NULL;
  14406. OPENSSL_REMOVE_THREAD_STATE();
  14407. return 0;
  14408. }
  14409. return 1;
  14410. }
  14411. /* Return OpenSSL error message (from CRYPTO lib) */
  14412. static const char *
  14413. ssl_error(void)
  14414. {
  14415. unsigned long err;
  14416. err = ERR_get_error();
  14417. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14418. }
  14419. static int
  14420. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14421. {
  14422. int i;
  14423. const char hexdigit[] = "0123456789abcdef";
  14424. if ((memlen <= 0) || (buflen <= 0)) {
  14425. return 0;
  14426. }
  14427. if (buflen < (3 * memlen)) {
  14428. return 0;
  14429. }
  14430. for (i = 0; i < memlen; i++) {
  14431. if (i > 0) {
  14432. buf[3 * i - 1] = ' ';
  14433. }
  14434. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14435. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14436. }
  14437. buf[3 * memlen - 1] = 0;
  14438. return 1;
  14439. }
  14440. static int
  14441. ssl_get_client_cert_info(const struct mg_connection *conn,
  14442. struct mg_client_cert *client_cert)
  14443. {
  14444. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14445. if (cert) {
  14446. char str_buf[1024];
  14447. unsigned char buf[256];
  14448. char *str_serial = NULL;
  14449. unsigned int ulen;
  14450. int ilen;
  14451. unsigned char *tmp_buf;
  14452. unsigned char *tmp_p;
  14453. /* Handle to algorithm used for fingerprint */
  14454. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14455. /* Get Subject and issuer */
  14456. X509_NAME *subj = X509_get_subject_name(cert);
  14457. X509_NAME *iss = X509_get_issuer_name(cert);
  14458. /* Get serial number */
  14459. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14460. /* Translate serial number to a hex string */
  14461. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14462. if (serial_bn) {
  14463. str_serial = BN_bn2hex(serial_bn);
  14464. BN_free(serial_bn);
  14465. }
  14466. client_cert->serial =
  14467. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14468. /* Translate subject and issuer to a string */
  14469. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14470. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14471. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14472. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14473. /* Calculate SHA1 fingerprint and store as a hex string */
  14474. ulen = 0;
  14475. /* ASN1_digest is deprecated. Do the calculation manually,
  14476. * using EVP_Digest. */
  14477. ilen = i2d_X509(cert, NULL);
  14478. tmp_buf = (ilen > 0)
  14479. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14480. conn->phys_ctx)
  14481. : NULL;
  14482. if (tmp_buf) {
  14483. tmp_p = tmp_buf;
  14484. (void)i2d_X509(cert, &tmp_p);
  14485. if (!EVP_Digest(
  14486. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14487. ulen = 0;
  14488. }
  14489. mg_free(tmp_buf);
  14490. }
  14491. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14492. *str_buf = 0;
  14493. }
  14494. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14495. client_cert->peer_cert = (void *)cert;
  14496. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14497. * see https://linux.die.net/man/3/bn_bn2hex */
  14498. OPENSSL_free(str_serial);
  14499. return 1;
  14500. }
  14501. return 0;
  14502. }
  14503. #if defined(OPENSSL_API_1_1)
  14504. #else
  14505. static void
  14506. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14507. {
  14508. (void)line;
  14509. (void)file;
  14510. if (mode & 1) {
  14511. /* 1 is CRYPTO_LOCK */
  14512. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14513. } else {
  14514. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14515. }
  14516. }
  14517. #endif /* OPENSSL_API_1_1 */
  14518. #if !defined(NO_SSL_DL)
  14519. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14520. static void *
  14521. load_tls_dll(char *ebuf,
  14522. size_t ebuf_len,
  14523. const char *dll_name,
  14524. struct ssl_func *sw,
  14525. int *feature_missing)
  14526. {
  14527. union {
  14528. void *p;
  14529. void (*fp)(void);
  14530. } u;
  14531. void *dll_handle;
  14532. struct ssl_func *fp;
  14533. int ok;
  14534. int truncated = 0;
  14535. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14536. mg_snprintf(NULL,
  14537. NULL, /* No truncation check for ebuf */
  14538. ebuf,
  14539. ebuf_len,
  14540. "%s: cannot load %s",
  14541. __func__,
  14542. dll_name);
  14543. return NULL;
  14544. }
  14545. ok = 1;
  14546. for (fp = sw; fp->name != NULL; fp++) {
  14547. #if defined(_WIN32)
  14548. /* GetProcAddress() returns pointer to function */
  14549. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14550. #else
  14551. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14552. * pointers to function pointers. We need to use a union to make a
  14553. * cast. */
  14554. u.p = dlsym(dll_handle, fp->name);
  14555. #endif /* _WIN32 */
  14556. /* Set pointer (might be NULL) */
  14557. fp->ptr = u.fp;
  14558. if (u.fp == NULL) {
  14559. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14560. if (feature_missing) {
  14561. feature_missing[fp->required]++;
  14562. }
  14563. if (fp->required == TLS_Mandatory) {
  14564. /* Mandatory function is missing */
  14565. if (ok) {
  14566. /* This is the first missing function.
  14567. * Create a new error message. */
  14568. mg_snprintf(NULL,
  14569. &truncated,
  14570. ebuf,
  14571. ebuf_len,
  14572. "%s: %s: cannot find %s",
  14573. __func__,
  14574. dll_name,
  14575. fp->name);
  14576. ok = 0;
  14577. } else {
  14578. /* This is yet anothermissing function.
  14579. * Append existing error message. */
  14580. size_t cur_len = strlen(ebuf);
  14581. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14582. mg_snprintf(NULL,
  14583. &truncated,
  14584. ebuf + cur_len,
  14585. ebuf_len - cur_len - 3,
  14586. ", %s",
  14587. fp->name);
  14588. if (truncated) {
  14589. /* If truncated, add "..." */
  14590. strcat(ebuf, "...");
  14591. }
  14592. }
  14593. }
  14594. }
  14595. }
  14596. }
  14597. if (!ok) {
  14598. (void)dlclose(dll_handle);
  14599. return NULL;
  14600. }
  14601. return dll_handle;
  14602. }
  14603. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14604. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14605. #endif /* NO_SSL_DL */
  14606. #if defined(SSL_ALREADY_INITIALIZED)
  14607. static volatile ptrdiff_t cryptolib_users =
  14608. 1; /* Reference counter for crypto library. */
  14609. #else
  14610. static volatile ptrdiff_t cryptolib_users =
  14611. 0; /* Reference counter for crypto library. */
  14612. #endif
  14613. static int
  14614. initialize_openssl(char *ebuf, size_t ebuf_len)
  14615. {
  14616. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14617. int i, num_locks;
  14618. size_t size;
  14619. #endif
  14620. if (ebuf_len > 0) {
  14621. ebuf[0] = 0;
  14622. }
  14623. #if !defined(NO_SSL_DL)
  14624. if (!cryptolib_dll_handle) {
  14625. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14626. cryptolib_dll_handle = load_tls_dll(
  14627. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14628. if (!cryptolib_dll_handle) {
  14629. mg_snprintf(NULL,
  14630. NULL, /* No truncation check for ebuf */
  14631. ebuf,
  14632. ebuf_len,
  14633. "%s: error loading library %s",
  14634. __func__,
  14635. CRYPTO_LIB);
  14636. DEBUG_TRACE("%s", ebuf);
  14637. return 0;
  14638. }
  14639. }
  14640. #endif /* NO_SSL_DL */
  14641. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14642. return 1;
  14643. }
  14644. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14645. /* Initialize locking callbacks, needed for thread safety.
  14646. * http://www.openssl.org/support/faq.html#PROG1
  14647. */
  14648. num_locks = CRYPTO_num_locks();
  14649. if (num_locks < 0) {
  14650. num_locks = 0;
  14651. }
  14652. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14653. /* allocate mutex array, if required */
  14654. if (num_locks == 0) {
  14655. /* No mutex array required */
  14656. ssl_mutexes = NULL;
  14657. } else {
  14658. /* Mutex array required - allocate it */
  14659. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14660. /* Check OOM */
  14661. if (ssl_mutexes == NULL) {
  14662. mg_snprintf(NULL,
  14663. NULL, /* No truncation check for ebuf */
  14664. ebuf,
  14665. ebuf_len,
  14666. "%s: cannot allocate mutexes: %s",
  14667. __func__,
  14668. ssl_error());
  14669. DEBUG_TRACE("%s", ebuf);
  14670. return 0;
  14671. }
  14672. /* initialize mutex array */
  14673. for (i = 0; i < num_locks; i++) {
  14674. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14675. mg_snprintf(NULL,
  14676. NULL, /* No truncation check for ebuf */
  14677. ebuf,
  14678. ebuf_len,
  14679. "%s: error initializing mutex %i of %i",
  14680. __func__,
  14681. i,
  14682. num_locks);
  14683. DEBUG_TRACE("%s", ebuf);
  14684. mg_free(ssl_mutexes);
  14685. return 0;
  14686. }
  14687. }
  14688. }
  14689. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14690. CRYPTO_set_id_callback(&mg_current_thread_id);
  14691. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14692. #if !defined(NO_SSL_DL)
  14693. if (!ssllib_dll_handle) {
  14694. ssllib_dll_handle =
  14695. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14696. if (!ssllib_dll_handle) {
  14697. #if !defined(OPENSSL_API_1_1)
  14698. mg_free(ssl_mutexes);
  14699. #endif
  14700. DEBUG_TRACE("%s", ebuf);
  14701. return 0;
  14702. }
  14703. }
  14704. #endif /* NO_SSL_DL */
  14705. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14706. && !defined(NO_SSL_DL)
  14707. /* Initialize SSL library */
  14708. OPENSSL_init_ssl(0, NULL);
  14709. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14710. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14711. NULL);
  14712. #else
  14713. /* Initialize SSL library */
  14714. SSL_library_init();
  14715. SSL_load_error_strings();
  14716. #endif
  14717. return 1;
  14718. }
  14719. static int
  14720. ssl_use_pem_file(struct mg_context *phys_ctx,
  14721. struct mg_domain_context *dom_ctx,
  14722. const char *pem,
  14723. const char *chain)
  14724. {
  14725. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14726. mg_cry_ctx_internal(phys_ctx,
  14727. "%s: cannot open certificate file %s: %s",
  14728. __func__,
  14729. pem,
  14730. ssl_error());
  14731. return 0;
  14732. }
  14733. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14734. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14735. mg_cry_ctx_internal(phys_ctx,
  14736. "%s: cannot open private key file %s: %s",
  14737. __func__,
  14738. pem,
  14739. ssl_error());
  14740. return 0;
  14741. }
  14742. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14743. mg_cry_ctx_internal(phys_ctx,
  14744. "%s: certificate and private key do not match: %s",
  14745. __func__,
  14746. pem);
  14747. return 0;
  14748. }
  14749. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14750. * chain files that contain private keys and certificates in
  14751. * SSL_CTX_use_certificate_chain_file.
  14752. * The CivetWeb-Server used pem-Files that contained both information.
  14753. * In order to make wolfSSL work, it is split in two files.
  14754. * One file that contains key and certificate used by the server and
  14755. * an optional chain file for the ssl stack.
  14756. */
  14757. if (chain) {
  14758. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14759. mg_cry_ctx_internal(phys_ctx,
  14760. "%s: cannot use certificate chain file %s: %s",
  14761. __func__,
  14762. chain,
  14763. ssl_error());
  14764. return 0;
  14765. }
  14766. }
  14767. return 1;
  14768. }
  14769. #if defined(OPENSSL_API_1_1)
  14770. static unsigned long
  14771. ssl_get_protocol(int version_id)
  14772. {
  14773. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14774. if (version_id > 0)
  14775. ret |= SSL_OP_NO_SSLv2;
  14776. if (version_id > 1)
  14777. ret |= SSL_OP_NO_SSLv3;
  14778. if (version_id > 2)
  14779. ret |= SSL_OP_NO_TLSv1;
  14780. if (version_id > 3)
  14781. ret |= SSL_OP_NO_TLSv1_1;
  14782. if (version_id > 4)
  14783. ret |= SSL_OP_NO_TLSv1_2;
  14784. #if defined(SSL_OP_NO_TLSv1_3)
  14785. if (version_id > 5)
  14786. ret |= SSL_OP_NO_TLSv1_3;
  14787. #endif
  14788. return ret;
  14789. }
  14790. #else
  14791. static long
  14792. ssl_get_protocol(int version_id)
  14793. {
  14794. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14795. if (version_id > 0)
  14796. ret |= SSL_OP_NO_SSLv2;
  14797. if (version_id > 1)
  14798. ret |= SSL_OP_NO_SSLv3;
  14799. if (version_id > 2)
  14800. ret |= SSL_OP_NO_TLSv1;
  14801. if (version_id > 3)
  14802. ret |= SSL_OP_NO_TLSv1_1;
  14803. if (version_id > 4)
  14804. ret |= SSL_OP_NO_TLSv1_2;
  14805. #if defined(SSL_OP_NO_TLSv1_3)
  14806. if (version_id > 5)
  14807. ret |= SSL_OP_NO_TLSv1_3;
  14808. #endif
  14809. return (long)ret;
  14810. }
  14811. #endif /* OPENSSL_API_1_1 */
  14812. /* SSL callback documentation:
  14813. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14814. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14815. * https://linux.die.net/man/3/ssl_set_info_callback */
  14816. /* Note: There is no "const" for the first argument in the documentation
  14817. * examples, however some (maybe most, but not all) headers of OpenSSL
  14818. * versions / OpenSSL compatibility layers have it. Having a different
  14819. * definition will cause a warning in C and an error in C++. Use "const SSL
  14820. * *", while automatical conversion from "SSL *" works for all compilers,
  14821. * but not other way around */
  14822. static void
  14823. ssl_info_callback(const SSL *ssl, int what, int ret)
  14824. {
  14825. (void)ret;
  14826. if (what & SSL_CB_HANDSHAKE_START) {
  14827. SSL_get_app_data(ssl);
  14828. }
  14829. if (what & SSL_CB_HANDSHAKE_DONE) {
  14830. /* TODO: check for openSSL 1.1 */
  14831. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14832. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14833. }
  14834. }
  14835. static int
  14836. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14837. {
  14838. #if defined(GCC_DIAGNOSTIC)
  14839. #pragma GCC diagnostic push
  14840. #pragma GCC diagnostic ignored "-Wcast-align"
  14841. #endif /* defined(GCC_DIAGNOSTIC) */
  14842. /* We used an aligned pointer in SSL_set_app_data */
  14843. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14844. #if defined(GCC_DIAGNOSTIC)
  14845. #pragma GCC diagnostic pop
  14846. #endif /* defined(GCC_DIAGNOSTIC) */
  14847. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14848. (void)ad;
  14849. (void)arg;
  14850. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14851. DEBUG_ASSERT(0);
  14852. return SSL_TLSEXT_ERR_NOACK;
  14853. }
  14854. conn->dom_ctx = &(conn->phys_ctx->dd);
  14855. /* Old clients (Win XP) will not support SNI. Then, there
  14856. * is no server name available in the request - we can
  14857. * only work with the default certificate.
  14858. * Multiple HTTPS hosts on one IP+port are only possible
  14859. * with a certificate containing all alternative names.
  14860. */
  14861. if ((servername == NULL) || (*servername == 0)) {
  14862. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14863. mg_lock_context(conn->phys_ctx);
  14864. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14865. mg_unlock_context(conn->phys_ctx);
  14866. return SSL_TLSEXT_ERR_NOACK;
  14867. }
  14868. DEBUG_TRACE("TLS connection to host %s", servername);
  14869. while (conn->dom_ctx) {
  14870. if (!mg_strcasecmp(servername,
  14871. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14872. /* Found matching domain */
  14873. DEBUG_TRACE("TLS domain %s found",
  14874. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14875. break;
  14876. }
  14877. mg_lock_context(conn->phys_ctx);
  14878. conn->dom_ctx = conn->dom_ctx->next;
  14879. mg_unlock_context(conn->phys_ctx);
  14880. }
  14881. if (conn->dom_ctx == NULL) {
  14882. /* Default domain */
  14883. DEBUG_TRACE("TLS default domain %s used",
  14884. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14885. conn->dom_ctx = &(conn->phys_ctx->dd);
  14886. }
  14887. mg_lock_context(conn->phys_ctx);
  14888. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14889. mg_unlock_context(conn->phys_ctx);
  14890. return SSL_TLSEXT_ERR_OK;
  14891. }
  14892. #if defined(USE_ALPN)
  14893. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14894. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14895. alpn_proto_list + 3 + 8,
  14896. NULL};
  14897. #if defined(USE_HTTP2)
  14898. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14899. alpn_proto_list + 3,
  14900. alpn_proto_list + 3 + 8,
  14901. NULL};
  14902. #endif
  14903. static int
  14904. alpn_select_cb(SSL *ssl,
  14905. const unsigned char **out,
  14906. unsigned char *outlen,
  14907. const unsigned char *in,
  14908. unsigned int inlen,
  14909. void *arg)
  14910. {
  14911. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14912. unsigned int i, j, enable_http2 = 0;
  14913. const char **alpn_proto_order = alpn_proto_order_http1;
  14914. struct mg_workerTLS *tls =
  14915. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14916. (void)ssl;
  14917. if (tls == NULL) {
  14918. /* Need to store protocol in Thread Local Storage */
  14919. /* If there is no Thread Local Storage, don't use ALPN */
  14920. return SSL_TLSEXT_ERR_NOACK;
  14921. }
  14922. #if defined(USE_HTTP2)
  14923. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14924. if (enable_http2) {
  14925. alpn_proto_order = alpn_proto_order_http2;
  14926. }
  14927. #endif
  14928. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14929. /* check all accepted protocols in this order */
  14930. const char *alpn_proto = alpn_proto_order[j];
  14931. /* search input for matching protocol */
  14932. for (i = 0; i < inlen; i++) {
  14933. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14934. *out = in + i + 1;
  14935. *outlen = in[i];
  14936. tls->alpn_proto = alpn_proto;
  14937. return SSL_TLSEXT_ERR_OK;
  14938. }
  14939. }
  14940. }
  14941. /* Nothing found */
  14942. return SSL_TLSEXT_ERR_NOACK;
  14943. }
  14944. static int
  14945. next_protos_advertised_cb(SSL *ssl,
  14946. const unsigned char **data,
  14947. unsigned int *len,
  14948. void *arg)
  14949. {
  14950. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14951. *data = (const unsigned char *)alpn_proto_list;
  14952. *len = (unsigned int)strlen((const char *)data);
  14953. (void)ssl;
  14954. (void)dom_ctx;
  14955. return SSL_TLSEXT_ERR_OK;
  14956. }
  14957. static int
  14958. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14959. {
  14960. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14961. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14962. (const unsigned char *)alpn_proto_list,
  14963. alpn_len);
  14964. if (ret != 0) {
  14965. mg_cry_ctx_internal(phys_ctx,
  14966. "SSL_CTX_set_alpn_protos error: %s",
  14967. ssl_error());
  14968. }
  14969. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14970. alpn_select_cb,
  14971. (void *)dom_ctx);
  14972. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14973. next_protos_advertised_cb,
  14974. (void *)dom_ctx);
  14975. return ret;
  14976. }
  14977. #endif
  14978. /* Setup SSL CTX as required by CivetWeb */
  14979. static int
  14980. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14981. struct mg_domain_context *dom_ctx,
  14982. const char *pem,
  14983. const char *chain)
  14984. {
  14985. int callback_ret;
  14986. int should_verify_peer;
  14987. int peer_certificate_optional;
  14988. const char *ca_path;
  14989. const char *ca_file;
  14990. int use_default_verify_paths;
  14991. int verify_depth;
  14992. struct timespec now_mt;
  14993. md5_byte_t ssl_context_id[16];
  14994. md5_state_t md5state;
  14995. int protocol_ver;
  14996. int ssl_cache_timeout;
  14997. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14998. && !defined(NO_SSL_DL)
  14999. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15000. mg_cry_ctx_internal(phys_ctx,
  15001. "SSL_CTX_new (server) error: %s",
  15002. ssl_error());
  15003. return 0;
  15004. }
  15005. #else
  15006. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15007. mg_cry_ctx_internal(phys_ctx,
  15008. "SSL_CTX_new (server) error: %s",
  15009. ssl_error());
  15010. return 0;
  15011. }
  15012. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15013. #if defined(SSL_OP_NO_TLSv1_3)
  15014. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15015. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15016. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15017. | SSL_OP_NO_TLSv1_3);
  15018. #else
  15019. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15020. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15021. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15022. #endif
  15023. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15024. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15025. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15026. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15027. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15028. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15029. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15030. #if defined(SSL_OP_NO_RENEGOTIATION)
  15031. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15032. #endif
  15033. #if !defined(NO_SSL_DL)
  15034. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15035. #endif /* NO_SSL_DL */
  15036. /* In SSL documentation examples callback defined without const
  15037. * specifier 'void (*)(SSL *, int, int)' See:
  15038. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15039. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15040. * But in the source code const SSL is used:
  15041. * 'void (*)(const SSL *, int, int)' See:
  15042. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15043. * Problem about wrong documentation described, but not resolved:
  15044. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15045. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15046. * But when compiled with modern C++ compiler, correct const should be
  15047. * provided
  15048. */
  15049. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15050. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15051. ssl_servername_callback);
  15052. /* If a callback has been specified, call it. */
  15053. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15054. ? 0
  15055. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15056. phys_ctx->user_data));
  15057. /* If callback returns 0, civetweb sets up the SSL certificate.
  15058. * If it returns 1, civetweb assumes the calback already did this.
  15059. * If it returns -1, initializing ssl fails. */
  15060. if (callback_ret < 0) {
  15061. mg_cry_ctx_internal(phys_ctx,
  15062. "SSL callback returned error: %i",
  15063. callback_ret);
  15064. return 0;
  15065. }
  15066. if (callback_ret > 0) {
  15067. /* Callback did everything. */
  15068. return 1;
  15069. }
  15070. /* If a domain callback has been specified, call it. */
  15071. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15072. ? 0
  15073. : (phys_ctx->callbacks.init_ssl_domain(
  15074. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15075. dom_ctx->ssl_ctx,
  15076. phys_ctx->user_data));
  15077. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15078. * If it returns 1, civetweb assumes the calback already did this.
  15079. * If it returns -1, initializing ssl fails. */
  15080. if (callback_ret < 0) {
  15081. mg_cry_ctx_internal(phys_ctx,
  15082. "Domain SSL callback returned error: %i",
  15083. callback_ret);
  15084. return 0;
  15085. }
  15086. if (callback_ret > 0) {
  15087. /* Domain callback did everything. */
  15088. return 1;
  15089. }
  15090. /* Use some combination of start time, domain and port as a SSL
  15091. * context ID. This should be unique on the current machine. */
  15092. md5_init(&md5state);
  15093. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15094. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15095. md5_append(&md5state,
  15096. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15097. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15098. md5_append(&md5state,
  15099. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15100. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15101. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15102. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15103. md5_finish(&md5state, ssl_context_id);
  15104. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15105. (unsigned char *)ssl_context_id,
  15106. sizeof(ssl_context_id));
  15107. if (pem != NULL) {
  15108. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15109. return 0;
  15110. }
  15111. }
  15112. /* Should we support client certificates? */
  15113. /* Default is "no". */
  15114. should_verify_peer = 0;
  15115. peer_certificate_optional = 0;
  15116. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15117. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15118. /* Yes, they are mandatory */
  15119. should_verify_peer = 1;
  15120. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15121. "optional")
  15122. == 0) {
  15123. /* Yes, they are optional */
  15124. should_verify_peer = 1;
  15125. peer_certificate_optional = 1;
  15126. }
  15127. }
  15128. use_default_verify_paths =
  15129. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15130. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15131. == 0);
  15132. if (should_verify_peer) {
  15133. ca_path = dom_ctx->config[SSL_CA_PATH];
  15134. ca_file = dom_ctx->config[SSL_CA_FILE];
  15135. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15136. != 1) {
  15137. mg_cry_ctx_internal(phys_ctx,
  15138. "SSL_CTX_load_verify_locations error: %s "
  15139. "ssl_verify_peer requires setting "
  15140. "either ssl_ca_path or ssl_ca_file. "
  15141. "Is any of them present in the "
  15142. ".conf file?",
  15143. ssl_error());
  15144. return 0;
  15145. }
  15146. if (peer_certificate_optional) {
  15147. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15148. } else {
  15149. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15150. SSL_VERIFY_PEER
  15151. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15152. NULL);
  15153. }
  15154. if (use_default_verify_paths
  15155. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15156. mg_cry_ctx_internal(phys_ctx,
  15157. "SSL_CTX_set_default_verify_paths error: %s",
  15158. ssl_error());
  15159. return 0;
  15160. }
  15161. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15162. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15163. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15164. }
  15165. }
  15166. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15167. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15168. dom_ctx->config[SSL_CIPHER_LIST])
  15169. != 1) {
  15170. mg_cry_ctx_internal(phys_ctx,
  15171. "SSL_CTX_set_cipher_list error: %s",
  15172. ssl_error());
  15173. }
  15174. }
  15175. /* SSL session caching */
  15176. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15177. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15178. : 0);
  15179. if (ssl_cache_timeout > 0) {
  15180. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15181. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15182. * default */
  15183. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15184. }
  15185. #if defined(USE_ALPN)
  15186. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15187. #if !defined(NO_SSL_DL)
  15188. if (!tls_feature_missing[TLS_ALPN])
  15189. #endif
  15190. {
  15191. init_alpn(phys_ctx, dom_ctx);
  15192. }
  15193. #endif
  15194. return 1;
  15195. }
  15196. /* Check if SSL is required.
  15197. * If so, dynamically load SSL library
  15198. * and set up ctx->ssl_ctx pointer. */
  15199. static int
  15200. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15201. {
  15202. void *ssl_ctx = 0;
  15203. int callback_ret;
  15204. const char *pem;
  15205. const char *chain;
  15206. char ebuf[128];
  15207. if (!phys_ctx) {
  15208. return 0;
  15209. }
  15210. if (!dom_ctx) {
  15211. dom_ctx = &(phys_ctx->dd);
  15212. }
  15213. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15214. /* No SSL port is set. No need to setup SSL. */
  15215. return 1;
  15216. }
  15217. /* Check for external SSL_CTX */
  15218. callback_ret =
  15219. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15220. ? 0
  15221. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15222. phys_ctx->user_data));
  15223. if (callback_ret < 0) {
  15224. /* Callback exists and returns <0: Initializing failed. */
  15225. mg_cry_ctx_internal(phys_ctx,
  15226. "external_ssl_ctx callback returned error: %i",
  15227. callback_ret);
  15228. return 0;
  15229. } else if (callback_ret > 0) {
  15230. /* Callback exists and returns >0: Initializing complete,
  15231. * civetweb should not modify the SSL context. */
  15232. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15233. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15234. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15235. return 0;
  15236. }
  15237. return 1;
  15238. }
  15239. /* If the callback does not exist or return 0, civetweb must initialize
  15240. * the SSL context. Handle "domain" callback next. */
  15241. /* Check for external domain SSL_CTX callback. */
  15242. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15243. ? 0
  15244. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15245. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15246. &ssl_ctx,
  15247. phys_ctx->user_data));
  15248. if (callback_ret < 0) {
  15249. /* Callback < 0: Error. Abort init. */
  15250. mg_cry_ctx_internal(
  15251. phys_ctx,
  15252. "external_ssl_ctx_domain callback returned error: %i",
  15253. callback_ret);
  15254. return 0;
  15255. } else if (callback_ret > 0) {
  15256. /* Callback > 0: Consider init done. */
  15257. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15258. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15259. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15260. return 0;
  15261. }
  15262. return 1;
  15263. }
  15264. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15265. * 0, CivetWeb should continue initializing SSL */
  15266. /* If PEM file is not specified and the init_ssl callbacks
  15267. * are not specified, setup will fail. */
  15268. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15269. && (phys_ctx->callbacks.init_ssl == NULL)
  15270. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15271. /* No certificate and no init_ssl callbacks:
  15272. * Essential data to set up TLS is missing.
  15273. */
  15274. mg_cry_ctx_internal(phys_ctx,
  15275. "Initializing SSL failed: -%s is not set",
  15276. config_options[SSL_CERTIFICATE].name);
  15277. return 0;
  15278. }
  15279. /* If a certificate chain is configured, use it. */
  15280. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15281. if (chain == NULL) {
  15282. /* Default: certificate chain in PEM file */
  15283. chain = pem;
  15284. }
  15285. if ((chain != NULL) && (*chain == 0)) {
  15286. /* If the chain is an empty string, don't use it. */
  15287. chain = NULL;
  15288. }
  15289. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15290. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15291. return 0;
  15292. }
  15293. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15294. }
  15295. static void
  15296. uninitialize_openssl(void)
  15297. {
  15298. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15299. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15300. /* Shutdown according to
  15301. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15302. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15303. */
  15304. CONF_modules_unload(1);
  15305. #else
  15306. int i;
  15307. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15308. /* Shutdown according to
  15309. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15310. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15311. */
  15312. CRYPTO_set_locking_callback(NULL);
  15313. CRYPTO_set_id_callback(NULL);
  15314. ENGINE_cleanup();
  15315. CONF_modules_unload(1);
  15316. ERR_free_strings();
  15317. EVP_cleanup();
  15318. CRYPTO_cleanup_all_ex_data();
  15319. OPENSSL_REMOVE_THREAD_STATE();
  15320. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15321. pthread_mutex_destroy(&ssl_mutexes[i]);
  15322. }
  15323. mg_free(ssl_mutexes);
  15324. ssl_mutexes = NULL;
  15325. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15326. }
  15327. }
  15328. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15329. #if !defined(NO_FILESYSTEMS)
  15330. static int
  15331. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15332. {
  15333. if (phys_ctx) {
  15334. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15335. const char *path;
  15336. struct mg_connection fc;
  15337. if (!dom_ctx) {
  15338. dom_ctx = &(phys_ctx->dd);
  15339. }
  15340. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15341. if ((path != NULL)
  15342. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15343. mg_cry_ctx_internal(phys_ctx,
  15344. "Cannot open %s: %s",
  15345. path,
  15346. strerror(ERRNO));
  15347. return 0;
  15348. }
  15349. return 1;
  15350. }
  15351. return 0;
  15352. }
  15353. #endif /* NO_FILESYSTEMS */
  15354. static int
  15355. set_acl_option(struct mg_context *phys_ctx)
  15356. {
  15357. union usa sa;
  15358. memset(&sa, 0, sizeof(sa));
  15359. #if defined(USE_IPV6)
  15360. sa.sin6.sin6_family = AF_INET6;
  15361. #else
  15362. sa.sin.sin_family = AF_INET;
  15363. #endif
  15364. return check_acl(phys_ctx, &sa) != -1;
  15365. }
  15366. static void
  15367. reset_per_request_attributes(struct mg_connection *conn)
  15368. {
  15369. if (!conn) {
  15370. return;
  15371. }
  15372. conn->num_bytes_sent = conn->consumed_content = 0;
  15373. conn->path_info = NULL;
  15374. conn->status_code = -1;
  15375. conn->content_len = -1;
  15376. conn->is_chunked = 0;
  15377. conn->must_close = 0;
  15378. conn->request_len = 0;
  15379. conn->request_state = 0;
  15380. conn->throttle = 0;
  15381. conn->accept_gzip = 0;
  15382. conn->response_info.content_length = conn->request_info.content_length = -1;
  15383. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15384. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15385. conn->response_info.status_text = NULL;
  15386. conn->response_info.status_code = 0;
  15387. conn->request_info.remote_user = NULL;
  15388. conn->request_info.request_method = NULL;
  15389. conn->request_info.request_uri = NULL;
  15390. /* Free cleaned local URI (if any) */
  15391. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15392. mg_free((void *)conn->request_info.local_uri);
  15393. conn->request_info.local_uri = NULL;
  15394. }
  15395. conn->request_info.local_uri = NULL;
  15396. #if defined(USE_SERVER_STATS)
  15397. conn->processing_time = 0;
  15398. #endif
  15399. }
  15400. static int
  15401. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15402. {
  15403. if ((so->lsa.sa.sa_family == AF_INET)
  15404. || (so->lsa.sa.sa_family == AF_INET6)) {
  15405. /* Only for TCP sockets */
  15406. if (setsockopt(so->sock,
  15407. IPPROTO_TCP,
  15408. TCP_NODELAY,
  15409. (SOCK_OPT_TYPE)&nodelay_on,
  15410. sizeof(nodelay_on))
  15411. != 0) {
  15412. /* Error */
  15413. return 1;
  15414. }
  15415. }
  15416. /* OK */
  15417. return 0;
  15418. }
  15419. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  15420. static void
  15421. close_socket_gracefully(struct mg_connection *conn)
  15422. {
  15423. #if defined(_WIN32)
  15424. char buf[MG_BUF_LEN];
  15425. int n;
  15426. #endif
  15427. struct linger linger;
  15428. int error_code = 0;
  15429. int linger_timeout = -2;
  15430. socklen_t opt_len = sizeof(error_code);
  15431. if (!conn) {
  15432. return;
  15433. }
  15434. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15435. * "Note that enabling a nonzero timeout on a nonblocking socket
  15436. * is not recommended.", so set it to blocking now */
  15437. set_blocking_mode(conn->client.sock);
  15438. /* Send FIN to the client */
  15439. shutdown(conn->client.sock, SHUTDOWN_WR);
  15440. #if defined(_WIN32)
  15441. /* Read and discard pending incoming data. If we do not do that and
  15442. * close
  15443. * the socket, the data in the send buffer may be discarded. This
  15444. * behaviour is seen on Windows, when client keeps sending data
  15445. * when server decides to close the connection; then when client
  15446. * does recv() it gets no data back. */
  15447. do {
  15448. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15449. } while (n > 0);
  15450. #endif
  15451. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15452. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15453. }
  15454. /* Set linger option according to configuration */
  15455. if (linger_timeout >= 0) {
  15456. /* Set linger option to avoid socket hanging out after close. This
  15457. * prevent ephemeral port exhaust problem under high QPS. */
  15458. linger.l_onoff = 1;
  15459. #if defined(_MSC_VER)
  15460. #pragma warning(push)
  15461. #pragma warning(disable : 4244)
  15462. #endif
  15463. #if defined(GCC_DIAGNOSTIC)
  15464. #pragma GCC diagnostic push
  15465. #pragma GCC diagnostic ignored "-Wconversion"
  15466. #endif
  15467. /* Data type of linger structure elements may differ,
  15468. * so we don't know what cast we need here.
  15469. * Disable type conversion warnings. */
  15470. linger.l_linger = (linger_timeout + 999) / 1000;
  15471. #if defined(GCC_DIAGNOSTIC)
  15472. #pragma GCC diagnostic pop
  15473. #endif
  15474. #if defined(_MSC_VER)
  15475. #pragma warning(pop)
  15476. #endif
  15477. } else {
  15478. linger.l_onoff = 0;
  15479. linger.l_linger = 0;
  15480. }
  15481. if (linger_timeout < -1) {
  15482. /* Default: don't configure any linger */
  15483. } else if (getsockopt(conn->client.sock,
  15484. SOL_SOCKET,
  15485. SO_ERROR,
  15486. #if defined(_WIN32) /* WinSock uses different data type here */
  15487. (char *)&error_code,
  15488. #else
  15489. &error_code,
  15490. #endif
  15491. &opt_len)
  15492. != 0) {
  15493. /* Cannot determine if socket is already closed. This should
  15494. * not occur and never did in a test. Log an error message
  15495. * and continue. */
  15496. mg_cry_internal(conn,
  15497. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15498. __func__,
  15499. strerror(ERRNO));
  15500. #if defined(_WIN32)
  15501. } else if (error_code == WSAECONNRESET) {
  15502. #else
  15503. } else if (error_code == ECONNRESET) {
  15504. #endif
  15505. /* Socket already closed by client/peer, close socket without linger
  15506. */
  15507. } else {
  15508. /* Set linger timeout */
  15509. if (setsockopt(conn->client.sock,
  15510. SOL_SOCKET,
  15511. SO_LINGER,
  15512. (char *)&linger,
  15513. sizeof(linger))
  15514. != 0) {
  15515. mg_cry_internal(
  15516. conn,
  15517. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15518. __func__,
  15519. linger.l_onoff,
  15520. linger.l_linger,
  15521. strerror(ERRNO));
  15522. }
  15523. }
  15524. /* Now we know that our FIN is ACK-ed, safe to close */
  15525. closesocket(conn->client.sock);
  15526. conn->client.sock = INVALID_SOCKET;
  15527. }
  15528. #endif
  15529. static void
  15530. close_connection(struct mg_connection *conn)
  15531. {
  15532. #if defined(USE_SERVER_STATS)
  15533. conn->conn_state = 6; /* to close */
  15534. #endif
  15535. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15536. if (conn->lua_websocket_state) {
  15537. lua_websocket_close(conn, conn->lua_websocket_state);
  15538. conn->lua_websocket_state = NULL;
  15539. }
  15540. #endif
  15541. mg_lock_connection(conn);
  15542. /* Set close flag, so keep-alive loops will stop */
  15543. conn->must_close = 1;
  15544. /* call the connection_close callback if assigned */
  15545. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15546. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15547. conn->phys_ctx->callbacks.connection_close(conn);
  15548. }
  15549. }
  15550. /* Reset user data, after close callback is called.
  15551. * Do not reuse it. If the user needs a destructor,
  15552. * it must be done in the connection_close callback. */
  15553. mg_set_user_connection_data(conn, NULL);
  15554. #if defined(USE_SERVER_STATS)
  15555. conn->conn_state = 7; /* closing */
  15556. #endif
  15557. #if defined(USE_MBEDTLS)
  15558. if (conn->ssl != NULL) {
  15559. mbed_ssl_close(conn->ssl);
  15560. conn->ssl = NULL;
  15561. }
  15562. #elif !defined(NO_SSL)
  15563. if (conn->ssl != NULL) {
  15564. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15565. */
  15566. SSL_shutdown(conn->ssl);
  15567. SSL_free(conn->ssl);
  15568. OPENSSL_REMOVE_THREAD_STATE();
  15569. conn->ssl = NULL;
  15570. }
  15571. #endif
  15572. if (conn->client.sock != INVALID_SOCKET) {
  15573. #if defined(__ZEPHYR__) || defined(ESP_PLATFORM)
  15574. closesocket(conn->client.sock);
  15575. #else
  15576. close_socket_gracefully(conn);
  15577. #endif
  15578. conn->client.sock = INVALID_SOCKET;
  15579. }
  15580. /* call the connection_closed callback if assigned */
  15581. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15582. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15583. conn->phys_ctx->callbacks.connection_closed(conn);
  15584. }
  15585. }
  15586. mg_unlock_connection(conn);
  15587. #if defined(USE_SERVER_STATS)
  15588. conn->conn_state = 8; /* closed */
  15589. #endif
  15590. }
  15591. CIVETWEB_API void
  15592. mg_close_connection(struct mg_connection *conn)
  15593. {
  15594. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15595. return;
  15596. }
  15597. #if defined(USE_WEBSOCKET)
  15598. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15599. if (conn->in_websocket_handling) {
  15600. /* Set close flag, so the server thread can exit. */
  15601. conn->must_close = 1;
  15602. return;
  15603. }
  15604. }
  15605. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15606. unsigned int i;
  15607. /* client context: loops must end */
  15608. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15609. conn->must_close = 1;
  15610. /* We need to get the client thread out of the select/recv call
  15611. * here. */
  15612. /* Since we use a sleep quantum of some seconds to check for recv
  15613. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15614. /* join worker thread */
  15615. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15616. // mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15617. }
  15618. }
  15619. #endif /* defined(USE_WEBSOCKET) */
  15620. close_connection(conn);
  15621. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15622. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15623. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15624. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15625. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15626. }
  15627. #endif
  15628. #if defined(USE_WEBSOCKET)
  15629. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15630. mg_free(conn->phys_ctx->worker_threadids);
  15631. (void)pthread_mutex_destroy(&conn->mutex);
  15632. mg_free(conn);
  15633. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15634. (void)pthread_mutex_destroy(&conn->mutex);
  15635. mg_free(conn);
  15636. }
  15637. #else
  15638. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15639. (void)pthread_mutex_destroy(&conn->mutex);
  15640. mg_free(conn);
  15641. }
  15642. #endif /* defined(USE_WEBSOCKET) */
  15643. }
  15644. static struct mg_connection *
  15645. mg_connect_client_impl(const struct mg_client_options *client_options,
  15646. int use_ssl,
  15647. struct mg_init_data *init,
  15648. struct mg_error_data *error)
  15649. {
  15650. struct mg_connection *conn = NULL;
  15651. SOCKET sock;
  15652. union usa sa;
  15653. struct sockaddr *psa;
  15654. socklen_t len;
  15655. unsigned max_req_size =
  15656. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15657. /* Size of structures, aligned to 8 bytes */
  15658. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15659. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15660. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15661. (void)init; /* TODO: Implement required options */
  15662. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15663. if (error != NULL) {
  15664. error->code = MG_ERROR_DATA_CODE_OK;
  15665. error->code_sub = 0;
  15666. if (error->text_buffer_size > 0) {
  15667. error->text[0] = 0;
  15668. }
  15669. }
  15670. if (conn == NULL) {
  15671. if (error != NULL) {
  15672. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15673. error->code_sub = (unsigned)alloc_size;
  15674. mg_snprintf(NULL,
  15675. NULL, /* No truncation check for ebuf */
  15676. error->text,
  15677. error->text_buffer_size,
  15678. "calloc(): %s",
  15679. strerror(ERRNO));
  15680. }
  15681. return NULL;
  15682. }
  15683. #if defined(GCC_DIAGNOSTIC)
  15684. #pragma GCC diagnostic push
  15685. #pragma GCC diagnostic ignored "-Wcast-align"
  15686. #endif /* defined(GCC_DIAGNOSTIC) */
  15687. /* conn_size is aligned to 8 bytes */
  15688. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15689. #if defined(GCC_DIAGNOSTIC)
  15690. #pragma GCC diagnostic pop
  15691. #endif /* defined(GCC_DIAGNOSTIC) */
  15692. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15693. conn->buf_size = (int)max_req_size;
  15694. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15695. conn->dom_ctx = &(conn->phys_ctx->dd);
  15696. if (!connect_socket(conn->phys_ctx,
  15697. client_options->host,
  15698. client_options->port,
  15699. use_ssl,
  15700. error,
  15701. &sock,
  15702. &sa)) {
  15703. /* "error" will be set by connect_socket. */
  15704. /* free all memory and return NULL; */
  15705. mg_free(conn);
  15706. return NULL;
  15707. }
  15708. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15709. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15710. && !defined(NO_SSL_DL)
  15711. if (use_ssl
  15712. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15713. == NULL) {
  15714. if (error != NULL) {
  15715. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15716. mg_snprintf(NULL,
  15717. NULL, /* No truncation check for ebuf */
  15718. error->text,
  15719. error->text_buffer_size,
  15720. "SSL_CTX_new error: %s",
  15721. ssl_error());
  15722. }
  15723. closesocket(sock);
  15724. mg_free(conn);
  15725. return NULL;
  15726. }
  15727. #else
  15728. if (use_ssl
  15729. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15730. == NULL) {
  15731. if (error != NULL) {
  15732. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15733. mg_snprintf(NULL,
  15734. NULL, /* No truncation check for ebuf */
  15735. error->text,
  15736. error->text_buffer_size,
  15737. "SSL_CTX_new error: %s",
  15738. ssl_error());
  15739. }
  15740. closesocket(sock);
  15741. mg_free(conn);
  15742. return NULL;
  15743. }
  15744. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15745. #endif /* NO_SSL */
  15746. #if defined(USE_IPV6)
  15747. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15748. : sizeof(conn->client.rsa.sin6);
  15749. psa = (sa.sa.sa_family == AF_INET)
  15750. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15751. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15752. #else
  15753. len = sizeof(conn->client.rsa.sin);
  15754. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15755. #endif
  15756. conn->client.sock = sock;
  15757. conn->client.lsa = sa;
  15758. if (getsockname(sock, psa, &len) != 0) {
  15759. mg_cry_internal(conn,
  15760. "%s: getsockname() failed: %s",
  15761. __func__,
  15762. strerror(ERRNO));
  15763. }
  15764. conn->client.is_ssl = use_ssl ? 1 : 0;
  15765. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15766. if (error != NULL) {
  15767. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15768. error->code_sub = (unsigned)ERRNO;
  15769. mg_snprintf(NULL,
  15770. NULL, /* No truncation check for ebuf */
  15771. error->text,
  15772. error->text_buffer_size,
  15773. "Can not create mutex");
  15774. }
  15775. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15776. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15777. #endif
  15778. closesocket(sock);
  15779. mg_free(conn);
  15780. return NULL;
  15781. }
  15782. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15783. if (use_ssl) {
  15784. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15785. * SSL_CTX_set_verify call is needed to switch off server
  15786. * certificate checking, which is off by default in OpenSSL and
  15787. * on in yaSSL. */
  15788. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15789. * SSL_VERIFY_PEER, verify_ssl_server); */
  15790. if (client_options->client_cert) {
  15791. if (!ssl_use_pem_file(conn->phys_ctx,
  15792. conn->dom_ctx,
  15793. client_options->client_cert,
  15794. NULL)) {
  15795. if (error != NULL) {
  15796. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15797. mg_snprintf(NULL,
  15798. NULL, /* No truncation check for ebuf */
  15799. error->text,
  15800. error->text_buffer_size,
  15801. "Can not use SSL client certificate");
  15802. }
  15803. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15804. closesocket(sock);
  15805. mg_free(conn);
  15806. return NULL;
  15807. }
  15808. }
  15809. if (client_options->server_cert) {
  15810. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15811. client_options->server_cert,
  15812. NULL)
  15813. != 1) {
  15814. if (error != NULL) {
  15815. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15816. mg_snprintf(NULL,
  15817. NULL, /* No truncation check for ebuf */
  15818. error->text,
  15819. error->text_buffer_size,
  15820. "SSL_CTX_load_verify_locations error: %s",
  15821. ssl_error());
  15822. }
  15823. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15824. closesocket(sock);
  15825. mg_free(conn);
  15826. return NULL;
  15827. }
  15828. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15829. } else {
  15830. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15831. }
  15832. if (!sslize(conn, SSL_connect, client_options)) {
  15833. if (error != NULL) {
  15834. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15835. mg_snprintf(NULL,
  15836. NULL, /* No truncation check for ebuf */
  15837. error->text,
  15838. error->text_buffer_size,
  15839. "SSL connection error");
  15840. }
  15841. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15842. closesocket(sock);
  15843. mg_free(conn);
  15844. return NULL;
  15845. }
  15846. }
  15847. #endif
  15848. return conn;
  15849. }
  15850. CIVETWEB_API struct mg_connection *
  15851. mg_connect_client_secure(const struct mg_client_options *client_options,
  15852. char *error_buffer,
  15853. size_t error_buffer_size)
  15854. {
  15855. struct mg_init_data init;
  15856. struct mg_error_data error;
  15857. memset(&init, 0, sizeof(init));
  15858. memset(&error, 0, sizeof(error));
  15859. error.text_buffer_size = error_buffer_size;
  15860. error.text = error_buffer;
  15861. return mg_connect_client_impl(client_options, 1, &init, &error);
  15862. }
  15863. CIVETWEB_API struct mg_connection *
  15864. mg_connect_client(const char *host,
  15865. int port,
  15866. int use_ssl,
  15867. char *error_buffer,
  15868. size_t error_buffer_size)
  15869. {
  15870. struct mg_client_options opts;
  15871. struct mg_init_data init;
  15872. struct mg_error_data error;
  15873. memset(&init, 0, sizeof(init));
  15874. memset(&error, 0, sizeof(error));
  15875. error.text_buffer_size = error_buffer_size;
  15876. error.text = error_buffer;
  15877. memset(&opts, 0, sizeof(opts));
  15878. opts.host = host;
  15879. opts.port = port;
  15880. if (use_ssl) {
  15881. opts.host_name = host;
  15882. }
  15883. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  15884. }
  15885. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15886. CIVETWEB_API struct mg_connection *
  15887. mg_connect_client2(const char *host,
  15888. const char *protocol,
  15889. int port,
  15890. const char *path,
  15891. struct mg_init_data *init,
  15892. struct mg_error_data *error)
  15893. {
  15894. (void)path;
  15895. int is_ssl, is_ws;
  15896. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15897. if (error != NULL) {
  15898. error->code = MG_ERROR_DATA_CODE_OK;
  15899. error->code_sub = 0;
  15900. if (error->text_buffer_size > 0) {
  15901. *error->text = 0;
  15902. }
  15903. }
  15904. if ((host == NULL) || (protocol == NULL)) {
  15905. if (error != NULL) {
  15906. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15907. mg_snprintf(NULL,
  15908. NULL, /* No truncation check for error buffers */
  15909. error->text,
  15910. error->text_buffer_size,
  15911. "%s",
  15912. "Invalid parameters");
  15913. }
  15914. return NULL;
  15915. }
  15916. /* check all known protocolls */
  15917. if (!mg_strcasecmp(protocol, "http")) {
  15918. is_ssl = 0;
  15919. is_ws = 0;
  15920. } else if (!mg_strcasecmp(protocol, "https")) {
  15921. is_ssl = 1;
  15922. is_ws = 0;
  15923. #if defined(USE_WEBSOCKET)
  15924. } else if (!mg_strcasecmp(protocol, "ws")) {
  15925. is_ssl = 0;
  15926. is_ws = 1;
  15927. } else if (!mg_strcasecmp(protocol, "wss")) {
  15928. is_ssl = 1;
  15929. is_ws = 1;
  15930. #endif
  15931. } else {
  15932. if (error != NULL) {
  15933. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15934. mg_snprintf(NULL,
  15935. NULL, /* No truncation check for error buffers */
  15936. error->text,
  15937. error->text_buffer_size,
  15938. "Protocol %s not supported",
  15939. protocol);
  15940. }
  15941. return NULL;
  15942. }
  15943. /* TODO: The current implementation here just calls the old
  15944. * implementations, without using any new options. This is just a first
  15945. * step to test the new interfaces. */
  15946. #if defined(USE_WEBSOCKET)
  15947. if (is_ws) {
  15948. /* TODO: implement all options */
  15949. return mg_connect_websocket_client(
  15950. host,
  15951. port,
  15952. is_ssl,
  15953. ((error != NULL) ? error->text : NULL),
  15954. ((error != NULL) ? error->text_buffer_size : 0),
  15955. (path ? path : ""),
  15956. NULL /* TODO: origin */,
  15957. experimental_websocket_client_data_wrapper,
  15958. experimental_websocket_client_close_wrapper,
  15959. (void *)init->callbacks);
  15960. }
  15961. #else
  15962. (void)is_ws;
  15963. #endif
  15964. /* TODO: all additional options */
  15965. struct mg_client_options opts;
  15966. memset(&opts, 0, sizeof(opts));
  15967. opts.host = host;
  15968. opts.port = port;
  15969. return mg_connect_client_impl(&opts, is_ssl, init, error);
  15970. }
  15971. #endif
  15972. static const struct {
  15973. const char *proto;
  15974. size_t proto_len;
  15975. unsigned default_port;
  15976. } abs_uri_protocols[] = {{"http://", 7, 80},
  15977. {"https://", 8, 443},
  15978. {"ws://", 5, 80},
  15979. {"wss://", 6, 443},
  15980. {NULL, 0, 0}};
  15981. /* Check if the uri is valid.
  15982. * return 0 for invalid uri,
  15983. * return 1 for *,
  15984. * return 2 for relative uri,
  15985. * return 3 for absolute uri without port,
  15986. * return 4 for absolute uri with port */
  15987. static int
  15988. get_uri_type(const char *uri)
  15989. {
  15990. int i;
  15991. const char *hostend, *portbegin;
  15992. char *portend;
  15993. unsigned long port;
  15994. /* According to the HTTP standard
  15995. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15996. * URI can be an asterisk (*) or should start with slash (relative uri),
  15997. * or it should start with the protocol (absolute uri). */
  15998. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15999. /* asterisk */
  16000. return 1;
  16001. }
  16002. /* Valid URIs according to RFC 3986
  16003. * (https://www.ietf.org/rfc/rfc3986.txt)
  16004. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16005. * and unreserved characters A-Z a-z 0-9 and -._~
  16006. * and % encoded symbols.
  16007. */
  16008. for (i = 0; uri[i] != 0; i++) {
  16009. if (uri[i] < 33) {
  16010. /* control characters and spaces are invalid */
  16011. return 0;
  16012. }
  16013. /* Allow everything else here (See #894) */
  16014. }
  16015. /* A relative uri starts with a / character */
  16016. if (uri[0] == '/') {
  16017. /* relative uri */
  16018. return 2;
  16019. }
  16020. /* It could be an absolute uri: */
  16021. /* This function only checks if the uri is valid, not if it is
  16022. * addressing the current server. So civetweb can also be used
  16023. * as a proxy server. */
  16024. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16025. if (mg_strncasecmp(uri,
  16026. abs_uri_protocols[i].proto,
  16027. abs_uri_protocols[i].proto_len)
  16028. == 0) {
  16029. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16030. if (!hostend) {
  16031. return 0;
  16032. }
  16033. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16034. if (!portbegin) {
  16035. return 3;
  16036. }
  16037. port = strtoul(portbegin + 1, &portend, 10);
  16038. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16039. return 0;
  16040. }
  16041. return 4;
  16042. }
  16043. }
  16044. return 0;
  16045. }
  16046. /* Return NULL or the relative uri at the current server */
  16047. static const char *
  16048. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16049. {
  16050. const char *server_domain;
  16051. size_t server_domain_len;
  16052. size_t request_domain_len = 0;
  16053. unsigned long port = 0;
  16054. int i, auth_domain_check_enabled;
  16055. const char *hostbegin = NULL;
  16056. const char *hostend = NULL;
  16057. const char *portbegin;
  16058. char *portend;
  16059. auth_domain_check_enabled =
  16060. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16061. /* DNS is case insensitive, so use case insensitive string compare here
  16062. */
  16063. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16064. if (mg_strncasecmp(uri,
  16065. abs_uri_protocols[i].proto,
  16066. abs_uri_protocols[i].proto_len)
  16067. == 0) {
  16068. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16069. hostend = strchr(hostbegin, '/');
  16070. if (!hostend) {
  16071. return 0;
  16072. }
  16073. portbegin = strchr(hostbegin, ':');
  16074. if ((!portbegin) || (portbegin > hostend)) {
  16075. port = abs_uri_protocols[i].default_port;
  16076. request_domain_len = (size_t)(hostend - hostbegin);
  16077. } else {
  16078. port = strtoul(portbegin + 1, &portend, 10);
  16079. if ((portend != hostend) || (port <= 0)
  16080. || !is_valid_port(port)) {
  16081. return 0;
  16082. }
  16083. request_domain_len = (size_t)(portbegin - hostbegin);
  16084. }
  16085. /* protocol found, port set */
  16086. break;
  16087. }
  16088. }
  16089. if (!port) {
  16090. /* port remains 0 if the protocol is not found */
  16091. return 0;
  16092. }
  16093. /* Check if the request is directed to a different server. */
  16094. /* First check if the port is the same. */
  16095. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16096. /* Request is directed to a different port */
  16097. return 0;
  16098. }
  16099. /* Finally check if the server corresponds to the authentication
  16100. * domain of the server (the server domain).
  16101. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16102. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16103. * but do not allow substrings (like
  16104. * http://notmydomain.com/path/file.ext
  16105. * or http://mydomain.com.fake/path/file.ext).
  16106. */
  16107. if (auth_domain_check_enabled) {
  16108. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16109. server_domain_len = strlen(server_domain);
  16110. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16111. return 0;
  16112. }
  16113. if ((request_domain_len == server_domain_len)
  16114. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16115. /* Request is directed to this server - full name match. */
  16116. } else {
  16117. if (request_domain_len < (server_domain_len + 2)) {
  16118. /* Request is directed to another server: The server name
  16119. * is longer than the request name.
  16120. * Drop this case here to avoid overflows in the
  16121. * following checks. */
  16122. return 0;
  16123. }
  16124. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16125. /* Request is directed to another server: It could be a
  16126. * substring
  16127. * like notmyserver.com */
  16128. return 0;
  16129. }
  16130. if (0
  16131. != memcmp(server_domain,
  16132. hostbegin + request_domain_len - server_domain_len,
  16133. server_domain_len)) {
  16134. /* Request is directed to another server:
  16135. * The server name is different. */
  16136. return 0;
  16137. }
  16138. }
  16139. }
  16140. return hostend;
  16141. }
  16142. static int
  16143. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16144. {
  16145. if (ebuf_len > 0) {
  16146. ebuf[0] = '\0';
  16147. }
  16148. *err = 0;
  16149. reset_per_request_attributes(conn);
  16150. if (!conn) {
  16151. mg_snprintf(conn,
  16152. NULL, /* No truncation check for ebuf */
  16153. ebuf,
  16154. ebuf_len,
  16155. "%s",
  16156. "Internal error");
  16157. *err = 500;
  16158. return 0;
  16159. }
  16160. /* Set the time the request was received. This value should be used for
  16161. * timeouts. */
  16162. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16163. conn->request_len =
  16164. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16165. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16166. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16167. mg_snprintf(conn,
  16168. NULL, /* No truncation check for ebuf */
  16169. ebuf,
  16170. ebuf_len,
  16171. "%s",
  16172. "Invalid message size");
  16173. *err = 500;
  16174. return 0;
  16175. }
  16176. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16177. mg_snprintf(conn,
  16178. NULL, /* No truncation check for ebuf */
  16179. ebuf,
  16180. ebuf_len,
  16181. "%s",
  16182. "Message too large");
  16183. *err = 413;
  16184. return 0;
  16185. }
  16186. if (conn->request_len <= 0) {
  16187. if (conn->data_len > 0) {
  16188. mg_snprintf(conn,
  16189. NULL, /* No truncation check for ebuf */
  16190. ebuf,
  16191. ebuf_len,
  16192. "%s",
  16193. "Malformed message");
  16194. *err = 400;
  16195. } else {
  16196. /* Server did not recv anything -> just close the connection */
  16197. conn->must_close = 1;
  16198. mg_snprintf(conn,
  16199. NULL, /* No truncation check for ebuf */
  16200. ebuf,
  16201. ebuf_len,
  16202. "%s",
  16203. "No data received");
  16204. *err = 0;
  16205. }
  16206. return 0;
  16207. }
  16208. return 1;
  16209. }
  16210. static int
  16211. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16212. {
  16213. const char *cl;
  16214. conn->connection_type =
  16215. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16216. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16217. return 0;
  16218. }
  16219. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16220. <= 0) {
  16221. mg_snprintf(conn,
  16222. NULL, /* No truncation check for ebuf */
  16223. ebuf,
  16224. ebuf_len,
  16225. "%s",
  16226. "Bad request");
  16227. *err = 400;
  16228. return 0;
  16229. }
  16230. /* Message is a valid request */
  16231. if (!switch_domain_context(conn)) {
  16232. mg_snprintf(conn,
  16233. NULL, /* No truncation check for ebuf */
  16234. ebuf,
  16235. ebuf_len,
  16236. "%s",
  16237. "Bad request: Host mismatch");
  16238. *err = 400;
  16239. return 0;
  16240. }
  16241. #if USE_ZLIB
  16242. if (((cl = get_header(conn->request_info.http_headers,
  16243. conn->request_info.num_headers,
  16244. "Accept-Encoding"))
  16245. != NULL)
  16246. && strstr(cl, "gzip")) {
  16247. conn->accept_gzip = 1;
  16248. }
  16249. #endif
  16250. if (((cl = get_header(conn->request_info.http_headers,
  16251. conn->request_info.num_headers,
  16252. "Transfer-Encoding"))
  16253. != NULL)
  16254. && mg_strcasecmp(cl, "identity")) {
  16255. if (mg_strcasecmp(cl, "chunked")) {
  16256. mg_snprintf(conn,
  16257. NULL, /* No truncation check for ebuf */
  16258. ebuf,
  16259. ebuf_len,
  16260. "%s",
  16261. "Bad request");
  16262. *err = 400;
  16263. return 0;
  16264. }
  16265. conn->is_chunked = 1;
  16266. conn->content_len = 0; /* not yet read */
  16267. } else if ((cl = get_header(conn->request_info.http_headers,
  16268. conn->request_info.num_headers,
  16269. "Content-Length"))
  16270. != NULL) {
  16271. /* Request has content length set */
  16272. char *endptr = NULL;
  16273. conn->content_len = strtoll(cl, &endptr, 10);
  16274. if ((endptr == cl) || (conn->content_len < 0)) {
  16275. mg_snprintf(conn,
  16276. NULL, /* No truncation check for ebuf */
  16277. ebuf,
  16278. ebuf_len,
  16279. "%s",
  16280. "Bad request");
  16281. *err = 411;
  16282. return 0;
  16283. }
  16284. /* Publish the content length back to the request info. */
  16285. conn->request_info.content_length = conn->content_len;
  16286. } else {
  16287. /* There is no exception, see RFC7230. */
  16288. conn->content_len = 0;
  16289. }
  16290. return 1;
  16291. }
  16292. /* conn is assumed to be valid in this internal function */
  16293. static int
  16294. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16295. {
  16296. const char *cl;
  16297. conn->connection_type =
  16298. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16299. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16300. return 0;
  16301. }
  16302. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16303. <= 0) {
  16304. mg_snprintf(conn,
  16305. NULL, /* No truncation check for ebuf */
  16306. ebuf,
  16307. ebuf_len,
  16308. "%s",
  16309. "Bad response");
  16310. *err = 400;
  16311. return 0;
  16312. }
  16313. /* Message is a valid response */
  16314. if (((cl = get_header(conn->response_info.http_headers,
  16315. conn->response_info.num_headers,
  16316. "Transfer-Encoding"))
  16317. != NULL)
  16318. && mg_strcasecmp(cl, "identity")) {
  16319. if (mg_strcasecmp(cl, "chunked")) {
  16320. mg_snprintf(conn,
  16321. NULL, /* No truncation check for ebuf */
  16322. ebuf,
  16323. ebuf_len,
  16324. "%s",
  16325. "Bad request");
  16326. *err = 400;
  16327. return 0;
  16328. }
  16329. conn->is_chunked = 1;
  16330. conn->content_len = 0; /* not yet read */
  16331. } else if ((cl = get_header(conn->response_info.http_headers,
  16332. conn->response_info.num_headers,
  16333. "Content-Length"))
  16334. != NULL) {
  16335. char *endptr = NULL;
  16336. conn->content_len = strtoll(cl, &endptr, 10);
  16337. if ((endptr == cl) || (conn->content_len < 0)) {
  16338. mg_snprintf(conn,
  16339. NULL, /* No truncation check for ebuf */
  16340. ebuf,
  16341. ebuf_len,
  16342. "%s",
  16343. "Bad request");
  16344. *err = 411;
  16345. return 0;
  16346. }
  16347. /* Publish the content length back to the response info. */
  16348. conn->response_info.content_length = conn->content_len;
  16349. /* TODO: check if it is still used in response_info */
  16350. conn->request_info.content_length = conn->content_len;
  16351. /* TODO: we should also consider HEAD method */
  16352. if (conn->response_info.status_code == 304) {
  16353. conn->content_len = 0;
  16354. }
  16355. } else {
  16356. /* TODO: we should also consider HEAD method */
  16357. if (((conn->response_info.status_code >= 100)
  16358. && (conn->response_info.status_code <= 199))
  16359. || (conn->response_info.status_code == 204)
  16360. || (conn->response_info.status_code == 304)) {
  16361. conn->content_len = 0;
  16362. } else {
  16363. conn->content_len = -1; /* unknown content length */
  16364. }
  16365. }
  16366. return 1;
  16367. }
  16368. CIVETWEB_API int
  16369. mg_get_response(struct mg_connection *conn,
  16370. char *ebuf,
  16371. size_t ebuf_len,
  16372. int timeout)
  16373. {
  16374. int err, ret;
  16375. char txt[32]; /* will not overflow */
  16376. char *save_timeout;
  16377. char *new_timeout;
  16378. if (ebuf_len > 0) {
  16379. ebuf[0] = '\0';
  16380. }
  16381. if (!conn) {
  16382. mg_snprintf(conn,
  16383. NULL, /* No truncation check for ebuf */
  16384. ebuf,
  16385. ebuf_len,
  16386. "%s",
  16387. "Parameter error");
  16388. return -1;
  16389. }
  16390. /* Reset the previous responses */
  16391. conn->data_len = 0;
  16392. /* Implementation of API function for HTTP clients */
  16393. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16394. if (timeout >= 0) {
  16395. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16396. new_timeout = txt;
  16397. } else {
  16398. new_timeout = NULL;
  16399. }
  16400. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16401. ret = get_response(conn, ebuf, ebuf_len, &err);
  16402. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16403. /* TODO: here, the URI is the http response code */
  16404. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16405. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16406. /* TODO (mid): Define proper return values - maybe return length?
  16407. * For the first test use <0 for error and >0 for OK */
  16408. return (ret == 0) ? -1 : +1;
  16409. }
  16410. CIVETWEB_API struct mg_connection *
  16411. mg_download(const char *host,
  16412. int port,
  16413. int use_ssl,
  16414. char *ebuf,
  16415. size_t ebuf_len,
  16416. const char *fmt,
  16417. ...)
  16418. {
  16419. struct mg_connection *conn;
  16420. va_list ap;
  16421. int i;
  16422. int reqerr;
  16423. if (ebuf_len > 0) {
  16424. ebuf[0] = '\0';
  16425. }
  16426. va_start(ap, fmt);
  16427. /* open a connection */
  16428. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16429. if (conn != NULL) {
  16430. i = mg_vprintf(conn, fmt, ap);
  16431. if (i <= 0) {
  16432. mg_snprintf(conn,
  16433. NULL, /* No truncation check for ebuf */
  16434. ebuf,
  16435. ebuf_len,
  16436. "%s",
  16437. "Error sending request");
  16438. } else {
  16439. /* make sure the buffer is clear */
  16440. conn->data_len = 0;
  16441. get_response(conn, ebuf, ebuf_len, &reqerr);
  16442. /* TODO: here, the URI is the http response code */
  16443. conn->request_info.local_uri = conn->request_info.request_uri;
  16444. }
  16445. }
  16446. /* if an error occurred, close the connection */
  16447. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16448. mg_close_connection(conn);
  16449. conn = NULL;
  16450. }
  16451. va_end(ap);
  16452. return conn;
  16453. }
  16454. struct websocket_client_thread_data {
  16455. struct mg_connection *conn;
  16456. mg_websocket_data_handler data_handler;
  16457. mg_websocket_close_handler close_handler;
  16458. void *callback_data;
  16459. };
  16460. #if defined(USE_WEBSOCKET)
  16461. #if defined(_WIN32)
  16462. static unsigned __stdcall websocket_client_thread(void *data)
  16463. #else
  16464. static void *
  16465. websocket_client_thread(void *data)
  16466. #endif
  16467. {
  16468. struct websocket_client_thread_data *cdata =
  16469. (struct websocket_client_thread_data *)data;
  16470. void *user_thread_ptr = NULL;
  16471. #if !defined(_WIN32) && !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  16472. struct sigaction sa;
  16473. /* Ignore SIGPIPE */
  16474. memset(&sa, 0, sizeof(sa));
  16475. sa.sa_handler = SIG_IGN;
  16476. sigaction(SIGPIPE, &sa, NULL);
  16477. #endif
  16478. mg_set_thread_name("ws-clnt");
  16479. if (cdata->conn->phys_ctx) {
  16480. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16481. /* 3 indicates a websocket client thread */
  16482. /* TODO: check if conn->phys_ctx can be set */
  16483. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16484. cdata->conn->phys_ctx, 3);
  16485. }
  16486. }
  16487. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16488. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16489. if (cdata->close_handler != NULL) {
  16490. cdata->close_handler(cdata->conn, cdata->callback_data);
  16491. }
  16492. /* The websocket_client context has only this thread. If it runs out,
  16493. set the stop_flag to 2 (= "stopped"). */
  16494. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16495. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16496. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16497. 3,
  16498. user_thread_ptr);
  16499. }
  16500. mg_free((void *)cdata);
  16501. #if defined(_WIN32)
  16502. return 0;
  16503. #else
  16504. return NULL;
  16505. #endif
  16506. }
  16507. #endif
  16508. static struct mg_connection *
  16509. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16510. int use_ssl,
  16511. char *error_buffer,
  16512. size_t error_buffer_size,
  16513. const char *path,
  16514. const char *origin,
  16515. const char *extensions,
  16516. mg_websocket_data_handler data_func,
  16517. mg_websocket_close_handler close_func,
  16518. void *user_data)
  16519. {
  16520. struct mg_connection *conn = NULL;
  16521. #if defined(USE_WEBSOCKET)
  16522. struct websocket_client_thread_data *thread_data;
  16523. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16524. const char *host = client_options->host;
  16525. int i;
  16526. struct mg_init_data init;
  16527. struct mg_error_data error;
  16528. memset(&init, 0, sizeof(init));
  16529. memset(&error, 0, sizeof(error));
  16530. error.text_buffer_size = error_buffer_size;
  16531. error.text = error_buffer;
  16532. #if defined(__clang__)
  16533. #pragma clang diagnostic push
  16534. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16535. #endif
  16536. /* Establish the client connection and request upgrade */
  16537. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16538. /* Connection object will be null if something goes wrong */
  16539. if (conn == NULL) {
  16540. /* error_buffer should be already filled ... */
  16541. if (!error_buffer[0]) {
  16542. /* ... if not add an error message */
  16543. mg_snprintf(conn,
  16544. NULL, /* No truncation check for ebuf */
  16545. error_buffer,
  16546. error_buffer_size,
  16547. "Unexpected error");
  16548. }
  16549. return NULL;
  16550. }
  16551. if (origin != NULL) {
  16552. if (extensions != NULL) {
  16553. i = mg_printf(conn,
  16554. "GET %s HTTP/1.1\r\n"
  16555. "Host: %s\r\n"
  16556. "Upgrade: websocket\r\n"
  16557. "Connection: Upgrade\r\n"
  16558. "Sec-WebSocket-Key: %s\r\n"
  16559. "Sec-WebSocket-Version: 13\r\n"
  16560. "Sec-WebSocket-Extensions: %s\r\n"
  16561. "Origin: %s\r\n"
  16562. "\r\n",
  16563. path,
  16564. host,
  16565. magic,
  16566. extensions,
  16567. origin);
  16568. } else {
  16569. i = mg_printf(conn,
  16570. "GET %s HTTP/1.1\r\n"
  16571. "Host: %s\r\n"
  16572. "Upgrade: websocket\r\n"
  16573. "Connection: Upgrade\r\n"
  16574. "Sec-WebSocket-Key: %s\r\n"
  16575. "Sec-WebSocket-Version: 13\r\n"
  16576. "Origin: %s\r\n"
  16577. "\r\n",
  16578. path,
  16579. host,
  16580. magic,
  16581. origin);
  16582. }
  16583. } else {
  16584. if (extensions != NULL) {
  16585. i = mg_printf(conn,
  16586. "GET %s HTTP/1.1\r\n"
  16587. "Host: %s\r\n"
  16588. "Upgrade: websocket\r\n"
  16589. "Connection: Upgrade\r\n"
  16590. "Sec-WebSocket-Key: %s\r\n"
  16591. "Sec-WebSocket-Version: 13\r\n"
  16592. "Sec-WebSocket-Extensions: %s\r\n"
  16593. "\r\n",
  16594. path,
  16595. host,
  16596. magic,
  16597. extensions);
  16598. } else {
  16599. i = mg_printf(conn,
  16600. "GET %s HTTP/1.1\r\n"
  16601. "Host: %s\r\n"
  16602. "Upgrade: websocket\r\n"
  16603. "Connection: Upgrade\r\n"
  16604. "Sec-WebSocket-Key: %s\r\n"
  16605. "Sec-WebSocket-Version: 13\r\n"
  16606. "\r\n",
  16607. path,
  16608. host,
  16609. magic);
  16610. }
  16611. }
  16612. if (i <= 0) {
  16613. mg_snprintf(conn,
  16614. NULL, /* No truncation check for ebuf */
  16615. error_buffer,
  16616. error_buffer_size,
  16617. "%s",
  16618. "Error sending request");
  16619. mg_close_connection(conn);
  16620. return NULL;
  16621. }
  16622. conn->data_len = 0;
  16623. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16624. mg_close_connection(conn);
  16625. return NULL;
  16626. }
  16627. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16628. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16629. #if defined(__clang__)
  16630. #pragma clang diagnostic pop
  16631. #endif
  16632. if (conn->response_info.status_code != 101) {
  16633. /* We sent an "upgrade" request. For a correct websocket
  16634. * protocol handshake, we expect a "101 Continue" response.
  16635. * Otherwise it is a protocol violation. Maybe the HTTP
  16636. * Server does not know websockets. */
  16637. if (!*error_buffer) {
  16638. /* set an error, if not yet set */
  16639. mg_snprintf(conn,
  16640. NULL, /* No truncation check for ebuf */
  16641. error_buffer,
  16642. error_buffer_size,
  16643. "Unexpected server reply");
  16644. }
  16645. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16646. mg_close_connection(conn);
  16647. return NULL;
  16648. }
  16649. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16650. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16651. if (!thread_data) {
  16652. DEBUG_TRACE("%s\r\n", "Out of memory");
  16653. mg_close_connection(conn);
  16654. return NULL;
  16655. }
  16656. thread_data->conn = conn;
  16657. thread_data->data_handler = data_func;
  16658. thread_data->close_handler = close_func;
  16659. thread_data->callback_data = user_data;
  16660. conn->phys_ctx->worker_threadids =
  16661. (cw_thread_handle_t *)mg_calloc_ctx(1, sizeof(cw_thread_handle_t), conn->phys_ctx);
  16662. if (!conn->phys_ctx->worker_threadids) {
  16663. DEBUG_TRACE("%s\r\n", "Out of memory");
  16664. mg_free(thread_data);
  16665. mg_close_connection(conn);
  16666. return NULL;
  16667. }
  16668. /* Now upgrade to ws/wss client context */
  16669. conn->phys_ctx->user_data = user_data;
  16670. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16671. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16672. /* Start a thread to read the websocket client connection
  16673. * This thread will automatically stop when mg_disconnect is
  16674. * called on the client connection */
  16675. if (mg_start_thread_with_id(websocket_client_thread,
  16676. thread_data,
  16677. conn->phys_ctx->worker_threadids)
  16678. != 0) {
  16679. conn->phys_ctx->cfg_worker_threads = 0;
  16680. mg_free(thread_data);
  16681. mg_close_connection(conn);
  16682. conn = NULL;
  16683. DEBUG_TRACE("%s",
  16684. "Websocket client connect thread could not be started\r\n");
  16685. }
  16686. #else
  16687. /* Appease "unused parameter" warnings */
  16688. (void)client_options;
  16689. (void)use_ssl;
  16690. (void)error_buffer;
  16691. (void)error_buffer_size;
  16692. (void)path;
  16693. (void)origin;
  16694. (void)extensions;
  16695. (void)user_data;
  16696. (void)data_func;
  16697. (void)close_func;
  16698. #endif
  16699. return conn;
  16700. }
  16701. CIVETWEB_API struct mg_connection *
  16702. mg_connect_websocket_client(const char *host,
  16703. int port,
  16704. int use_ssl,
  16705. char *error_buffer,
  16706. size_t error_buffer_size,
  16707. const char *path,
  16708. const char *origin,
  16709. mg_websocket_data_handler data_func,
  16710. mg_websocket_close_handler close_func,
  16711. void *user_data)
  16712. {
  16713. struct mg_client_options client_options;
  16714. memset(&client_options, 0, sizeof(client_options));
  16715. client_options.host = host;
  16716. client_options.port = port;
  16717. return mg_connect_websocket_client_impl(&client_options,
  16718. use_ssl,
  16719. error_buffer,
  16720. error_buffer_size,
  16721. path,
  16722. origin,
  16723. NULL,
  16724. data_func,
  16725. close_func,
  16726. user_data);
  16727. }
  16728. CIVETWEB_API struct mg_connection *
  16729. mg_connect_websocket_client_secure(
  16730. const struct mg_client_options *client_options,
  16731. char *error_buffer,
  16732. size_t error_buffer_size,
  16733. const char *path,
  16734. const char *origin,
  16735. mg_websocket_data_handler data_func,
  16736. mg_websocket_close_handler close_func,
  16737. void *user_data)
  16738. {
  16739. if (!client_options) {
  16740. return NULL;
  16741. }
  16742. return mg_connect_websocket_client_impl(client_options,
  16743. 1,
  16744. error_buffer,
  16745. error_buffer_size,
  16746. path,
  16747. origin,
  16748. NULL,
  16749. data_func,
  16750. close_func,
  16751. user_data);
  16752. }
  16753. CIVETWEB_API struct mg_connection *
  16754. mg_connect_websocket_client_extensions(const char *host,
  16755. int port,
  16756. int use_ssl,
  16757. char *error_buffer,
  16758. size_t error_buffer_size,
  16759. const char *path,
  16760. const char *origin,
  16761. const char *extensions,
  16762. mg_websocket_data_handler data_func,
  16763. mg_websocket_close_handler close_func,
  16764. void *user_data)
  16765. {
  16766. struct mg_client_options client_options;
  16767. memset(&client_options, 0, sizeof(client_options));
  16768. client_options.host = host;
  16769. client_options.port = port;
  16770. return mg_connect_websocket_client_impl(&client_options,
  16771. use_ssl,
  16772. error_buffer,
  16773. error_buffer_size,
  16774. path,
  16775. origin,
  16776. extensions,
  16777. data_func,
  16778. close_func,
  16779. user_data);
  16780. }
  16781. CIVETWEB_API struct mg_connection *
  16782. mg_connect_websocket_client_secure_extensions(
  16783. const struct mg_client_options *client_options,
  16784. char *error_buffer,
  16785. size_t error_buffer_size,
  16786. const char *path,
  16787. const char *origin,
  16788. const char *extensions,
  16789. mg_websocket_data_handler data_func,
  16790. mg_websocket_close_handler close_func,
  16791. void *user_data)
  16792. {
  16793. if (!client_options) {
  16794. return NULL;
  16795. }
  16796. return mg_connect_websocket_client_impl(client_options,
  16797. 1,
  16798. error_buffer,
  16799. error_buffer_size,
  16800. path,
  16801. origin,
  16802. extensions,
  16803. data_func,
  16804. close_func,
  16805. user_data);
  16806. }
  16807. /* Prepare connection data structure */
  16808. static void
  16809. init_connection(struct mg_connection *conn)
  16810. {
  16811. /* Is keep alive allowed by the server */
  16812. int keep_alive_enabled =
  16813. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16814. if (!keep_alive_enabled) {
  16815. conn->must_close = 1;
  16816. }
  16817. /* Important: on new connection, reset the receiving buffer. Credit
  16818. * goes to crule42. */
  16819. conn->data_len = 0;
  16820. conn->handled_requests = 0;
  16821. conn->connection_type = CONNECTION_TYPE_INVALID;
  16822. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  16823. mg_set_user_connection_data(conn, NULL);
  16824. #if defined(USE_SERVER_STATS)
  16825. conn->conn_state = 2; /* init */
  16826. #endif
  16827. /* call the init_connection callback if assigned */
  16828. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16829. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16830. void *conn_data = NULL;
  16831. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16832. mg_set_user_connection_data(conn, conn_data);
  16833. }
  16834. }
  16835. }
  16836. /* Process a connection - may handle multiple requests
  16837. * using the same connection.
  16838. * Must be called with a valid connection (conn and
  16839. * conn->phys_ctx must be valid).
  16840. */
  16841. static void
  16842. process_new_connection(struct mg_connection *conn)
  16843. {
  16844. struct mg_request_info *ri = &conn->request_info;
  16845. int keep_alive, discard_len;
  16846. char ebuf[100];
  16847. const char *hostend;
  16848. int reqerr, uri_type;
  16849. #if defined(USE_SERVER_STATS)
  16850. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16851. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16852. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16853. #endif
  16854. DEBUG_TRACE("Start processing connection from %s",
  16855. conn->request_info.remote_addr);
  16856. /* Loop over multiple requests sent using the same connection
  16857. * (while "keep alive"). */
  16858. do {
  16859. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16860. conn->handled_requests + 1);
  16861. #if defined(USE_SERVER_STATS)
  16862. conn->conn_state = 3; /* ready */
  16863. #endif
  16864. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16865. /* The request sent by the client could not be understood by
  16866. * the server, or it was incomplete or a timeout. Send an
  16867. * error message and close the connection. */
  16868. if (reqerr > 0) {
  16869. DEBUG_ASSERT(ebuf[0] != '\0');
  16870. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16871. }
  16872. } else if (strcmp(ri->http_version, "1.0")
  16873. && strcmp(ri->http_version, "1.1")) {
  16874. /* HTTP/2 is not allowed here */
  16875. mg_snprintf(conn,
  16876. NULL, /* No truncation check for ebuf */
  16877. ebuf,
  16878. sizeof(ebuf),
  16879. "Bad HTTP version: [%s]",
  16880. ri->http_version);
  16881. mg_send_http_error(conn, 505, "%s", ebuf);
  16882. }
  16883. if (ebuf[0] == '\0') {
  16884. uri_type = get_uri_type(conn->request_info.request_uri);
  16885. switch (uri_type) {
  16886. case 1:
  16887. /* Asterisk */
  16888. conn->request_info.local_uri_raw = 0;
  16889. /* TODO: Deal with '*'. */
  16890. break;
  16891. case 2:
  16892. /* relative uri */
  16893. conn->request_info.local_uri_raw =
  16894. conn->request_info.request_uri;
  16895. break;
  16896. case 3:
  16897. case 4:
  16898. /* absolute uri (with/without port) */
  16899. hostend = get_rel_url_at_current_server(
  16900. conn->request_info.request_uri, conn);
  16901. if (hostend) {
  16902. conn->request_info.local_uri_raw = hostend;
  16903. } else {
  16904. conn->request_info.local_uri_raw = NULL;
  16905. }
  16906. break;
  16907. default:
  16908. mg_snprintf(conn,
  16909. NULL, /* No truncation check for ebuf */
  16910. ebuf,
  16911. sizeof(ebuf),
  16912. "Invalid URI");
  16913. mg_send_http_error(conn, 400, "%s", ebuf);
  16914. conn->request_info.local_uri_raw = NULL;
  16915. break;
  16916. }
  16917. conn->request_info.local_uri =
  16918. (char *)conn->request_info.local_uri_raw;
  16919. }
  16920. if (ebuf[0] != '\0') {
  16921. conn->protocol_type = -1;
  16922. } else {
  16923. /* HTTP/1 allows protocol upgrade */
  16924. conn->protocol_type = should_switch_to_protocol(conn);
  16925. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16926. /* This will occur, if a HTTP/1.1 request should be upgraded
  16927. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16928. * Since most (all?) major browsers only support HTTP/2 using
  16929. * ALPN, this is hard to test and very low priority.
  16930. * Deactivate it (at least for now).
  16931. */
  16932. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16933. }
  16934. }
  16935. DEBUG_TRACE("http: %s, error: %s",
  16936. (ri->http_version ? ri->http_version : "none"),
  16937. (ebuf[0] ? ebuf : "none"));
  16938. if (ebuf[0] == '\0') {
  16939. if (conn->request_info.local_uri) {
  16940. /* handle request to local server */
  16941. handle_request_stat_log(conn);
  16942. } else {
  16943. /* TODO: handle non-local request (PROXY) */
  16944. conn->must_close = 1;
  16945. }
  16946. } else {
  16947. conn->must_close = 1;
  16948. }
  16949. /* Response complete. Free header buffer */
  16950. free_buffered_response_header_list(conn);
  16951. if (ri->remote_user != NULL) {
  16952. mg_free((void *)ri->remote_user);
  16953. /* Important! When having connections with and without auth
  16954. * would cause double free and then crash */
  16955. ri->remote_user = NULL;
  16956. }
  16957. /* NOTE(lsm): order is important here. should_keep_alive() call
  16958. * is using parsed request, which will be invalid after
  16959. * memmove's below.
  16960. * Therefore, memorize should_keep_alive() result now for later
  16961. * use in loop exit condition. */
  16962. /* Enable it only if this request is completely discardable. */
  16963. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16964. && should_keep_alive(conn) && (conn->content_len >= 0)
  16965. && (conn->request_len > 0)
  16966. && ((conn->is_chunked == 4)
  16967. || (!conn->is_chunked
  16968. && ((conn->consumed_content == conn->content_len)
  16969. || ((conn->request_len + conn->content_len)
  16970. <= conn->data_len))))
  16971. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16972. if (keep_alive) {
  16973. /* Discard all buffered data for this request */
  16974. discard_len =
  16975. ((conn->request_len + conn->content_len) < conn->data_len)
  16976. ? (int)(conn->request_len + conn->content_len)
  16977. : conn->data_len;
  16978. conn->data_len -= discard_len;
  16979. if (conn->data_len > 0) {
  16980. DEBUG_TRACE("discard_len = %d", discard_len);
  16981. memmove(conn->buf,
  16982. conn->buf + discard_len,
  16983. (size_t)conn->data_len);
  16984. }
  16985. }
  16986. DEBUG_ASSERT(conn->data_len >= 0);
  16987. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16988. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16989. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16990. (long int)conn->data_len,
  16991. (long int)conn->buf_size);
  16992. break;
  16993. }
  16994. conn->handled_requests++;
  16995. } while (keep_alive);
  16996. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16997. conn->request_info.remote_addr,
  16998. difftime(time(NULL), conn->conn_birth_time));
  16999. close_connection(conn);
  17000. #if defined(USE_SERVER_STATS)
  17001. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17002. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17003. #endif
  17004. }
  17005. #if defined(ALTERNATIVE_QUEUE)
  17006. static void
  17007. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17008. {
  17009. unsigned int i;
  17010. while (!ctx->stop_flag) {
  17011. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17012. /* find a free worker slot and signal it */
  17013. if (ctx->client_socks[i].in_use == 2) {
  17014. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17015. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17016. ctx->client_socks[i] = *sp;
  17017. ctx->client_socks[i].in_use = 1;
  17018. /* socket has been moved to the consumer */
  17019. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17020. (void)event_signal(ctx->client_wait_events[i]);
  17021. return;
  17022. }
  17023. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17024. }
  17025. }
  17026. /* queue is full */
  17027. mg_sleep(1);
  17028. }
  17029. /* must consume */
  17030. set_blocking_mode(sp->sock);
  17031. closesocket(sp->sock);
  17032. }
  17033. static int
  17034. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  17035. {
  17036. DEBUG_TRACE("%s", "going idle");
  17037. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17038. ctx->client_socks[thread_index].in_use = 2;
  17039. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17040. event_wait(ctx->client_wait_events[thread_index]);
  17041. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17042. *sp = ctx->client_socks[thread_index];
  17043. if (ctx->stop_flag) {
  17044. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17045. if (sp->in_use == 1) {
  17046. /* must consume */
  17047. set_blocking_mode(sp->sock);
  17048. closesocket(sp->sock);
  17049. }
  17050. return 0;
  17051. }
  17052. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17053. if (sp->in_use == 1) {
  17054. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17055. return 1;
  17056. }
  17057. /* must not reach here */
  17058. DEBUG_ASSERT(0);
  17059. return 0;
  17060. }
  17061. #else /* ALTERNATIVE_QUEUE */
  17062. /* Worker threads take accepted socket from the queue */
  17063. static int
  17064. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  17065. {
  17066. (void)thread_index;
  17067. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17068. DEBUG_TRACE("%s", "going idle");
  17069. /* If the queue is empty, wait. We're idle at this point. */
  17070. while ((ctx->sq_head == ctx->sq_tail)
  17071. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17072. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17073. }
  17074. /* If we're stopping, sq_head may be equal to sq_tail. */
  17075. if (ctx->sq_head > ctx->sq_tail) {
  17076. /* Copy socket from the queue and increment tail */
  17077. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17078. ctx->sq_tail++;
  17079. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17080. /* Wrap pointers if needed */
  17081. while (ctx->sq_tail > ctx->sq_size) {
  17082. ctx->sq_tail -= ctx->sq_size;
  17083. ctx->sq_head -= ctx->sq_size;
  17084. }
  17085. }
  17086. (void)pthread_cond_signal(&ctx->sq_empty);
  17087. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17088. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17089. }
  17090. /* Master thread adds accepted socket to a queue */
  17091. static void
  17092. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17093. {
  17094. int queue_filled;
  17095. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17096. queue_filled = ctx->sq_head - ctx->sq_tail;
  17097. /* If the queue is full, wait */
  17098. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17099. && (queue_filled >= ctx->sq_size)) {
  17100. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17101. #if defined(USE_SERVER_STATS)
  17102. if (queue_filled > ctx->sq_max_fill) {
  17103. ctx->sq_max_fill = queue_filled;
  17104. }
  17105. #endif
  17106. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17107. ctx->sq_blocked = 0; /* Not blocked now */
  17108. queue_filled = ctx->sq_head - ctx->sq_tail;
  17109. }
  17110. if (queue_filled < ctx->sq_size) {
  17111. /* Copy socket to the queue and increment head */
  17112. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17113. ctx->sq_head++;
  17114. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17115. }
  17116. queue_filled = ctx->sq_head - ctx->sq_tail;
  17117. #if defined(USE_SERVER_STATS)
  17118. if (queue_filled > ctx->sq_max_fill) {
  17119. ctx->sq_max_fill = queue_filled;
  17120. }
  17121. #endif
  17122. (void)pthread_cond_signal(&ctx->sq_full);
  17123. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17124. }
  17125. #endif /* ALTERNATIVE_QUEUE */
  17126. static void
  17127. worker_thread_run(struct mg_connection *conn)
  17128. {
  17129. struct mg_context *ctx = conn->phys_ctx;
  17130. int thread_index;
  17131. struct mg_workerTLS tls;
  17132. mg_set_thread_name("worker");
  17133. tls.is_master = 0;
  17134. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17135. #if defined(_WIN32)
  17136. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17137. #endif
  17138. /* Initialize thread local storage before calling any callback */
  17139. pthread_setspecific(sTlsKey, &tls);
  17140. /* Check if there is a user callback */
  17141. if (ctx->callbacks.init_thread) {
  17142. /* call init_thread for a worker thread (type 1), and store the
  17143. * return value */
  17144. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17145. } else {
  17146. /* No callback: set user pointer to NULL */
  17147. tls.user_ptr = NULL;
  17148. }
  17149. /* Connection structure has been pre-allocated */
  17150. thread_index = (int)(conn - ctx->worker_connections);
  17151. if ((thread_index < 0)
  17152. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  17153. mg_cry_ctx_internal(ctx,
  17154. "Internal error: Invalid worker index %i",
  17155. thread_index);
  17156. return;
  17157. }
  17158. /* Request buffers are not pre-allocated. They are private to the
  17159. * request and do not contain any state information that might be
  17160. * of interest to anyone observing a server status. */
  17161. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17162. if (conn->buf == NULL) {
  17163. mg_cry_ctx_internal(
  17164. ctx,
  17165. "Out of memory: Cannot allocate buffer for worker %i",
  17166. thread_index);
  17167. return;
  17168. }
  17169. conn->buf_size = (int)ctx->max_request_size;
  17170. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17171. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17172. conn->request_info.user_data = ctx->user_data;
  17173. /* Allocate a mutex for this connection to allow communication both
  17174. * within the request handler and from elsewhere in the application
  17175. */
  17176. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17177. mg_free(conn->buf);
  17178. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17179. return;
  17180. }
  17181. #if defined(USE_SERVER_STATS)
  17182. conn->conn_state = 1; /* not consumed */
  17183. #endif
  17184. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17185. * signal sq_empty condvar to wake up the master waiting in
  17186. * produce_socket() */
  17187. while (consume_socket(ctx, &conn->client, thread_index)) {
  17188. /* New connections must start with new protocol negotiation */
  17189. tls.alpn_proto = NULL;
  17190. #if defined(USE_SERVER_STATS)
  17191. conn->conn_close_time = 0;
  17192. #endif
  17193. conn->conn_birth_time = time(NULL);
  17194. /* Fill in IP, port info early so even if SSL setup below fails,
  17195. * error handler would have the corresponding info.
  17196. * Thanks to Johannes Winkelmann for the patch.
  17197. */
  17198. conn->request_info.remote_port =
  17199. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17200. conn->request_info.server_port =
  17201. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17202. sockaddr_to_string(conn->request_info.remote_addr,
  17203. sizeof(conn->request_info.remote_addr),
  17204. &conn->client.rsa);
  17205. DEBUG_TRACE("Incomming %sconnection from %s",
  17206. (conn->client.is_ssl ? "SSL " : ""),
  17207. conn->request_info.remote_addr);
  17208. conn->request_info.is_ssl = conn->client.is_ssl;
  17209. if (conn->client.is_ssl) {
  17210. #if defined(USE_MBEDTLS)
  17211. /* HTTPS connection */
  17212. if (mbed_ssl_accept(&(conn->ssl),
  17213. conn->dom_ctx->ssl_ctx,
  17214. (int *)&(conn->client.sock),
  17215. conn->phys_ctx)
  17216. == 0) {
  17217. /* conn->dom_ctx is set in get_request */
  17218. /* process HTTPS connection */
  17219. init_connection(conn);
  17220. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17221. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17222. process_new_connection(conn);
  17223. } else {
  17224. /* make sure the connection is cleaned up on SSL failure */
  17225. close_connection(conn);
  17226. }
  17227. #elif !defined(NO_SSL)
  17228. /* HTTPS connection */
  17229. if (sslize(conn, SSL_accept, NULL)) {
  17230. /* conn->dom_ctx is set in get_request */
  17231. /* Get SSL client certificate information (if set) */
  17232. struct mg_client_cert client_cert;
  17233. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17234. conn->request_info.client_cert = &client_cert;
  17235. }
  17236. /* process HTTPS connection */
  17237. #if defined(USE_HTTP2)
  17238. if ((tls.alpn_proto != NULL)
  17239. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17240. /* process HTTPS/2 connection */
  17241. init_connection(conn);
  17242. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17243. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17244. conn->content_len =
  17245. -1; /* content length is not predefined */
  17246. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17247. process_new_http2_connection(conn);
  17248. } else
  17249. #endif
  17250. {
  17251. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17252. init_connection(conn);
  17253. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17254. /* Start with HTTP, WS will be an "upgrade" request later */
  17255. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17256. process_new_connection(conn);
  17257. }
  17258. /* Free client certificate info */
  17259. if (conn->request_info.client_cert) {
  17260. mg_free((void *)(conn->request_info.client_cert->subject));
  17261. mg_free((void *)(conn->request_info.client_cert->issuer));
  17262. mg_free((void *)(conn->request_info.client_cert->serial));
  17263. mg_free((void *)(conn->request_info.client_cert->finger));
  17264. /* Free certificate memory */
  17265. X509_free(
  17266. (X509 *)conn->request_info.client_cert->peer_cert);
  17267. conn->request_info.client_cert->peer_cert = 0;
  17268. conn->request_info.client_cert->subject = 0;
  17269. conn->request_info.client_cert->issuer = 0;
  17270. conn->request_info.client_cert->serial = 0;
  17271. conn->request_info.client_cert->finger = 0;
  17272. conn->request_info.client_cert = 0;
  17273. }
  17274. } else {
  17275. /* make sure the connection is cleaned up on SSL failure */
  17276. close_connection(conn);
  17277. }
  17278. #endif
  17279. } else {
  17280. /* process HTTP connection */
  17281. init_connection(conn);
  17282. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17283. /* Start with HTTP, WS will be an "upgrade" request later */
  17284. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17285. process_new_connection(conn);
  17286. }
  17287. DEBUG_TRACE("%s", "Connection closed");
  17288. #if defined(USE_SERVER_STATS)
  17289. conn->conn_close_time = time(NULL);
  17290. #endif
  17291. }
  17292. /* Call exit thread user callback */
  17293. if (ctx->callbacks.exit_thread) {
  17294. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17295. }
  17296. /* delete thread local storage objects */
  17297. pthread_setspecific(sTlsKey, NULL);
  17298. #if defined(_WIN32)
  17299. CloseHandle(tls.pthread_cond_helper_mutex);
  17300. #endif
  17301. pthread_mutex_destroy(&conn->mutex);
  17302. /* Free the request buffer. */
  17303. conn->buf_size = 0;
  17304. mg_free(conn->buf);
  17305. conn->buf = NULL;
  17306. /* Free cleaned URI (if any) */
  17307. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17308. mg_free((void *)conn->request_info.local_uri);
  17309. conn->request_info.local_uri = NULL;
  17310. }
  17311. #if defined(USE_SERVER_STATS)
  17312. conn->conn_state = 9; /* done */
  17313. #endif
  17314. DEBUG_TRACE("%s", "exiting");
  17315. }
  17316. /* Threads have different return types on Windows and Unix. */
  17317. #if defined(_WIN32)
  17318. static unsigned __stdcall worker_thread(void *thread_func_param)
  17319. {
  17320. worker_thread_run((struct mg_connection *)thread_func_param);
  17321. return 0;
  17322. }
  17323. #else
  17324. static void *
  17325. worker_thread(void *thread_func_param)
  17326. {
  17327. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  17328. struct sigaction sa;
  17329. /* Ignore SIGPIPE */
  17330. memset(&sa, 0, sizeof(sa));
  17331. sa.sa_handler = SIG_IGN;
  17332. sigaction(SIGPIPE, &sa, NULL);
  17333. #endif
  17334. worker_thread_run((struct mg_connection *)thread_func_param);
  17335. return NULL;
  17336. }
  17337. #endif /* _WIN32 */
  17338. /* This is an internal function, thus all arguments are expected to be
  17339. * valid - a NULL check is not required. */
  17340. static void
  17341. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17342. {
  17343. struct socket so;
  17344. char src_addr[IP_ADDR_STR_LEN];
  17345. socklen_t len = sizeof(so.rsa);
  17346. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  17347. int on = 1;
  17348. #endif
  17349. memset(&so, 0, sizeof(so));
  17350. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17351. == INVALID_SOCKET) {
  17352. } else if (check_acl(ctx, &so.rsa) != 1) {
  17353. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17354. mg_cry_ctx_internal(ctx,
  17355. "%s: %s is not allowed to connect",
  17356. __func__,
  17357. src_addr);
  17358. closesocket(so.sock);
  17359. } else {
  17360. /* Put so socket structure into the queue */
  17361. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17362. set_close_on_exec(so.sock, NULL, ctx);
  17363. so.is_ssl = listener->is_ssl;
  17364. so.ssl_redir = listener->ssl_redir;
  17365. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17366. mg_cry_ctx_internal(ctx,
  17367. "%s: getsockname() failed: %s",
  17368. __func__,
  17369. strerror(ERRNO));
  17370. }
  17371. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  17372. if ((so.lsa.sa.sa_family == AF_INET)
  17373. || (so.lsa.sa.sa_family == AF_INET6)) {
  17374. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17375. * This is needed because if HTTP-level keep-alive
  17376. * is enabled, and client resets the connection, server won't get
  17377. * TCP FIN or RST and will keep the connection open forever. With
  17378. * TCP keep-alive, next keep-alive handshake will figure out that
  17379. * the client is down and will close the server end.
  17380. * Thanks to Igor Klopov who suggested the patch. */
  17381. if (setsockopt(so.sock,
  17382. SOL_SOCKET,
  17383. SO_KEEPALIVE,
  17384. (SOCK_OPT_TYPE)&on,
  17385. sizeof(on))
  17386. != 0) {
  17387. mg_cry_ctx_internal(
  17388. ctx,
  17389. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17390. __func__,
  17391. strerror(ERRNO));
  17392. }
  17393. }
  17394. #endif
  17395. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17396. * to effectively fill up the underlying IP packet payload and
  17397. * reduce the overhead of sending lots of small buffers. However
  17398. * this hurts the server's throughput (ie. operations per second)
  17399. * when HTTP 1.1 persistent connections are used and the responses
  17400. * are relatively small (eg. less than 1400 bytes).
  17401. */
  17402. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17403. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17404. if (set_tcp_nodelay(&so, 1) != 0) {
  17405. mg_cry_ctx_internal(
  17406. ctx,
  17407. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17408. __func__,
  17409. strerror(ERRNO));
  17410. }
  17411. }
  17412. /* The "non blocking" property should already be
  17413. * inherited from the parent socket. Set it for
  17414. * non-compliant socket implementations. */
  17415. set_non_blocking_mode(so.sock);
  17416. so.in_use = 0;
  17417. produce_socket(ctx, &so);
  17418. }
  17419. }
  17420. static void
  17421. master_thread_run(struct mg_context *ctx)
  17422. {
  17423. struct mg_workerTLS tls;
  17424. struct mg_pollfd *pfd;
  17425. unsigned int i;
  17426. unsigned int workerthreadcount;
  17427. if (!ctx) {
  17428. return;
  17429. }
  17430. mg_set_thread_name("master");
  17431. /* Increase priority of the master thread */
  17432. #if defined(_WIN32)
  17433. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17434. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17435. int min_prio = sched_get_priority_min(SCHED_RR);
  17436. int max_prio = sched_get_priority_max(SCHED_RR);
  17437. if ((min_prio >= 0) && (max_prio >= 0)
  17438. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17439. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17440. struct sched_param sched_param = {0};
  17441. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17442. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17443. }
  17444. #endif
  17445. /* Initialize thread local storage */
  17446. #if defined(_WIN32)
  17447. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17448. #endif
  17449. tls.is_master = 1;
  17450. pthread_setspecific(sTlsKey, &tls);
  17451. if (ctx->callbacks.init_thread) {
  17452. /* Callback for the master thread (type 0) */
  17453. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17454. } else {
  17455. tls.user_ptr = NULL;
  17456. }
  17457. /* Lua background script "start" event */
  17458. #if defined(USE_LUA)
  17459. if (ctx->lua_background_state) {
  17460. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17461. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17462. /* call "start()" in Lua */
  17463. lua_getglobal(lstate, "start");
  17464. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17465. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17466. if (ret != 0) {
  17467. struct mg_connection fc;
  17468. lua_cry(fake_connection(&fc, ctx),
  17469. ret,
  17470. lstate,
  17471. "lua_background_script",
  17472. "start");
  17473. }
  17474. } else {
  17475. lua_pop(lstate, 1);
  17476. }
  17477. /* determine if there is a "log()" function in Lua background script */
  17478. lua_getglobal(lstate, "log");
  17479. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17480. ctx->lua_bg_log_available = 1;
  17481. }
  17482. lua_pop(lstate, 1);
  17483. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17484. }
  17485. #endif
  17486. /* Server starts *now* */
  17487. ctx->start_time = time(NULL);
  17488. /* Server accept loop */
  17489. pfd = ctx->listening_socket_fds;
  17490. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17491. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17492. pfd[i].fd = ctx->listening_sockets[i].sock;
  17493. pfd[i].events = POLLIN;
  17494. }
  17495. if (mg_poll(pfd,
  17496. ctx->num_listening_sockets,
  17497. SOCKET_TIMEOUT_QUANTUM,
  17498. &(ctx->stop_flag))
  17499. > 0) {
  17500. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17501. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17502. * successful poll, and POLLIN is defined as
  17503. * (POLLRDNORM | POLLRDBAND)
  17504. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17505. * pfd[i].revents == POLLIN. */
  17506. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17507. && (pfd[i].revents & POLLIN)) {
  17508. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17509. }
  17510. }
  17511. }
  17512. }
  17513. /* Here stop_flag is 1 - Initiate shutdown. */
  17514. DEBUG_TRACE("%s", "stopping workers");
  17515. /* Stop signal received: somebody called mg_stop. Quit. */
  17516. close_all_listening_sockets(ctx);
  17517. /* Wakeup workers that are waiting for connections to handle. */
  17518. #if defined(ALTERNATIVE_QUEUE)
  17519. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17520. event_signal(ctx->client_wait_events[i]);
  17521. }
  17522. #else
  17523. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17524. pthread_cond_broadcast(&ctx->sq_full);
  17525. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17526. #endif
  17527. /* Join all worker threads to avoid leaking threads. */
  17528. workerthreadcount = ctx->cfg_worker_threads;
  17529. for (i = 0; i < workerthreadcount; i++) {
  17530. if (!cw_is_thread_null(&ctx->worker_threadids[i])) {
  17531. mg_join_thread(ctx->worker_threadids[i]);
  17532. }
  17533. }
  17534. #if defined(USE_LUA)
  17535. /* Free Lua state of lua background task */
  17536. if (ctx->lua_background_state) {
  17537. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17538. ctx->lua_bg_log_available = 0;
  17539. /* call "stop()" in Lua */
  17540. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17541. lua_getglobal(lstate, "stop");
  17542. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17543. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17544. if (ret != 0) {
  17545. struct mg_connection fc;
  17546. lua_cry(fake_connection(&fc, ctx),
  17547. ret,
  17548. lstate,
  17549. "lua_background_script",
  17550. "stop");
  17551. }
  17552. }
  17553. lua_close(lstate);
  17554. ctx->lua_background_state = 0;
  17555. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17556. }
  17557. #endif
  17558. DEBUG_TRACE("%s", "exiting");
  17559. /* call exit thread callback */
  17560. if (ctx->callbacks.exit_thread) {
  17561. /* Callback for the master thread (type 0) */
  17562. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17563. }
  17564. #if defined(_WIN32)
  17565. CloseHandle(tls.pthread_cond_helper_mutex);
  17566. #endif
  17567. pthread_setspecific(sTlsKey, NULL);
  17568. /* Signal mg_stop() that we're done.
  17569. * WARNING: This must be the very last thing this
  17570. * thread does, as ctx becomes invalid after this line. */
  17571. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17572. }
  17573. /* Threads have different return types on Windows and Unix. */
  17574. #if defined(_WIN32)
  17575. static unsigned __stdcall master_thread(void *thread_func_param)
  17576. {
  17577. master_thread_run((struct mg_context *)thread_func_param);
  17578. return 0;
  17579. }
  17580. #else
  17581. static void *
  17582. master_thread(void *thread_func_param)
  17583. {
  17584. #if !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  17585. struct sigaction sa;
  17586. /* Ignore SIGPIPE */
  17587. memset(&sa, 0, sizeof(sa));
  17588. sa.sa_handler = SIG_IGN;
  17589. sigaction(SIGPIPE, &sa, NULL);
  17590. #endif
  17591. master_thread_run((struct mg_context *)thread_func_param);
  17592. return NULL;
  17593. }
  17594. #endif /* _WIN32 */
  17595. static void
  17596. free_context(struct mg_context *ctx)
  17597. {
  17598. int i;
  17599. struct mg_handler_info *tmp_rh;
  17600. if (ctx == NULL) {
  17601. return;
  17602. }
  17603. /* Call user callback */
  17604. if (ctx->callbacks.exit_context) {
  17605. ctx->callbacks.exit_context(ctx);
  17606. }
  17607. /* All threads exited, no sync is needed. Destroy thread mutex and
  17608. * condvars
  17609. */
  17610. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17611. #if defined(ALTERNATIVE_QUEUE)
  17612. mg_free(ctx->client_socks);
  17613. if (ctx->client_wait_events != NULL) {
  17614. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17615. event_destroy(ctx->client_wait_events[i]);
  17616. }
  17617. mg_free(ctx->client_wait_events);
  17618. }
  17619. #else
  17620. (void)pthread_cond_destroy(&ctx->sq_empty);
  17621. (void)pthread_cond_destroy(&ctx->sq_full);
  17622. mg_free(ctx->squeue);
  17623. #endif
  17624. /* Destroy other context global data structures mutex */
  17625. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17626. #if defined(USE_LUA)
  17627. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17628. #endif
  17629. /* Deallocate config parameters */
  17630. for (i = 0; i < NUM_OPTIONS; i++) {
  17631. if (ctx->dd.config[i] != NULL) {
  17632. #if defined(_MSC_VER)
  17633. #pragma warning(suppress : 6001)
  17634. #endif
  17635. mg_free(ctx->dd.config[i]);
  17636. }
  17637. }
  17638. /* Deallocate request handlers */
  17639. while (ctx->dd.handlers) {
  17640. tmp_rh = ctx->dd.handlers;
  17641. ctx->dd.handlers = tmp_rh->next;
  17642. mg_free(tmp_rh->uri);
  17643. mg_free(tmp_rh);
  17644. }
  17645. #if defined(USE_MBEDTLS)
  17646. if (ctx->dd.ssl_ctx != NULL) {
  17647. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17648. mg_free(ctx->dd.ssl_ctx);
  17649. ctx->dd.ssl_ctx = NULL;
  17650. }
  17651. #elif !defined(NO_SSL)
  17652. /* Deallocate SSL context */
  17653. if (ctx->dd.ssl_ctx != NULL) {
  17654. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17655. int callback_ret =
  17656. (ctx->callbacks.external_ssl_ctx == NULL)
  17657. ? 0
  17658. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17659. if (callback_ret == 0) {
  17660. SSL_CTX_free(ctx->dd.ssl_ctx);
  17661. }
  17662. /* else: ignore error and ommit SSL_CTX_free in case
  17663. * callback_ret is 1 */
  17664. }
  17665. #endif /* !NO_SSL */
  17666. /* Deallocate worker thread ID array */
  17667. mg_free(ctx->worker_threadids);
  17668. /* Deallocate worker thread ID array */
  17669. mg_free(ctx->worker_connections);
  17670. /* deallocate system name string */
  17671. mg_free(ctx->systemName);
  17672. /* Deallocate context itself */
  17673. mg_free(ctx);
  17674. }
  17675. CIVETWEB_API void
  17676. mg_stop(struct mg_context *ctx)
  17677. {
  17678. cw_thread_handle_t mt;
  17679. if (!ctx) {
  17680. return;
  17681. }
  17682. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17683. * two threads is not allowed. */
  17684. mt = ctx->masterthreadid;
  17685. if (cw_is_thread_null(&mt)) {
  17686. return;
  17687. }
  17688. cw_stop_thread(&ctx->masterthreadid);
  17689. /* Set stop flag, so all threads know they have to exit. */
  17690. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17691. /* Join timer thread */
  17692. #if defined(USE_TIMERS)
  17693. timers_exit(ctx);
  17694. #endif
  17695. /* Wait until everything has stopped. */
  17696. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17697. (void)mg_sleep(10);
  17698. }
  17699. /* Wait to stop master thread */
  17700. mg_join_thread(mt);
  17701. /* Close remaining Lua states */
  17702. #if defined(USE_LUA)
  17703. lua_ctx_exit(ctx);
  17704. #endif
  17705. /* Free memory */
  17706. free_context(ctx);
  17707. }
  17708. static void
  17709. get_system_name(char **sysName)
  17710. {
  17711. #if defined(_WIN32)
  17712. char name[128];
  17713. DWORD dwVersion = 0;
  17714. DWORD dwMajorVersion = 0;
  17715. DWORD dwMinorVersion = 0;
  17716. DWORD dwBuild = 0;
  17717. BOOL wowRet, isWoW = FALSE;
  17718. #if defined(_MSC_VER)
  17719. #pragma warning(push)
  17720. /* GetVersion was declared deprecated */
  17721. #pragma warning(disable : 4996)
  17722. #endif
  17723. dwVersion = GetVersion();
  17724. #if defined(_MSC_VER)
  17725. #pragma warning(pop)
  17726. #endif
  17727. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17728. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17729. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17730. (void)dwBuild;
  17731. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17732. sprintf(name,
  17733. "Windows %u.%u%s",
  17734. (unsigned)dwMajorVersion,
  17735. (unsigned)dwMinorVersion,
  17736. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17737. *sysName = mg_strdup(name);
  17738. #elif defined(__ZEPHYR__)
  17739. *sysName = mg_strdup("Zephyr OS");
  17740. #elif defined(ESP_PLATFORM)
  17741. *sysName = mg_strdup("Espressif ESP32");
  17742. #else
  17743. struct utsname name;
  17744. memset(&name, 0, sizeof(name));
  17745. uname(&name);
  17746. *sysName = mg_strdup(name.sysname);
  17747. #endif
  17748. }
  17749. static void
  17750. legacy_init(const char **options)
  17751. {
  17752. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17753. if (options) {
  17754. const char **run_options = options;
  17755. const char *optname = config_options[LISTENING_PORTS].name;
  17756. /* Try to find the "listening_ports" option */
  17757. while (*run_options) {
  17758. if (!strcmp(*run_options, optname)) {
  17759. ports_option = run_options[1];
  17760. }
  17761. run_options += 2;
  17762. }
  17763. }
  17764. if (is_ssl_port_used(ports_option)) {
  17765. /* Initialize with SSL support */
  17766. mg_init_library(MG_FEATURES_TLS);
  17767. } else {
  17768. /* Initialize without SSL support */
  17769. mg_init_library(MG_FEATURES_DEFAULT);
  17770. }
  17771. }
  17772. CIVETWEB_API struct mg_context *
  17773. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17774. {
  17775. struct mg_context *ctx;
  17776. const char *name, *value, *default_value;
  17777. int idx, ok, workerthreadcount;
  17778. unsigned int i;
  17779. int itmp;
  17780. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17781. const char **options =
  17782. ((init != NULL) ? (init->configuration_options) : (NULL));
  17783. struct mg_workerTLS tls;
  17784. if (error != NULL) {
  17785. error->code = MG_ERROR_DATA_CODE_OK;
  17786. error->code_sub = 0;
  17787. if (error->text_buffer_size > 0) {
  17788. *error->text = 0;
  17789. }
  17790. }
  17791. if (mg_init_library_called == 0) {
  17792. /* Legacy INIT, if mg_start is called without mg_init_library.
  17793. * Note: This will cause a memory leak when unloading the library.
  17794. */
  17795. legacy_init(options);
  17796. }
  17797. if (mg_init_library_called == 0) {
  17798. if (error != NULL) {
  17799. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  17800. mg_snprintf(NULL,
  17801. NULL, /* No truncation check for error buffers */
  17802. error->text,
  17803. error->text_buffer_size,
  17804. "%s",
  17805. "Library uninitialized");
  17806. }
  17807. return NULL;
  17808. }
  17809. /* Allocate context and initialize reasonable general case defaults. */
  17810. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  17811. if (ctx == NULL) {
  17812. if (error != NULL) {
  17813. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17814. error->code_sub = (unsigned)sizeof(*ctx);
  17815. mg_snprintf(NULL,
  17816. NULL, /* No truncation check for error buffers */
  17817. error->text,
  17818. error->text_buffer_size,
  17819. "%s",
  17820. "Out of memory");
  17821. }
  17822. return NULL;
  17823. }
  17824. /* Random number generator will initialize at the first call */
  17825. ctx->dd.auth_nonce_mask =
  17826. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17827. /* Save started thread index to reuse in other external API calls
  17828. * For the sake of thread synchronization all non-civetweb threads
  17829. * can be considered as single external thread */
  17830. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17831. tls.is_master = -1; /* Thread calling mg_start */
  17832. tls.thread_idx = ctx->starter_thread_idx;
  17833. #if defined(_WIN32)
  17834. tls.pthread_cond_helper_mutex = NULL;
  17835. #endif
  17836. pthread_setspecific(sTlsKey, &tls);
  17837. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17838. #if !defined(ALTERNATIVE_QUEUE)
  17839. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17840. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17841. ctx->sq_blocked = 0;
  17842. #endif
  17843. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17844. #if defined(USE_LUA)
  17845. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17846. #endif
  17847. if (!ok) {
  17848. unsigned error_id = (unsigned)ERRNO;
  17849. const char *err_msg =
  17850. "Cannot initialize thread synchronization objects";
  17851. /* Fatal error - abort start. However, this situation should never
  17852. * occur in practice. */
  17853. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17854. if (error != NULL) {
  17855. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  17856. error->code_sub = error_id;
  17857. mg_snprintf(NULL,
  17858. NULL, /* No truncation check for error buffers */
  17859. error->text,
  17860. error->text_buffer_size,
  17861. "%s",
  17862. err_msg);
  17863. }
  17864. mg_free(ctx);
  17865. pthread_setspecific(sTlsKey, NULL);
  17866. return NULL;
  17867. }
  17868. if ((init != NULL) && (init->callbacks != NULL)) {
  17869. /* Set all callbacks except exit_context. */
  17870. ctx->callbacks = *init->callbacks;
  17871. exit_callback = init->callbacks->exit_context;
  17872. /* The exit callback is activated once the context is successfully
  17873. * created. It should not be called, if an incomplete context object
  17874. * is deleted during a failed initialization. */
  17875. ctx->callbacks.exit_context = 0;
  17876. }
  17877. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17878. ctx->dd.handlers = NULL;
  17879. ctx->dd.next = NULL;
  17880. #if defined(USE_LUA)
  17881. lua_ctx_init(ctx);
  17882. #endif
  17883. /* Store options */
  17884. while (options && (name = *options++) != NULL) {
  17885. idx = get_option_index(name);
  17886. if (idx == -1) {
  17887. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17888. if (error != NULL) {
  17889. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17890. error->code_sub = (unsigned)-1;
  17891. mg_snprintf(NULL,
  17892. NULL, /* No truncation check for error buffers */
  17893. error->text,
  17894. error->text_buffer_size,
  17895. "Invalid configuration option: %s",
  17896. name);
  17897. }
  17898. free_context(ctx);
  17899. pthread_setspecific(sTlsKey, NULL);
  17900. return NULL;
  17901. } else if ((value = *options++) == NULL) {
  17902. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17903. if (error != NULL) {
  17904. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17905. error->code_sub = (unsigned)idx;
  17906. mg_snprintf(NULL,
  17907. NULL, /* No truncation check for error buffers */
  17908. error->text,
  17909. error->text_buffer_size,
  17910. "Invalid configuration option value: %s",
  17911. name);
  17912. }
  17913. free_context(ctx);
  17914. pthread_setspecific(sTlsKey, NULL);
  17915. return NULL;
  17916. }
  17917. if (ctx->dd.config[idx] != NULL) {
  17918. /* A duplicate configuration option is not an error - the last
  17919. * option value will be used. */
  17920. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17921. mg_free(ctx->dd.config[idx]);
  17922. }
  17923. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17924. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17925. }
  17926. /* Set default value if needed */
  17927. for (i = 0; config_options[i].name != NULL; i++) {
  17928. default_value = config_options[i].default_value;
  17929. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17930. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17931. }
  17932. }
  17933. /* Request size option */
  17934. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17935. if (itmp < 1024) {
  17936. mg_cry_ctx_internal(ctx,
  17937. "%s too small",
  17938. config_options[MAX_REQUEST_SIZE].name);
  17939. if (error != NULL) {
  17940. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17941. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  17942. mg_snprintf(NULL,
  17943. NULL, /* No truncation check for error buffers */
  17944. error->text,
  17945. error->text_buffer_size,
  17946. "Invalid configuration option value: %s",
  17947. config_options[MAX_REQUEST_SIZE].name);
  17948. }
  17949. free_context(ctx);
  17950. pthread_setspecific(sTlsKey, NULL);
  17951. return NULL;
  17952. }
  17953. ctx->max_request_size = (unsigned)itmp;
  17954. /* Queue length */
  17955. #if !defined(ALTERNATIVE_QUEUE)
  17956. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17957. if (itmp < 1) {
  17958. mg_cry_ctx_internal(ctx,
  17959. "%s too small",
  17960. config_options[CONNECTION_QUEUE_SIZE].name);
  17961. if (error != NULL) {
  17962. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17963. error->code_sub = CONNECTION_QUEUE_SIZE;
  17964. mg_snprintf(NULL,
  17965. NULL, /* No truncation check for error buffers */
  17966. error->text,
  17967. error->text_buffer_size,
  17968. "Invalid configuration option value: %s",
  17969. config_options[CONNECTION_QUEUE_SIZE].name);
  17970. }
  17971. free_context(ctx);
  17972. pthread_setspecific(sTlsKey, NULL);
  17973. return NULL;
  17974. }
  17975. ctx->squeue =
  17976. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17977. if (ctx->squeue == NULL) {
  17978. mg_cry_ctx_internal(ctx,
  17979. "Out of memory: Cannot allocate %s",
  17980. config_options[CONNECTION_QUEUE_SIZE].name);
  17981. if (error != NULL) {
  17982. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17983. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  17984. mg_snprintf(NULL,
  17985. NULL, /* No truncation check for error buffers */
  17986. error->text,
  17987. error->text_buffer_size,
  17988. "Out of memory: Cannot allocate %s",
  17989. config_options[CONNECTION_QUEUE_SIZE].name);
  17990. }
  17991. free_context(ctx);
  17992. pthread_setspecific(sTlsKey, NULL);
  17993. return NULL;
  17994. }
  17995. ctx->sq_size = itmp;
  17996. #endif
  17997. /* Worker thread count option */
  17998. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17999. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18000. if (workerthreadcount <= 0) {
  18001. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18002. } else {
  18003. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18004. }
  18005. if (error != NULL) {
  18006. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18007. error->code_sub = NUM_THREADS;
  18008. mg_snprintf(NULL,
  18009. NULL, /* No truncation check for error buffers */
  18010. error->text,
  18011. error->text_buffer_size,
  18012. "Invalid configuration option value: %s",
  18013. config_options[NUM_THREADS].name);
  18014. }
  18015. free_context(ctx);
  18016. pthread_setspecific(sTlsKey, NULL);
  18017. return NULL;
  18018. }
  18019. /* Document root */
  18020. #if defined(NO_FILES)
  18021. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18022. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18023. if (error != NULL) {
  18024. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18025. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18026. mg_snprintf(NULL,
  18027. NULL, /* No truncation check for error buffers */
  18028. error->text,
  18029. error->text_buffer_size,
  18030. "Invalid configuration option value: %s",
  18031. config_options[DOCUMENT_ROOT].name);
  18032. }
  18033. free_context(ctx);
  18034. pthread_setspecific(sTlsKey, NULL);
  18035. return NULL;
  18036. }
  18037. #endif
  18038. get_system_name(&ctx->systemName);
  18039. #if defined(USE_LUA)
  18040. /* If a Lua background script has been configured, start it. */
  18041. ctx->lua_bg_log_available = 0;
  18042. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18043. char ebuf[256];
  18044. struct vec opt_vec;
  18045. struct vec eq_vec;
  18046. const char *sparams;
  18047. memset(ebuf, 0, sizeof(ebuf));
  18048. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18049. /* Create a Lua state, load all standard libraries and the mg table */
  18050. lua_State *state = mg_lua_context_script_prepare(
  18051. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18052. if (!state) {
  18053. mg_cry_ctx_internal(ctx,
  18054. "lua_background_script load error: %s",
  18055. ebuf);
  18056. if (error != NULL) {
  18057. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18058. mg_snprintf(NULL,
  18059. NULL, /* No truncation check for error buffers */
  18060. error->text,
  18061. error->text_buffer_size,
  18062. "Error in script %s: %s",
  18063. config_options[LUA_BACKGROUND_SCRIPT].name,
  18064. ebuf);
  18065. }
  18066. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18067. free_context(ctx);
  18068. pthread_setspecific(sTlsKey, NULL);
  18069. return NULL;
  18070. }
  18071. /* Add a table with parameters into mg.params */
  18072. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18073. if (sparams && sparams[0]) {
  18074. lua_getglobal(state, "mg");
  18075. lua_pushstring(state, "params");
  18076. lua_newtable(state);
  18077. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18078. != NULL) {
  18079. reg_llstring(
  18080. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18081. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18082. break;
  18083. }
  18084. lua_rawset(state, -3);
  18085. lua_pop(state, 1);
  18086. }
  18087. /* Call script */
  18088. state = mg_lua_context_script_run(state,
  18089. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18090. ctx,
  18091. ebuf,
  18092. sizeof(ebuf));
  18093. if (!state) {
  18094. mg_cry_ctx_internal(ctx,
  18095. "lua_background_script start error: %s",
  18096. ebuf);
  18097. if (error != NULL) {
  18098. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18099. mg_snprintf(NULL,
  18100. NULL, /* No truncation check for error buffers */
  18101. error->text,
  18102. error->text_buffer_size,
  18103. "Error in script %s: %s",
  18104. config_options[DOCUMENT_ROOT].name,
  18105. ebuf);
  18106. }
  18107. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18108. free_context(ctx);
  18109. pthread_setspecific(sTlsKey, NULL);
  18110. return NULL;
  18111. }
  18112. /* state remains valid */
  18113. ctx->lua_background_state = (void *)state;
  18114. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18115. } else {
  18116. ctx->lua_background_state = 0;
  18117. }
  18118. #endif
  18119. /* Step by step initialization of ctx - depending on build options */
  18120. #if !defined(NO_FILESYSTEMS)
  18121. if (!set_gpass_option(ctx, NULL)) {
  18122. const char *err_msg = "Invalid global password file";
  18123. /* Fatal error - abort start. */
  18124. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18125. if (error != NULL) {
  18126. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18127. mg_snprintf(NULL,
  18128. NULL, /* No truncation check for error buffers */
  18129. error->text,
  18130. error->text_buffer_size,
  18131. "%s",
  18132. err_msg);
  18133. }
  18134. free_context(ctx);
  18135. pthread_setspecific(sTlsKey, NULL);
  18136. return NULL;
  18137. }
  18138. #endif
  18139. #if defined(USE_MBEDTLS)
  18140. if (!mg_sslctx_init(ctx, NULL)) {
  18141. const char *err_msg = "Error initializing SSL context";
  18142. /* Fatal error - abort start. */
  18143. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18144. if (error != NULL) {
  18145. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18146. mg_snprintf(NULL,
  18147. NULL, /* No truncation check for error buffers */
  18148. error->text,
  18149. error->text_buffer_size,
  18150. "%s",
  18151. err_msg);
  18152. }
  18153. free_context(ctx);
  18154. pthread_setspecific(sTlsKey, NULL);
  18155. return NULL;
  18156. }
  18157. #elif !defined(NO_SSL)
  18158. if (!init_ssl_ctx(ctx, NULL)) {
  18159. const char *err_msg = "Error initializing SSL context";
  18160. /* Fatal error - abort start. */
  18161. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18162. if (error != NULL) {
  18163. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18164. mg_snprintf(NULL,
  18165. NULL, /* No truncation check for error buffers */
  18166. error->text,
  18167. error->text_buffer_size,
  18168. "%s",
  18169. err_msg);
  18170. }
  18171. free_context(ctx);
  18172. pthread_setspecific(sTlsKey, NULL);
  18173. return NULL;
  18174. }
  18175. #endif
  18176. if (!set_ports_option(ctx)) {
  18177. const char *err_msg = "Failed to setup server ports";
  18178. /* Fatal error - abort start. */
  18179. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18180. if (error != NULL) {
  18181. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18182. mg_snprintf(NULL,
  18183. NULL, /* No truncation check for error buffers */
  18184. error->text,
  18185. error->text_buffer_size,
  18186. "%s",
  18187. err_msg);
  18188. }
  18189. free_context(ctx);
  18190. pthread_setspecific(sTlsKey, NULL);
  18191. return NULL;
  18192. }
  18193. #if !defined(_WIN32) && !defined(__ZEPHYR__) && !defined(ESP_PLATFORM)
  18194. if (!set_uid_option(ctx)) {
  18195. const char *err_msg = "Failed to run as configured user";
  18196. /* Fatal error - abort start. */
  18197. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18198. if (error != NULL) {
  18199. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18200. mg_snprintf(NULL,
  18201. NULL, /* No truncation check for error buffers */
  18202. error->text,
  18203. error->text_buffer_size,
  18204. "%s",
  18205. err_msg);
  18206. }
  18207. free_context(ctx);
  18208. pthread_setspecific(sTlsKey, NULL);
  18209. return NULL;
  18210. }
  18211. #endif
  18212. if (!set_acl_option(ctx)) {
  18213. const char *err_msg = "Failed to setup access control list";
  18214. /* Fatal error - abort start. */
  18215. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18216. if (error != NULL) {
  18217. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18218. mg_snprintf(NULL,
  18219. NULL, /* No truncation check for error buffers */
  18220. error->text,
  18221. error->text_buffer_size,
  18222. "%s",
  18223. err_msg);
  18224. }
  18225. free_context(ctx);
  18226. pthread_setspecific(sTlsKey, NULL);
  18227. return NULL;
  18228. }
  18229. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  18230. ctx->worker_threadids = (cw_thread_handle_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18231. sizeof(cw_thread_handle_t),
  18232. ctx);
  18233. if (ctx->worker_threadids == NULL) {
  18234. const char *err_msg = "Not enough memory for worker thread ID array";
  18235. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18236. if (error != NULL) {
  18237. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18238. error->code_sub =
  18239. (unsigned)ctx->cfg_worker_threads * (unsigned)sizeof(cw_thread_handle_t);
  18240. mg_snprintf(NULL,
  18241. NULL, /* No truncation check for error buffers */
  18242. error->text,
  18243. error->text_buffer_size,
  18244. "%s",
  18245. err_msg);
  18246. }
  18247. free_context(ctx);
  18248. pthread_setspecific(sTlsKey, NULL);
  18249. return NULL;
  18250. }
  18251. ctx->worker_connections =
  18252. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18253. sizeof(struct mg_connection),
  18254. ctx);
  18255. if (ctx->worker_connections == NULL) {
  18256. const char *err_msg =
  18257. "Not enough memory for worker thread connection array";
  18258. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18259. if (error != NULL) {
  18260. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18261. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18262. * (unsigned)sizeof(struct mg_connection);
  18263. mg_snprintf(NULL,
  18264. NULL, /* No truncation check for error buffers */
  18265. error->text,
  18266. error->text_buffer_size,
  18267. "%s",
  18268. err_msg);
  18269. }
  18270. free_context(ctx);
  18271. pthread_setspecific(sTlsKey, NULL);
  18272. return NULL;
  18273. }
  18274. #if defined(ALTERNATIVE_QUEUE)
  18275. ctx->client_wait_events =
  18276. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  18277. sizeof(ctx->client_wait_events[0]),
  18278. ctx);
  18279. if (ctx->client_wait_events == NULL) {
  18280. const char *err_msg = "Not enough memory for worker event array";
  18281. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18282. mg_free(ctx->worker_threadids);
  18283. if (error != NULL) {
  18284. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18285. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18286. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18287. mg_snprintf(NULL,
  18288. NULL, /* No truncation check for error buffers */
  18289. error->text,
  18290. error->text_buffer_size,
  18291. "%s",
  18292. err_msg);
  18293. }
  18294. free_context(ctx);
  18295. pthread_setspecific(sTlsKey, NULL);
  18296. return NULL;
  18297. }
  18298. ctx->client_socks =
  18299. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18300. sizeof(ctx->client_socks[0]),
  18301. ctx);
  18302. if (ctx->client_socks == NULL) {
  18303. const char *err_msg = "Not enough memory for worker socket array";
  18304. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18305. mg_free(ctx->client_wait_events);
  18306. mg_free(ctx->worker_threadids);
  18307. if (error != NULL) {
  18308. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18309. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18310. * (unsigned)sizeof(ctx->client_socks[0]);
  18311. mg_snprintf(NULL,
  18312. NULL, /* No truncation check for error buffers */
  18313. error->text,
  18314. error->text_buffer_size,
  18315. "%s",
  18316. err_msg);
  18317. }
  18318. free_context(ctx);
  18319. pthread_setspecific(sTlsKey, NULL);
  18320. return NULL;
  18321. }
  18322. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  18323. ctx->client_wait_events[i] = event_create();
  18324. if (ctx->client_wait_events[i] == 0) {
  18325. const char *err_msg = "Error creating worker event %i";
  18326. mg_cry_ctx_internal(ctx, err_msg, i);
  18327. while (i > 0) {
  18328. i--;
  18329. event_destroy(ctx->client_wait_events[i]);
  18330. }
  18331. mg_free(ctx->client_socks);
  18332. mg_free(ctx->client_wait_events);
  18333. mg_free(ctx->worker_threadids);
  18334. if (error != NULL) {
  18335. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18336. error->code_sub = ERRNO;
  18337. mg_snprintf(NULL,
  18338. NULL, /* No truncation check for error buffers */
  18339. error->text,
  18340. error->text_buffer_size,
  18341. err_msg,
  18342. i);
  18343. }
  18344. free_context(ctx);
  18345. pthread_setspecific(sTlsKey, NULL);
  18346. return NULL;
  18347. }
  18348. }
  18349. #endif
  18350. #if defined(USE_TIMERS)
  18351. if (timers_init(ctx) != 0) {
  18352. const char *err_msg = "Error creating timers";
  18353. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18354. if (error != NULL) {
  18355. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18356. error->code_sub = ERRNO;
  18357. mg_snprintf(NULL,
  18358. NULL, /* No truncation check for error buffers */
  18359. error->text,
  18360. error->text_buffer_size,
  18361. "%s",
  18362. err_msg);
  18363. }
  18364. free_context(ctx);
  18365. pthread_setspecific(sTlsKey, NULL);
  18366. return NULL;
  18367. }
  18368. #endif
  18369. /* Context has been created - init user libraries */
  18370. if (ctx->callbacks.init_context) {
  18371. ctx->callbacks.init_context(ctx);
  18372. }
  18373. /* From now, the context is successfully created.
  18374. * When it is destroyed, the exit callback should be called. */
  18375. ctx->callbacks.exit_context = exit_callback;
  18376. ctx->context_type = CONTEXT_SERVER; /* server context */
  18377. /* Start worker threads */
  18378. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  18379. /* worker_thread sets up the other fields */
  18380. ctx->worker_connections[i].phys_ctx = ctx;
  18381. if (mg_start_thread_with_id(worker_thread,
  18382. &ctx->worker_connections[i],
  18383. &ctx->worker_threadids[i])
  18384. != 0) {
  18385. long error_no = (long)ERRNO;
  18386. /* thread was not created */
  18387. if (i > 0) {
  18388. /* If the second, third, ... thread cannot be created, set a
  18389. * warning, but keep running. */
  18390. mg_cry_ctx_internal(ctx,
  18391. "Cannot start worker thread %i: error %ld",
  18392. i + 1,
  18393. error_no);
  18394. /* If the server initialization should stop here, all
  18395. * threads that have already been created must be stopped
  18396. * first, before any free_context(ctx) call.
  18397. */
  18398. } else {
  18399. /* If the first worker thread cannot be created, stop
  18400. * initialization and free the entire server context. */
  18401. mg_cry_ctx_internal(ctx,
  18402. "Cannot create threads: error %ld",
  18403. error_no);
  18404. if (error != NULL) {
  18405. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18406. error->code_sub = (unsigned)error_no;
  18407. mg_snprintf(
  18408. NULL,
  18409. NULL, /* No truncation check for error buffers */
  18410. error->text,
  18411. error->text_buffer_size,
  18412. "Cannot create first worker thread: error %ld",
  18413. error_no);
  18414. }
  18415. free_context(ctx);
  18416. pthread_setspecific(sTlsKey, NULL);
  18417. return NULL;
  18418. }
  18419. break;
  18420. }
  18421. }
  18422. /* Start master (listening) thread */
  18423. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18424. pthread_setspecific(sTlsKey, NULL);
  18425. return ctx;
  18426. }
  18427. CIVETWEB_API struct mg_context *
  18428. mg_start(const struct mg_callbacks *callbacks,
  18429. void *user_data,
  18430. const char **options)
  18431. {
  18432. struct mg_init_data init = {0};
  18433. init.callbacks = callbacks;
  18434. init.user_data = user_data;
  18435. init.configuration_options = options;
  18436. return mg_start2(&init, NULL);
  18437. }
  18438. /* Add an additional domain to an already running web server. */
  18439. CIVETWEB_API int
  18440. mg_start_domain2(struct mg_context *ctx,
  18441. const char **options,
  18442. struct mg_error_data *error)
  18443. {
  18444. const char *name;
  18445. const char *value;
  18446. const char *default_value;
  18447. struct mg_domain_context *new_dom;
  18448. struct mg_domain_context *dom;
  18449. int idx, i;
  18450. if (error != NULL) {
  18451. error->code = MG_ERROR_DATA_CODE_OK;
  18452. error->code_sub = 0;
  18453. if (error->text_buffer_size > 0) {
  18454. *error->text = 0;
  18455. }
  18456. }
  18457. if ((ctx == NULL) || (options == NULL)) {
  18458. if (error != NULL) {
  18459. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18460. mg_snprintf(NULL,
  18461. NULL, /* No truncation check for error buffers */
  18462. error->text,
  18463. error->text_buffer_size,
  18464. "%s",
  18465. "Invalid parameters");
  18466. }
  18467. return -1;
  18468. }
  18469. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18470. if (error != NULL) {
  18471. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18472. mg_snprintf(NULL,
  18473. NULL, /* No truncation check for error buffers */
  18474. error->text,
  18475. error->text_buffer_size,
  18476. "%s",
  18477. "Server already stopped");
  18478. }
  18479. return -7;
  18480. }
  18481. new_dom = (struct mg_domain_context *)
  18482. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18483. if (!new_dom) {
  18484. /* Out of memory */
  18485. if (error != NULL) {
  18486. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18487. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18488. mg_snprintf(NULL,
  18489. NULL, /* No truncation check for error buffers */
  18490. error->text,
  18491. error->text_buffer_size,
  18492. "%s",
  18493. "Out or memory");
  18494. }
  18495. return -6;
  18496. }
  18497. /* Store options - TODO: unite duplicate code */
  18498. while (options && (name = *options++) != NULL) {
  18499. idx = get_option_index(name);
  18500. if (idx == -1) {
  18501. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18502. if (error != NULL) {
  18503. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18504. error->code_sub = (unsigned)-1;
  18505. mg_snprintf(NULL,
  18506. NULL, /* No truncation check for error buffers */
  18507. error->text,
  18508. error->text_buffer_size,
  18509. "Invalid option: %s",
  18510. name);
  18511. }
  18512. mg_free(new_dom);
  18513. return -2;
  18514. } else if ((value = *options++) == NULL) {
  18515. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18516. if (error != NULL) {
  18517. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18518. error->code_sub = idx;
  18519. mg_snprintf(NULL,
  18520. NULL, /* No truncation check for error buffers */
  18521. error->text,
  18522. error->text_buffer_size,
  18523. "Invalid option value: %s",
  18524. name);
  18525. }
  18526. mg_free(new_dom);
  18527. return -2;
  18528. }
  18529. if (new_dom->config[idx] != NULL) {
  18530. /* Duplicate option: Later values overwrite earlier ones. */
  18531. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18532. mg_free(new_dom->config[idx]);
  18533. }
  18534. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18535. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18536. }
  18537. /* Authentication domain is mandatory */
  18538. /* TODO: Maybe use a new option hostname? */
  18539. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18540. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18541. if (error != NULL) {
  18542. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18543. error->code_sub = AUTHENTICATION_DOMAIN;
  18544. mg_snprintf(NULL,
  18545. NULL, /* No truncation check for error buffers */
  18546. error->text,
  18547. error->text_buffer_size,
  18548. "Mandatory option %s missing",
  18549. config_options[AUTHENTICATION_DOMAIN].name);
  18550. }
  18551. mg_free(new_dom);
  18552. return -4;
  18553. }
  18554. /* Set default value if needed. Take the config value from
  18555. * ctx as a default value. */
  18556. for (i = 0; config_options[i].name != NULL; i++) {
  18557. default_value = ctx->dd.config[i];
  18558. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18559. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18560. }
  18561. }
  18562. new_dom->handlers = NULL;
  18563. new_dom->next = NULL;
  18564. new_dom->nonce_count = 0;
  18565. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18566. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18567. new_dom->shared_lua_websockets = NULL;
  18568. #endif
  18569. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18570. if (!init_ssl_ctx(ctx, new_dom)) {
  18571. /* Init SSL failed */
  18572. if (error != NULL) {
  18573. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18574. mg_snprintf(NULL,
  18575. NULL, /* No truncation check for error buffers */
  18576. error->text,
  18577. error->text_buffer_size,
  18578. "%s",
  18579. "Initializing SSL context failed");
  18580. }
  18581. mg_free(new_dom);
  18582. return -3;
  18583. }
  18584. #endif
  18585. /* Add element to linked list. */
  18586. mg_lock_context(ctx);
  18587. idx = 0;
  18588. dom = &(ctx->dd);
  18589. for (;;) {
  18590. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18591. dom->config[AUTHENTICATION_DOMAIN])) {
  18592. /* Domain collision */
  18593. mg_cry_ctx_internal(ctx,
  18594. "domain %s already in use",
  18595. new_dom->config[AUTHENTICATION_DOMAIN]);
  18596. if (error != NULL) {
  18597. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18598. mg_snprintf(NULL,
  18599. NULL, /* No truncation check for error buffers */
  18600. error->text,
  18601. error->text_buffer_size,
  18602. "Domain %s specified by %s is already in use",
  18603. new_dom->config[AUTHENTICATION_DOMAIN],
  18604. config_options[AUTHENTICATION_DOMAIN].name);
  18605. }
  18606. mg_free(new_dom);
  18607. mg_unlock_context(ctx);
  18608. return -5;
  18609. }
  18610. /* Count number of domains */
  18611. idx++;
  18612. if (dom->next == NULL) {
  18613. dom->next = new_dom;
  18614. break;
  18615. }
  18616. dom = dom->next;
  18617. }
  18618. mg_unlock_context(ctx);
  18619. /* Return domain number */
  18620. return idx;
  18621. }
  18622. CIVETWEB_API int
  18623. mg_start_domain(struct mg_context *ctx, const char **options)
  18624. {
  18625. return mg_start_domain2(ctx, options, NULL);
  18626. }
  18627. /* Feature check API function */
  18628. CIVETWEB_API unsigned
  18629. mg_check_feature(unsigned feature)
  18630. {
  18631. static const unsigned feature_set = 0
  18632. /* Set bits for available features according to API documentation.
  18633. * This bit mask is created at compile time, according to the active
  18634. * preprocessor defines. It is a single const value at runtime. */
  18635. #if !defined(NO_FILES)
  18636. | MG_FEATURES_FILES
  18637. #endif
  18638. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18639. | MG_FEATURES_SSL
  18640. #endif
  18641. #if !defined(NO_CGI)
  18642. | MG_FEATURES_CGI
  18643. #endif
  18644. #if defined(USE_IPV6)
  18645. | MG_FEATURES_IPV6
  18646. #endif
  18647. #if defined(USE_WEBSOCKET)
  18648. | MG_FEATURES_WEBSOCKET
  18649. #endif
  18650. #if defined(USE_LUA)
  18651. | MG_FEATURES_LUA
  18652. #endif
  18653. #if defined(USE_DUKTAPE)
  18654. | MG_FEATURES_SSJS
  18655. #endif
  18656. #if !defined(NO_CACHING)
  18657. | MG_FEATURES_CACHE
  18658. #endif
  18659. #if defined(USE_SERVER_STATS)
  18660. | MG_FEATURES_STATS
  18661. #endif
  18662. #if defined(USE_ZLIB)
  18663. | MG_FEATURES_COMPRESSION
  18664. #endif
  18665. #if defined(USE_HTTP2)
  18666. | MG_FEATURES_HTTP2
  18667. #endif
  18668. #if defined(USE_X_DOM_SOCKET)
  18669. | MG_FEATURES_X_DOMAIN_SOCKET
  18670. #endif
  18671. /* Set some extra bits not defined in the API documentation.
  18672. * These bits may change without further notice. */
  18673. #if defined(MG_LEGACY_INTERFACE)
  18674. | 0x80000000u
  18675. #endif
  18676. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18677. | 0x40000000u
  18678. #endif
  18679. #if !defined(NO_RESPONSE_BUFFERING)
  18680. | 0x20000000u
  18681. #endif
  18682. #if defined(MEMORY_DEBUGGING)
  18683. | 0x10000000u
  18684. #endif
  18685. ;
  18686. return (feature & feature_set);
  18687. }
  18688. static size_t
  18689. mg_str_append(char **dst, char *end, const char *src)
  18690. {
  18691. size_t len = strlen(src);
  18692. if (*dst != end) {
  18693. /* Append src if enough space, or close dst. */
  18694. if ((size_t)(end - *dst) > len) {
  18695. strcpy(*dst, src);
  18696. *dst += len;
  18697. } else {
  18698. *dst = end;
  18699. }
  18700. }
  18701. return len;
  18702. }
  18703. /* Get system information. It can be printed or stored by the caller.
  18704. * Return the size of available information. */
  18705. CIVETWEB_API int
  18706. mg_get_system_info(char *buffer, int buflen)
  18707. {
  18708. char *end, *append_eoobj = NULL, block[256];
  18709. size_t system_info_length = 0;
  18710. #if defined(_WIN32)
  18711. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18712. #else
  18713. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18714. #endif
  18715. if ((buffer == NULL) || (buflen < 1)) {
  18716. buflen = 0;
  18717. end = buffer;
  18718. } else {
  18719. *buffer = 0;
  18720. end = buffer + buflen;
  18721. }
  18722. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18723. /* has enough space to append eoobj */
  18724. append_eoobj = buffer;
  18725. if (end) {
  18726. end -= sizeof(eoobj) - 1;
  18727. }
  18728. }
  18729. system_info_length += mg_str_append(&buffer, end, "{");
  18730. /* Server version */
  18731. {
  18732. const char *version = mg_version();
  18733. mg_snprintf(NULL,
  18734. NULL,
  18735. block,
  18736. sizeof(block),
  18737. "%s\"version\" : \"%s\"",
  18738. eol,
  18739. version);
  18740. system_info_length += mg_str_append(&buffer, end, block);
  18741. }
  18742. /* System info */
  18743. {
  18744. #if defined(_WIN32)
  18745. DWORD dwVersion = 0;
  18746. DWORD dwMajorVersion = 0;
  18747. DWORD dwMinorVersion = 0;
  18748. SYSTEM_INFO si;
  18749. GetSystemInfo(&si);
  18750. #if defined(_MSC_VER)
  18751. #pragma warning(push)
  18752. /* GetVersion was declared deprecated */
  18753. #pragma warning(disable : 4996)
  18754. #endif
  18755. dwVersion = GetVersion();
  18756. #if defined(_MSC_VER)
  18757. #pragma warning(pop)
  18758. #endif
  18759. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18760. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18761. mg_snprintf(NULL,
  18762. NULL,
  18763. block,
  18764. sizeof(block),
  18765. ",%s\"os\" : \"Windows %u.%u\"",
  18766. eol,
  18767. (unsigned)dwMajorVersion,
  18768. (unsigned)dwMinorVersion);
  18769. system_info_length += mg_str_append(&buffer, end, block);
  18770. mg_snprintf(NULL,
  18771. NULL,
  18772. block,
  18773. sizeof(block),
  18774. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18775. eol,
  18776. (unsigned)si.wProcessorArchitecture,
  18777. (unsigned)si.dwNumberOfProcessors,
  18778. (unsigned)si.dwActiveProcessorMask);
  18779. system_info_length += mg_str_append(&buffer, end, block);
  18780. #elif defined(__ZEPHYR__)
  18781. mg_snprintf(NULL,
  18782. NULL,
  18783. block,
  18784. sizeof(block),
  18785. ",%s\"os\" : \"%s %s\"",
  18786. eol,
  18787. "Zephyr OS",
  18788. ZEPHYR_VERSION);
  18789. system_info_length += mg_str_append(&buffer, end, block);
  18790. #elif defined(ESP_PLATFORM)
  18791. mg_snprintf(NULL,
  18792. NULL,
  18793. block,
  18794. sizeof(block),
  18795. ",%s\"os\" : \"%s %s\"",
  18796. eol,
  18797. "Espressif",
  18798. "Bell");
  18799. system_info_length += mg_str_append(&buffer, end, block);
  18800. #else
  18801. struct utsname name;
  18802. memset(&name, 0, sizeof(name));
  18803. uname(&name);
  18804. mg_snprintf(NULL,
  18805. NULL,
  18806. block,
  18807. sizeof(block),
  18808. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18809. eol,
  18810. name.sysname,
  18811. name.version,
  18812. name.release,
  18813. name.machine);
  18814. system_info_length += mg_str_append(&buffer, end, block);
  18815. #endif
  18816. }
  18817. /* Features */
  18818. {
  18819. mg_snprintf(NULL,
  18820. NULL,
  18821. block,
  18822. sizeof(block),
  18823. ",%s\"features\" : %lu"
  18824. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18825. eol,
  18826. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18827. eol,
  18828. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18829. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18830. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18831. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18832. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18833. : "",
  18834. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18835. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18836. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18837. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18838. system_info_length += mg_str_append(&buffer, end, block);
  18839. #if defined(USE_LUA)
  18840. mg_snprintf(NULL,
  18841. NULL,
  18842. block,
  18843. sizeof(block),
  18844. ",%s\"lua_version\" : \"%u (%s)\"",
  18845. eol,
  18846. (unsigned)LUA_VERSION_NUM,
  18847. LUA_RELEASE);
  18848. system_info_length += mg_str_append(&buffer, end, block);
  18849. #endif
  18850. #if defined(USE_DUKTAPE)
  18851. mg_snprintf(NULL,
  18852. NULL,
  18853. block,
  18854. sizeof(block),
  18855. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18856. eol,
  18857. (unsigned)DUK_VERSION / 10000,
  18858. ((unsigned)DUK_VERSION / 100) % 100,
  18859. (unsigned)DUK_VERSION % 100);
  18860. system_info_length += mg_str_append(&buffer, end, block);
  18861. #endif
  18862. }
  18863. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18864. {
  18865. #if defined(BUILD_DATE)
  18866. const char *bd = BUILD_DATE;
  18867. #else
  18868. #if defined(GCC_DIAGNOSTIC)
  18869. #if GCC_VERSION >= 40900
  18870. #pragma GCC diagnostic push
  18871. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18872. * does not work in some versions. If "BUILD_DATE" is defined to some
  18873. * string, it is used instead of __DATE__. */
  18874. #pragma GCC diagnostic ignored "-Wdate-time"
  18875. #endif
  18876. #endif
  18877. const char *bd = __DATE__;
  18878. #if defined(GCC_DIAGNOSTIC)
  18879. #if GCC_VERSION >= 40900
  18880. #pragma GCC diagnostic pop
  18881. #endif
  18882. #endif
  18883. #endif
  18884. mg_snprintf(
  18885. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18886. system_info_length += mg_str_append(&buffer, end, block);
  18887. }
  18888. /* Compiler information */
  18889. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18890. {
  18891. #if defined(_MSC_VER)
  18892. mg_snprintf(NULL,
  18893. NULL,
  18894. block,
  18895. sizeof(block),
  18896. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18897. eol,
  18898. (unsigned)_MSC_VER,
  18899. (unsigned)_MSC_FULL_VER);
  18900. system_info_length += mg_str_append(&buffer, end, block);
  18901. #elif defined(__MINGW64__)
  18902. mg_snprintf(NULL,
  18903. NULL,
  18904. block,
  18905. sizeof(block),
  18906. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18907. eol,
  18908. (unsigned)__MINGW64_VERSION_MAJOR,
  18909. (unsigned)__MINGW64_VERSION_MINOR);
  18910. system_info_length += mg_str_append(&buffer, end, block);
  18911. mg_snprintf(NULL,
  18912. NULL,
  18913. block,
  18914. sizeof(block),
  18915. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18916. eol,
  18917. (unsigned)__MINGW32_MAJOR_VERSION,
  18918. (unsigned)__MINGW32_MINOR_VERSION);
  18919. system_info_length += mg_str_append(&buffer, end, block);
  18920. #elif defined(__MINGW32__)
  18921. mg_snprintf(NULL,
  18922. NULL,
  18923. block,
  18924. sizeof(block),
  18925. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18926. eol,
  18927. (unsigned)__MINGW32_MAJOR_VERSION,
  18928. (unsigned)__MINGW32_MINOR_VERSION);
  18929. system_info_length += mg_str_append(&buffer, end, block);
  18930. #elif defined(__clang__)
  18931. mg_snprintf(NULL,
  18932. NULL,
  18933. block,
  18934. sizeof(block),
  18935. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18936. eol,
  18937. __clang_major__,
  18938. __clang_minor__,
  18939. __clang_patchlevel__,
  18940. __clang_version__);
  18941. system_info_length += mg_str_append(&buffer, end, block);
  18942. #elif defined(__GNUC__)
  18943. mg_snprintf(NULL,
  18944. NULL,
  18945. block,
  18946. sizeof(block),
  18947. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18948. eol,
  18949. (unsigned)__GNUC__,
  18950. (unsigned)__GNUC_MINOR__,
  18951. (unsigned)__GNUC_PATCHLEVEL__);
  18952. system_info_length += mg_str_append(&buffer, end, block);
  18953. #elif defined(__INTEL_COMPILER)
  18954. mg_snprintf(NULL,
  18955. NULL,
  18956. block,
  18957. sizeof(block),
  18958. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18959. eol,
  18960. (unsigned)__INTEL_COMPILER);
  18961. system_info_length += mg_str_append(&buffer, end, block);
  18962. #elif defined(__BORLANDC__)
  18963. mg_snprintf(NULL,
  18964. NULL,
  18965. block,
  18966. sizeof(block),
  18967. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18968. eol,
  18969. (unsigned)__BORLANDC__);
  18970. system_info_length += mg_str_append(&buffer, end, block);
  18971. #elif defined(__SUNPRO_C)
  18972. mg_snprintf(NULL,
  18973. NULL,
  18974. block,
  18975. sizeof(block),
  18976. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18977. eol,
  18978. (unsigned)__SUNPRO_C);
  18979. system_info_length += mg_str_append(&buffer, end, block);
  18980. #else
  18981. mg_snprintf(NULL,
  18982. NULL,
  18983. block,
  18984. sizeof(block),
  18985. ",%s\"compiler\" : \"other\"",
  18986. eol);
  18987. system_info_length += mg_str_append(&buffer, end, block);
  18988. #endif
  18989. }
  18990. /* Determine 32/64 bit data mode.
  18991. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18992. {
  18993. mg_snprintf(NULL,
  18994. NULL,
  18995. block,
  18996. sizeof(block),
  18997. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18998. "char:%u/%u, "
  18999. "ptr:%u, size:%u, time:%u\"",
  19000. eol,
  19001. (unsigned)sizeof(short),
  19002. (unsigned)sizeof(int),
  19003. (unsigned)sizeof(long),
  19004. (unsigned)sizeof(long long),
  19005. (unsigned)sizeof(float),
  19006. (unsigned)sizeof(double),
  19007. (unsigned)sizeof(long double),
  19008. (unsigned)sizeof(char),
  19009. (unsigned)sizeof(wchar_t),
  19010. (unsigned)sizeof(void *),
  19011. (unsigned)sizeof(size_t),
  19012. (unsigned)sizeof(time_t));
  19013. system_info_length += mg_str_append(&buffer, end, block);
  19014. }
  19015. /* Terminate string */
  19016. if (append_eoobj) {
  19017. strcat(append_eoobj, eoobj);
  19018. }
  19019. system_info_length += sizeof(eoobj) - 1;
  19020. return (int)system_info_length;
  19021. }
  19022. /* Get context information. It can be printed or stored by the caller.
  19023. * Return the size of available information. */
  19024. CIVETWEB_API int
  19025. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19026. {
  19027. #if defined(USE_SERVER_STATS)
  19028. char *end, *append_eoobj = NULL, block[256];
  19029. size_t context_info_length = 0;
  19030. #if defined(_WIN32)
  19031. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19032. #else
  19033. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19034. #endif
  19035. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19036. if ((buffer == NULL) || (buflen < 1)) {
  19037. buflen = 0;
  19038. end = buffer;
  19039. } else {
  19040. *buffer = 0;
  19041. end = buffer + buflen;
  19042. }
  19043. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19044. /* has enough space to append eoobj */
  19045. append_eoobj = buffer;
  19046. end -= sizeof(eoobj) - 1;
  19047. }
  19048. context_info_length += mg_str_append(&buffer, end, "{");
  19049. if (ms) { /* <-- should be always true */
  19050. /* Memory information */
  19051. int blockCount = (int)ms->blockCount;
  19052. int64_t totalMemUsed = ms->totalMemUsed;
  19053. int64_t maxMemUsed = ms->maxMemUsed;
  19054. if (totalMemUsed > maxMemUsed) {
  19055. maxMemUsed = totalMemUsed;
  19056. }
  19057. mg_snprintf(NULL,
  19058. NULL,
  19059. block,
  19060. sizeof(block),
  19061. "%s\"memory\" : {%s"
  19062. "\"blocks\" : %i,%s"
  19063. "\"used\" : %" INT64_FMT ",%s"
  19064. "\"maxUsed\" : %" INT64_FMT "%s"
  19065. "}",
  19066. eol,
  19067. eol,
  19068. blockCount,
  19069. eol,
  19070. totalMemUsed,
  19071. eol,
  19072. maxMemUsed,
  19073. eol);
  19074. context_info_length += mg_str_append(&buffer, end, block);
  19075. }
  19076. if (ctx) {
  19077. /* Declare all variables at begin of the block, to comply
  19078. * with old C standards. */
  19079. char start_time_str[64] = {0};
  19080. char now_str[64] = {0};
  19081. time_t start_time = ctx->start_time;
  19082. time_t now = time(NULL);
  19083. int64_t total_data_read, total_data_written;
  19084. int active_connections = (int)ctx->active_connections;
  19085. int max_active_connections = (int)ctx->max_active_connections;
  19086. int total_connections = (int)ctx->total_connections;
  19087. if (active_connections > max_active_connections) {
  19088. max_active_connections = active_connections;
  19089. }
  19090. if (active_connections > total_connections) {
  19091. total_connections = active_connections;
  19092. }
  19093. /* Connections information */
  19094. mg_snprintf(NULL,
  19095. NULL,
  19096. block,
  19097. sizeof(block),
  19098. ",%s\"connections\" : {%s"
  19099. "\"active\" : %i,%s"
  19100. "\"maxActive\" : %i,%s"
  19101. "\"total\" : %i%s"
  19102. "}",
  19103. eol,
  19104. eol,
  19105. active_connections,
  19106. eol,
  19107. max_active_connections,
  19108. eol,
  19109. total_connections,
  19110. eol);
  19111. context_info_length += mg_str_append(&buffer, end, block);
  19112. /* Queue information */
  19113. #if !defined(ALTERNATIVE_QUEUE)
  19114. mg_snprintf(NULL,
  19115. NULL,
  19116. block,
  19117. sizeof(block),
  19118. ",%s\"queue\" : {%s"
  19119. "\"length\" : %i,%s"
  19120. "\"filled\" : %i,%s"
  19121. "\"maxFilled\" : %i,%s"
  19122. "\"full\" : %s%s"
  19123. "}",
  19124. eol,
  19125. eol,
  19126. ctx->sq_size,
  19127. eol,
  19128. ctx->sq_head - ctx->sq_tail,
  19129. eol,
  19130. ctx->sq_max_fill,
  19131. eol,
  19132. (ctx->sq_blocked ? "true" : "false"),
  19133. eol);
  19134. context_info_length += mg_str_append(&buffer, end, block);
  19135. #endif
  19136. /* Requests information */
  19137. mg_snprintf(NULL,
  19138. NULL,
  19139. block,
  19140. sizeof(block),
  19141. ",%s\"requests\" : {%s"
  19142. "\"total\" : %lu%s"
  19143. "}",
  19144. eol,
  19145. eol,
  19146. (unsigned long)ctx->total_requests,
  19147. eol);
  19148. context_info_length += mg_str_append(&buffer, end, block);
  19149. /* Data information */
  19150. total_data_read =
  19151. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19152. total_data_written =
  19153. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19154. mg_snprintf(NULL,
  19155. NULL,
  19156. block,
  19157. sizeof(block),
  19158. ",%s\"data\" : {%s"
  19159. "\"read\" : %" INT64_FMT ",%s"
  19160. "\"written\" : %" INT64_FMT "%s"
  19161. "}",
  19162. eol,
  19163. eol,
  19164. total_data_read,
  19165. eol,
  19166. total_data_written,
  19167. eol);
  19168. context_info_length += mg_str_append(&buffer, end, block);
  19169. /* Execution time information */
  19170. gmt_time_string(start_time_str,
  19171. sizeof(start_time_str) - 1,
  19172. &start_time);
  19173. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19174. mg_snprintf(NULL,
  19175. NULL,
  19176. block,
  19177. sizeof(block),
  19178. ",%s\"time\" : {%s"
  19179. "\"uptime\" : %.0f,%s"
  19180. "\"start\" : \"%s\",%s"
  19181. "\"now\" : \"%s\"%s"
  19182. "}",
  19183. eol,
  19184. eol,
  19185. difftime(now, start_time),
  19186. eol,
  19187. start_time_str,
  19188. eol,
  19189. now_str,
  19190. eol);
  19191. context_info_length += mg_str_append(&buffer, end, block);
  19192. }
  19193. /* Terminate string */
  19194. if (append_eoobj) {
  19195. strcat(append_eoobj, eoobj);
  19196. }
  19197. context_info_length += sizeof(eoobj) - 1;
  19198. return (int)context_info_length;
  19199. #else
  19200. (void)ctx;
  19201. if ((buffer != NULL) && (buflen > 0)) {
  19202. *buffer = 0;
  19203. }
  19204. return 0;
  19205. #endif
  19206. }
  19207. CIVETWEB_API void
  19208. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19209. {
  19210. /* https://github.com/civetweb/civetweb/issues/727 */
  19211. if (conn != NULL) {
  19212. conn->must_close = 1;
  19213. }
  19214. }
  19215. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19216. /* Get connection information. It can be printed or stored by the caller.
  19217. * Return the size of available information. */
  19218. CIVETWEB_API int
  19219. mg_get_connection_info(const struct mg_context *ctx,
  19220. int idx,
  19221. char *buffer,
  19222. int buflen)
  19223. {
  19224. const struct mg_connection *conn;
  19225. const struct mg_request_info *ri;
  19226. char *end, *append_eoobj = NULL, block[256];
  19227. size_t connection_info_length = 0;
  19228. int state = 0;
  19229. const char *state_str = "unknown";
  19230. #if defined(_WIN32)
  19231. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19232. #else
  19233. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19234. #endif
  19235. if ((buffer == NULL) || (buflen < 1)) {
  19236. buflen = 0;
  19237. end = buffer;
  19238. } else {
  19239. *buffer = 0;
  19240. end = buffer + buflen;
  19241. }
  19242. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19243. /* has enough space to append eoobj */
  19244. append_eoobj = buffer;
  19245. end -= sizeof(eoobj) - 1;
  19246. }
  19247. if ((ctx == NULL) || (idx < 0)) {
  19248. /* Parameter error */
  19249. return 0;
  19250. }
  19251. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  19252. /* Out of range */
  19253. return 0;
  19254. }
  19255. /* Take connection [idx]. This connection is not locked in
  19256. * any way, so some other thread might use it. */
  19257. conn = (ctx->worker_connections) + idx;
  19258. /* Initialize output string */
  19259. connection_info_length += mg_str_append(&buffer, end, "{");
  19260. /* Init variables */
  19261. ri = &(conn->request_info);
  19262. #if defined(USE_SERVER_STATS)
  19263. state = conn->conn_state;
  19264. /* State as string */
  19265. switch (state) {
  19266. case 0:
  19267. state_str = "undefined";
  19268. break;
  19269. case 1:
  19270. state_str = "not used";
  19271. break;
  19272. case 2:
  19273. state_str = "init";
  19274. break;
  19275. case 3:
  19276. state_str = "ready";
  19277. break;
  19278. case 4:
  19279. state_str = "processing";
  19280. break;
  19281. case 5:
  19282. state_str = "processed";
  19283. break;
  19284. case 6:
  19285. state_str = "to close";
  19286. break;
  19287. case 7:
  19288. state_str = "closing";
  19289. break;
  19290. case 8:
  19291. state_str = "closed";
  19292. break;
  19293. case 9:
  19294. state_str = "done";
  19295. break;
  19296. }
  19297. #endif
  19298. /* Connection info */
  19299. if ((state >= 3) && (state < 9)) {
  19300. mg_snprintf(NULL,
  19301. NULL,
  19302. block,
  19303. sizeof(block),
  19304. "%s\"connection\" : {%s"
  19305. "\"remote\" : {%s"
  19306. "\"protocol\" : \"%s\",%s"
  19307. "\"addr\" : \"%s\",%s"
  19308. "\"port\" : %u%s"
  19309. "},%s"
  19310. "\"handled_requests\" : %u%s"
  19311. "}",
  19312. eol,
  19313. eol,
  19314. eol,
  19315. get_proto_name(conn),
  19316. eol,
  19317. ri->remote_addr,
  19318. eol,
  19319. ri->remote_port,
  19320. eol,
  19321. eol,
  19322. conn->handled_requests,
  19323. eol);
  19324. connection_info_length += mg_str_append(&buffer, end, block);
  19325. }
  19326. /* Request info */
  19327. if ((state >= 4) && (state < 6)) {
  19328. mg_snprintf(NULL,
  19329. NULL,
  19330. block,
  19331. sizeof(block),
  19332. "%s%s\"request_info\" : {%s"
  19333. "\"method\" : \"%s\",%s"
  19334. "\"uri\" : \"%s\",%s"
  19335. "\"query\" : %s%s%s%s"
  19336. "}",
  19337. (connection_info_length > 1 ? "," : ""),
  19338. eol,
  19339. eol,
  19340. ri->request_method,
  19341. eol,
  19342. ri->request_uri,
  19343. eol,
  19344. ri->query_string ? "\"" : "",
  19345. ri->query_string ? ri->query_string : "null",
  19346. ri->query_string ? "\"" : "",
  19347. eol);
  19348. connection_info_length += mg_str_append(&buffer, end, block);
  19349. }
  19350. /* Execution time information */
  19351. if ((state >= 2) && (state < 9)) {
  19352. char start_time_str[64] = {0};
  19353. char close_time_str[64] = {0};
  19354. time_t start_time = conn->conn_birth_time;
  19355. time_t close_time = 0;
  19356. double time_diff;
  19357. gmt_time_string(start_time_str,
  19358. sizeof(start_time_str) - 1,
  19359. &start_time);
  19360. #if defined(USE_SERVER_STATS)
  19361. close_time = conn->conn_close_time;
  19362. #endif
  19363. if (close_time != 0) {
  19364. time_diff = difftime(close_time, start_time);
  19365. gmt_time_string(close_time_str,
  19366. sizeof(close_time_str) - 1,
  19367. &close_time);
  19368. } else {
  19369. time_t now = time(NULL);
  19370. time_diff = difftime(now, start_time);
  19371. close_time_str[0] = 0; /* or use "now" ? */
  19372. }
  19373. mg_snprintf(NULL,
  19374. NULL,
  19375. block,
  19376. sizeof(block),
  19377. "%s%s\"time\" : {%s"
  19378. "\"uptime\" : %.0f,%s"
  19379. "\"start\" : \"%s\",%s"
  19380. "\"closed\" : \"%s\"%s"
  19381. "}",
  19382. (connection_info_length > 1 ? "," : ""),
  19383. eol,
  19384. eol,
  19385. time_diff,
  19386. eol,
  19387. start_time_str,
  19388. eol,
  19389. close_time_str,
  19390. eol);
  19391. connection_info_length += mg_str_append(&buffer, end, block);
  19392. }
  19393. /* Remote user name */
  19394. if ((ri->remote_user) && (state < 9)) {
  19395. mg_snprintf(NULL,
  19396. NULL,
  19397. block,
  19398. sizeof(block),
  19399. "%s%s\"user\" : {%s"
  19400. "\"name\" : \"%s\",%s"
  19401. "}",
  19402. (connection_info_length > 1 ? "," : ""),
  19403. eol,
  19404. eol,
  19405. ri->remote_user,
  19406. eol);
  19407. connection_info_length += mg_str_append(&buffer, end, block);
  19408. }
  19409. /* Data block */
  19410. if (state >= 3) {
  19411. mg_snprintf(NULL,
  19412. NULL,
  19413. block,
  19414. sizeof(block),
  19415. "%s%s\"data\" : {%s"
  19416. "\"read\" : %" INT64_FMT ",%s"
  19417. "\"written\" : %" INT64_FMT "%s"
  19418. "}",
  19419. (connection_info_length > 1 ? "," : ""),
  19420. eol,
  19421. eol,
  19422. conn->consumed_content,
  19423. eol,
  19424. conn->num_bytes_sent,
  19425. eol);
  19426. connection_info_length += mg_str_append(&buffer, end, block);
  19427. }
  19428. /* State */
  19429. mg_snprintf(NULL,
  19430. NULL,
  19431. block,
  19432. sizeof(block),
  19433. "%s%s\"state\" : \"%s\"",
  19434. (connection_info_length > 1 ? "," : ""),
  19435. eol,
  19436. state_str);
  19437. connection_info_length += mg_str_append(&buffer, end, block);
  19438. /* Terminate string */
  19439. if (append_eoobj) {
  19440. strcat(append_eoobj, eoobj);
  19441. }
  19442. connection_info_length += sizeof(eoobj) - 1;
  19443. return (int)connection_info_length;
  19444. }
  19445. #if 0
  19446. /* Get handler information. It can be printed or stored by the caller.
  19447. * Return the size of available information. */
  19448. CIVETWEB_API int
  19449. mg_get_handler_info(struct mg_context *ctx,
  19450. char *buffer,
  19451. int buflen)
  19452. {
  19453. int handler_info_len = 0;
  19454. struct mg_handler_info *tmp_rh;
  19455. mg_lock_context(ctx);
  19456. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19457. if (buflen > handler_info_len+ tmp_rh->uri_len) {
  19458. memcpy(buffer+handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19459. }
  19460. handler_info_len += tmp_rh->uri_len;
  19461. switch (tmp_rh->handler_type) {
  19462. case REQUEST_HANDLER:
  19463. (void)tmp_rh->handler;
  19464. break;
  19465. case WEBSOCKET_HANDLER:
  19466. (void)tmp_rh->connect_handler;
  19467. (void) tmp_rh->ready_handler;
  19468. (void) tmp_rh->data_handler;
  19469. (void) tmp_rh->close_handler;
  19470. break;
  19471. case AUTH_HANDLER:
  19472. (void) tmp_rh->auth_handler;
  19473. break;
  19474. }
  19475. (void)cbdata;
  19476. }
  19477. mg_unlock_context(ctx);
  19478. return handler_info_len;
  19479. }
  19480. #endif
  19481. #endif
  19482. /* Initialize this library. This function does not need to be thread safe.
  19483. */
  19484. CIVETWEB_API unsigned
  19485. mg_init_library(unsigned features)
  19486. {
  19487. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19488. unsigned features_inited = features_to_init;
  19489. if (mg_init_library_called <= 0) {
  19490. /* Not initialized yet */
  19491. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19492. return 0;
  19493. }
  19494. }
  19495. mg_global_lock();
  19496. if (mg_init_library_called <= 0) {
  19497. int i, len;
  19498. #if defined(_WIN32)
  19499. int file_mutex_init = 1;
  19500. int wsa = 1;
  19501. #else
  19502. int mutexattr_init = 1;
  19503. #endif
  19504. int failed = 1;
  19505. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19506. if (key_create == 0) {
  19507. #if defined(_WIN32)
  19508. file_mutex_init =
  19509. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19510. if (file_mutex_init == 0) {
  19511. /* Start WinSock */
  19512. WSADATA data;
  19513. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19514. }
  19515. #else
  19516. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19517. if (mutexattr_init == 0) {
  19518. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19519. PTHREAD_MUTEX_RECURSIVE);
  19520. }
  19521. #endif
  19522. }
  19523. if (failed) {
  19524. #if defined(_WIN32)
  19525. if (wsa == 0) {
  19526. (void)WSACleanup();
  19527. }
  19528. if (file_mutex_init == 0) {
  19529. (void)pthread_mutex_destroy(&global_log_file_lock);
  19530. }
  19531. #else
  19532. if (mutexattr_init == 0) {
  19533. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19534. }
  19535. #endif
  19536. if (key_create == 0) {
  19537. (void)pthread_key_delete(sTlsKey);
  19538. }
  19539. mg_global_unlock();
  19540. (void)pthread_mutex_destroy(&global_lock_mutex);
  19541. return 0;
  19542. }
  19543. len = 1;
  19544. for (i = 0; http_methods[i].name != NULL; i++) {
  19545. size_t sl = strlen(http_methods[i].name);
  19546. len += (int)sl;
  19547. if (i > 0) {
  19548. len += 2;
  19549. }
  19550. }
  19551. all_methods = mg_malloc(len);
  19552. if (!all_methods) {
  19553. /* Must never happen */
  19554. mg_global_unlock();
  19555. (void)pthread_mutex_destroy(&global_lock_mutex);
  19556. return 0;
  19557. }
  19558. all_methods[0] = 0;
  19559. for (i = 0; http_methods[i].name != NULL; i++) {
  19560. if (i > 0) {
  19561. strcat(all_methods, ", ");
  19562. strcat(all_methods, http_methods[i].name);
  19563. } else {
  19564. strcpy(all_methods, http_methods[i].name);
  19565. }
  19566. }
  19567. }
  19568. #if defined(USE_LUA)
  19569. lua_init_optional_libraries();
  19570. #endif
  19571. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19572. || defined(OPENSSL_API_3_0)) \
  19573. && !defined(NO_SSL)
  19574. if (features_to_init & MG_FEATURES_SSL) {
  19575. if (!mg_openssl_initialized) {
  19576. char ebuf[128];
  19577. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19578. mg_openssl_initialized = 1;
  19579. } else {
  19580. (void)ebuf;
  19581. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19582. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19583. }
  19584. } else {
  19585. /* ssl already initialized */
  19586. }
  19587. }
  19588. #endif
  19589. if (mg_init_library_called <= 0) {
  19590. mg_init_library_called = 1;
  19591. } else {
  19592. mg_init_library_called++;
  19593. }
  19594. mg_global_unlock();
  19595. return features_inited;
  19596. }
  19597. /* Un-initialize this library. */
  19598. CIVETWEB_API unsigned
  19599. mg_exit_library(void)
  19600. {
  19601. if (mg_init_library_called <= 0) {
  19602. return 0;
  19603. }
  19604. mg_global_lock();
  19605. mg_init_library_called--;
  19606. if (mg_init_library_called == 0) {
  19607. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19608. if (mg_openssl_initialized) {
  19609. uninitialize_openssl();
  19610. mg_openssl_initialized = 0;
  19611. }
  19612. #endif
  19613. #if defined(_WIN32)
  19614. (void)WSACleanup();
  19615. (void)pthread_mutex_destroy(&global_log_file_lock);
  19616. #else
  19617. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19618. #endif
  19619. (void)pthread_key_delete(sTlsKey);
  19620. #if defined(USE_LUA)
  19621. lua_exit_optional_libraries();
  19622. #endif
  19623. mg_free(all_methods);
  19624. all_methods = NULL;
  19625. mg_global_unlock();
  19626. (void)pthread_mutex_destroy(&global_lock_mutex);
  19627. return 1;
  19628. }
  19629. mg_global_unlock();
  19630. return 1;
  19631. }
  19632. /* End of civetweb.c */