civetweb.c 619 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175
  1. /* Copyright (c) 2013-2024 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #ifndef GCC_VERSION
  24. #define GCC_VERSION \
  25. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  26. #endif
  27. #if GCC_VERSION >= 40500
  28. /* gcc diagnostic pragmas available */
  29. #define GCC_DIAGNOSTIC
  30. #endif
  31. #endif
  32. #if defined(GCC_DIAGNOSTIC)
  33. /* Disable unused macros warnings - not all defines are required
  34. * for all systems and all compilers. */
  35. #pragma GCC diagnostic ignored "-Wunused-macros"
  36. /* A padding warning is just plain useless */
  37. #pragma GCC diagnostic ignored "-Wpadded"
  38. #endif
  39. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  40. /* We must set some flags for the headers we include. These flags
  41. * are reserved ids according to C99, so we need to disable a
  42. * warning for that. */
  43. #pragma GCC diagnostic push
  44. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  45. #endif
  46. #if defined(_WIN32)
  47. #if !defined(_CRT_SECURE_NO_WARNINGS)
  48. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  49. #endif
  50. #if !defined(_WIN32_WINNT) /* Minimum API version */
  51. #define _WIN32_WINNT 0x0601
  52. #endif
  53. #else
  54. #if !defined(_GNU_SOURCE)
  55. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  56. #endif
  57. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  58. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  59. #endif
  60. #if defined(__LSB_VERSION__) || defined(__sun)
  61. #define NEED_TIMEGM
  62. #define NO_THREAD_NAME
  63. #endif
  64. #if !defined(_LARGEFILE_SOURCE)
  65. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  66. #endif
  67. #if !defined(_FILE_OFFSET_BITS)
  68. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  69. #endif
  70. #if !defined(__STDC_FORMAT_MACROS)
  71. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  72. #endif
  73. #if !defined(__STDC_LIMIT_MACROS)
  74. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  75. #endif
  76. #if !defined(_DARWIN_UNLIMITED_SELECT)
  77. #define _DARWIN_UNLIMITED_SELECT
  78. #endif
  79. #if defined(__sun)
  80. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  81. #define __inline inline /* not recognized on older compiler versions */
  82. #endif
  83. #endif
  84. #if defined(__clang__)
  85. /* Enable reserved-id-macro warning again. */
  86. #pragma GCC diagnostic pop
  87. #endif
  88. #if defined(USE_LUA)
  89. #define USE_TIMERS
  90. #endif
  91. #if defined(_MSC_VER)
  92. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  93. #pragma warning(disable : 4306)
  94. /* conditional expression is constant: introduced by FD_SET(..) */
  95. #pragma warning(disable : 4127)
  96. /* non-constant aggregate initializer: issued due to missing C99 support */
  97. #pragma warning(disable : 4204)
  98. /* padding added after data member */
  99. #pragma warning(disable : 4820)
  100. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  101. #pragma warning(disable : 4668)
  102. /* no function prototype given: converting '()' to '(void)' */
  103. #pragma warning(disable : 4255)
  104. /* function has been selected for automatic inline expansion */
  105. #pragma warning(disable : 4711)
  106. #endif
  107. /* This code uses static_assert to check some conditions.
  108. * Unfortunately some compilers still do not support it, so we have a
  109. * replacement function here. */
  110. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  111. #define mg_static_assert _Static_assert
  112. #elif defined(__cplusplus) && __cplusplus >= 201103L
  113. #define mg_static_assert static_assert
  114. #else
  115. char static_assert_replacement[1];
  116. #define mg_static_assert(cond, txt) \
  117. extern char static_assert_replacement[(cond) ? 1 : -1]
  118. #endif
  119. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  120. "int data type size check");
  121. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  122. "pointer data type size check");
  123. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  124. /* Select queue implementation. Diagnosis features originally only implemented
  125. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  126. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  127. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  128. * implementation, since the queue length is independent from the number of
  129. * worker threads there, while the new queue is one element per worker thread.
  130. *
  131. */
  132. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  133. /* The queues are exclusive or - only one can be used. */
  134. #error \
  135. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  136. #endif
  137. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  138. /* Use a default implementation */
  139. #define NO_ALTERNATIVE_QUEUE
  140. #endif
  141. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  142. /* File system access:
  143. * NO_FILES = do not serve any files from the file system automatically.
  144. * However, with NO_FILES CivetWeb may still write log files, read access
  145. * control files, default error page files or use API functions like
  146. * mg_send_file in callbacks to send files from the server local
  147. * file system.
  148. * NO_FILES only disables the automatic mapping between URLs and local
  149. * file names.
  150. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  151. * devices without file system. Logging to files in not available
  152. * (use callbacks instead) and API functions like mg_send_file are not
  153. * available.
  154. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  155. */
  156. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  157. #endif
  158. /* DTL -- including winsock2.h works better if lean and mean */
  159. #if !defined(WIN32_LEAN_AND_MEAN)
  160. #define WIN32_LEAN_AND_MEAN
  161. #endif
  162. #if defined(__SYMBIAN32__)
  163. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  164. * Symbian is no longer maintained since 2014-01-01.
  165. * Support for Symbian has been removed from CivetWeb
  166. */
  167. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  168. #endif /* __SYMBIAN32__ */
  169. #if defined(__rtems__)
  170. #include <rtems/version.h>
  171. #endif
  172. #if defined(__ZEPHYR__)
  173. #include <ctype.h>
  174. #include <fcntl.h>
  175. #include <netdb.h>
  176. #include <poll.h>
  177. #include <pthread.h>
  178. #include <stdio.h>
  179. #include <stdlib.h>
  180. #include <string.h>
  181. #include <sys/socket.h>
  182. #include <time.h>
  183. #include <zephyr/kernel.h>
  184. /* Max worker threads is the max of pthreads minus the main application thread
  185. * and minus the main civetweb thread, thus -2
  186. */
  187. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  188. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  189. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  190. #else
  191. #define ZEPHYR_STACK_SIZE (1024 * 16)
  192. #endif
  193. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  194. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  195. MAX_WORKER_THREADS,
  196. ZEPHYR_STACK_SIZE);
  197. static int zephyr_worker_stack_index;
  198. #endif
  199. #if !defined(CIVETWEB_HEADER_INCLUDED)
  200. /* Include the header file here, so the CivetWeb interface is defined for the
  201. * entire implementation, including the following forward definitions. */
  202. #include "civetweb.h"
  203. #endif
  204. #if !defined(DEBUG_TRACE)
  205. #if defined(DEBUG)
  206. static void DEBUG_TRACE_FUNC(const char *func,
  207. unsigned line,
  208. PRINTF_FORMAT_STRING(const char *fmt),
  209. ...) PRINTF_ARGS(3, 4);
  210. #define DEBUG_TRACE(fmt, ...) \
  211. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  212. #define NEED_DEBUG_TRACE_FUNC
  213. #if !defined(DEBUG_TRACE_STREAM)
  214. #define DEBUG_TRACE_STREAM stdout
  215. #endif
  216. #else
  217. #define DEBUG_TRACE(fmt, ...) \
  218. do { \
  219. } while (0)
  220. #endif /* DEBUG */
  221. #endif /* DEBUG_TRACE */
  222. #if !defined(DEBUG_ASSERT)
  223. #if defined(DEBUG)
  224. #include <stdlib.h>
  225. #define DEBUG_ASSERT(cond) \
  226. do { \
  227. if (!(cond)) { \
  228. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  229. exit(2); /* Exit with error */ \
  230. } \
  231. } while (0)
  232. #else
  233. #define DEBUG_ASSERT(cond)
  234. #endif /* DEBUG */
  235. #endif
  236. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  237. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  238. __attribute__((no_instrument_function));
  239. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  240. __attribute__((no_instrument_function));
  241. void
  242. __cyg_profile_func_enter(void *this_fn, void *call_site)
  243. {
  244. if ((void *)this_fn != (void *)printf) {
  245. printf("E %p %p\n", this_fn, call_site);
  246. }
  247. }
  248. void
  249. __cyg_profile_func_exit(void *this_fn, void *call_site)
  250. {
  251. if ((void *)this_fn != (void *)printf) {
  252. printf("X %p %p\n", this_fn, call_site);
  253. }
  254. }
  255. #endif
  256. #if !defined(IGNORE_UNUSED_RESULT)
  257. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  258. #endif
  259. #if defined(__GNUC__) || defined(__MINGW32__)
  260. /* GCC unused function attribute seems fundamentally broken.
  261. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  262. * OR UNUSED" for individual functions failed.
  263. * Either the compiler creates an "unused-function" warning if a
  264. * function is not marked with __attribute__((unused)).
  265. * On the other hand, if the function is marked with this attribute,
  266. * but is used, the compiler raises a completely idiotic
  267. * "used-but-marked-unused" warning - and
  268. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  269. * raises error: unknown option after "#pragma GCC diagnostic".
  270. * Disable this warning completely, until the GCC guys sober up
  271. * again.
  272. */
  273. #pragma GCC diagnostic ignored "-Wunused-function"
  274. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  275. #else
  276. #define FUNCTION_MAY_BE_UNUSED
  277. #endif
  278. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  279. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  280. #include <errno.h>
  281. #include <fcntl.h>
  282. #include <signal.h>
  283. #include <stdlib.h>
  284. #include <sys/stat.h>
  285. #include <sys/types.h>
  286. #endif /* !_WIN32_WCE */
  287. #if defined(__clang__)
  288. /* When using -Weverything, clang does not accept it's own headers
  289. * in a release build configuration. Disable what is too much in
  290. * -Weverything. */
  291. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  292. #endif
  293. #if defined(__GNUC__) || defined(__MINGW32__)
  294. /* Who on earth came to the conclusion, using __DATE__ should rise
  295. * an "expansion of date or time macro is not reproducible"
  296. * warning. That's exactly what was intended by using this macro.
  297. * Just disable this nonsense warning. */
  298. /* And disabling them does not work either:
  299. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  300. * #pragma clang diagnostic ignored "-Wdate-time"
  301. * So we just have to disable ALL warnings for some lines
  302. * of code.
  303. * This seems to be a known GCC bug, not resolved since 2012:
  304. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  305. */
  306. #endif
  307. #if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
  308. #if defined(__clang__)
  309. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  310. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  311. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  312. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  313. #endif
  314. #endif
  315. #ifndef CLOCK_MONOTONIC
  316. #define CLOCK_MONOTONIC (1)
  317. #endif
  318. #ifndef CLOCK_REALTIME
  319. #define CLOCK_REALTIME (2)
  320. #endif
  321. #include <mach/clock.h>
  322. #include <mach/mach.h>
  323. #include <mach/mach_time.h>
  324. #include <sys/errno.h>
  325. #include <sys/time.h>
  326. /* clock_gettime is not implemented on OSX prior to 10.12 */
  327. static int
  328. _civet_clock_gettime(int clk_id, struct timespec *t)
  329. {
  330. memset(t, 0, sizeof(*t));
  331. if (clk_id == CLOCK_REALTIME) {
  332. struct timeval now;
  333. int rv = gettimeofday(&now, NULL);
  334. if (rv) {
  335. return rv;
  336. }
  337. t->tv_sec = now.tv_sec;
  338. t->tv_nsec = now.tv_usec * 1000;
  339. return 0;
  340. } else if (clk_id == CLOCK_MONOTONIC) {
  341. static uint64_t clock_start_time = 0;
  342. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  343. uint64_t now = mach_absolute_time();
  344. if (clock_start_time == 0) {
  345. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  346. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  347. /* appease "unused variable" warning for release builds */
  348. (void)mach_status;
  349. clock_start_time = now;
  350. }
  351. now = (uint64_t)((double)(now - clock_start_time)
  352. * (double)timebase_ifo.numer
  353. / (double)timebase_ifo.denom);
  354. t->tv_sec = now / 1000000000;
  355. t->tv_nsec = now % 1000000000;
  356. return 0;
  357. }
  358. return -1; /* EINVAL - Clock ID is unknown */
  359. }
  360. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  361. #if defined(__CLOCK_AVAILABILITY)
  362. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  363. * declared but it may be NULL at runtime. So we need to check before using
  364. * it. */
  365. static int
  366. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  367. {
  368. if (clock_gettime) {
  369. return clock_gettime(clk_id, t);
  370. }
  371. return _civet_clock_gettime(clk_id, t);
  372. }
  373. #define clock_gettime _civet_safe_clock_gettime
  374. #else
  375. #define clock_gettime _civet_clock_gettime
  376. #endif
  377. #endif
  378. #if defined(_WIN32)
  379. #define ERROR_TRY_AGAIN(err) ((err) == WSAEWOULDBLOCK)
  380. #else
  381. /* Unix might return different error codes indicating to try again.
  382. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  383. * decades ago, but better check both and let the compiler optimize it. */
  384. #define ERROR_TRY_AGAIN(err) \
  385. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  386. #endif
  387. #if defined(USE_ZLIB)
  388. #include "zconf.h"
  389. #include "zlib.h"
  390. #endif
  391. /********************************************************************/
  392. /* CivetWeb configuration defines */
  393. /********************************************************************/
  394. /* Maximum number of threads that can be configured.
  395. * The number of threads actually created depends on the "num_threads"
  396. * configuration parameter, but this is the upper limit. */
  397. #if !defined(MAX_WORKER_THREADS)
  398. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  399. #endif
  400. /* Timeout interval for select/poll calls.
  401. * The timeouts depend on "*_timeout_ms" configuration values, but long
  402. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  403. * This reduces the time required to stop the server. */
  404. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  405. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  406. #endif
  407. /* Do not try to compress files smaller than this limit. */
  408. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  409. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  410. #endif
  411. #if !defined(PASSWORDS_FILE_NAME)
  412. #define PASSWORDS_FILE_NAME ".htpasswd"
  413. #endif
  414. /* Initial buffer size for all CGI environment variables. In case there is
  415. * not enough space, another block is allocated. */
  416. #if !defined(CGI_ENVIRONMENT_SIZE)
  417. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  418. #endif
  419. /* Maximum number of environment variables. */
  420. #if !defined(MAX_CGI_ENVIR_VARS)
  421. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  422. #endif
  423. /* General purpose buffer size. */
  424. #if !defined(MG_BUF_LEN) /* in bytes */
  425. #define MG_BUF_LEN (1024 * 8)
  426. #endif
  427. /********************************************************************/
  428. /* Helper macros */
  429. #if !defined(ARRAY_SIZE)
  430. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  431. #endif
  432. #include <stdint.h>
  433. /* Standard defines */
  434. #if !defined(INT64_MAX)
  435. #define INT64_MAX (9223372036854775807)
  436. #endif
  437. #define SHUTDOWN_RD (0)
  438. #define SHUTDOWN_WR (1)
  439. #define SHUTDOWN_BOTH (2)
  440. mg_static_assert(MAX_WORKER_THREADS >= 1,
  441. "worker threads must be a positive number");
  442. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  443. "size_t data type size check");
  444. #if defined(_WIN32) /* WINDOWS include block */
  445. #include <malloc.h> /* *alloc( */
  446. #include <stdlib.h> /* *alloc( */
  447. #include <time.h> /* struct timespec */
  448. #include <windows.h>
  449. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  450. #include <ws2tcpip.h>
  451. typedef const char *SOCK_OPT_TYPE;
  452. /* For a detailed description of these *_PATH_MAX defines, see
  453. * https://github.com/civetweb/civetweb/issues/937. */
  454. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  455. * null termination, rounded up to the next 4 bytes boundary */
  456. #define UTF8_PATH_MAX (3 * 260)
  457. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  458. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  459. #define UTF16_PATH_MAX (260)
  460. #if !defined(_IN_PORT_T)
  461. #if !defined(in_port_t)
  462. #define in_port_t u_short
  463. #endif
  464. #endif
  465. #if defined(_WIN32_WCE)
  466. #error "WinCE support has ended"
  467. #endif
  468. #include <direct.h>
  469. #include <io.h>
  470. #include <process.h>
  471. #define MAKEUQUAD(lo, hi) \
  472. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  473. #define RATE_DIFF (10000000) /* 100 nsecs */
  474. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  475. #define SYS2UNIX_TIME(lo, hi) \
  476. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  477. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  478. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  479. * Also use _strtoui64 on modern M$ compilers */
  480. #if defined(_MSC_VER)
  481. #if (_MSC_VER < 1300)
  482. #define STRX(x) #x
  483. #define STR(x) STRX(x)
  484. #define __func__ __FILE__ ":" STR(__LINE__)
  485. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  486. #define strtoll(x, y, z) (_atoi64(x))
  487. #else
  488. #define __func__ __FUNCTION__
  489. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  490. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  491. #endif
  492. #endif /* _MSC_VER */
  493. #define ERRNO ((int)(GetLastError()))
  494. #define NO_SOCKLEN_T
  495. #if defined(_WIN64) || defined(__MINGW64__)
  496. #if !defined(SSL_LIB)
  497. #if defined(OPENSSL_API_3_0)
  498. #define SSL_LIB "libssl-3-x64.dll"
  499. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  500. #endif
  501. #if defined(OPENSSL_API_1_1)
  502. #define SSL_LIB "libssl-1_1-x64.dll"
  503. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  504. #endif /* OPENSSL_API_1_1 */
  505. #if defined(OPENSSL_API_1_0)
  506. #define SSL_LIB "ssleay64.dll"
  507. #define CRYPTO_LIB "libeay64.dll"
  508. #endif /* OPENSSL_API_1_0 */
  509. #endif
  510. #else /* defined(_WIN64) || defined(__MINGW64__) */
  511. #if !defined(SSL_LIB)
  512. #if defined(OPENSSL_API_3_0)
  513. #define SSL_LIB "libssl-3.dll"
  514. #define CRYPTO_LIB "libcrypto-3.dll"
  515. #endif
  516. #if defined(OPENSSL_API_1_1)
  517. #define SSL_LIB "libssl-1_1.dll"
  518. #define CRYPTO_LIB "libcrypto-1_1.dll"
  519. #endif /* OPENSSL_API_1_1 */
  520. #if defined(OPENSSL_API_1_0)
  521. #define SSL_LIB "ssleay32.dll"
  522. #define CRYPTO_LIB "libeay32.dll"
  523. #endif /* OPENSSL_API_1_0 */
  524. #endif /* SSL_LIB */
  525. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  526. #define O_NONBLOCK (0)
  527. #if !defined(W_OK)
  528. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  529. #endif
  530. #define _POSIX_
  531. #define INT64_FMT "I64d"
  532. #define UINT64_FMT "I64u"
  533. #define WINCDECL __cdecl
  534. #define vsnprintf_impl _vsnprintf
  535. #define access _access
  536. #define mg_sleep(x) (Sleep(x))
  537. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  538. #if !defined(popen)
  539. #define popen(x, y) (_popen(x, y))
  540. #endif
  541. #if !defined(pclose)
  542. #define pclose(x) (_pclose(x))
  543. #endif
  544. #define close(x) (_close(x))
  545. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  546. #define RTLD_LAZY (0)
  547. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  548. #define fdopen(x, y) (_fdopen((x), (y)))
  549. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  550. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  551. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  552. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  553. #define sleep(x) (Sleep((x)*1000))
  554. #define rmdir(x) (_rmdir(x))
  555. #if defined(_WIN64) || !defined(__MINGW32__)
  556. /* Only MinGW 32 bit is missing this function */
  557. #define timegm(x) (_mkgmtime(x))
  558. #else
  559. time_t timegm(struct tm *tm);
  560. #define NEED_TIMEGM
  561. #endif
  562. #if !defined(fileno)
  563. #define fileno(x) (_fileno(x))
  564. #endif /* !fileno MINGW #defines fileno */
  565. typedef struct {
  566. CRITICAL_SECTION sec; /* Immovable */
  567. } pthread_mutex_t;
  568. typedef DWORD pthread_key_t;
  569. typedef HANDLE pthread_t;
  570. typedef struct {
  571. pthread_mutex_t threadIdSec;
  572. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  573. } pthread_cond_t;
  574. #if !defined(__clockid_t_defined)
  575. typedef DWORD clockid_t;
  576. #endif
  577. #if !defined(CLOCK_MONOTONIC)
  578. #define CLOCK_MONOTONIC (1)
  579. #endif
  580. #if !defined(CLOCK_REALTIME)
  581. #define CLOCK_REALTIME (2)
  582. #endif
  583. #if !defined(CLOCK_THREAD)
  584. #define CLOCK_THREAD (3)
  585. #endif
  586. #if !defined(CLOCK_PROCESS)
  587. #define CLOCK_PROCESS (4)
  588. #endif
  589. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  590. #define _TIMESPEC_DEFINED
  591. #endif
  592. #if !defined(_TIMESPEC_DEFINED)
  593. struct timespec {
  594. time_t tv_sec; /* seconds */
  595. long tv_nsec; /* nanoseconds */
  596. };
  597. #endif
  598. #if !defined(WIN_PTHREADS_TIME_H)
  599. #define MUST_IMPLEMENT_CLOCK_GETTIME
  600. #endif
  601. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  602. #define clock_gettime mg_clock_gettime
  603. static int
  604. clock_gettime(clockid_t clk_id, struct timespec *tp)
  605. {
  606. FILETIME ft;
  607. ULARGE_INTEGER li, li2;
  608. BOOL ok = FALSE;
  609. double d;
  610. static double perfcnt_per_sec = 0.0;
  611. static BOOL initialized = FALSE;
  612. if (!initialized) {
  613. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  614. perfcnt_per_sec = 1.0 / li.QuadPart;
  615. initialized = TRUE;
  616. }
  617. if (tp) {
  618. memset(tp, 0, sizeof(*tp));
  619. if (clk_id == CLOCK_REALTIME) {
  620. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  621. GetSystemTimeAsFileTime(&ft);
  622. li.LowPart = ft.dwLowDateTime;
  623. li.HighPart = ft.dwHighDateTime;
  624. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  625. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  626. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  627. ok = TRUE;
  628. /* END: CLOCK_REALTIME */
  629. } else if (clk_id == CLOCK_MONOTONIC) {
  630. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  631. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  632. d = li.QuadPart * perfcnt_per_sec;
  633. tp->tv_sec = (time_t)d;
  634. d -= (double)tp->tv_sec;
  635. tp->tv_nsec = (long)(d * 1.0E9);
  636. ok = TRUE;
  637. /* END: CLOCK_MONOTONIC */
  638. } else if (clk_id == CLOCK_THREAD) {
  639. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  640. FILETIME t_create, t_exit, t_kernel, t_user;
  641. if (GetThreadTimes(GetCurrentThread(),
  642. &t_create,
  643. &t_exit,
  644. &t_kernel,
  645. &t_user)) {
  646. li.LowPart = t_user.dwLowDateTime;
  647. li.HighPart = t_user.dwHighDateTime;
  648. li2.LowPart = t_kernel.dwLowDateTime;
  649. li2.HighPart = t_kernel.dwHighDateTime;
  650. li.QuadPart += li2.QuadPart;
  651. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  652. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  653. ok = TRUE;
  654. }
  655. /* END: CLOCK_THREAD */
  656. } else if (clk_id == CLOCK_PROCESS) {
  657. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  658. FILETIME t_create, t_exit, t_kernel, t_user;
  659. if (GetProcessTimes(GetCurrentProcess(),
  660. &t_create,
  661. &t_exit,
  662. &t_kernel,
  663. &t_user)) {
  664. li.LowPart = t_user.dwLowDateTime;
  665. li.HighPart = t_user.dwHighDateTime;
  666. li2.LowPart = t_kernel.dwLowDateTime;
  667. li2.HighPart = t_kernel.dwHighDateTime;
  668. li.QuadPart += li2.QuadPart;
  669. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  670. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  671. ok = TRUE;
  672. }
  673. /* END: CLOCK_PROCESS */
  674. } else {
  675. /* BEGIN: unknown clock */
  676. /* ok = FALSE; already set by init */
  677. /* END: unknown clock */
  678. }
  679. }
  680. return ok ? 0 : -1;
  681. }
  682. #endif
  683. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  684. static int pthread_mutex_lock(pthread_mutex_t *);
  685. static int pthread_mutex_unlock(pthread_mutex_t *);
  686. static void path_to_unicode(const struct mg_connection *conn,
  687. const char *path,
  688. wchar_t *wbuf,
  689. size_t wbuf_len);
  690. /* All file operations need to be rewritten to solve #246. */
  691. struct mg_file;
  692. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  693. /* POSIX dirent interface */
  694. struct dirent {
  695. char d_name[UTF8_PATH_MAX];
  696. };
  697. typedef struct DIR {
  698. HANDLE handle;
  699. WIN32_FIND_DATAW info;
  700. struct dirent result;
  701. } DIR;
  702. #if defined(HAVE_POLL)
  703. #define mg_pollfd pollfd
  704. #else
  705. struct mg_pollfd {
  706. SOCKET fd;
  707. short events;
  708. short revents;
  709. };
  710. #endif
  711. /* Mark required libraries */
  712. #if defined(_MSC_VER)
  713. #pragma comment(lib, "Ws2_32.lib")
  714. #endif
  715. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  716. #include <inttypes.h>
  717. /* Linux & co. internally use UTF8 */
  718. #define UTF8_PATH_MAX (PATH_MAX)
  719. typedef const void *SOCK_OPT_TYPE;
  720. #if defined(ANDROID)
  721. typedef unsigned short int in_port_t;
  722. #endif
  723. #if !defined(__ZEPHYR__)
  724. #include <arpa/inet.h>
  725. #include <ctype.h>
  726. #include <dirent.h>
  727. #include <grp.h>
  728. #include <limits.h>
  729. #include <netdb.h>
  730. #include <netinet/in.h>
  731. #include <netinet/tcp.h>
  732. #include <poll.h>
  733. #include <pthread.h>
  734. #include <pwd.h>
  735. #include <stdarg.h>
  736. #include <stddef.h>
  737. #include <stdio.h>
  738. #include <stdlib.h>
  739. #include <string.h>
  740. #include <sys/socket.h>
  741. #include <sys/time.h>
  742. #if !defined(__rtems__)
  743. #include <sys/utsname.h>
  744. #endif
  745. #include <sys/wait.h>
  746. #include <time.h>
  747. #include <unistd.h>
  748. #if defined(USE_X_DOM_SOCKET)
  749. #include <sys/un.h>
  750. #endif
  751. #endif
  752. #define vsnprintf_impl vsnprintf
  753. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  754. #include <dlfcn.h>
  755. #endif
  756. #if defined(__MACH__) && defined(__APPLE__)
  757. #if defined(OPENSSL_API_3_0)
  758. #define SSL_LIB "libssl.3.dylib"
  759. #define CRYPTO_LIB "libcrypto.3.dylib"
  760. #endif
  761. #if defined(OPENSSL_API_1_1)
  762. #define SSL_LIB "libssl.1.1.dylib"
  763. #define CRYPTO_LIB "libcrypto.1.1.dylib"
  764. #endif /* OPENSSL_API_1_1 */
  765. #if defined(OPENSSL_API_1_0)
  766. #define SSL_LIB "libssl.1.0.dylib"
  767. #define CRYPTO_LIB "libcrypto.1.0.dylib"
  768. #endif /* OPENSSL_API_1_0 */
  769. #else
  770. #if !defined(SSL_LIB)
  771. #define SSL_LIB "libssl.so"
  772. #endif
  773. #if !defined(CRYPTO_LIB)
  774. #define CRYPTO_LIB "libcrypto.so"
  775. #endif
  776. #endif
  777. #if !defined(O_BINARY)
  778. #define O_BINARY (0)
  779. #endif /* O_BINARY */
  780. #define closesocket(a) (close(a))
  781. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  782. #define mg_remove(conn, x) (remove(x))
  783. #define mg_sleep(x) (usleep((x)*1000))
  784. #define mg_opendir(conn, x) (opendir(x))
  785. #define mg_closedir(x) (closedir(x))
  786. #define mg_readdir(x) (readdir(x))
  787. #define ERRNO (errno)
  788. #define INVALID_SOCKET (-1)
  789. #define INT64_FMT PRId64
  790. #define UINT64_FMT PRIu64
  791. typedef int SOCKET;
  792. #define WINCDECL
  793. #if defined(__hpux)
  794. /* HPUX 11 does not have monotonic, fall back to realtime */
  795. #if !defined(CLOCK_MONOTONIC)
  796. #define CLOCK_MONOTONIC CLOCK_REALTIME
  797. #endif
  798. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  799. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  800. * the prototypes use int* rather than socklen_t* which matches the
  801. * actual library expectation. When called with the wrong size arg
  802. * accept() returns a zero client inet addr and check_acl() always
  803. * fails. Since socklen_t is widely used below, just force replace
  804. * their typedef with int. - DTL
  805. */
  806. #define socklen_t int
  807. #endif /* hpux */
  808. #define mg_pollfd pollfd
  809. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  810. /* In case our C library is missing "timegm", provide an implementation */
  811. #if defined(NEED_TIMEGM)
  812. static inline int
  813. is_leap(int y)
  814. {
  815. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  816. }
  817. static inline int
  818. count_leap(int y)
  819. {
  820. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  821. }
  822. static time_t
  823. timegm(struct tm *tm)
  824. {
  825. static const unsigned short ydays[] = {
  826. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  827. int year = tm->tm_year + 1900;
  828. int mon = tm->tm_mon;
  829. int mday = tm->tm_mday - 1;
  830. int hour = tm->tm_hour;
  831. int min = tm->tm_min;
  832. int sec = tm->tm_sec;
  833. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  834. || (mday >= ydays[mon + 1] - ydays[mon]
  835. + (mon == 1 && is_leap(year) ? 1 : 0))
  836. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  837. return -1;
  838. time_t res = year - 1970;
  839. res *= 365;
  840. res += mday;
  841. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  842. res += count_leap(year);
  843. res *= 24;
  844. res += hour;
  845. res *= 60;
  846. res += min;
  847. res *= 60;
  848. res += sec;
  849. return res;
  850. }
  851. #endif /* NEED_TIMEGM */
  852. /* va_copy should always be a macro, C99 and C++11 - DTL */
  853. #if !defined(va_copy)
  854. #define va_copy(x, y) ((x) = (y))
  855. #endif
  856. #if defined(_WIN32)
  857. /* Create substitutes for POSIX functions in Win32. */
  858. #if defined(GCC_DIAGNOSTIC)
  859. /* Show no warning in case system functions are not used. */
  860. #pragma GCC diagnostic push
  861. #pragma GCC diagnostic ignored "-Wunused-function"
  862. #endif
  863. static pthread_mutex_t global_log_file_lock;
  864. FUNCTION_MAY_BE_UNUSED
  865. static DWORD
  866. pthread_self(void)
  867. {
  868. return GetCurrentThreadId();
  869. }
  870. FUNCTION_MAY_BE_UNUSED
  871. static int
  872. pthread_key_create(
  873. pthread_key_t *key,
  874. void (*_ignored)(void *) /* destructor not supported for Windows */
  875. )
  876. {
  877. (void)_ignored;
  878. if ((key != 0)) {
  879. *key = TlsAlloc();
  880. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  881. }
  882. return -2;
  883. }
  884. FUNCTION_MAY_BE_UNUSED
  885. static int
  886. pthread_key_delete(pthread_key_t key)
  887. {
  888. return TlsFree(key) ? 0 : 1;
  889. }
  890. FUNCTION_MAY_BE_UNUSED
  891. static int
  892. pthread_setspecific(pthread_key_t key, void *value)
  893. {
  894. return TlsSetValue(key, value) ? 0 : 1;
  895. }
  896. FUNCTION_MAY_BE_UNUSED
  897. static void *
  898. pthread_getspecific(pthread_key_t key)
  899. {
  900. return TlsGetValue(key);
  901. }
  902. #if defined(GCC_DIAGNOSTIC)
  903. /* Enable unused function warning again */
  904. #pragma GCC diagnostic pop
  905. #endif
  906. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  907. #else
  908. static pthread_mutexattr_t pthread_mutex_attr;
  909. #endif /* _WIN32 */
  910. #if defined(GCC_DIAGNOSTIC)
  911. /* Show no warning in case system functions are not used. */
  912. #pragma GCC diagnostic push
  913. #pragma GCC diagnostic ignored "-Wunused-function"
  914. #endif /* defined(GCC_DIAGNOSTIC) */
  915. #if defined(__clang__)
  916. /* Show no warning in case system functions are not used. */
  917. #pragma clang diagnostic push
  918. #pragma clang diagnostic ignored "-Wunused-function"
  919. #endif
  920. static pthread_mutex_t global_lock_mutex;
  921. FUNCTION_MAY_BE_UNUSED
  922. static void
  923. mg_global_lock(void)
  924. {
  925. (void)pthread_mutex_lock(&global_lock_mutex);
  926. }
  927. FUNCTION_MAY_BE_UNUSED
  928. static void
  929. mg_global_unlock(void)
  930. {
  931. (void)pthread_mutex_unlock(&global_lock_mutex);
  932. }
  933. #if defined(_WIN64)
  934. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  935. #elif defined(_WIN32)
  936. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  937. #endif
  938. /* Atomic functions working on ptrdiff_t ("signed size_t").
  939. * Operations: Increment, Decrement, Add, Maximum.
  940. * Up to size_t, they do not an atomic "load" operation.
  941. */
  942. FUNCTION_MAY_BE_UNUSED
  943. static ptrdiff_t
  944. mg_atomic_inc(volatile ptrdiff_t *addr)
  945. {
  946. ptrdiff_t ret;
  947. #if defined(_WIN64) && !defined(NO_ATOMICS)
  948. ret = InterlockedIncrement64(addr);
  949. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  950. #ifdef __cplusplus
  951. /* For C++ the Microsoft Visual Studio compiler can not decide what
  952. * overloaded function prototpye in the SDC corresponds to "ptrdiff_t". */
  953. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  954. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  955. ret = InterlockedIncrement((LONG *)addr);
  956. #else
  957. ret = InterlockedIncrement(addr);
  958. #endif
  959. #elif defined(__GNUC__) \
  960. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  961. && !defined(NO_ATOMICS)
  962. ret = __sync_add_and_fetch(addr, 1);
  963. #else
  964. mg_global_lock();
  965. ret = (++(*addr));
  966. mg_global_unlock();
  967. #endif
  968. return ret;
  969. }
  970. FUNCTION_MAY_BE_UNUSED
  971. static ptrdiff_t
  972. mg_atomic_dec(volatile ptrdiff_t *addr)
  973. {
  974. ptrdiff_t ret;
  975. #if defined(_WIN64) && !defined(NO_ATOMICS)
  976. ret = InterlockedDecrement64(addr);
  977. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  978. #ifdef __cplusplus
  979. /* see mg_atomic_inc */
  980. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  981. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  982. ret = InterlockedDecrement((LONG *)addr);
  983. #else
  984. ret = InterlockedDecrement(addr);
  985. #endif
  986. #elif defined(__GNUC__) \
  987. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  988. && !defined(NO_ATOMICS)
  989. ret = __sync_sub_and_fetch(addr, 1);
  990. #else
  991. mg_global_lock();
  992. ret = (--(*addr));
  993. mg_global_unlock();
  994. #endif
  995. return ret;
  996. }
  997. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  998. static ptrdiff_t
  999. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1000. {
  1001. ptrdiff_t ret;
  1002. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1003. ret = InterlockedAdd64(addr, value);
  1004. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1005. ret = InterlockedExchangeAdd(addr, value) + value;
  1006. #elif defined(__GNUC__) \
  1007. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1008. && !defined(NO_ATOMICS)
  1009. ret = __sync_add_and_fetch(addr, value);
  1010. #else
  1011. mg_global_lock();
  1012. *addr += value;
  1013. ret = (*addr);
  1014. mg_global_unlock();
  1015. #endif
  1016. return ret;
  1017. }
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static ptrdiff_t
  1020. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1021. ptrdiff_t oldval,
  1022. ptrdiff_t newval)
  1023. {
  1024. ptrdiff_t ret;
  1025. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1026. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1027. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1028. ret = InterlockedCompareExchange(addr, newval, oldval);
  1029. #elif defined(__GNUC__) \
  1030. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1031. && !defined(NO_ATOMICS)
  1032. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1033. #else
  1034. mg_global_lock();
  1035. ret = *addr;
  1036. if ((ret != newval) && (ret == oldval)) {
  1037. *addr = newval;
  1038. }
  1039. mg_global_unlock();
  1040. #endif
  1041. return ret;
  1042. }
  1043. static void
  1044. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1045. {
  1046. register ptrdiff_t tmp = *addr;
  1047. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1048. while (tmp < value) {
  1049. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1050. }
  1051. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1052. while (tmp < value) {
  1053. tmp = InterlockedCompareExchange(addr, value, tmp);
  1054. }
  1055. #elif defined(__GNUC__) \
  1056. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1057. && !defined(NO_ATOMICS)
  1058. while (tmp < value) {
  1059. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1060. }
  1061. #else
  1062. mg_global_lock();
  1063. if (*addr < value) {
  1064. *addr = value;
  1065. }
  1066. mg_global_unlock();
  1067. #endif
  1068. }
  1069. static int64_t
  1070. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1071. {
  1072. int64_t ret;
  1073. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1074. ret = InterlockedAdd64(addr, value);
  1075. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1076. ret = InterlockedExchangeAdd64(addr, value) + value;
  1077. #elif defined(__GNUC__) \
  1078. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1079. && !defined(NO_ATOMICS)
  1080. ret = __sync_add_and_fetch(addr, value);
  1081. #else
  1082. mg_global_lock();
  1083. *addr += value;
  1084. ret = (*addr);
  1085. mg_global_unlock();
  1086. #endif
  1087. return ret;
  1088. }
  1089. #endif
  1090. #if defined(GCC_DIAGNOSTIC)
  1091. /* Show no warning in case system functions are not used. */
  1092. #pragma GCC diagnostic pop
  1093. #endif /* defined(GCC_DIAGNOSTIC) */
  1094. #if defined(__clang__)
  1095. /* Show no warning in case system functions are not used. */
  1096. #pragma clang diagnostic pop
  1097. #endif
  1098. #if defined(USE_SERVER_STATS)
  1099. struct mg_memory_stat {
  1100. volatile ptrdiff_t totalMemUsed;
  1101. volatile ptrdiff_t maxMemUsed;
  1102. volatile ptrdiff_t blockCount;
  1103. };
  1104. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1105. static void *
  1106. mg_malloc_ex(size_t size,
  1107. struct mg_context *ctx,
  1108. const char *file,
  1109. unsigned line)
  1110. {
  1111. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1112. void *memory = 0;
  1113. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1114. #if defined(MEMORY_DEBUGGING)
  1115. char mallocStr[256];
  1116. #else
  1117. (void)file;
  1118. (void)line;
  1119. #endif
  1120. if (data) {
  1121. uintptr_t *tmp = (uintptr_t *)data;
  1122. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1123. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1124. mg_atomic_inc(&mstat->blockCount);
  1125. tmp[0] = size;
  1126. tmp[1] = (uintptr_t)mstat;
  1127. memory = (void *)&tmp[2];
  1128. }
  1129. #if defined(MEMORY_DEBUGGING)
  1130. sprintf(mallocStr,
  1131. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1132. memory,
  1133. (unsigned long)size,
  1134. (unsigned long)mstat->totalMemUsed,
  1135. (unsigned long)mstat->blockCount,
  1136. file,
  1137. line);
  1138. DEBUG_TRACE("%s", mallocStr);
  1139. #endif
  1140. return memory;
  1141. }
  1142. static void *
  1143. mg_calloc_ex(size_t count,
  1144. size_t size,
  1145. struct mg_context *ctx,
  1146. const char *file,
  1147. unsigned line)
  1148. {
  1149. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1150. if (data) {
  1151. memset(data, 0, size * count);
  1152. }
  1153. return data;
  1154. }
  1155. static void
  1156. mg_free_ex(void *memory, const char *file, unsigned line)
  1157. {
  1158. #if defined(MEMORY_DEBUGGING)
  1159. char mallocStr[256];
  1160. #else
  1161. (void)file;
  1162. (void)line;
  1163. #endif
  1164. if (memory) {
  1165. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1166. uintptr_t size = ((uintptr_t *)data)[0];
  1167. struct mg_memory_stat *mstat =
  1168. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1169. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1170. mg_atomic_dec(&mstat->blockCount);
  1171. #if defined(MEMORY_DEBUGGING)
  1172. sprintf(mallocStr,
  1173. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1174. memory,
  1175. (unsigned long)size,
  1176. (unsigned long)mstat->totalMemUsed,
  1177. (unsigned long)mstat->blockCount,
  1178. file,
  1179. line);
  1180. DEBUG_TRACE("%s", mallocStr);
  1181. #endif
  1182. free(data);
  1183. }
  1184. }
  1185. static void *
  1186. mg_realloc_ex(void *memory,
  1187. size_t newsize,
  1188. struct mg_context *ctx,
  1189. const char *file,
  1190. unsigned line)
  1191. {
  1192. void *data;
  1193. void *_realloc;
  1194. uintptr_t oldsize;
  1195. #if defined(MEMORY_DEBUGGING)
  1196. char mallocStr[256];
  1197. #else
  1198. (void)file;
  1199. (void)line;
  1200. #endif
  1201. if (newsize) {
  1202. if (memory) {
  1203. /* Reallocate existing block */
  1204. struct mg_memory_stat *mstat;
  1205. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1206. oldsize = ((uintptr_t *)data)[0];
  1207. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1208. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1209. if (_realloc) {
  1210. data = _realloc;
  1211. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1212. #if defined(MEMORY_DEBUGGING)
  1213. sprintf(mallocStr,
  1214. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1215. memory,
  1216. (unsigned long)oldsize,
  1217. (unsigned long)mstat->totalMemUsed,
  1218. (unsigned long)mstat->blockCount,
  1219. file,
  1220. line);
  1221. DEBUG_TRACE("%s", mallocStr);
  1222. #endif
  1223. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1224. #if defined(MEMORY_DEBUGGING)
  1225. sprintf(mallocStr,
  1226. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1227. memory,
  1228. (unsigned long)newsize,
  1229. (unsigned long)mstat->totalMemUsed,
  1230. (unsigned long)mstat->blockCount,
  1231. file,
  1232. line);
  1233. DEBUG_TRACE("%s", mallocStr);
  1234. #endif
  1235. *(uintptr_t *)data = newsize;
  1236. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1237. } else {
  1238. #if defined(MEMORY_DEBUGGING)
  1239. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1240. #endif
  1241. return _realloc;
  1242. }
  1243. } else {
  1244. /* Allocate new block */
  1245. data = mg_malloc_ex(newsize, ctx, file, line);
  1246. }
  1247. } else {
  1248. /* Free existing block */
  1249. data = 0;
  1250. mg_free_ex(memory, file, line);
  1251. }
  1252. return data;
  1253. }
  1254. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1255. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1256. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1257. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1258. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1259. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1260. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1261. #else /* USE_SERVER_STATS */
  1262. static __inline void *
  1263. mg_malloc(size_t a)
  1264. {
  1265. return malloc(a);
  1266. }
  1267. static __inline void *
  1268. mg_calloc(size_t a, size_t b)
  1269. {
  1270. return calloc(a, b);
  1271. }
  1272. static __inline void *
  1273. mg_realloc(void *a, size_t b)
  1274. {
  1275. return realloc(a, b);
  1276. }
  1277. static __inline void
  1278. mg_free(void *a)
  1279. {
  1280. free(a);
  1281. }
  1282. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1283. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1284. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1285. #define mg_free_ctx(a, c) mg_free(a)
  1286. #endif /* USE_SERVER_STATS */
  1287. static void mg_vsnprintf(const struct mg_connection *conn,
  1288. int *truncated,
  1289. char *buf,
  1290. size_t buflen,
  1291. const char *fmt,
  1292. va_list ap);
  1293. static void mg_snprintf(const struct mg_connection *conn,
  1294. int *truncated,
  1295. char *buf,
  1296. size_t buflen,
  1297. PRINTF_FORMAT_STRING(const char *fmt),
  1298. ...) PRINTF_ARGS(5, 6);
  1299. /* This following lines are just meant as a reminder to use the mg-functions
  1300. * for memory management */
  1301. #if defined(malloc)
  1302. #undef malloc
  1303. #endif
  1304. #if defined(calloc)
  1305. #undef calloc
  1306. #endif
  1307. #if defined(realloc)
  1308. #undef realloc
  1309. #endif
  1310. #if defined(free)
  1311. #undef free
  1312. #endif
  1313. #if defined(snprintf)
  1314. #undef snprintf
  1315. #endif
  1316. #if defined(vsnprintf)
  1317. #undef vsnprintf
  1318. #endif
  1319. #if !defined(NDEBUG)
  1320. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1321. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1322. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1323. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1324. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1325. #endif
  1326. #if defined(_WIN32)
  1327. /* vsnprintf must not be used in any system,
  1328. * but this define only works well for Windows. */
  1329. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1330. #endif
  1331. /* mg_init_library counter */
  1332. static int mg_init_library_called = 0;
  1333. #if !defined(NO_SSL)
  1334. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1335. || defined(OPENSSL_API_3_0)
  1336. static int mg_openssl_initialized = 0;
  1337. #endif
  1338. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1339. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS) \
  1340. && !defined(USE_GNUTLS)
  1341. #error "Please define OPENSSL_API_#_# or USE_MBEDTLS or USE_GNUTLS"
  1342. #endif
  1343. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1344. #error "Multiple OPENSSL_API versions defined"
  1345. #endif
  1346. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1347. #error "Multiple OPENSSL_API versions defined"
  1348. #endif
  1349. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1350. #error "Multiple OPENSSL_API versions defined"
  1351. #endif
  1352. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1353. || defined(OPENSSL_API_3_0)) \
  1354. && (defined(USE_MBEDTLS) || defined(USE_GNUTLS))
  1355. #error "Multiple SSL libraries defined"
  1356. #endif
  1357. #if defined(USE_MBEDTLS) && defined(USE_GNUTLS)
  1358. #error "Multiple SSL libraries defined"
  1359. #endif
  1360. #endif
  1361. static pthread_key_t sTlsKey; /* Thread local storage index */
  1362. static volatile ptrdiff_t thread_idx_max = 0;
  1363. #if defined(MG_LEGACY_INTERFACE)
  1364. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1365. #endif
  1366. struct mg_workerTLS {
  1367. int is_master;
  1368. unsigned long thread_idx;
  1369. void *user_ptr;
  1370. #if defined(_WIN32)
  1371. HANDLE pthread_cond_helper_mutex;
  1372. struct mg_workerTLS *next_waiting_thread;
  1373. #endif
  1374. const char *alpn_proto;
  1375. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1376. char txtbuf[4];
  1377. #endif
  1378. };
  1379. #if defined(GCC_DIAGNOSTIC)
  1380. /* Show no warning in case system functions are not used. */
  1381. #pragma GCC diagnostic push
  1382. #pragma GCC diagnostic ignored "-Wunused-function"
  1383. #endif /* defined(GCC_DIAGNOSTIC) */
  1384. #if defined(__clang__)
  1385. /* Show no warning in case system functions are not used. */
  1386. #pragma clang diagnostic push
  1387. #pragma clang diagnostic ignored "-Wunused-function"
  1388. #endif
  1389. /* Get a unique thread ID as unsigned long, independent from the data type
  1390. * of thread IDs defined by the operating system API.
  1391. * If two calls to mg_current_thread_id return the same value, they calls
  1392. * are done from the same thread. If they return different values, they are
  1393. * done from different threads. (Provided this function is used in the same
  1394. * process context and threads are not repeatedly created and deleted, but
  1395. * CivetWeb does not do that).
  1396. * This function must match the signature required for SSL id callbacks:
  1397. * CRYPTO_set_id_callback
  1398. */
  1399. FUNCTION_MAY_BE_UNUSED
  1400. static unsigned long
  1401. mg_current_thread_id(void)
  1402. {
  1403. #if defined(_WIN32)
  1404. return GetCurrentThreadId();
  1405. #else
  1406. #if defined(__clang__)
  1407. #pragma clang diagnostic push
  1408. #pragma clang diagnostic ignored "-Wunreachable-code"
  1409. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1410. * or not, so one of the two conditions will be unreachable by construction.
  1411. * Unfortunately the C standard does not define a way to check this at
  1412. * compile time, since the #if preprocessor conditions can not use the
  1413. * sizeof operator as an argument. */
  1414. #endif
  1415. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1416. /* This is the problematic case for CRYPTO_set_id_callback:
  1417. * The OS pthread_t can not be cast to unsigned long. */
  1418. struct mg_workerTLS *tls =
  1419. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1420. if (tls == NULL) {
  1421. /* SSL called from an unknown thread: Create some thread index.
  1422. */
  1423. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1424. tls->is_master = -2; /* -2 means "3rd party thread" */
  1425. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1426. pthread_setspecific(sTlsKey, tls);
  1427. }
  1428. return tls->thread_idx;
  1429. } else {
  1430. /* pthread_t may be any data type, so a simple cast to unsigned long
  1431. * can rise a warning/error, depending on the platform.
  1432. * Here memcpy is used as an anything-to-anything cast. */
  1433. unsigned long ret = 0;
  1434. pthread_t t = pthread_self();
  1435. memcpy(&ret, &t, sizeof(pthread_t));
  1436. return ret;
  1437. }
  1438. #if defined(__clang__)
  1439. #pragma clang diagnostic pop
  1440. #endif
  1441. #endif
  1442. }
  1443. FUNCTION_MAY_BE_UNUSED
  1444. static uint64_t
  1445. mg_get_current_time_ns(void)
  1446. {
  1447. struct timespec tsnow;
  1448. clock_gettime(CLOCK_REALTIME, &tsnow);
  1449. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1450. }
  1451. #if defined(GCC_DIAGNOSTIC)
  1452. /* Show no warning in case system functions are not used. */
  1453. #pragma GCC diagnostic pop
  1454. #endif /* defined(GCC_DIAGNOSTIC) */
  1455. #if defined(__clang__)
  1456. /* Show no warning in case system functions are not used. */
  1457. #pragma clang diagnostic pop
  1458. #endif
  1459. #if defined(NEED_DEBUG_TRACE_FUNC)
  1460. static void
  1461. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1462. {
  1463. va_list args;
  1464. struct timespec tsnow;
  1465. /* Get some operating system independent thread id */
  1466. unsigned long thread_id = mg_current_thread_id();
  1467. clock_gettime(CLOCK_REALTIME, &tsnow);
  1468. flockfile(DEBUG_TRACE_STREAM);
  1469. fprintf(DEBUG_TRACE_STREAM,
  1470. "*** %lu.%09lu %lu %s:%u: ",
  1471. (unsigned long)tsnow.tv_sec,
  1472. (unsigned long)tsnow.tv_nsec,
  1473. thread_id,
  1474. func,
  1475. line);
  1476. va_start(args, fmt);
  1477. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1478. va_end(args);
  1479. putc('\n', DEBUG_TRACE_STREAM);
  1480. fflush(DEBUG_TRACE_STREAM);
  1481. funlockfile(DEBUG_TRACE_STREAM);
  1482. }
  1483. #endif /* NEED_DEBUG_TRACE_FUNC */
  1484. #define MD5_STATIC static
  1485. #include "md5.inl"
  1486. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1487. #if defined(NO_SOCKLEN_T)
  1488. typedef int socklen_t;
  1489. #endif /* NO_SOCKLEN_T */
  1490. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1491. #if !defined(MSG_NOSIGNAL)
  1492. #define MSG_NOSIGNAL (0)
  1493. #endif
  1494. /* SSL: mbedTLS vs. GnuTLS vs. no-ssl vs. OpenSSL */
  1495. #if defined(USE_MBEDTLS)
  1496. /* mbedTLS */
  1497. #include "mod_mbedtls.inl"
  1498. #elif defined(USE_GNUTLS)
  1499. /* GnuTLS */
  1500. #include "mod_gnutls.inl"
  1501. #elif defined(NO_SSL)
  1502. /* no SSL */
  1503. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1504. typedef struct SSL_CTX SSL_CTX;
  1505. #elif defined(NO_SSL_DL)
  1506. /* OpenSSL without dynamic loading */
  1507. #include <openssl/bn.h>
  1508. #include <openssl/conf.h>
  1509. #include <openssl/crypto.h>
  1510. #include <openssl/dh.h>
  1511. #include <openssl/engine.h>
  1512. #include <openssl/err.h>
  1513. #include <openssl/opensslv.h>
  1514. #include <openssl/pem.h>
  1515. #include <openssl/ssl.h>
  1516. #include <openssl/tls1.h>
  1517. #include <openssl/x509.h>
  1518. #if defined(WOLFSSL_VERSION)
  1519. /* Additional defines for WolfSSL, see
  1520. * https://github.com/civetweb/civetweb/issues/583 */
  1521. #include "wolfssl_extras.inl"
  1522. #endif
  1523. #if defined(OPENSSL_IS_BORINGSSL)
  1524. /* From boringssl/src/include/openssl/mem.h:
  1525. *
  1526. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1527. * However, that was written in a time before Valgrind and ASAN. Since we now
  1528. * have those tools, the OpenSSL allocation functions are simply macros around
  1529. * the standard memory functions.
  1530. *
  1531. * #define OPENSSL_free free */
  1532. #define free free
  1533. // disable for boringssl
  1534. #define CONF_modules_unload(a) ((void)0)
  1535. #define ENGINE_cleanup() ((void)0)
  1536. #endif
  1537. /* If OpenSSL headers are included, automatically select the API version */
  1538. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1539. #if !defined(OPENSSL_API_3_0)
  1540. #define OPENSSL_API_3_0
  1541. #endif
  1542. #define OPENSSL_REMOVE_THREAD_STATE()
  1543. #else
  1544. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1545. #if !defined(OPENSSL_API_1_1)
  1546. #define OPENSSL_API_1_1
  1547. #endif
  1548. #define OPENSSL_REMOVE_THREAD_STATE()
  1549. #else
  1550. #if !defined(OPENSSL_API_1_0)
  1551. #define OPENSSL_API_1_0
  1552. #endif
  1553. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1554. #endif
  1555. #endif
  1556. #else
  1557. /* SSL loaded dynamically from DLL / shared object */
  1558. /* Add all prototypes here, to be independent from OpenSSL source
  1559. * installation. */
  1560. #include "openssl_dl.inl"
  1561. #endif /* Various SSL bindings */
  1562. #if !defined(NO_CACHING)
  1563. static const char month_names[][4] = {"Jan",
  1564. "Feb",
  1565. "Mar",
  1566. "Apr",
  1567. "May",
  1568. "Jun",
  1569. "Jul",
  1570. "Aug",
  1571. "Sep",
  1572. "Oct",
  1573. "Nov",
  1574. "Dec"};
  1575. #endif /* !NO_CACHING */
  1576. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1577. * the union u. */
  1578. union usa {
  1579. struct sockaddr sa;
  1580. struct sockaddr_in sin;
  1581. #if defined(USE_IPV6)
  1582. struct sockaddr_in6 sin6;
  1583. #endif
  1584. #if defined(USE_X_DOM_SOCKET)
  1585. struct sockaddr_un sun;
  1586. #endif
  1587. };
  1588. #if defined(USE_X_DOM_SOCKET)
  1589. static unsigned short
  1590. USA_IN_PORT_UNSAFE(union usa *s)
  1591. {
  1592. if (s->sa.sa_family == AF_INET)
  1593. return s->sin.sin_port;
  1594. #if defined(USE_IPV6)
  1595. if (s->sa.sa_family == AF_INET6)
  1596. return s->sin6.sin6_port;
  1597. #endif
  1598. return 0;
  1599. }
  1600. #endif
  1601. #if defined(USE_IPV6)
  1602. #define USA_IN_PORT_UNSAFE(s) \
  1603. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1604. #else
  1605. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1606. #endif
  1607. /* Describes a string (chunk of memory). */
  1608. struct vec {
  1609. const char *ptr;
  1610. size_t len;
  1611. };
  1612. struct mg_file_stat {
  1613. /* File properties filled by mg_stat: */
  1614. uint64_t size;
  1615. time_t last_modified;
  1616. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1617. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1618. * case we need a "Content-Eencoding: gzip" header */
  1619. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1620. };
  1621. struct mg_file_access {
  1622. /* File properties filled by mg_fopen: */
  1623. FILE *fp;
  1624. };
  1625. struct mg_file {
  1626. struct mg_file_stat stat;
  1627. struct mg_file_access access;
  1628. };
  1629. #define STRUCT_FILE_INITIALIZER \
  1630. { \
  1631. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1632. { \
  1633. (FILE *)NULL \
  1634. } \
  1635. }
  1636. /* Describes listening socket, or socket which was accept()-ed by the master
  1637. * thread and queued for future handling by the worker thread. */
  1638. struct socket {
  1639. SOCKET sock; /* Listening socket */
  1640. union usa lsa; /* Local socket address */
  1641. union usa rsa; /* Remote socket address */
  1642. unsigned char is_ssl; /* Is port SSL-ed */
  1643. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1644. * port */
  1645. unsigned char
  1646. is_optional; /* Shouldn't cause us to exit if we can't bind to it */
  1647. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1648. };
  1649. /* Enum const for all options must be in sync with
  1650. * static struct mg_option config_options[]
  1651. * This is tested in the unit test (test/private.c)
  1652. * "Private Config Options"
  1653. */
  1654. enum {
  1655. /* Once for each server */
  1656. LISTENING_PORTS,
  1657. NUM_THREADS,
  1658. PRESPAWN_THREADS,
  1659. RUN_AS_USER,
  1660. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1661. * socket option typedef TCP_NODELAY. */
  1662. MAX_REQUEST_SIZE,
  1663. LINGER_TIMEOUT,
  1664. CONNECTION_QUEUE_SIZE,
  1665. LISTEN_BACKLOG_SIZE,
  1666. #if defined(__linux__)
  1667. ALLOW_SENDFILE_CALL,
  1668. #endif
  1669. #if defined(_WIN32)
  1670. CASE_SENSITIVE_FILES,
  1671. #endif
  1672. THROTTLE,
  1673. ENABLE_KEEP_ALIVE,
  1674. REQUEST_TIMEOUT,
  1675. KEEP_ALIVE_TIMEOUT,
  1676. #if defined(USE_WEBSOCKET)
  1677. WEBSOCKET_TIMEOUT,
  1678. ENABLE_WEBSOCKET_PING_PONG,
  1679. #endif
  1680. DECODE_URL,
  1681. DECODE_QUERY_STRING,
  1682. #if defined(USE_LUA)
  1683. LUA_BACKGROUND_SCRIPT,
  1684. LUA_BACKGROUND_SCRIPT_PARAMS,
  1685. #endif
  1686. #if defined(USE_HTTP2)
  1687. ENABLE_HTTP2,
  1688. #endif
  1689. /* Once for each domain */
  1690. DOCUMENT_ROOT,
  1691. FALLBACK_DOCUMENT_ROOT,
  1692. ACCESS_LOG_FILE,
  1693. ERROR_LOG_FILE,
  1694. CGI_EXTENSIONS,
  1695. CGI_ENVIRONMENT,
  1696. CGI_INTERPRETER,
  1697. CGI_INTERPRETER_ARGS,
  1698. #if defined(USE_TIMERS)
  1699. CGI_TIMEOUT,
  1700. #endif
  1701. CGI_BUFFERING,
  1702. CGI2_EXTENSIONS,
  1703. CGI2_ENVIRONMENT,
  1704. CGI2_INTERPRETER,
  1705. CGI2_INTERPRETER_ARGS,
  1706. #if defined(USE_TIMERS)
  1707. CGI2_TIMEOUT,
  1708. #endif
  1709. CGI2_BUFFERING,
  1710. #if defined(USE_4_CGI)
  1711. CGI3_EXTENSIONS,
  1712. CGI3_ENVIRONMENT,
  1713. CGI3_INTERPRETER,
  1714. CGI3_INTERPRETER_ARGS,
  1715. #if defined(USE_TIMERS)
  1716. CGI3_TIMEOUT,
  1717. #endif
  1718. CGI3_BUFFERING,
  1719. CGI4_EXTENSIONS,
  1720. CGI4_ENVIRONMENT,
  1721. CGI4_INTERPRETER,
  1722. CGI4_INTERPRETER_ARGS,
  1723. #if defined(USE_TIMERS)
  1724. CGI4_TIMEOUT,
  1725. #endif
  1726. CGI4_BUFFERING,
  1727. #endif
  1728. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1729. PROTECT_URI,
  1730. AUTHENTICATION_DOMAIN,
  1731. ENABLE_AUTH_DOMAIN_CHECK,
  1732. SSI_EXTENSIONS,
  1733. ENABLE_DIRECTORY_LISTING,
  1734. ENABLE_WEBDAV,
  1735. GLOBAL_PASSWORDS_FILE,
  1736. INDEX_FILES,
  1737. ACCESS_CONTROL_LIST,
  1738. EXTRA_MIME_TYPES,
  1739. SSL_CERTIFICATE,
  1740. SSL_CERTIFICATE_CHAIN,
  1741. URL_REWRITE_PATTERN,
  1742. HIDE_FILES,
  1743. SSL_DO_VERIFY_PEER,
  1744. SSL_CACHE_TIMEOUT,
  1745. SSL_CA_PATH,
  1746. SSL_CA_FILE,
  1747. SSL_VERIFY_DEPTH,
  1748. SSL_DEFAULT_VERIFY_PATHS,
  1749. SSL_CIPHER_LIST,
  1750. SSL_PROTOCOL_VERSION,
  1751. SSL_SHORT_TRUST,
  1752. #if defined(USE_LUA)
  1753. LUA_PRELOAD_FILE,
  1754. LUA_SCRIPT_EXTENSIONS,
  1755. LUA_SERVER_PAGE_EXTENSIONS,
  1756. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1757. LUA_DEBUG_PARAMS,
  1758. #endif
  1759. #endif
  1760. #if defined(USE_DUKTAPE)
  1761. DUKTAPE_SCRIPT_EXTENSIONS,
  1762. #endif
  1763. #if defined(USE_WEBSOCKET)
  1764. WEBSOCKET_ROOT,
  1765. FALLBACK_WEBSOCKET_ROOT,
  1766. #endif
  1767. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1768. LUA_WEBSOCKET_EXTENSIONS,
  1769. #endif
  1770. ACCESS_CONTROL_ALLOW_ORIGIN,
  1771. ACCESS_CONTROL_ALLOW_METHODS,
  1772. ACCESS_CONTROL_ALLOW_HEADERS,
  1773. ACCESS_CONTROL_EXPOSE_HEADERS,
  1774. ACCESS_CONTROL_ALLOW_CREDENTIALS,
  1775. ERROR_PAGES,
  1776. #if !defined(NO_CACHING)
  1777. STATIC_FILE_MAX_AGE,
  1778. STATIC_FILE_CACHE_CONTROL,
  1779. #endif
  1780. #if !defined(NO_SSL)
  1781. STRICT_HTTPS_MAX_AGE,
  1782. #endif
  1783. ADDITIONAL_HEADER,
  1784. ALLOW_INDEX_SCRIPT_SUB_RES,
  1785. NUM_OPTIONS
  1786. };
  1787. /* Config option name, config types, default value.
  1788. * Must be in the same order as the enum const above.
  1789. */
  1790. static const struct mg_option config_options[] = {
  1791. /* Once for each server */
  1792. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1793. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1794. {"prespawn_threads", MG_CONFIG_TYPE_NUMBER, "0"},
  1795. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1796. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1797. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1798. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1799. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1800. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1801. #if defined(__linux__)
  1802. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1803. #endif
  1804. #if defined(_WIN32)
  1805. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1806. #endif
  1807. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1808. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1809. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1810. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1811. #if defined(USE_WEBSOCKET)
  1812. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1813. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1814. #endif
  1815. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1816. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1817. #if defined(USE_LUA)
  1818. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1819. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1820. #endif
  1821. #if defined(USE_HTTP2)
  1822. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1823. #endif
  1824. /* Once for each domain */
  1825. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1826. {"fallback_document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1827. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1828. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1829. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1830. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1831. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1832. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1833. #if defined(USE_TIMERS)
  1834. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1835. #endif
  1836. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1837. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1838. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1839. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1840. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1841. #if defined(USE_TIMERS)
  1842. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1843. #endif
  1844. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1845. #if defined(USE_4_CGI)
  1846. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1847. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1848. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1849. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1850. #if defined(USE_TIMERS)
  1851. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1852. #endif
  1853. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1854. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1855. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1856. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1857. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1858. #if defined(USE_TIMERS)
  1859. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1860. #endif
  1861. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1862. #endif
  1863. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1864. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1865. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1866. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1867. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1868. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1869. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1870. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1871. {"index_files",
  1872. MG_CONFIG_TYPE_STRING_LIST,
  1873. #if defined(USE_LUA)
  1874. "index.xhtml,index.html,index.htm,"
  1875. "index.lp,index.lsp,index.lua,index.cgi,"
  1876. "index.shtml,index.php"},
  1877. #else
  1878. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1879. #endif
  1880. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1881. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1882. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1883. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1884. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1885. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1886. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1887. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1888. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1889. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1890. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1891. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1892. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1893. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1894. * as a minimum in 2020 */
  1895. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1896. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1897. #if defined(USE_LUA)
  1898. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1899. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1900. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1901. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1902. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1903. #endif
  1904. #endif
  1905. #if defined(USE_DUKTAPE)
  1906. /* The support for duktape is still in alpha version state.
  1907. * The name of this config option might change. */
  1908. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1909. #endif
  1910. #if defined(USE_WEBSOCKET)
  1911. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1912. {"fallback_websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1913. #endif
  1914. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1915. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1916. #endif
  1917. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1918. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1919. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1920. {"access_control_expose_headers", MG_CONFIG_TYPE_STRING, ""},
  1921. {"access_control_allow_credentials", MG_CONFIG_TYPE_STRING, ""},
  1922. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1923. #if !defined(NO_CACHING)
  1924. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1925. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1926. #endif
  1927. #if !defined(NO_SSL)
  1928. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1929. #endif
  1930. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1931. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1932. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1933. /* Check if the config_options and the corresponding enum have compatible
  1934. * sizes. */
  1935. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1936. == (NUM_OPTIONS + 1),
  1937. "config_options and enum not sync");
  1938. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1939. struct mg_handler_info {
  1940. /* Name/Pattern of the URI. */
  1941. char *uri;
  1942. size_t uri_len;
  1943. /* handler type */
  1944. int handler_type;
  1945. /* Handler for http/https or requests. */
  1946. mg_request_handler handler;
  1947. unsigned int refcount;
  1948. int removing;
  1949. /* Handler for ws/wss (websocket) requests. */
  1950. mg_websocket_connect_handler connect_handler;
  1951. mg_websocket_ready_handler ready_handler;
  1952. mg_websocket_data_handler data_handler;
  1953. mg_websocket_close_handler close_handler;
  1954. /* accepted subprotocols for ws/wss requests. */
  1955. struct mg_websocket_subprotocols *subprotocols;
  1956. /* Handler for authorization requests */
  1957. mg_authorization_handler auth_handler;
  1958. /* User supplied argument for the handler function. */
  1959. void *cbdata;
  1960. /* next handler in a linked list */
  1961. struct mg_handler_info *next;
  1962. };
  1963. enum {
  1964. CONTEXT_INVALID,
  1965. CONTEXT_SERVER,
  1966. CONTEXT_HTTP_CLIENT,
  1967. CONTEXT_WS_CLIENT
  1968. };
  1969. struct mg_domain_context {
  1970. SSL_CTX *ssl_ctx; /* SSL context */
  1971. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1972. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1973. int64_t ssl_cert_last_mtime;
  1974. /* Server nonce */
  1975. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1976. unsigned long nonce_count; /* Used nonces, used for authentication */
  1977. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1978. /* linked list of shared lua websockets */
  1979. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1980. #endif
  1981. /* Linked list of domains */
  1982. struct mg_domain_context *next;
  1983. };
  1984. /* Stop flag can be "volatile" or require a lock.
  1985. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1986. * states a read operation for int is always atomic. */
  1987. #if defined(STOP_FLAG_NEEDS_LOCK)
  1988. typedef ptrdiff_t volatile stop_flag_t;
  1989. static int
  1990. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1991. {
  1992. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1993. return (sf == 0);
  1994. }
  1995. static int
  1996. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1997. {
  1998. stop_flag_t sf = mg_atomic_add(f, 0);
  1999. return (sf == 2);
  2000. }
  2001. static void
  2002. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2003. {
  2004. stop_flag_t sf = 0;
  2005. do {
  2006. sf = mg_atomic_compare_and_swap(f, *f, v);
  2007. } while (sf != v);
  2008. }
  2009. #else /* STOP_FLAG_NEEDS_LOCK */
  2010. typedef int volatile stop_flag_t;
  2011. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2012. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2013. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2014. #endif /* STOP_FLAG_NEEDS_LOCK */
  2015. #if !defined(NUM_WEBDAV_LOCKS)
  2016. #define NUM_WEBDAV_LOCKS 10
  2017. #endif
  2018. #if !defined(LOCK_DURATION_S)
  2019. #define LOCK_DURATION_S 60
  2020. #endif
  2021. struct twebdav_lock {
  2022. uint64_t locktime;
  2023. char token[33];
  2024. char path[UTF8_PATH_MAX * 2];
  2025. char user[UTF8_PATH_MAX * 2];
  2026. };
  2027. struct mg_context {
  2028. /* Part 1 - Physical context:
  2029. * This holds threads, ports, timeouts, ...
  2030. * set for the entire server, independent from the
  2031. * addressed hostname.
  2032. */
  2033. /* Connection related */
  2034. int context_type; /* See CONTEXT_* above */
  2035. struct socket *listening_sockets;
  2036. struct mg_pollfd *listening_socket_fds;
  2037. unsigned int num_listening_sockets;
  2038. struct mg_connection *worker_connections; /* The connection struct, pre-
  2039. * allocated for each worker */
  2040. #if defined(USE_SERVER_STATS)
  2041. volatile ptrdiff_t active_connections;
  2042. volatile ptrdiff_t max_active_connections;
  2043. volatile ptrdiff_t total_connections;
  2044. volatile ptrdiff_t total_requests;
  2045. volatile int64_t total_data_read;
  2046. volatile int64_t total_data_written;
  2047. #endif
  2048. /* Thread related */
  2049. stop_flag_t stop_flag; /* Should we stop event loop */
  2050. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2051. pthread_t masterthreadid; /* The master thread ID */
  2052. unsigned int cfg_max_worker_threads; /* How many worker-threads we are
  2053. allowed to create, total */
  2054. unsigned int spawned_worker_threads; /* How many worker-threads currently
  2055. exist (modified by master thread) */
  2056. unsigned int
  2057. idle_worker_thread_count; /* How many worker-threads are currently
  2058. sitting around with nothing to do */
  2059. /* Access to this value MUST be synchronized by thread_mutex */
  2060. pthread_t *worker_threadids; /* The worker thread IDs */
  2061. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2062. /* Connection to thread dispatching */
  2063. #if defined(ALTERNATIVE_QUEUE)
  2064. struct socket *client_socks;
  2065. void **client_wait_events;
  2066. #else
  2067. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2068. worker thread */
  2069. volatile int sq_head; /* Head of the socket queue */
  2070. volatile int sq_tail; /* Tail of the socket queue */
  2071. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2072. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2073. volatile int sq_blocked; /* Status information: sq is full */
  2074. int sq_size; /* No of elements in socket queue */
  2075. #if defined(USE_SERVER_STATS)
  2076. int sq_max_fill;
  2077. #endif /* USE_SERVER_STATS */
  2078. #endif /* ALTERNATIVE_QUEUE */
  2079. /* Memory related */
  2080. unsigned int max_request_size; /* The max request size */
  2081. #if defined(USE_SERVER_STATS)
  2082. struct mg_memory_stat ctx_memory;
  2083. #endif
  2084. /* WebDAV lock structures */
  2085. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2086. /* Operating system related */
  2087. char *systemName; /* What operating system is running */
  2088. time_t start_time; /* Server start time, used for authentication
  2089. * and for diagnstics. */
  2090. #if defined(USE_TIMERS)
  2091. struct ttimers *timers;
  2092. #endif
  2093. /* Lua specific: Background operations and shared websockets */
  2094. #if defined(USE_LUA)
  2095. void *lua_background_state; /* lua_State (here as void *) */
  2096. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2097. int lua_bg_log_available; /* Use Lua background state for access log */
  2098. #endif
  2099. int user_shutdown_notification_socket; /* mg_stop() will close this
  2100. socket... */
  2101. int thread_shutdown_notification_socket; /* to cause poll() in all threads
  2102. to return immediately */
  2103. /* Server nonce */
  2104. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2105. * ssl_cert_last_mtime, nonce_count, and
  2106. * next (linked list) */
  2107. /* Server callbacks */
  2108. struct mg_callbacks callbacks; /* User-defined callback function */
  2109. void *user_data; /* User-defined data */
  2110. /* Part 2 - Logical domain:
  2111. * This holds hostname, TLS certificate, document root, ...
  2112. * set for a domain hosted at the server.
  2113. * There may be multiple domains hosted at one physical server.
  2114. * The default domain "dd" is the first element of a list of
  2115. * domains.
  2116. */
  2117. struct mg_domain_context dd; /* default domain */
  2118. };
  2119. #if defined(USE_SERVER_STATS)
  2120. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2121. static struct mg_memory_stat *
  2122. get_memory_stat(struct mg_context *ctx)
  2123. {
  2124. if (ctx) {
  2125. return &(ctx->ctx_memory);
  2126. }
  2127. return &mg_common_memory;
  2128. }
  2129. #endif
  2130. enum {
  2131. CONNECTION_TYPE_INVALID = 0,
  2132. CONNECTION_TYPE_REQUEST = 1,
  2133. CONNECTION_TYPE_RESPONSE = 2
  2134. };
  2135. enum {
  2136. PROTOCOL_TYPE_HTTP1 = 0,
  2137. PROTOCOL_TYPE_WEBSOCKET = 1,
  2138. PROTOCOL_TYPE_HTTP2 = 2
  2139. };
  2140. #if defined(USE_HTTP2)
  2141. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2142. #define HTTP2_DYN_TABLE_SIZE (256)
  2143. #endif
  2144. struct mg_http2_connection {
  2145. uint32_t stream_id;
  2146. uint32_t dyn_table_size;
  2147. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2148. };
  2149. #endif
  2150. struct mg_connection {
  2151. int connection_type; /* see CONNECTION_TYPE_* above */
  2152. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2153. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2154. fully sent */
  2155. #if defined(USE_HTTP2)
  2156. struct mg_http2_connection http2;
  2157. #endif
  2158. struct mg_request_info request_info;
  2159. struct mg_response_info response_info;
  2160. struct mg_context *phys_ctx;
  2161. struct mg_domain_context *dom_ctx;
  2162. #if defined(USE_SERVER_STATS)
  2163. int conn_state; /* 0 = undef, numerical value may change in different
  2164. * versions. For the current definition, see
  2165. * mg_get_connection_info_impl */
  2166. #endif
  2167. SSL *ssl; /* SSL descriptor */
  2168. struct socket client; /* Connected client */
  2169. time_t conn_birth_time; /* Time (wall clock) when connection was
  2170. * established */
  2171. #if defined(USE_SERVER_STATS)
  2172. time_t conn_close_time; /* Time (wall clock) when connection was
  2173. * closed (or 0 if still open) */
  2174. double processing_time; /* Processing time for one request. */
  2175. #endif
  2176. struct timespec req_time; /* Time (since system start) when the request
  2177. * was received */
  2178. int64_t num_bytes_sent; /* Total bytes sent to client */
  2179. int64_t content_len; /* How many bytes of content can be read
  2180. * !is_chunked: Content-Length header value
  2181. * or -1 (until connection closed,
  2182. * not allowed for a request)
  2183. * is_chunked: >= 0, appended gradually
  2184. */
  2185. int64_t consumed_content; /* How many bytes of content have been read */
  2186. int is_chunked; /* Transfer-Encoding is chunked:
  2187. * 0 = not chunked,
  2188. * 1 = chunked, not yet, or some data read,
  2189. * 2 = chunked, has error,
  2190. * 3 = chunked, all data read except trailer,
  2191. * 4 = chunked, all data read
  2192. */
  2193. char *buf; /* Buffer for received data */
  2194. char *path_info; /* PATH_INFO part of the URL */
  2195. int must_close; /* 1 if connection must be closed */
  2196. int accept_gzip; /* 1 if gzip encoding is accepted */
  2197. int in_error_handler; /* 1 if in handler for user defined error
  2198. * pages */
  2199. #if defined(USE_WEBSOCKET)
  2200. int in_websocket_handling; /* 1 if in read_websocket */
  2201. #endif
  2202. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2203. && defined(MG_EXPERIMENTAL_INTERFACES)
  2204. /* Parameters for websocket data compression according to rfc7692 */
  2205. int websocket_deflate_server_max_windows_bits;
  2206. int websocket_deflate_client_max_windows_bits;
  2207. int websocket_deflate_server_no_context_takeover;
  2208. int websocket_deflate_client_no_context_takeover;
  2209. int websocket_deflate_initialized;
  2210. int websocket_deflate_flush;
  2211. z_stream websocket_deflate_state;
  2212. z_stream websocket_inflate_state;
  2213. #endif
  2214. int handled_requests; /* Number of requests handled by this connection
  2215. */
  2216. int buf_size; /* Buffer size */
  2217. int request_len; /* Size of the request + headers in a buffer */
  2218. int data_len; /* Total size of data in a buffer */
  2219. int status_code; /* HTTP reply status code, e.g. 200 */
  2220. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2221. * throttle */
  2222. time_t last_throttle_time; /* Last time throttled data was sent */
  2223. int last_throttle_bytes; /* Bytes sent this second */
  2224. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2225. * atomic transmissions for websockets */
  2226. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2227. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2228. #endif
  2229. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2230. * for quick access */
  2231. };
  2232. /* Directory entry */
  2233. struct de {
  2234. char *file_name;
  2235. struct mg_file_stat file;
  2236. };
  2237. #define mg_cry_internal(conn, fmt, ...) \
  2238. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2239. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2240. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2241. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2242. struct mg_context *ctx,
  2243. const char *func,
  2244. unsigned line,
  2245. const char *fmt,
  2246. ...) PRINTF_ARGS(5, 6);
  2247. #if !defined(NO_THREAD_NAME)
  2248. #if defined(_WIN32) && defined(_MSC_VER)
  2249. /* Set the thread name for debugging purposes in Visual Studio
  2250. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2251. */
  2252. #pragma pack(push, 8)
  2253. typedef struct tagTHREADNAME_INFO {
  2254. DWORD dwType; /* Must be 0x1000. */
  2255. LPCSTR szName; /* Pointer to name (in user addr space). */
  2256. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2257. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2258. } THREADNAME_INFO;
  2259. #pragma pack(pop)
  2260. #elif defined(__linux__)
  2261. #include <sys/prctl.h>
  2262. #include <sys/sendfile.h>
  2263. #if defined(ALTERNATIVE_QUEUE)
  2264. #include <sys/eventfd.h>
  2265. #endif /* ALTERNATIVE_QUEUE */
  2266. #if defined(ALTERNATIVE_QUEUE)
  2267. static void *
  2268. event_create(void)
  2269. {
  2270. int evhdl = eventfd(0, EFD_CLOEXEC);
  2271. int *ret;
  2272. if (evhdl == -1) {
  2273. /* Linux uses -1 on error, Windows NULL. */
  2274. /* However, Linux does not return 0 on success either. */
  2275. return 0;
  2276. }
  2277. ret = (int *)mg_malloc(sizeof(int));
  2278. if (ret) {
  2279. *ret = evhdl;
  2280. } else {
  2281. (void)close(evhdl);
  2282. }
  2283. return (void *)ret;
  2284. }
  2285. static int
  2286. event_wait(void *eventhdl)
  2287. {
  2288. uint64_t u;
  2289. int evhdl, s;
  2290. if (!eventhdl) {
  2291. /* error */
  2292. return 0;
  2293. }
  2294. evhdl = *(int *)eventhdl;
  2295. s = (int)read(evhdl, &u, sizeof(u));
  2296. if (s != sizeof(u)) {
  2297. /* error */
  2298. return 0;
  2299. }
  2300. (void)u; /* the value is not required */
  2301. return 1;
  2302. }
  2303. static int
  2304. event_signal(void *eventhdl)
  2305. {
  2306. uint64_t u = 1;
  2307. int evhdl, s;
  2308. if (!eventhdl) {
  2309. /* error */
  2310. return 0;
  2311. }
  2312. evhdl = *(int *)eventhdl;
  2313. s = (int)write(evhdl, &u, sizeof(u));
  2314. if (s != sizeof(u)) {
  2315. /* error */
  2316. return 0;
  2317. }
  2318. return 1;
  2319. }
  2320. static void
  2321. event_destroy(void *eventhdl)
  2322. {
  2323. int evhdl;
  2324. if (!eventhdl) {
  2325. /* error */
  2326. return;
  2327. }
  2328. evhdl = *(int *)eventhdl;
  2329. close(evhdl);
  2330. mg_free(eventhdl);
  2331. }
  2332. #endif
  2333. #endif
  2334. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2335. struct posix_event {
  2336. pthread_mutex_t mutex;
  2337. pthread_cond_t cond;
  2338. int signaled;
  2339. };
  2340. static void *
  2341. event_create(void)
  2342. {
  2343. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2344. if (ret == 0) {
  2345. /* out of memory */
  2346. return 0;
  2347. }
  2348. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2349. /* pthread mutex not available */
  2350. mg_free(ret);
  2351. return 0;
  2352. }
  2353. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2354. /* pthread cond not available */
  2355. pthread_mutex_destroy(&(ret->mutex));
  2356. mg_free(ret);
  2357. return 0;
  2358. }
  2359. ret->signaled = 0;
  2360. return (void *)ret;
  2361. }
  2362. static int
  2363. event_wait(void *eventhdl)
  2364. {
  2365. struct posix_event *ev = (struct posix_event *)eventhdl;
  2366. pthread_mutex_lock(&(ev->mutex));
  2367. while (!ev->signaled) {
  2368. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2369. }
  2370. ev->signaled = 0;
  2371. pthread_mutex_unlock(&(ev->mutex));
  2372. return 1;
  2373. }
  2374. static int
  2375. event_signal(void *eventhdl)
  2376. {
  2377. struct posix_event *ev = (struct posix_event *)eventhdl;
  2378. pthread_mutex_lock(&(ev->mutex));
  2379. pthread_cond_signal(&(ev->cond));
  2380. ev->signaled = 1;
  2381. pthread_mutex_unlock(&(ev->mutex));
  2382. return 1;
  2383. }
  2384. static void
  2385. event_destroy(void *eventhdl)
  2386. {
  2387. struct posix_event *ev = (struct posix_event *)eventhdl;
  2388. pthread_cond_destroy(&(ev->cond));
  2389. pthread_mutex_destroy(&(ev->mutex));
  2390. mg_free(ev);
  2391. }
  2392. #endif
  2393. static void
  2394. mg_set_thread_name(const char *name)
  2395. {
  2396. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2397. mg_snprintf(
  2398. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2399. #if defined(_WIN32)
  2400. #if defined(_MSC_VER)
  2401. /* Windows and Visual Studio Compiler */
  2402. __try {
  2403. THREADNAME_INFO info;
  2404. info.dwType = 0x1000;
  2405. info.szName = threadName;
  2406. info.dwThreadID = ~0U;
  2407. info.dwFlags = 0;
  2408. RaiseException(0x406D1388,
  2409. 0,
  2410. sizeof(info) / sizeof(ULONG_PTR),
  2411. (ULONG_PTR *)&info);
  2412. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2413. }
  2414. #elif defined(__MINGW32__)
  2415. /* No option known to set thread name for MinGW known */
  2416. #endif
  2417. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2418. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2419. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2420. #if defined(__MACH__) && defined(__APPLE__)
  2421. /* OS X only current thread name can be changed */
  2422. (void)pthread_setname_np(threadName);
  2423. #else
  2424. (void)pthread_setname_np(pthread_self(), threadName);
  2425. #endif
  2426. #elif defined(__linux__)
  2427. /* On Linux we can use the prctl function.
  2428. * When building for Linux Standard Base (LSB) use
  2429. * NO_THREAD_NAME. However, thread names are a big
  2430. * help for debugging, so the stadard is to set them.
  2431. */
  2432. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2433. #endif
  2434. }
  2435. #else /* !defined(NO_THREAD_NAME) */
  2436. static void
  2437. mg_set_thread_name(const char *threadName)
  2438. {
  2439. }
  2440. #endif
  2441. CIVETWEB_API const struct mg_option *
  2442. mg_get_valid_options(void)
  2443. {
  2444. return config_options;
  2445. }
  2446. /* Do not open file (unused) */
  2447. #define MG_FOPEN_MODE_NONE (0)
  2448. /* Open file for read only access */
  2449. #define MG_FOPEN_MODE_READ (1)
  2450. /* Open file for writing, create and overwrite */
  2451. #define MG_FOPEN_MODE_WRITE (2)
  2452. /* Open file for writing, create and append */
  2453. #define MG_FOPEN_MODE_APPEND (4)
  2454. static int
  2455. is_file_opened(const struct mg_file_access *fileacc)
  2456. {
  2457. if (!fileacc) {
  2458. return 0;
  2459. }
  2460. return (fileacc->fp != NULL);
  2461. }
  2462. #if !defined(NO_FILESYSTEMS)
  2463. static int mg_stat(const struct mg_connection *conn,
  2464. const char *path,
  2465. struct mg_file_stat *filep);
  2466. /* Reject files with special characters (for Windows) */
  2467. static int
  2468. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2469. {
  2470. const uint8_t *c = (const uint8_t *)path;
  2471. (void)conn; /* not used */
  2472. if ((c == NULL) || (c[0] == 0)) {
  2473. /* Null pointer or empty path --> suspicious */
  2474. return 1;
  2475. }
  2476. #if defined(_WIN32)
  2477. while (*c) {
  2478. if (*c < 32) {
  2479. /* Control character */
  2480. return 1;
  2481. }
  2482. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2483. /* stdin/stdout redirection character */
  2484. return 1;
  2485. }
  2486. if ((*c == '*') || (*c == '?')) {
  2487. /* Wildcard character */
  2488. return 1;
  2489. }
  2490. if (*c == '"') {
  2491. /* Windows quotation */
  2492. return 1;
  2493. }
  2494. c++;
  2495. }
  2496. #endif
  2497. /* Nothing suspicious found */
  2498. return 0;
  2499. }
  2500. /* mg_fopen will open a file either in memory or on the disk.
  2501. * The input parameter path is a string in UTF-8 encoding.
  2502. * The input parameter mode is MG_FOPEN_MODE_*
  2503. * On success, fp will be set in the output struct mg_file.
  2504. * All status members will also be set.
  2505. * The function returns 1 on success, 0 on error. */
  2506. static int
  2507. mg_fopen(const struct mg_connection *conn,
  2508. const char *path,
  2509. int mode,
  2510. struct mg_file *filep)
  2511. {
  2512. int found;
  2513. if (!filep) {
  2514. return 0;
  2515. }
  2516. filep->access.fp = NULL;
  2517. if (mg_path_suspicious(conn, path)) {
  2518. return 0;
  2519. }
  2520. /* filep is initialized in mg_stat: all fields with memset to,
  2521. * some fields like size and modification date with values */
  2522. found = mg_stat(conn, path, &(filep->stat));
  2523. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2524. /* file does not exist and will not be created */
  2525. return 0;
  2526. }
  2527. #if defined(_WIN32)
  2528. {
  2529. wchar_t wbuf[UTF16_PATH_MAX];
  2530. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2531. switch (mode) {
  2532. case MG_FOPEN_MODE_READ:
  2533. filep->access.fp = _wfopen(wbuf, L"rb");
  2534. break;
  2535. case MG_FOPEN_MODE_WRITE:
  2536. filep->access.fp = _wfopen(wbuf, L"wb");
  2537. break;
  2538. case MG_FOPEN_MODE_APPEND:
  2539. filep->access.fp = _wfopen(wbuf, L"ab");
  2540. break;
  2541. }
  2542. }
  2543. #else
  2544. /* Linux et al already use unicode. No need to convert. */
  2545. switch (mode) {
  2546. case MG_FOPEN_MODE_READ:
  2547. filep->access.fp = fopen(path, "r");
  2548. break;
  2549. case MG_FOPEN_MODE_WRITE:
  2550. filep->access.fp = fopen(path, "w");
  2551. break;
  2552. case MG_FOPEN_MODE_APPEND:
  2553. filep->access.fp = fopen(path, "a");
  2554. break;
  2555. }
  2556. #endif
  2557. if (!found) {
  2558. /* File did not exist before fopen was called.
  2559. * Maybe it has been created now. Get stat info
  2560. * like creation time now. */
  2561. found = mg_stat(conn, path, &(filep->stat));
  2562. (void)found;
  2563. }
  2564. /* return OK if file is opened */
  2565. return (filep->access.fp != NULL);
  2566. }
  2567. /* return 0 on success, just like fclose */
  2568. static int
  2569. mg_fclose(struct mg_file_access *fileacc)
  2570. {
  2571. int ret = -1;
  2572. if (fileacc != NULL) {
  2573. if (fileacc->fp != NULL) {
  2574. ret = fclose(fileacc->fp);
  2575. }
  2576. /* reset all members of fileacc */
  2577. memset(fileacc, 0, sizeof(*fileacc));
  2578. }
  2579. return ret;
  2580. }
  2581. #endif /* NO_FILESYSTEMS */
  2582. static void
  2583. mg_strlcpy(char *dst, const char *src, size_t n)
  2584. {
  2585. for (; *src != '\0' && n > 1; n--) {
  2586. *dst++ = *src++;
  2587. }
  2588. *dst = '\0';
  2589. }
  2590. static int
  2591. lowercase(const char *s)
  2592. {
  2593. return tolower((unsigned char)*s);
  2594. }
  2595. CIVETWEB_API int
  2596. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2597. {
  2598. int diff = 0;
  2599. if (len > 0) {
  2600. do {
  2601. diff = lowercase(s1++) - lowercase(s2++);
  2602. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2603. }
  2604. return diff;
  2605. }
  2606. CIVETWEB_API int
  2607. mg_strcasecmp(const char *s1, const char *s2)
  2608. {
  2609. int diff;
  2610. do {
  2611. diff = lowercase(s1++) - lowercase(s2++);
  2612. } while (diff == 0 && s1[-1] != '\0');
  2613. return diff;
  2614. }
  2615. static char *
  2616. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2617. {
  2618. char *p;
  2619. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2620. * defined */
  2621. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2622. mg_strlcpy(p, ptr, len + 1);
  2623. }
  2624. return p;
  2625. }
  2626. static char *
  2627. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2628. {
  2629. return mg_strndup_ctx(str, strlen(str), ctx);
  2630. }
  2631. static char *
  2632. mg_strdup(const char *str)
  2633. {
  2634. return mg_strndup_ctx(str, strlen(str), NULL);
  2635. }
  2636. static const char *
  2637. mg_strcasestr(const char *big_str, const char *small_str)
  2638. {
  2639. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2640. if (big_len >= small_len) {
  2641. for (i = 0; i <= (big_len - small_len); i++) {
  2642. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2643. return big_str + i;
  2644. }
  2645. }
  2646. }
  2647. return NULL;
  2648. }
  2649. /* Return null terminated string of given maximum length.
  2650. * Report errors if length is exceeded. */
  2651. static void
  2652. mg_vsnprintf(const struct mg_connection *conn,
  2653. int *truncated,
  2654. char *buf,
  2655. size_t buflen,
  2656. const char *fmt,
  2657. va_list ap)
  2658. {
  2659. int n, ok;
  2660. if (buflen == 0) {
  2661. if (truncated) {
  2662. *truncated = 1;
  2663. }
  2664. return;
  2665. }
  2666. #if defined(__clang__)
  2667. #pragma clang diagnostic push
  2668. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2669. /* Using fmt as a non-literal is intended here, since it is mostly called
  2670. * indirectly by mg_snprintf */
  2671. #endif
  2672. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2673. ok = (n >= 0) && ((size_t)n < buflen);
  2674. #if defined(__clang__)
  2675. #pragma clang diagnostic pop
  2676. #endif
  2677. if (ok) {
  2678. if (truncated) {
  2679. *truncated = 0;
  2680. }
  2681. } else {
  2682. if (truncated) {
  2683. *truncated = 1;
  2684. }
  2685. mg_cry_internal(conn,
  2686. "truncating vsnprintf buffer: [%.*s]",
  2687. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2688. buf);
  2689. n = (int)buflen - 1;
  2690. }
  2691. buf[n] = '\0';
  2692. }
  2693. static void
  2694. mg_snprintf(const struct mg_connection *conn,
  2695. int *truncated,
  2696. char *buf,
  2697. size_t buflen,
  2698. const char *fmt,
  2699. ...)
  2700. {
  2701. va_list ap;
  2702. va_start(ap, fmt);
  2703. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2704. va_end(ap);
  2705. }
  2706. static int
  2707. get_option_index(const char *name)
  2708. {
  2709. int i;
  2710. for (i = 0; config_options[i].name != NULL; i++) {
  2711. if (strcmp(config_options[i].name, name) == 0) {
  2712. return i;
  2713. }
  2714. }
  2715. return -1;
  2716. }
  2717. CIVETWEB_API const char *
  2718. mg_get_option(const struct mg_context *ctx, const char *name)
  2719. {
  2720. int i;
  2721. if ((i = get_option_index(name)) == -1) {
  2722. return NULL;
  2723. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2724. return "";
  2725. } else {
  2726. return ctx->dd.config[i];
  2727. }
  2728. }
  2729. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2730. CIVETWEB_API struct mg_context *
  2731. mg_get_context(const struct mg_connection *conn)
  2732. {
  2733. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2734. }
  2735. CIVETWEB_API void *
  2736. mg_get_user_data(const struct mg_context *ctx)
  2737. {
  2738. return (ctx == NULL) ? NULL : ctx->user_data;
  2739. }
  2740. CIVETWEB_API void *
  2741. mg_get_user_context_data(const struct mg_connection *conn)
  2742. {
  2743. return mg_get_user_data(mg_get_context(conn));
  2744. }
  2745. CIVETWEB_API void *
  2746. mg_get_thread_pointer(const struct mg_connection *conn)
  2747. {
  2748. /* both methods should return the same pointer */
  2749. if (conn) {
  2750. /* quick access, in case conn is known */
  2751. return conn->tls_user_ptr;
  2752. } else {
  2753. /* otherwise get pointer from thread local storage (TLS) */
  2754. struct mg_workerTLS *tls =
  2755. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2756. return tls->user_ptr;
  2757. }
  2758. }
  2759. CIVETWEB_API void
  2760. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2761. {
  2762. if (const_conn != NULL) {
  2763. /* Const cast, since "const struct mg_connection *" does not mean
  2764. * the connection object is not modified. Here "const" is used,
  2765. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2766. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2767. conn->request_info.conn_data = data;
  2768. }
  2769. }
  2770. CIVETWEB_API void *
  2771. mg_get_user_connection_data(const struct mg_connection *conn)
  2772. {
  2773. if (conn != NULL) {
  2774. return conn->request_info.conn_data;
  2775. }
  2776. return NULL;
  2777. }
  2778. CIVETWEB_API int
  2779. mg_get_server_ports(const struct mg_context *ctx,
  2780. int size,
  2781. struct mg_server_port *ports)
  2782. {
  2783. int i, cnt = 0;
  2784. if (size <= 0) {
  2785. return -1;
  2786. }
  2787. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2788. if (!ctx) {
  2789. return -1;
  2790. }
  2791. if (!ctx->listening_sockets) {
  2792. return -1;
  2793. }
  2794. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2795. ports[cnt].port =
  2796. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2797. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2798. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2799. ports[cnt].is_optional = ctx->listening_sockets[i].is_optional;
  2800. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2801. /* IPv4 */
  2802. ports[cnt].protocol = 1;
  2803. cnt++;
  2804. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2805. /* IPv6 */
  2806. ports[cnt].protocol = 3;
  2807. cnt++;
  2808. }
  2809. }
  2810. return cnt;
  2811. }
  2812. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2813. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2814. #endif
  2815. static void
  2816. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2817. {
  2818. buf[0] = '\0';
  2819. if (!usa) {
  2820. return;
  2821. }
  2822. if (usa->sa.sa_family == AF_INET) {
  2823. getnameinfo(&usa->sa,
  2824. sizeof(usa->sin),
  2825. buf,
  2826. (unsigned)len,
  2827. NULL,
  2828. 0,
  2829. NI_NUMERICHOST);
  2830. }
  2831. #if defined(USE_IPV6)
  2832. else if (usa->sa.sa_family == AF_INET6) {
  2833. getnameinfo(&usa->sa,
  2834. sizeof(usa->sin6),
  2835. buf,
  2836. (unsigned)len,
  2837. NULL,
  2838. 0,
  2839. NI_NUMERICHOST);
  2840. }
  2841. #endif
  2842. #if defined(USE_X_DOM_SOCKET)
  2843. else if (usa->sa.sa_family == AF_UNIX) {
  2844. /* TODO: Define a remote address for unix domain sockets.
  2845. * This code will always return "localhost", identical to http+tcp:
  2846. getnameinfo(&usa->sa,
  2847. sizeof(usa->sun),
  2848. buf,
  2849. (unsigned)len,
  2850. NULL,
  2851. 0,
  2852. NI_NUMERICHOST);
  2853. */
  2854. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2855. }
  2856. #endif
  2857. }
  2858. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2859. * included in all responses other than 100, 101, 5xx. */
  2860. static void
  2861. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2862. {
  2863. #if !defined(REENTRANT_TIME)
  2864. struct tm *tm;
  2865. tm = ((t != NULL) ? gmtime(t) : NULL);
  2866. if (tm != NULL) {
  2867. #else
  2868. struct tm _tm;
  2869. struct tm *tm = &_tm;
  2870. if (t != NULL) {
  2871. gmtime_r(t, tm);
  2872. #endif
  2873. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2874. } else {
  2875. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2876. }
  2877. }
  2878. /* difftime for struct timespec. Return value is in seconds. */
  2879. static double
  2880. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2881. {
  2882. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2883. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2884. }
  2885. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2886. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2887. const char *func,
  2888. unsigned line,
  2889. const char *fmt,
  2890. va_list ap);
  2891. #include "external_mg_cry_internal_impl.inl"
  2892. #elif !defined(NO_FILESYSTEMS)
  2893. /* Print error message to the opened error log stream. */
  2894. static void
  2895. mg_cry_internal_impl(const struct mg_connection *conn,
  2896. const char *func,
  2897. unsigned line,
  2898. const char *fmt,
  2899. va_list ap)
  2900. {
  2901. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2902. struct mg_file fi;
  2903. time_t timestamp;
  2904. /* Unused, in the RELEASE build */
  2905. (void)func;
  2906. (void)line;
  2907. #if defined(GCC_DIAGNOSTIC)
  2908. #pragma GCC diagnostic push
  2909. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2910. #endif
  2911. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2912. #if defined(GCC_DIAGNOSTIC)
  2913. #pragma GCC diagnostic pop
  2914. #endif
  2915. buf[sizeof(buf) - 1] = 0;
  2916. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2917. if (!conn) {
  2918. puts(buf);
  2919. return;
  2920. }
  2921. /* Do not lock when getting the callback value, here and below.
  2922. * I suppose this is fine, since function cannot disappear in the
  2923. * same way string option can. */
  2924. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2925. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2926. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2927. if (mg_fopen(conn,
  2928. conn->dom_ctx->config[ERROR_LOG_FILE],
  2929. MG_FOPEN_MODE_APPEND,
  2930. &fi)
  2931. == 0) {
  2932. fi.access.fp = NULL;
  2933. }
  2934. } else {
  2935. fi.access.fp = NULL;
  2936. }
  2937. if (fi.access.fp != NULL) {
  2938. flockfile(fi.access.fp);
  2939. timestamp = time(NULL);
  2940. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2941. fprintf(fi.access.fp,
  2942. "[%010lu] [error] [client %s] ",
  2943. (unsigned long)timestamp,
  2944. src_addr);
  2945. if (conn->request_info.request_method != NULL) {
  2946. fprintf(fi.access.fp,
  2947. "%s %s: ",
  2948. conn->request_info.request_method,
  2949. conn->request_info.request_uri
  2950. ? conn->request_info.request_uri
  2951. : "");
  2952. }
  2953. fprintf(fi.access.fp, "%s", buf);
  2954. fputc('\n', fi.access.fp);
  2955. fflush(fi.access.fp);
  2956. funlockfile(fi.access.fp);
  2957. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2958. * mg_cry here anyway ;-) */
  2959. }
  2960. }
  2961. }
  2962. #else
  2963. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2964. #endif /* Externally provided function */
  2965. /* Construct fake connection structure. Used for logging, if connection
  2966. * is not applicable at the moment of logging. */
  2967. static struct mg_connection *
  2968. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2969. {
  2970. static const struct mg_connection conn_zero = {0};
  2971. *fc = conn_zero;
  2972. fc->phys_ctx = ctx;
  2973. fc->dom_ctx = &(ctx->dd);
  2974. return fc;
  2975. }
  2976. static void
  2977. mg_cry_internal_wrap(const struct mg_connection *conn,
  2978. struct mg_context *ctx,
  2979. const char *func,
  2980. unsigned line,
  2981. const char *fmt,
  2982. ...)
  2983. {
  2984. va_list ap;
  2985. va_start(ap, fmt);
  2986. if (!conn && ctx) {
  2987. struct mg_connection fc;
  2988. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2989. } else {
  2990. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2991. }
  2992. va_end(ap);
  2993. }
  2994. CIVETWEB_API void
  2995. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2996. {
  2997. va_list ap;
  2998. va_start(ap, fmt);
  2999. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3000. va_end(ap);
  3001. }
  3002. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3003. CIVETWEB_API const char *
  3004. mg_version(void)
  3005. {
  3006. return CIVETWEB_VERSION;
  3007. }
  3008. CIVETWEB_API const struct mg_request_info *
  3009. mg_get_request_info(const struct mg_connection *conn)
  3010. {
  3011. if (!conn) {
  3012. return NULL;
  3013. }
  3014. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3015. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3016. char txt[16];
  3017. struct mg_workerTLS *tls =
  3018. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3019. sprintf(txt, "%03i", conn->response_info.status_code);
  3020. if (strlen(txt) == 3) {
  3021. memcpy(tls->txtbuf, txt, 4);
  3022. } else {
  3023. strcpy(tls->txtbuf, "ERR");
  3024. }
  3025. ((struct mg_connection *)conn)->request_info.local_uri =
  3026. tls->txtbuf; /* use thread safe buffer */
  3027. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3028. tls->txtbuf; /* use the same thread safe buffer */
  3029. ((struct mg_connection *)conn)->request_info.request_uri =
  3030. tls->txtbuf; /* use the same thread safe buffer */
  3031. ((struct mg_connection *)conn)->request_info.num_headers =
  3032. conn->response_info.num_headers;
  3033. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3034. conn->response_info.http_headers,
  3035. sizeof(conn->response_info.http_headers));
  3036. } else
  3037. #endif
  3038. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3039. return NULL;
  3040. }
  3041. return &conn->request_info;
  3042. }
  3043. CIVETWEB_API const struct mg_response_info *
  3044. mg_get_response_info(const struct mg_connection *conn)
  3045. {
  3046. if (!conn) {
  3047. return NULL;
  3048. }
  3049. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3050. return NULL;
  3051. }
  3052. return &conn->response_info;
  3053. }
  3054. static const char *
  3055. get_proto_name(const struct mg_connection *conn)
  3056. {
  3057. #if defined(__clang__)
  3058. #pragma clang diagnostic push
  3059. #pragma clang diagnostic ignored "-Wunreachable-code"
  3060. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3061. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3062. * unreachable, but splitting into four different #ifdef clauses here is
  3063. * more complicated.
  3064. */
  3065. #endif
  3066. const struct mg_request_info *ri = &conn->request_info;
  3067. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3068. ? (ri->is_ssl ? "wss" : "ws")
  3069. : (ri->is_ssl ? "https" : "http"));
  3070. return proto;
  3071. #if defined(__clang__)
  3072. #pragma clang diagnostic pop
  3073. #endif
  3074. }
  3075. static int
  3076. mg_construct_local_link(const struct mg_connection *conn,
  3077. char *buf,
  3078. size_t buflen,
  3079. const char *define_proto,
  3080. int define_port,
  3081. const char *define_uri)
  3082. {
  3083. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3084. return -1;
  3085. } else {
  3086. int i, j;
  3087. int truncated = 0;
  3088. const struct mg_request_info *ri = &conn->request_info;
  3089. const char *proto =
  3090. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3091. const char *uri =
  3092. (define_uri != NULL)
  3093. ? define_uri
  3094. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3095. int port = (define_port > 0) ? define_port : ri->server_port;
  3096. int default_port = 80;
  3097. char *uri_encoded;
  3098. size_t uri_encoded_len;
  3099. if (uri == NULL) {
  3100. return -1;
  3101. }
  3102. uri_encoded_len = strlen(uri) * 3 + 1;
  3103. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3104. if (uri_encoded == NULL) {
  3105. return -1;
  3106. }
  3107. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3108. /* Directory separator should be preserved. */
  3109. for (i = j = 0; uri_encoded[i]; j++) {
  3110. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3111. uri_encoded[j] = '/';
  3112. i += 3;
  3113. } else {
  3114. uri_encoded[j] = uri_encoded[i++];
  3115. }
  3116. }
  3117. uri_encoded[j] = '\0';
  3118. #if defined(USE_X_DOM_SOCKET)
  3119. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3120. /* TODO: Define and document a link for UNIX domain sockets. */
  3121. /* There seems to be no official standard for this.
  3122. * Common uses seem to be "httpunix://", "http.unix://" or
  3123. * "http+unix://" as a protocol definition string, followed by
  3124. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3125. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3126. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3127. * "" (completely skipping the server name part). In any case, the
  3128. * last part is the server local path. */
  3129. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3130. mg_snprintf(conn,
  3131. &truncated,
  3132. buf,
  3133. buflen,
  3134. "%s.unix://%s%s",
  3135. proto,
  3136. server_name,
  3137. ri->local_uri);
  3138. default_port = 0;
  3139. mg_free(uri_encoded);
  3140. return 0;
  3141. }
  3142. #endif
  3143. if (define_proto) {
  3144. /* If we got a protocol name, use the default port accordingly. */
  3145. if ((0 == strcmp(define_proto, "https"))
  3146. || (0 == strcmp(define_proto, "wss"))) {
  3147. default_port = 443;
  3148. }
  3149. } else if (ri->is_ssl) {
  3150. /* If we did not get a protocol name, use TLS as default if it is
  3151. * already used. */
  3152. default_port = 443;
  3153. }
  3154. {
  3155. #if defined(USE_IPV6)
  3156. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3157. #endif
  3158. int auth_domain_check_enabled =
  3159. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3160. && (!mg_strcasecmp(
  3161. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3162. const char *server_domain =
  3163. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3164. char portstr[16];
  3165. char server_ip[48];
  3166. if (port != default_port) {
  3167. sprintf(portstr, ":%u", (unsigned)port);
  3168. } else {
  3169. portstr[0] = 0;
  3170. }
  3171. if (!auth_domain_check_enabled || !server_domain) {
  3172. sockaddr_to_string(server_ip,
  3173. sizeof(server_ip),
  3174. &conn->client.lsa);
  3175. server_domain = server_ip;
  3176. }
  3177. mg_snprintf(conn,
  3178. &truncated,
  3179. buf,
  3180. buflen,
  3181. #if defined(USE_IPV6)
  3182. "%s://%s%s%s%s%s",
  3183. proto,
  3184. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3185. server_domain,
  3186. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3187. #else
  3188. "%s://%s%s%s",
  3189. proto,
  3190. server_domain,
  3191. #endif
  3192. portstr,
  3193. uri_encoded);
  3194. mg_free(uri_encoded);
  3195. if (truncated) {
  3196. return -1;
  3197. }
  3198. return 0;
  3199. }
  3200. }
  3201. }
  3202. CIVETWEB_API int
  3203. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3204. {
  3205. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3206. }
  3207. /* Skip the characters until one of the delimiters characters found.
  3208. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3209. * Advance pointer to buffer to the next word. Return found 0-terminated
  3210. * word.
  3211. * Delimiters can be quoted with quotechar. */
  3212. static char *
  3213. skip_quoted(char **buf,
  3214. const char *delimiters,
  3215. const char *whitespace,
  3216. char quotechar)
  3217. {
  3218. char *p, *begin_word, *end_word, *end_whitespace;
  3219. begin_word = *buf;
  3220. end_word = begin_word + strcspn(begin_word, delimiters);
  3221. /* Check for quotechar */
  3222. if (end_word > begin_word) {
  3223. p = end_word - 1;
  3224. while (*p == quotechar) {
  3225. /* While the delimiter is quoted, look for the next delimiter. */
  3226. /* This happens, e.g., in calls from parse_auth_header,
  3227. * if the user name contains a " character. */
  3228. /* If there is anything beyond end_word, copy it. */
  3229. if (*end_word != '\0') {
  3230. size_t end_off = strcspn(end_word + 1, delimiters);
  3231. memmove(p, end_word, end_off + 1);
  3232. p += end_off; /* p must correspond to end_word - 1 */
  3233. end_word += end_off + 1;
  3234. } else {
  3235. *p = '\0';
  3236. break;
  3237. }
  3238. }
  3239. for (p++; p < end_word; p++) {
  3240. *p = '\0';
  3241. }
  3242. }
  3243. if (*end_word == '\0') {
  3244. *buf = end_word;
  3245. } else {
  3246. #if defined(GCC_DIAGNOSTIC)
  3247. /* Disable spurious conversion warning for GCC */
  3248. #pragma GCC diagnostic push
  3249. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3250. #endif /* defined(GCC_DIAGNOSTIC) */
  3251. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3252. #if defined(GCC_DIAGNOSTIC)
  3253. #pragma GCC diagnostic pop
  3254. #endif /* defined(GCC_DIAGNOSTIC) */
  3255. for (p = end_word; p < end_whitespace; p++) {
  3256. *p = '\0';
  3257. }
  3258. *buf = end_whitespace;
  3259. }
  3260. return begin_word;
  3261. }
  3262. /* Return HTTP header value, or NULL if not found. */
  3263. static const char *
  3264. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3265. {
  3266. int i;
  3267. for (i = 0; i < num_hdr; i++) {
  3268. if (!mg_strcasecmp(name, hdr[i].name)) {
  3269. return hdr[i].value;
  3270. }
  3271. }
  3272. return NULL;
  3273. }
  3274. /* Retrieve requested HTTP header multiple values, and return the number of
  3275. * found occurrences */
  3276. static int
  3277. get_req_headers(const struct mg_request_info *ri,
  3278. const char *name,
  3279. const char **output,
  3280. int output_max_size)
  3281. {
  3282. int i;
  3283. int cnt = 0;
  3284. if (ri) {
  3285. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3286. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3287. output[cnt++] = ri->http_headers[i].value;
  3288. }
  3289. }
  3290. }
  3291. return cnt;
  3292. }
  3293. CIVETWEB_API const char *
  3294. mg_get_header(const struct mg_connection *conn, const char *name)
  3295. {
  3296. if (!conn) {
  3297. return NULL;
  3298. }
  3299. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3300. return get_header(conn->request_info.http_headers,
  3301. conn->request_info.num_headers,
  3302. name);
  3303. }
  3304. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3305. return get_header(conn->response_info.http_headers,
  3306. conn->response_info.num_headers,
  3307. name);
  3308. }
  3309. return NULL;
  3310. }
  3311. static const char *
  3312. get_http_version(const struct mg_connection *conn)
  3313. {
  3314. if (!conn) {
  3315. return NULL;
  3316. }
  3317. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3318. return conn->request_info.http_version;
  3319. }
  3320. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3321. return conn->response_info.http_version;
  3322. }
  3323. return NULL;
  3324. }
  3325. /* A helper function for traversing a comma separated list of values.
  3326. * It returns a list pointer shifted to the next value, or NULL if the end
  3327. * of the list found.
  3328. * Value is stored in val vector. If value has form "x=y", then eq_val
  3329. * vector is initialized to point to the "y" part, and val vector length
  3330. * is adjusted to point only to "x". */
  3331. static const char *
  3332. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3333. {
  3334. int end;
  3335. reparse:
  3336. if (val == NULL || list == NULL || *list == '\0') {
  3337. /* End of the list */
  3338. return NULL;
  3339. }
  3340. /* Skip over leading LWS */
  3341. while (*list == ' ' || *list == '\t')
  3342. list++;
  3343. val->ptr = list;
  3344. if ((list = strchr(val->ptr, ',')) != NULL) {
  3345. /* Comma found. Store length and shift the list ptr */
  3346. val->len = ((size_t)(list - val->ptr));
  3347. list++;
  3348. } else {
  3349. /* This value is the last one */
  3350. list = val->ptr + strlen(val->ptr);
  3351. val->len = ((size_t)(list - val->ptr));
  3352. }
  3353. /* Adjust length for trailing LWS */
  3354. end = (int)val->len - 1;
  3355. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3356. end--;
  3357. val->len = (size_t)(end) + (size_t)(1);
  3358. if (val->len == 0) {
  3359. /* Ignore any empty entries. */
  3360. goto reparse;
  3361. }
  3362. if (eq_val != NULL) {
  3363. /* Value has form "x=y", adjust pointers and lengths
  3364. * so that val points to "x", and eq_val points to "y". */
  3365. eq_val->len = 0;
  3366. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3367. if (eq_val->ptr != NULL) {
  3368. eq_val->ptr++; /* Skip over '=' character */
  3369. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3370. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3371. }
  3372. }
  3373. return list;
  3374. }
  3375. /* A helper function for checking if a comma separated list of values
  3376. * contains
  3377. * the given option (case insensitvely).
  3378. * 'header' can be NULL, in which case false is returned. */
  3379. static int
  3380. header_has_option(const char *header, const char *option)
  3381. {
  3382. struct vec opt_vec;
  3383. struct vec eq_vec;
  3384. DEBUG_ASSERT(option != NULL);
  3385. DEBUG_ASSERT(option[0] != '\0');
  3386. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3387. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3388. return 1;
  3389. }
  3390. return 0;
  3391. }
  3392. /* Sorting function implemented in a separate file */
  3393. #include "sort.inl"
  3394. /* Pattern matching has been reimplemented in a new file */
  3395. #include "match.inl"
  3396. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3397. * This function must tolerate situations when connection info is not
  3398. * set up, for example if request parsing failed. */
  3399. static int
  3400. should_keep_alive(const struct mg_connection *conn)
  3401. {
  3402. const char *http_version;
  3403. const char *header;
  3404. /* First satisfy needs of the server */
  3405. if ((conn == NULL) || conn->must_close) {
  3406. /* Close, if civetweb framework needs to close */
  3407. return 0;
  3408. }
  3409. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3410. /* Close, if keep alive is not enabled */
  3411. return 0;
  3412. }
  3413. /* Check explicit wish of the client */
  3414. header = mg_get_header(conn, "Connection");
  3415. if (header) {
  3416. /* If there is a connection header from the client, obey */
  3417. if (header_has_option(header, "keep-alive")) {
  3418. return 1;
  3419. }
  3420. return 0;
  3421. }
  3422. /* Use default of the standard */
  3423. http_version = get_http_version(conn);
  3424. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3425. /* HTTP 1.1 default is keep alive */
  3426. return 1;
  3427. }
  3428. /* HTTP 1.0 (and earlier) default is to close the connection */
  3429. return 0;
  3430. }
  3431. static int
  3432. should_decode_url(const struct mg_connection *conn)
  3433. {
  3434. if (!conn || !conn->dom_ctx) {
  3435. return 0;
  3436. }
  3437. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3438. }
  3439. static int
  3440. should_decode_query_string(const struct mg_connection *conn)
  3441. {
  3442. if (!conn || !conn->dom_ctx) {
  3443. return 0;
  3444. }
  3445. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3446. == 0);
  3447. }
  3448. static const char *
  3449. suggest_connection_header(const struct mg_connection *conn)
  3450. {
  3451. return should_keep_alive(conn) ? "keep-alive" : "close";
  3452. }
  3453. #include "response.inl"
  3454. static void
  3455. send_no_cache_header(struct mg_connection *conn)
  3456. {
  3457. /* Send all current and obsolete cache opt-out directives. */
  3458. mg_response_header_add(conn,
  3459. "Cache-Control",
  3460. "no-cache, no-store, "
  3461. "must-revalidate, private, max-age=0",
  3462. -1);
  3463. mg_response_header_add(conn, "Expires", "0", -1);
  3464. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3465. /* Obsolete, but still send it for HTTP/1.0 */
  3466. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3467. }
  3468. }
  3469. static void
  3470. send_static_cache_header(struct mg_connection *conn)
  3471. {
  3472. #if !defined(NO_CACHING)
  3473. int max_age;
  3474. char val[64];
  3475. const char *cache_control =
  3476. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3477. /* If there is a full cache-control option configured,0 use it */
  3478. if (cache_control != NULL) {
  3479. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3480. return;
  3481. }
  3482. /* Read the server config to check how long a file may be cached.
  3483. * The configuration is in seconds. */
  3484. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3485. if (max_age <= 0) {
  3486. /* 0 means "do not cache". All values <0 are reserved
  3487. * and may be used differently in the future. */
  3488. /* If a file should not be cached, do not only send
  3489. * max-age=0, but also pragmas and Expires headers. */
  3490. send_no_cache_header(conn);
  3491. return;
  3492. }
  3493. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3494. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3495. /* See also https://www.mnot.net/cache_docs/ */
  3496. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3497. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3498. * leap
  3499. * year to 31622400 seconds. For the moment, we just send whatever has
  3500. * been configured, still the behavior for >1 year should be considered
  3501. * as undefined. */
  3502. mg_snprintf(
  3503. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3504. mg_response_header_add(conn, "Cache-Control", val, -1);
  3505. #else /* NO_CACHING */
  3506. send_no_cache_header(conn);
  3507. #endif /* !NO_CACHING */
  3508. }
  3509. static void
  3510. send_additional_header(struct mg_connection *conn)
  3511. {
  3512. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3513. #if !defined(NO_SSL)
  3514. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3515. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3516. if (max_age >= 0) {
  3517. char val[64];
  3518. mg_snprintf(conn,
  3519. NULL,
  3520. val,
  3521. sizeof(val),
  3522. "max-age=%lu",
  3523. (unsigned long)max_age);
  3524. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3525. }
  3526. }
  3527. #endif
  3528. // Content-Security-Policy
  3529. if (header && header[0]) {
  3530. mg_response_header_add_lines(conn, header);
  3531. }
  3532. }
  3533. static void
  3534. send_cors_header(struct mg_connection *conn)
  3535. {
  3536. const char *origin_hdr = mg_get_header(conn, "Origin");
  3537. const char *cors_orig_cfg =
  3538. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3539. const char *cors_cred_cfg =
  3540. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  3541. const char *cors_hdr_cfg =
  3542. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  3543. const char *cors_exphdr_cfg =
  3544. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  3545. const char *cors_meth_cfg =
  3546. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  3547. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3548. /* Cross-origin resource sharing (CORS), see
  3549. * http://www.html5rocks.com/en/tutorials/cors/,
  3550. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3551. * CORS preflight is not supported for files. */
  3552. mg_response_header_add(conn,
  3553. "Access-Control-Allow-Origin",
  3554. cors_orig_cfg,
  3555. -1);
  3556. }
  3557. if (cors_cred_cfg && *cors_cred_cfg && origin_hdr && *origin_hdr) {
  3558. /* Cross-origin resource sharing (CORS), see
  3559. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  3560. */
  3561. mg_response_header_add(conn,
  3562. "Access-Control-Allow-Credentials",
  3563. cors_cred_cfg,
  3564. -1);
  3565. }
  3566. if (cors_hdr_cfg && *cors_hdr_cfg) {
  3567. mg_response_header_add(conn,
  3568. "Access-Control-Allow-Headers",
  3569. cors_hdr_cfg,
  3570. -1);
  3571. }
  3572. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  3573. mg_response_header_add(conn,
  3574. "Access-Control-Expose-Headers",
  3575. cors_exphdr_cfg,
  3576. -1);
  3577. }
  3578. if (cors_meth_cfg && *cors_meth_cfg) {
  3579. mg_response_header_add(conn,
  3580. "Access-Control-Allow-Methods",
  3581. cors_meth_cfg,
  3582. -1);
  3583. }
  3584. }
  3585. #if !defined(NO_FILESYSTEMS)
  3586. static void handle_file_based_request(struct mg_connection *conn,
  3587. const char *path,
  3588. struct mg_file *filep);
  3589. #endif /* NO_FILESYSTEMS */
  3590. CIVETWEB_API const char *
  3591. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3592. {
  3593. /* See IANA HTTP status code assignment:
  3594. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3595. */
  3596. switch (response_code) {
  3597. /* RFC2616 Section 10.1 - Informational 1xx */
  3598. case 100:
  3599. return "Continue"; /* RFC2616 Section 10.1.1 */
  3600. case 101:
  3601. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3602. case 102:
  3603. return "Processing"; /* RFC2518 Section 10.1 */
  3604. /* RFC2616 Section 10.2 - Successful 2xx */
  3605. case 200:
  3606. return "OK"; /* RFC2616 Section 10.2.1 */
  3607. case 201:
  3608. return "Created"; /* RFC2616 Section 10.2.2 */
  3609. case 202:
  3610. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3611. case 203:
  3612. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3613. case 204:
  3614. return "No Content"; /* RFC2616 Section 10.2.5 */
  3615. case 205:
  3616. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3617. case 206:
  3618. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3619. case 207:
  3620. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3621. */
  3622. case 208:
  3623. return "Already Reported"; /* RFC5842 Section 7.1 */
  3624. case 226:
  3625. return "IM used"; /* RFC3229 Section 10.4.1 */
  3626. /* RFC2616 Section 10.3 - Redirection 3xx */
  3627. case 300:
  3628. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3629. case 301:
  3630. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3631. case 302:
  3632. return "Found"; /* RFC2616 Section 10.3.3 */
  3633. case 303:
  3634. return "See Other"; /* RFC2616 Section 10.3.4 */
  3635. case 304:
  3636. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3637. case 305:
  3638. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3639. case 307:
  3640. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3641. case 308:
  3642. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3643. /* RFC2616 Section 10.4 - Client Error 4xx */
  3644. case 400:
  3645. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3646. case 401:
  3647. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3648. case 402:
  3649. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3650. case 403:
  3651. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3652. case 404:
  3653. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3654. case 405:
  3655. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3656. case 406:
  3657. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3658. case 407:
  3659. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3660. case 408:
  3661. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3662. case 409:
  3663. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3664. case 410:
  3665. return "Gone"; /* RFC2616 Section 10.4.11 */
  3666. case 411:
  3667. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3668. case 412:
  3669. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3670. case 413:
  3671. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3672. case 414:
  3673. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3674. case 415:
  3675. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3676. case 416:
  3677. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3678. */
  3679. case 417:
  3680. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3681. case 421:
  3682. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3683. case 422:
  3684. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3685. * Section 11.2 */
  3686. case 423:
  3687. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3688. case 424:
  3689. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3690. * Section 11.4 */
  3691. case 426:
  3692. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3693. case 428:
  3694. return "Precondition Required"; /* RFC 6585, Section 3 */
  3695. case 429:
  3696. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3697. case 431:
  3698. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3699. case 451:
  3700. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3701. * Section 3 */
  3702. /* RFC2616 Section 10.5 - Server Error 5xx */
  3703. case 500:
  3704. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3705. case 501:
  3706. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3707. case 502:
  3708. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3709. case 503:
  3710. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3711. case 504:
  3712. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3713. case 505:
  3714. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3715. case 506:
  3716. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3717. case 507:
  3718. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3719. * Section 11.5 */
  3720. case 508:
  3721. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3722. case 510:
  3723. return "Not Extended"; /* RFC 2774, Section 7 */
  3724. case 511:
  3725. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3726. /* Other status codes, not shown in the IANA HTTP status code
  3727. * assignment.
  3728. * E.g., "de facto" standards due to common use, ... */
  3729. case 418:
  3730. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3731. case 419:
  3732. return "Authentication Timeout"; /* common use */
  3733. case 420:
  3734. return "Enhance Your Calm"; /* common use */
  3735. case 440:
  3736. return "Login Timeout"; /* common use */
  3737. case 509:
  3738. return "Bandwidth Limit Exceeded"; /* common use */
  3739. default:
  3740. /* This error code is unknown. This should not happen. */
  3741. if (conn) {
  3742. mg_cry_internal(conn,
  3743. "Unknown HTTP response code: %u",
  3744. response_code);
  3745. }
  3746. /* Return at least a category according to RFC 2616 Section 10. */
  3747. if (response_code >= 100 && response_code < 200) {
  3748. /* Unknown informational status code */
  3749. return "Information";
  3750. }
  3751. if (response_code >= 200 && response_code < 300) {
  3752. /* Unknown success code */
  3753. return "Success";
  3754. }
  3755. if (response_code >= 300 && response_code < 400) {
  3756. /* Unknown redirection code */
  3757. return "Redirection";
  3758. }
  3759. if (response_code >= 400 && response_code < 500) {
  3760. /* Unknown request error code */
  3761. return "Client Error";
  3762. }
  3763. if (response_code >= 500 && response_code < 600) {
  3764. /* Unknown server error code */
  3765. return "Server Error";
  3766. }
  3767. /* Response code not even within reasonable range */
  3768. return "";
  3769. }
  3770. }
  3771. static int
  3772. mg_send_http_error_impl(struct mg_connection *conn,
  3773. int status,
  3774. const char *fmt,
  3775. va_list args)
  3776. {
  3777. char errmsg_buf[MG_BUF_LEN];
  3778. va_list ap;
  3779. int has_body;
  3780. #if !defined(NO_FILESYSTEMS)
  3781. char path_buf[UTF8_PATH_MAX];
  3782. int len, i, page_handler_found, scope, truncated;
  3783. const char *error_handler = NULL;
  3784. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3785. const char *error_page_file_ext, *tstr;
  3786. #endif /* NO_FILESYSTEMS */
  3787. int handled_by_callback = 0;
  3788. if ((conn == NULL) || (fmt == NULL)) {
  3789. return -2;
  3790. }
  3791. /* Set status (for log) */
  3792. conn->status_code = status;
  3793. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3794. has_body = ((status > 199) && (status != 204) && (status != 304));
  3795. /* Prepare message in buf, if required */
  3796. if (has_body
  3797. || (!conn->in_error_handler
  3798. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3799. /* Store error message in errmsg_buf */
  3800. va_copy(ap, args);
  3801. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3802. va_end(ap);
  3803. /* In a debug build, print all html errors */
  3804. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3805. }
  3806. /* If there is a http_error callback, call it.
  3807. * But don't do it recursively, if callback calls mg_send_http_error again.
  3808. */
  3809. if (!conn->in_error_handler
  3810. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3811. /* Mark in_error_handler to avoid recursion and call user callback. */
  3812. conn->in_error_handler = 1;
  3813. handled_by_callback =
  3814. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3815. == 0);
  3816. conn->in_error_handler = 0;
  3817. }
  3818. if (!handled_by_callback) {
  3819. /* Check for recursion */
  3820. if (conn->in_error_handler) {
  3821. DEBUG_TRACE(
  3822. "Recursion when handling error %u - fall back to default",
  3823. status);
  3824. #if !defined(NO_FILESYSTEMS)
  3825. } else {
  3826. /* Send user defined error pages, if defined */
  3827. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3828. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3829. page_handler_found = 0;
  3830. if (error_handler != NULL) {
  3831. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3832. switch (scope) {
  3833. case 1: /* Handler for specific error, e.g. 404 error */
  3834. mg_snprintf(conn,
  3835. &truncated,
  3836. path_buf,
  3837. sizeof(path_buf) - 32,
  3838. "%serror%03u.",
  3839. error_handler,
  3840. status);
  3841. break;
  3842. case 2: /* Handler for error group, e.g., 5xx error
  3843. * handler
  3844. * for all server errors (500-599) */
  3845. mg_snprintf(conn,
  3846. &truncated,
  3847. path_buf,
  3848. sizeof(path_buf) - 32,
  3849. "%serror%01uxx.",
  3850. error_handler,
  3851. status / 100);
  3852. break;
  3853. default: /* Handler for all errors */
  3854. mg_snprintf(conn,
  3855. &truncated,
  3856. path_buf,
  3857. sizeof(path_buf) - 32,
  3858. "%serror.",
  3859. error_handler);
  3860. break;
  3861. }
  3862. /* String truncation in buf may only occur if
  3863. * error_handler is too long. This string is
  3864. * from the config, not from a client. */
  3865. (void)truncated;
  3866. /* The following code is redundant, but it should avoid
  3867. * false positives in static source code analyzers and
  3868. * vulnerability scanners.
  3869. */
  3870. path_buf[sizeof(path_buf) - 32] = 0;
  3871. len = (int)strlen(path_buf);
  3872. if (len > (int)sizeof(path_buf) - 32) {
  3873. len = (int)sizeof(path_buf) - 32;
  3874. }
  3875. /* Start with the file extension from the configuration. */
  3876. tstr = strchr(error_page_file_ext, '.');
  3877. while (tstr) {
  3878. for (i = 1;
  3879. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3880. i++) {
  3881. /* buffer overrun is not possible here, since
  3882. * (i < 32) && (len < sizeof(path_buf) - 32)
  3883. * ==> (i + len) < sizeof(path_buf) */
  3884. path_buf[len + i - 1] = tstr[i];
  3885. }
  3886. /* buffer overrun is not possible here, since
  3887. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3888. * ==> (i + len) <= sizeof(path_buf) */
  3889. path_buf[len + i - 1] = 0;
  3890. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3891. DEBUG_TRACE("Check error page %s - found",
  3892. path_buf);
  3893. page_handler_found = 1;
  3894. break;
  3895. }
  3896. DEBUG_TRACE("Check error page %s - not found",
  3897. path_buf);
  3898. /* Continue with the next file extension from the
  3899. * configuration (if there is a next one). */
  3900. tstr = strchr(tstr + i, '.');
  3901. }
  3902. }
  3903. }
  3904. if (page_handler_found) {
  3905. conn->in_error_handler = 1;
  3906. handle_file_based_request(conn, path_buf, &error_page_file);
  3907. conn->in_error_handler = 0;
  3908. return 0;
  3909. }
  3910. #endif /* NO_FILESYSTEMS */
  3911. }
  3912. /* No custom error page. Send default error page. */
  3913. conn->must_close = 1;
  3914. mg_response_header_start(conn, status);
  3915. send_no_cache_header(conn);
  3916. send_additional_header(conn);
  3917. send_cors_header(conn);
  3918. if (has_body) {
  3919. mg_response_header_add(conn,
  3920. "Content-Type",
  3921. "text/plain; charset=utf-8",
  3922. -1);
  3923. }
  3924. mg_response_header_send(conn);
  3925. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3926. if (has_body) {
  3927. /* For other errors, send a generic error message. */
  3928. const char *status_text = mg_get_response_code_text(conn, status);
  3929. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3930. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3931. } else {
  3932. /* No body allowed. Close the connection. */
  3933. DEBUG_TRACE("Error %i", status);
  3934. }
  3935. }
  3936. return 0;
  3937. }
  3938. CIVETWEB_API int
  3939. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3940. {
  3941. va_list ap;
  3942. int ret;
  3943. va_start(ap, fmt);
  3944. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3945. va_end(ap);
  3946. return ret;
  3947. }
  3948. CIVETWEB_API int
  3949. mg_send_http_ok(struct mg_connection *conn,
  3950. const char *mime_type,
  3951. long long content_length)
  3952. {
  3953. if ((mime_type == NULL) || (*mime_type == 0)) {
  3954. /* No content type defined: default to text/html */
  3955. mime_type = "text/html";
  3956. }
  3957. mg_response_header_start(conn, 200);
  3958. send_no_cache_header(conn);
  3959. send_additional_header(conn);
  3960. send_cors_header(conn);
  3961. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3962. if (content_length < 0) {
  3963. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3964. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3965. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3966. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3967. }
  3968. } else {
  3969. char len[32];
  3970. int trunc = 0;
  3971. mg_snprintf(conn,
  3972. &trunc,
  3973. len,
  3974. sizeof(len),
  3975. "%" UINT64_FMT,
  3976. (uint64_t)content_length);
  3977. if (!trunc) {
  3978. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3979. * !trunc is always true */
  3980. mg_response_header_add(conn, "Content-Length", len, -1);
  3981. }
  3982. }
  3983. mg_response_header_send(conn);
  3984. return 0;
  3985. }
  3986. CIVETWEB_API int
  3987. mg_send_http_redirect(struct mg_connection *conn,
  3988. const char *target_url,
  3989. int redirect_code)
  3990. {
  3991. /* Send a 30x redirect response.
  3992. *
  3993. * Redirect types (status codes):
  3994. *
  3995. * Status | Perm/Temp | Method | Version
  3996. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3997. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3998. * 303 | temporary | always use GET | HTTP/1.1
  3999. * 307 | temporary | always keep method | HTTP/1.1
  4000. * 308 | permanent | always keep method | HTTP/1.1
  4001. */
  4002. #if defined(MG_SEND_REDIRECT_BODY)
  4003. char redirect_body[MG_BUF_LEN];
  4004. size_t content_len = 0;
  4005. char content_len_text[32];
  4006. #endif
  4007. /* In case redirect_code=0, use 307. */
  4008. if (redirect_code == 0) {
  4009. redirect_code = 307;
  4010. }
  4011. /* In case redirect_code is none of the above, return error. */
  4012. if ((redirect_code != 301) && (redirect_code != 302)
  4013. && (redirect_code != 303) && (redirect_code != 307)
  4014. && (redirect_code != 308)) {
  4015. /* Parameter error */
  4016. return -2;
  4017. }
  4018. /* If target_url is not defined, redirect to "/". */
  4019. if ((target_url == NULL) || (*target_url == 0)) {
  4020. target_url = "/";
  4021. }
  4022. #if defined(MG_SEND_REDIRECT_BODY)
  4023. /* TODO: condition name? */
  4024. /* Prepare a response body with a hyperlink.
  4025. *
  4026. * According to RFC2616 (and RFC1945 before):
  4027. * Unless the request method was HEAD, the entity of the
  4028. * response SHOULD contain a short hypertext note with a hyperlink to
  4029. * the new URI(s).
  4030. *
  4031. * However, this response body is not useful in M2M communication.
  4032. * Probably the original reason in the RFC was, clients not supporting
  4033. * a 30x HTTP redirect could still show the HTML page and let the user
  4034. * press the link. Since current browsers support 30x HTTP, the additional
  4035. * HTML body does not seem to make sense anymore.
  4036. *
  4037. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4038. * but it only notes:
  4039. * The server's response payload usually contains a short
  4040. * hypertext note with a hyperlink to the new URI(s).
  4041. *
  4042. * Deactivated by default. If you need the 30x body, set the define.
  4043. */
  4044. mg_snprintf(
  4045. conn,
  4046. NULL /* ignore truncation */,
  4047. redirect_body,
  4048. sizeof(redirect_body),
  4049. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4050. redirect_text,
  4051. target_url,
  4052. target_url);
  4053. content_len = strlen(reply);
  4054. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4055. #endif
  4056. /* Send all required headers */
  4057. mg_response_header_start(conn, redirect_code);
  4058. mg_response_header_add(conn, "Location", target_url, -1);
  4059. if ((redirect_code == 301) || (redirect_code == 308)) {
  4060. /* Permanent redirect */
  4061. send_static_cache_header(conn);
  4062. } else {
  4063. /* Temporary redirect */
  4064. send_no_cache_header(conn);
  4065. }
  4066. send_additional_header(conn);
  4067. send_cors_header(conn);
  4068. #if defined(MG_SEND_REDIRECT_BODY)
  4069. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4070. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4071. #else
  4072. mg_response_header_add(conn, "Content-Length", "0", 1);
  4073. #endif
  4074. mg_response_header_send(conn);
  4075. #if defined(MG_SEND_REDIRECT_BODY)
  4076. /* Send response body */
  4077. /* ... unless it is a HEAD request */
  4078. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4079. ret = mg_write(conn, redirect_body, content_len);
  4080. }
  4081. #endif
  4082. return 1;
  4083. }
  4084. #if defined(_WIN32)
  4085. /* Create substitutes for POSIX functions in Win32. */
  4086. #if defined(GCC_DIAGNOSTIC)
  4087. /* Show no warning in case system functions are not used. */
  4088. #pragma GCC diagnostic push
  4089. #pragma GCC diagnostic ignored "-Wunused-function"
  4090. #endif
  4091. static int
  4092. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4093. {
  4094. (void)unused;
  4095. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4096. InitializeCriticalSection(&mutex->sec);
  4097. return 0;
  4098. }
  4099. static int
  4100. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4101. {
  4102. DeleteCriticalSection(&mutex->sec);
  4103. return 0;
  4104. }
  4105. static int
  4106. pthread_mutex_lock(pthread_mutex_t *mutex)
  4107. {
  4108. EnterCriticalSection(&mutex->sec);
  4109. return 0;
  4110. }
  4111. static int
  4112. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4113. {
  4114. LeaveCriticalSection(&mutex->sec);
  4115. return 0;
  4116. }
  4117. FUNCTION_MAY_BE_UNUSED
  4118. static int
  4119. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4120. {
  4121. (void)unused;
  4122. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4123. cv->waiting_thread = NULL;
  4124. return 0;
  4125. }
  4126. FUNCTION_MAY_BE_UNUSED
  4127. static int
  4128. pthread_cond_timedwait(pthread_cond_t *cv,
  4129. pthread_mutex_t *mutex,
  4130. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4131. {
  4132. struct mg_workerTLS **ptls,
  4133. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4134. int ok;
  4135. uint64_t nsnow, nswaitabs;
  4136. int64_t nswaitrel;
  4137. DWORD mswaitrel;
  4138. pthread_mutex_lock(&cv->threadIdSec);
  4139. /* Add this thread to cv's waiting list */
  4140. ptls = &cv->waiting_thread;
  4141. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4142. ;
  4143. tls->next_waiting_thread = NULL;
  4144. *ptls = tls;
  4145. pthread_mutex_unlock(&cv->threadIdSec);
  4146. if (abstime) {
  4147. nsnow = mg_get_current_time_ns();
  4148. nswaitabs =
  4149. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4150. nswaitrel = nswaitabs - nsnow;
  4151. if (nswaitrel < 0) {
  4152. nswaitrel = 0;
  4153. }
  4154. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4155. } else {
  4156. mswaitrel = (DWORD)INFINITE;
  4157. }
  4158. pthread_mutex_unlock(mutex);
  4159. ok = (WAIT_OBJECT_0
  4160. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4161. if (!ok) {
  4162. ok = 1;
  4163. pthread_mutex_lock(&cv->threadIdSec);
  4164. ptls = &cv->waiting_thread;
  4165. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4166. if (*ptls == tls) {
  4167. *ptls = tls->next_waiting_thread;
  4168. ok = 0;
  4169. break;
  4170. }
  4171. }
  4172. pthread_mutex_unlock(&cv->threadIdSec);
  4173. if (ok) {
  4174. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4175. (DWORD)INFINITE);
  4176. }
  4177. }
  4178. /* This thread has been removed from cv's waiting list */
  4179. pthread_mutex_lock(mutex);
  4180. return ok ? 0 : -1;
  4181. }
  4182. FUNCTION_MAY_BE_UNUSED
  4183. static int
  4184. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4185. {
  4186. return pthread_cond_timedwait(cv, mutex, NULL);
  4187. }
  4188. FUNCTION_MAY_BE_UNUSED
  4189. static int
  4190. pthread_cond_signal(pthread_cond_t *cv)
  4191. {
  4192. HANDLE wkup = NULL;
  4193. BOOL ok = FALSE;
  4194. pthread_mutex_lock(&cv->threadIdSec);
  4195. if (cv->waiting_thread) {
  4196. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4197. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4198. ok = SetEvent(wkup);
  4199. DEBUG_ASSERT(ok);
  4200. }
  4201. pthread_mutex_unlock(&cv->threadIdSec);
  4202. return ok ? 0 : 1;
  4203. }
  4204. FUNCTION_MAY_BE_UNUSED
  4205. static int
  4206. pthread_cond_broadcast(pthread_cond_t *cv)
  4207. {
  4208. pthread_mutex_lock(&cv->threadIdSec);
  4209. while (cv->waiting_thread) {
  4210. pthread_cond_signal(cv);
  4211. }
  4212. pthread_mutex_unlock(&cv->threadIdSec);
  4213. return 0;
  4214. }
  4215. FUNCTION_MAY_BE_UNUSED
  4216. static int
  4217. pthread_cond_destroy(pthread_cond_t *cv)
  4218. {
  4219. pthread_mutex_lock(&cv->threadIdSec);
  4220. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4221. pthread_mutex_unlock(&cv->threadIdSec);
  4222. pthread_mutex_destroy(&cv->threadIdSec);
  4223. return 0;
  4224. }
  4225. #if defined(ALTERNATIVE_QUEUE)
  4226. FUNCTION_MAY_BE_UNUSED
  4227. static void *
  4228. event_create(void)
  4229. {
  4230. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4231. }
  4232. FUNCTION_MAY_BE_UNUSED
  4233. static int
  4234. event_wait(void *eventhdl)
  4235. {
  4236. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4237. return (res == WAIT_OBJECT_0);
  4238. }
  4239. FUNCTION_MAY_BE_UNUSED
  4240. static int
  4241. event_signal(void *eventhdl)
  4242. {
  4243. return (int)SetEvent((HANDLE)eventhdl);
  4244. }
  4245. FUNCTION_MAY_BE_UNUSED
  4246. static void
  4247. event_destroy(void *eventhdl)
  4248. {
  4249. CloseHandle((HANDLE)eventhdl);
  4250. }
  4251. #endif
  4252. #if defined(GCC_DIAGNOSTIC)
  4253. /* Enable unused function warning again */
  4254. #pragma GCC diagnostic pop
  4255. #endif
  4256. /* For Windows, change all slashes to backslashes in path names. */
  4257. static void
  4258. change_slashes_to_backslashes(char *path)
  4259. {
  4260. int i;
  4261. for (i = 0; path[i] != '\0'; i++) {
  4262. if (path[i] == '/') {
  4263. path[i] = '\\';
  4264. }
  4265. /* remove double backslash (check i > 0 to preserve UNC paths,
  4266. * like \\server\file.txt) */
  4267. if ((i > 0) && (path[i] == '\\')) {
  4268. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4269. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4270. }
  4271. }
  4272. }
  4273. }
  4274. static int
  4275. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4276. {
  4277. int diff;
  4278. do {
  4279. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4280. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4281. s1++;
  4282. s2++;
  4283. } while ((diff == 0) && (s1[-1] != L'\0'));
  4284. return diff;
  4285. }
  4286. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4287. * wbuf and wbuf_len is a target buffer and its length. */
  4288. static void
  4289. path_to_unicode(const struct mg_connection *conn,
  4290. const char *path,
  4291. wchar_t *wbuf,
  4292. size_t wbuf_len)
  4293. {
  4294. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4295. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4296. DWORD long_len, err;
  4297. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4298. mg_strlcpy(buf, path, sizeof(buf));
  4299. change_slashes_to_backslashes(buf);
  4300. /* Convert to Unicode and back. If doubly-converted string does not
  4301. * match the original, something is fishy, reject. */
  4302. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4303. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4304. WideCharToMultiByte(
  4305. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4306. if (strcmp(buf, buf2) != 0) {
  4307. wbuf[0] = L'\0';
  4308. }
  4309. /* Windows file systems are not case sensitive, but you can still use
  4310. * uppercase and lowercase letters (on all modern file systems).
  4311. * The server can check if the URI uses the same upper/lowercase
  4312. * letters an the file system, effectively making Windows servers
  4313. * case sensitive (like Linux servers are). It is still not possible
  4314. * to use two files with the same name in different cases on Windows
  4315. * (like /a and /A) - this would be possible in Linux.
  4316. * As a default, Windows is not case sensitive, but the case sensitive
  4317. * file name check can be activated by an additional configuration. */
  4318. if (conn) {
  4319. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4320. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4321. "yes")) {
  4322. /* Use case sensitive compare function */
  4323. fcompare = wcscmp;
  4324. }
  4325. }
  4326. (void)conn; /* conn is currently unused */
  4327. /* Only accept a full file path, not a Windows short (8.3) path. */
  4328. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4329. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4330. if (long_len == 0) {
  4331. err = GetLastError();
  4332. if (err == ERROR_FILE_NOT_FOUND) {
  4333. /* File does not exist. This is not always a problem here. */
  4334. return;
  4335. }
  4336. }
  4337. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4338. /* Short name is used. */
  4339. wbuf[0] = L'\0';
  4340. }
  4341. }
  4342. #if !defined(NO_FILESYSTEMS)
  4343. /* Get file information, return 1 if file exists, 0 if not */
  4344. static int
  4345. mg_stat(const struct mg_connection *conn,
  4346. const char *path,
  4347. struct mg_file_stat *filep)
  4348. {
  4349. wchar_t wbuf[UTF16_PATH_MAX];
  4350. WIN32_FILE_ATTRIBUTE_DATA info;
  4351. time_t creation_time;
  4352. size_t len;
  4353. if (!filep) {
  4354. return 0;
  4355. }
  4356. memset(filep, 0, sizeof(*filep));
  4357. if (mg_path_suspicious(conn, path)) {
  4358. return 0;
  4359. }
  4360. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4361. /* Windows happily opens files with some garbage at the end of file name.
  4362. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4363. * "a.cgi", despite one would expect an error back. */
  4364. len = strlen(path);
  4365. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4366. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4367. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4368. filep->last_modified =
  4369. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4370. info.ftLastWriteTime.dwHighDateTime);
  4371. /* On Windows, the file creation time can be higher than the
  4372. * modification time, e.g. when a file is copied.
  4373. * Since the Last-Modified timestamp is used for caching
  4374. * it should be based on the most recent timestamp. */
  4375. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4376. info.ftCreationTime.dwHighDateTime);
  4377. if (creation_time > filep->last_modified) {
  4378. filep->last_modified = creation_time;
  4379. }
  4380. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4381. return 1;
  4382. }
  4383. return 0;
  4384. }
  4385. #endif
  4386. static int
  4387. mg_remove(const struct mg_connection *conn, const char *path)
  4388. {
  4389. wchar_t wbuf[UTF16_PATH_MAX];
  4390. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4391. return DeleteFileW(wbuf) ? 0 : -1;
  4392. }
  4393. static int
  4394. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4395. {
  4396. wchar_t wbuf[UTF16_PATH_MAX];
  4397. (void)mode;
  4398. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4399. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4400. }
  4401. /* Create substitutes for POSIX functions in Win32. */
  4402. #if defined(GCC_DIAGNOSTIC)
  4403. /* Show no warning in case system functions are not used. */
  4404. #pragma GCC diagnostic push
  4405. #pragma GCC diagnostic ignored "-Wunused-function"
  4406. #endif
  4407. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4408. FUNCTION_MAY_BE_UNUSED
  4409. static DIR *
  4410. mg_opendir(const struct mg_connection *conn, const char *name)
  4411. {
  4412. DIR *dir = NULL;
  4413. wchar_t wpath[UTF16_PATH_MAX];
  4414. DWORD attrs;
  4415. if (name == NULL) {
  4416. SetLastError(ERROR_BAD_ARGUMENTS);
  4417. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4418. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4419. } else {
  4420. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4421. attrs = GetFileAttributesW(wpath);
  4422. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4423. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4424. (void)wcscat(wpath, L"\\*");
  4425. dir->handle = FindFirstFileW(wpath, &dir->info);
  4426. dir->result.d_name[0] = '\0';
  4427. } else {
  4428. mg_free(dir);
  4429. dir = NULL;
  4430. }
  4431. }
  4432. return dir;
  4433. }
  4434. FUNCTION_MAY_BE_UNUSED
  4435. static int
  4436. mg_closedir(DIR *dir)
  4437. {
  4438. int result = 0;
  4439. if (dir != NULL) {
  4440. if (dir->handle != INVALID_HANDLE_VALUE)
  4441. result = FindClose(dir->handle) ? 0 : -1;
  4442. mg_free(dir);
  4443. } else {
  4444. result = -1;
  4445. SetLastError(ERROR_BAD_ARGUMENTS);
  4446. }
  4447. return result;
  4448. }
  4449. FUNCTION_MAY_BE_UNUSED
  4450. static struct dirent *
  4451. mg_readdir(DIR *dir)
  4452. {
  4453. struct dirent *result = 0;
  4454. if (dir) {
  4455. if (dir->handle != INVALID_HANDLE_VALUE) {
  4456. result = &dir->result;
  4457. (void)WideCharToMultiByte(CP_UTF8,
  4458. 0,
  4459. dir->info.cFileName,
  4460. -1,
  4461. result->d_name,
  4462. sizeof(result->d_name),
  4463. NULL,
  4464. NULL);
  4465. if (!FindNextFileW(dir->handle, &dir->info)) {
  4466. (void)FindClose(dir->handle);
  4467. dir->handle = INVALID_HANDLE_VALUE;
  4468. }
  4469. } else {
  4470. SetLastError(ERROR_FILE_NOT_FOUND);
  4471. }
  4472. } else {
  4473. SetLastError(ERROR_BAD_ARGUMENTS);
  4474. }
  4475. return result;
  4476. }
  4477. #if !defined(HAVE_POLL)
  4478. #undef POLLIN
  4479. #undef POLLPRI
  4480. #undef POLLOUT
  4481. #undef POLLERR
  4482. #define POLLIN (1) /* Data ready - read will not block. */
  4483. #define POLLPRI (2) /* Priority data ready. */
  4484. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4485. #define POLLERR (8) /* Error event */
  4486. FUNCTION_MAY_BE_UNUSED
  4487. static int
  4488. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4489. {
  4490. struct timeval tv;
  4491. fd_set rset;
  4492. fd_set wset;
  4493. fd_set eset;
  4494. unsigned int i;
  4495. int result;
  4496. SOCKET maxfd = 0;
  4497. memset(&tv, 0, sizeof(tv));
  4498. tv.tv_sec = milliseconds / 1000;
  4499. tv.tv_usec = (milliseconds % 1000) * 1000;
  4500. FD_ZERO(&rset);
  4501. FD_ZERO(&wset);
  4502. FD_ZERO(&eset);
  4503. for (i = 0; i < n; i++) {
  4504. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4505. if (pfd[i].events & POLLIN) {
  4506. FD_SET(pfd[i].fd, &rset);
  4507. }
  4508. if (pfd[i].events & POLLOUT) {
  4509. FD_SET(pfd[i].fd, &wset);
  4510. }
  4511. /* Check for errors for any FD in the set */
  4512. FD_SET(pfd[i].fd, &eset);
  4513. }
  4514. pfd[i].revents = 0;
  4515. if (pfd[i].fd > maxfd) {
  4516. maxfd = pfd[i].fd;
  4517. }
  4518. }
  4519. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4520. for (i = 0; i < n; i++) {
  4521. if (FD_ISSET(pfd[i].fd, &rset)) {
  4522. pfd[i].revents |= POLLIN;
  4523. }
  4524. if (FD_ISSET(pfd[i].fd, &wset)) {
  4525. pfd[i].revents |= POLLOUT;
  4526. }
  4527. if (FD_ISSET(pfd[i].fd, &eset)) {
  4528. pfd[i].revents |= POLLERR;
  4529. }
  4530. }
  4531. }
  4532. /* We should subtract the time used in select from remaining
  4533. * "milliseconds", in particular if called from mg_poll with a
  4534. * timeout quantum.
  4535. * Unfortunately, the remaining time is not stored in "tv" in all
  4536. * implementations, so the result in "tv" must be considered undefined.
  4537. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4538. return result;
  4539. }
  4540. #endif /* HAVE_POLL */
  4541. #if defined(GCC_DIAGNOSTIC)
  4542. /* Enable unused function warning again */
  4543. #pragma GCC diagnostic pop
  4544. #endif
  4545. static void
  4546. set_close_on_exec(SOCKET sock,
  4547. const struct mg_connection *conn /* may be null */,
  4548. struct mg_context *ctx /* may be null */)
  4549. {
  4550. (void)conn; /* Unused. */
  4551. (void)ctx;
  4552. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4553. }
  4554. CIVETWEB_API int
  4555. mg_start_thread(mg_thread_func_t f, void *p)
  4556. {
  4557. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4558. /* Compile-time option to control stack size, e.g.
  4559. * -DUSE_STACK_SIZE=16384
  4560. */
  4561. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4562. == ((uintptr_t)(-1L)))
  4563. ? -1
  4564. : 0);
  4565. #else
  4566. return (
  4567. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4568. ? -1
  4569. : 0);
  4570. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4571. }
  4572. /* Start a thread storing the thread context. */
  4573. static int
  4574. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4575. void *p,
  4576. pthread_t *threadidptr)
  4577. {
  4578. uintptr_t uip;
  4579. HANDLE threadhandle;
  4580. int result = -1;
  4581. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4582. threadhandle = (HANDLE)uip;
  4583. if ((uip != 0) && (threadidptr != NULL)) {
  4584. *threadidptr = threadhandle;
  4585. result = 0;
  4586. }
  4587. return result;
  4588. }
  4589. /* Wait for a thread to finish. */
  4590. static int
  4591. mg_join_thread(pthread_t threadid)
  4592. {
  4593. int result;
  4594. DWORD dwevent;
  4595. result = -1;
  4596. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4597. if (dwevent == WAIT_FAILED) {
  4598. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4599. } else {
  4600. if (dwevent == WAIT_OBJECT_0) {
  4601. CloseHandle(threadid);
  4602. result = 0;
  4603. }
  4604. }
  4605. return result;
  4606. }
  4607. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4608. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4609. /* Create substitutes for POSIX functions in Win32. */
  4610. #if defined(GCC_DIAGNOSTIC)
  4611. /* Show no warning in case system functions are not used. */
  4612. #pragma GCC diagnostic push
  4613. #pragma GCC diagnostic ignored "-Wunused-function"
  4614. #endif
  4615. FUNCTION_MAY_BE_UNUSED
  4616. static HANDLE
  4617. dlopen(const char *dll_name, int flags)
  4618. {
  4619. wchar_t wbuf[UTF16_PATH_MAX];
  4620. (void)flags;
  4621. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4622. return LoadLibraryW(wbuf);
  4623. }
  4624. FUNCTION_MAY_BE_UNUSED
  4625. static int
  4626. dlclose(void *handle)
  4627. {
  4628. int result;
  4629. if (FreeLibrary((HMODULE)handle) != 0) {
  4630. result = 0;
  4631. } else {
  4632. result = -1;
  4633. }
  4634. return result;
  4635. }
  4636. #if defined(GCC_DIAGNOSTIC)
  4637. /* Enable unused function warning again */
  4638. #pragma GCC diagnostic pop
  4639. #endif
  4640. #endif
  4641. #if !defined(NO_CGI)
  4642. #define SIGKILL (0)
  4643. static int
  4644. kill(pid_t pid, int sig_num)
  4645. {
  4646. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4647. (void)CloseHandle((HANDLE)pid);
  4648. return 0;
  4649. }
  4650. #if !defined(WNOHANG)
  4651. #define WNOHANG (1)
  4652. #endif
  4653. static pid_t
  4654. waitpid(pid_t pid, int *status, int flags)
  4655. {
  4656. DWORD timeout = INFINITE;
  4657. DWORD waitres;
  4658. (void)status; /* Currently not used by any client here */
  4659. if ((flags | WNOHANG) == WNOHANG) {
  4660. timeout = 0;
  4661. }
  4662. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4663. if (waitres == WAIT_OBJECT_0) {
  4664. return pid;
  4665. }
  4666. if (waitres == WAIT_TIMEOUT) {
  4667. return 0;
  4668. }
  4669. return (pid_t)-1;
  4670. }
  4671. static void
  4672. trim_trailing_whitespaces(char *s)
  4673. {
  4674. char *e = s + strlen(s);
  4675. while ((e > s) && isspace((unsigned char)e[-1])) {
  4676. *(--e) = '\0';
  4677. }
  4678. }
  4679. static pid_t
  4680. spawn_process(struct mg_connection *conn,
  4681. const char *prog,
  4682. char *envblk,
  4683. char *envp[],
  4684. int fdin[2],
  4685. int fdout[2],
  4686. int fderr[2],
  4687. const char *dir,
  4688. int cgi_config_idx)
  4689. {
  4690. HANDLE me;
  4691. char *interp;
  4692. char *interp_arg = 0;
  4693. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4694. int truncated;
  4695. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4696. STARTUPINFOA si;
  4697. PROCESS_INFORMATION pi = {0};
  4698. (void)envp;
  4699. memset(&si, 0, sizeof(si));
  4700. si.cb = sizeof(si);
  4701. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4702. si.wShowWindow = SW_HIDE;
  4703. me = GetCurrentProcess();
  4704. DuplicateHandle(me,
  4705. (HANDLE)_get_osfhandle(fdin[0]),
  4706. me,
  4707. &si.hStdInput,
  4708. 0,
  4709. TRUE,
  4710. DUPLICATE_SAME_ACCESS);
  4711. DuplicateHandle(me,
  4712. (HANDLE)_get_osfhandle(fdout[1]),
  4713. me,
  4714. &si.hStdOutput,
  4715. 0,
  4716. TRUE,
  4717. DUPLICATE_SAME_ACCESS);
  4718. DuplicateHandle(me,
  4719. (HANDLE)_get_osfhandle(fderr[1]),
  4720. me,
  4721. &si.hStdError,
  4722. 0,
  4723. TRUE,
  4724. DUPLICATE_SAME_ACCESS);
  4725. /* Mark handles that should not be inherited. See
  4726. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4727. */
  4728. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4729. HANDLE_FLAG_INHERIT,
  4730. 0);
  4731. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4732. HANDLE_FLAG_INHERIT,
  4733. 0);
  4734. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4735. HANDLE_FLAG_INHERIT,
  4736. 0);
  4737. /* First check, if there is a CGI interpreter configured for all CGI
  4738. * scripts. */
  4739. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4740. if (interp != NULL) {
  4741. /* If there is a configured interpreter, check for additional arguments
  4742. */
  4743. interp_arg =
  4744. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4745. } else {
  4746. /* Otherwise, the interpreter must be stated in the first line of the
  4747. * CGI script file, after a #! (shebang) mark. */
  4748. buf[0] = buf[1] = '\0';
  4749. /* Get the full script path */
  4750. mg_snprintf(
  4751. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4752. if (truncated) {
  4753. pi.hProcess = (pid_t)-1;
  4754. goto spawn_cleanup;
  4755. }
  4756. /* Open the script file, to read the first line */
  4757. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4758. /* Read the first line of the script into the buffer */
  4759. mg_fgets(buf, sizeof(buf), &file);
  4760. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4761. buf[sizeof(buf) - 1] = '\0';
  4762. }
  4763. if ((buf[0] == '#') && (buf[1] == '!')) {
  4764. trim_trailing_whitespaces(buf + 2);
  4765. } else {
  4766. buf[2] = '\0';
  4767. }
  4768. interp = buf + 2;
  4769. }
  4770. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4771. if (interp[0] != '\0') {
  4772. /* This is an interpreted script file. We must call the interpreter. */
  4773. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4774. mg_snprintf(conn,
  4775. &truncated,
  4776. cmdline,
  4777. sizeof(cmdline),
  4778. "\"%s\" %s \"%s\\%s\"",
  4779. interp,
  4780. interp_arg,
  4781. full_dir,
  4782. prog);
  4783. } else {
  4784. mg_snprintf(conn,
  4785. &truncated,
  4786. cmdline,
  4787. sizeof(cmdline),
  4788. "\"%s\" \"%s\\%s\"",
  4789. interp,
  4790. full_dir,
  4791. prog);
  4792. }
  4793. } else {
  4794. /* This is (probably) a compiled program. We call it directly. */
  4795. mg_snprintf(conn,
  4796. &truncated,
  4797. cmdline,
  4798. sizeof(cmdline),
  4799. "\"%s\\%s\"",
  4800. full_dir,
  4801. prog);
  4802. }
  4803. if (truncated) {
  4804. pi.hProcess = (pid_t)-1;
  4805. goto spawn_cleanup;
  4806. }
  4807. DEBUG_TRACE("Running [%s]", cmdline);
  4808. if (CreateProcessA(NULL,
  4809. cmdline,
  4810. NULL,
  4811. NULL,
  4812. TRUE,
  4813. CREATE_NEW_PROCESS_GROUP,
  4814. envblk,
  4815. NULL,
  4816. &si,
  4817. &pi)
  4818. == 0) {
  4819. mg_cry_internal(
  4820. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4821. pi.hProcess = (pid_t)-1;
  4822. /* goto spawn_cleanup; */
  4823. }
  4824. spawn_cleanup:
  4825. (void)CloseHandle(si.hStdOutput);
  4826. (void)CloseHandle(si.hStdError);
  4827. (void)CloseHandle(si.hStdInput);
  4828. if (pi.hThread != NULL) {
  4829. (void)CloseHandle(pi.hThread);
  4830. }
  4831. return (pid_t)pi.hProcess;
  4832. }
  4833. #endif /* !NO_CGI */
  4834. static int
  4835. set_blocking_mode(SOCKET sock)
  4836. {
  4837. unsigned long non_blocking = 0;
  4838. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4839. }
  4840. static int
  4841. set_non_blocking_mode(SOCKET sock)
  4842. {
  4843. unsigned long non_blocking = 1;
  4844. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4845. }
  4846. #else
  4847. #if !defined(NO_FILESYSTEMS)
  4848. static int
  4849. mg_stat(const struct mg_connection *conn,
  4850. const char *path,
  4851. struct mg_file_stat *filep)
  4852. {
  4853. struct stat st;
  4854. if (!filep) {
  4855. return 0;
  4856. }
  4857. memset(filep, 0, sizeof(*filep));
  4858. if (mg_path_suspicious(conn, path)) {
  4859. return 0;
  4860. }
  4861. if (0 == stat(path, &st)) {
  4862. filep->size = (uint64_t)(st.st_size);
  4863. filep->last_modified = st.st_mtime;
  4864. filep->is_directory = S_ISDIR(st.st_mode);
  4865. return 1;
  4866. }
  4867. return 0;
  4868. }
  4869. #endif /* NO_FILESYSTEMS */
  4870. static void
  4871. set_close_on_exec(int fd,
  4872. const struct mg_connection *conn /* may be null */,
  4873. struct mg_context *ctx /* may be null */)
  4874. {
  4875. #if defined(__ZEPHYR__)
  4876. (void)fd;
  4877. (void)conn;
  4878. (void)ctx;
  4879. #else
  4880. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4881. if (conn || ctx) {
  4882. struct mg_connection fc;
  4883. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4884. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4885. __func__,
  4886. strerror(ERRNO));
  4887. }
  4888. }
  4889. #endif
  4890. }
  4891. CIVETWEB_API int
  4892. mg_start_thread(mg_thread_func_t func, void *param)
  4893. {
  4894. pthread_t thread_id;
  4895. pthread_attr_t attr;
  4896. int result;
  4897. (void)pthread_attr_init(&attr);
  4898. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4899. #if defined(__ZEPHYR__)
  4900. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4901. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4902. /* Compile-time option to control stack size,
  4903. * e.g. -DUSE_STACK_SIZE=16384 */
  4904. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4905. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4906. result = pthread_create(&thread_id, &attr, func, param);
  4907. pthread_attr_destroy(&attr);
  4908. return result;
  4909. }
  4910. /* Start a thread storing the thread context. */
  4911. static int
  4912. mg_start_thread_with_id(mg_thread_func_t func,
  4913. void *param,
  4914. pthread_t *threadidptr)
  4915. {
  4916. pthread_t thread_id;
  4917. pthread_attr_t attr;
  4918. int result;
  4919. (void)pthread_attr_init(&attr);
  4920. #if defined(__ZEPHYR__)
  4921. pthread_attr_setstack(&attr,
  4922. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4923. ZEPHYR_STACK_SIZE);
  4924. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4925. /* Compile-time option to control stack size,
  4926. * e.g. -DUSE_STACK_SIZE=16384 */
  4927. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4928. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4929. result = pthread_create(&thread_id, &attr, func, param);
  4930. pthread_attr_destroy(&attr);
  4931. if ((result == 0) && (threadidptr != NULL)) {
  4932. *threadidptr = thread_id;
  4933. }
  4934. return result;
  4935. }
  4936. /* Wait for a thread to finish. */
  4937. static int
  4938. mg_join_thread(pthread_t threadid)
  4939. {
  4940. int result;
  4941. result = pthread_join(threadid, NULL);
  4942. return result;
  4943. }
  4944. #if !defined(NO_CGI)
  4945. static pid_t
  4946. spawn_process(struct mg_connection *conn,
  4947. const char *prog,
  4948. char *envblk,
  4949. char *envp[],
  4950. int fdin[2],
  4951. int fdout[2],
  4952. int fderr[2],
  4953. const char *dir,
  4954. int cgi_config_idx)
  4955. {
  4956. pid_t pid;
  4957. const char *interp;
  4958. (void)envblk;
  4959. if ((pid = fork()) == -1) {
  4960. /* Parent */
  4961. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4962. } else if (pid != 0) {
  4963. /* Make sure children close parent-side descriptors.
  4964. * The caller will close the child-side immediately. */
  4965. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4966. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4967. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4968. } else {
  4969. /* Child */
  4970. if (chdir(dir) != 0) {
  4971. mg_cry_internal(
  4972. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4973. } else if (dup2(fdin[0], 0) == -1) {
  4974. mg_cry_internal(conn,
  4975. "%s: dup2(%d, 0): %s",
  4976. __func__,
  4977. fdin[0],
  4978. strerror(ERRNO));
  4979. } else if (dup2(fdout[1], 1) == -1) {
  4980. mg_cry_internal(conn,
  4981. "%s: dup2(%d, 1): %s",
  4982. __func__,
  4983. fdout[1],
  4984. strerror(ERRNO));
  4985. } else if (dup2(fderr[1], 2) == -1) {
  4986. mg_cry_internal(conn,
  4987. "%s: dup2(%d, 2): %s",
  4988. __func__,
  4989. fderr[1],
  4990. strerror(ERRNO));
  4991. } else {
  4992. struct sigaction sa;
  4993. /* Keep stderr and stdout in two different pipes.
  4994. * Stdout will be sent back to the client,
  4995. * stderr should go into a server error log. */
  4996. (void)close(fdin[0]);
  4997. (void)close(fdout[1]);
  4998. (void)close(fderr[1]);
  4999. /* Close write end fdin and read end fdout and fderr */
  5000. (void)close(fdin[1]);
  5001. (void)close(fdout[0]);
  5002. (void)close(fderr[0]);
  5003. /* After exec, all signal handlers are restored to their default
  5004. * values, with one exception of SIGCHLD. According to
  5005. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5006. * will leave unchanged after exec if it was set to be ignored.
  5007. * Restore it to default action. */
  5008. memset(&sa, 0, sizeof(sa));
  5009. sa.sa_handler = SIG_DFL;
  5010. sigaction(SIGCHLD, &sa, NULL);
  5011. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  5012. if (interp == NULL) {
  5013. /* no interpreter configured, call the program directly */
  5014. (void)execle(prog, prog, NULL, envp);
  5015. mg_cry_internal(conn,
  5016. "%s: execle(%s): %s",
  5017. __func__,
  5018. prog,
  5019. strerror(ERRNO));
  5020. } else {
  5021. /* call the configured interpreter */
  5022. const char *interp_args =
  5023. conn->dom_ctx
  5024. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5025. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5026. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5027. } else {
  5028. (void)execle(interp, interp, prog, NULL, envp);
  5029. }
  5030. mg_cry_internal(conn,
  5031. "%s: execle(%s %s): %s",
  5032. __func__,
  5033. interp,
  5034. prog,
  5035. strerror(ERRNO));
  5036. }
  5037. }
  5038. exit(EXIT_FAILURE);
  5039. }
  5040. return pid;
  5041. }
  5042. #endif /* !NO_CGI */
  5043. static int
  5044. set_non_blocking_mode(SOCKET sock)
  5045. {
  5046. int flags = fcntl(sock, F_GETFL, 0);
  5047. if (flags < 0) {
  5048. return -1;
  5049. }
  5050. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5051. return -1;
  5052. }
  5053. return 0;
  5054. }
  5055. static int
  5056. set_blocking_mode(SOCKET sock)
  5057. {
  5058. int flags = fcntl(sock, F_GETFL, 0);
  5059. if (flags < 0) {
  5060. return -1;
  5061. }
  5062. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5063. return -1;
  5064. }
  5065. return 0;
  5066. }
  5067. #endif /* _WIN32 / else */
  5068. /* End of initial operating system specific define block. */
  5069. /* Get a random number (independent of C rand function) */
  5070. static uint64_t
  5071. get_random(void)
  5072. {
  5073. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5074. static uint64_t lcg = 0; /* Linear congruential generator */
  5075. uint64_t now = mg_get_current_time_ns();
  5076. if (lfsr == 0) {
  5077. /* lfsr will be only 0 if has not been initialized,
  5078. * so this code is called only once. */
  5079. lfsr = mg_get_current_time_ns();
  5080. lcg = mg_get_current_time_ns();
  5081. } else {
  5082. /* Get the next step of both random number generators. */
  5083. lfsr = (lfsr >> 1)
  5084. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5085. << 63);
  5086. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5087. }
  5088. /* Combining two pseudo-random number generators and a high resolution
  5089. * part
  5090. * of the current server time will make it hard (impossible?) to guess
  5091. * the
  5092. * next number. */
  5093. return (lfsr ^ lcg ^ now);
  5094. }
  5095. static int
  5096. mg_poll(struct mg_pollfd *pfd,
  5097. unsigned int n,
  5098. int milliseconds,
  5099. const stop_flag_t *stop_flag)
  5100. {
  5101. /* Call poll, but only for a maximum time of a few seconds.
  5102. * This will allow to stop the server after some seconds, instead
  5103. * of having to wait for a long socket timeout. */
  5104. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5105. int check_pollerr = 0;
  5106. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5107. /* If we wait for only one file descriptor, wait on error as well */
  5108. pfd[0].events |= POLLERR;
  5109. check_pollerr = 1;
  5110. }
  5111. do {
  5112. int result;
  5113. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5114. /* Shut down signal */
  5115. return -2;
  5116. }
  5117. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5118. ms_now = milliseconds;
  5119. }
  5120. result = poll(pfd, n, ms_now);
  5121. if (result != 0) {
  5122. int err = ERRNO;
  5123. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5124. /* Poll returned either success (1) or error (-1).
  5125. * Forward both to the caller. */
  5126. if ((check_pollerr)
  5127. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5128. == POLLERR)) {
  5129. /* One and only file descriptor returned error */
  5130. return -1;
  5131. }
  5132. return result;
  5133. }
  5134. }
  5135. /* Poll returned timeout (0). */
  5136. if (milliseconds > 0) {
  5137. milliseconds -= ms_now;
  5138. }
  5139. } while (milliseconds > 0);
  5140. /* timeout: return 0 */
  5141. return 0;
  5142. }
  5143. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5144. * descriptor.
  5145. * Return value:
  5146. * >=0 .. number of bytes successfully written
  5147. * -1 .. timeout
  5148. * -2 .. error
  5149. */
  5150. static int
  5151. push_inner(struct mg_context *ctx,
  5152. FILE *fp,
  5153. SOCKET sock,
  5154. SSL *ssl,
  5155. const char *buf,
  5156. int len,
  5157. double timeout)
  5158. {
  5159. uint64_t start = 0, now = 0, timeout_ns = 0;
  5160. int n, err;
  5161. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5162. #if defined(_WIN32)
  5163. typedef int len_t;
  5164. #else
  5165. typedef size_t len_t;
  5166. #endif
  5167. if (timeout > 0) {
  5168. now = mg_get_current_time_ns();
  5169. start = now;
  5170. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5171. }
  5172. if (ctx == NULL) {
  5173. return -2;
  5174. }
  5175. #if defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  5176. if (ssl) {
  5177. return -2;
  5178. }
  5179. #endif
  5180. /* Try to read until it succeeds, fails, times out, or the server
  5181. * shuts down. */
  5182. for (;;) {
  5183. #if defined(USE_MBEDTLS)
  5184. if (ssl != NULL) {
  5185. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5186. if (n <= 0) {
  5187. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5188. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5189. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5190. n = 0;
  5191. } else {
  5192. fprintf(stderr, "SSL write failed, error %d\n", n);
  5193. return -2;
  5194. }
  5195. } else {
  5196. err = 0;
  5197. }
  5198. } else
  5199. #elif defined(USE_GNUTLS)
  5200. if (ssl != NULL) {
  5201. n = gtls_ssl_write(ssl, (const unsigned char *)buf, (size_t) len);
  5202. if (n < 0) {
  5203. fprintf(stderr, "SSL write failed (%d): %s", n, gnutls_strerror(n));
  5204. return -2;
  5205. } else {
  5206. err = 0;
  5207. }
  5208. } else
  5209. #elif !defined(NO_SSL)
  5210. if (ssl != NULL) {
  5211. ERR_clear_error();
  5212. n = SSL_write(ssl, buf, len);
  5213. if (n <= 0) {
  5214. err = SSL_get_error(ssl, n);
  5215. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5216. err = ERRNO;
  5217. } else if ((err == SSL_ERROR_WANT_READ)
  5218. || (err == SSL_ERROR_WANT_WRITE)) {
  5219. n = 0;
  5220. } else {
  5221. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5222. ERR_clear_error();
  5223. return -2;
  5224. }
  5225. ERR_clear_error();
  5226. } else {
  5227. err = 0;
  5228. }
  5229. } else
  5230. #endif
  5231. if (fp != NULL) {
  5232. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5233. if (ferror(fp)) {
  5234. n = -1;
  5235. err = ERRNO;
  5236. } else {
  5237. err = 0;
  5238. }
  5239. } else {
  5240. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5241. err = (n < 0) ? ERRNO : 0;
  5242. if (ERROR_TRY_AGAIN(err)) {
  5243. err = 0;
  5244. n = 0;
  5245. }
  5246. if (n < 0) {
  5247. /* shutdown of the socket at client side */
  5248. return -2;
  5249. }
  5250. }
  5251. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5252. return -2;
  5253. }
  5254. if ((n > 0) || ((n == 0) && (len == 0))) {
  5255. /* some data has been read, or no data was requested */
  5256. return n;
  5257. }
  5258. if (n < 0) {
  5259. /* socket error - check errno */
  5260. DEBUG_TRACE("send() failed, error %d", err);
  5261. /* TODO (mid): error handling depending on the error code.
  5262. * These codes are different between Windows and Linux.
  5263. * Currently there is no problem with failing send calls,
  5264. * if there is a reproducible situation, it should be
  5265. * investigated in detail.
  5266. */
  5267. return -2;
  5268. }
  5269. /* Only in case n=0 (timeout), repeat calling the write function */
  5270. /* If send failed, wait before retry */
  5271. if (fp != NULL) {
  5272. /* For files, just wait a fixed time.
  5273. * Maybe it helps, maybe not. */
  5274. mg_sleep(5);
  5275. } else {
  5276. /* For sockets, wait for the socket using poll */
  5277. struct mg_pollfd pfd[2];
  5278. int pollres;
  5279. unsigned int num_sock = 1;
  5280. pfd[0].fd = sock;
  5281. pfd[0].events = POLLOUT;
  5282. if (ctx->context_type == CONTEXT_SERVER) {
  5283. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  5284. pfd[num_sock].events = POLLIN;
  5285. num_sock++;
  5286. }
  5287. pollres = mg_poll(pfd, num_sock, (int)(ms_wait), &(ctx->stop_flag));
  5288. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5289. return -2;
  5290. }
  5291. if (pollres > 0) {
  5292. continue;
  5293. }
  5294. }
  5295. if (timeout > 0) {
  5296. now = mg_get_current_time_ns();
  5297. if ((now - start) > timeout_ns) {
  5298. /* Timeout */
  5299. break;
  5300. }
  5301. }
  5302. }
  5303. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5304. used */
  5305. return -1;
  5306. }
  5307. static int
  5308. push_all(struct mg_context *ctx,
  5309. FILE *fp,
  5310. SOCKET sock,
  5311. SSL *ssl,
  5312. const char *buf,
  5313. int len)
  5314. {
  5315. double timeout = -1.0;
  5316. int n, nwritten = 0;
  5317. if (ctx == NULL) {
  5318. return -1;
  5319. }
  5320. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5321. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5322. }
  5323. if (timeout <= 0.0) {
  5324. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5325. / 1000.0;
  5326. }
  5327. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5328. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5329. if (n < 0) {
  5330. if (nwritten == 0) {
  5331. nwritten = -1; /* Propagate the error */
  5332. }
  5333. break;
  5334. } else if (n == 0) {
  5335. break; /* No more data to write */
  5336. } else {
  5337. nwritten += n;
  5338. len -= n;
  5339. }
  5340. }
  5341. return nwritten;
  5342. }
  5343. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5344. * Return value:
  5345. * >=0 .. number of bytes successfully read
  5346. * -1 .. timeout
  5347. * -2 .. error
  5348. */
  5349. static int
  5350. pull_inner(FILE *fp,
  5351. struct mg_connection *conn,
  5352. char *buf,
  5353. int len,
  5354. double timeout)
  5355. {
  5356. int nread, err = 0;
  5357. #if defined(_WIN32)
  5358. typedef int len_t;
  5359. #else
  5360. typedef size_t len_t;
  5361. #endif
  5362. /* We need an additional wait loop around this, because in some cases
  5363. * with TLSwe may get data from the socket but not from SSL_read.
  5364. * In this case we need to repeat at least once.
  5365. */
  5366. if (fp != NULL) {
  5367. /* Use read() instead of fread(), because if we're reading from the
  5368. * CGI pipe, fread() may block until IO buffer is filled up. We
  5369. * cannot afford to block and must pass all read bytes immediately
  5370. * to the client. */
  5371. nread = (int)read(fileno(fp), buf, (size_t)len);
  5372. err = (nread < 0) ? ERRNO : 0;
  5373. if ((nread == 0) && (len > 0)) {
  5374. /* Should get data, but got EOL */
  5375. return -2;
  5376. }
  5377. #if defined(USE_MBEDTLS)
  5378. } else if (conn->ssl != NULL) {
  5379. struct mg_pollfd pfd[2];
  5380. int to_read;
  5381. int pollres;
  5382. unsigned int num_sock = 1;
  5383. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5384. if (to_read > 0) {
  5385. /* We already know there is no more data buffered in conn->buf
  5386. * but there is more available in the SSL layer. So don't poll
  5387. * conn->client.sock yet. */
  5388. pollres = 1;
  5389. if (to_read > len)
  5390. to_read = len;
  5391. } else {
  5392. pfd[0].fd = conn->client.sock;
  5393. pfd[0].events = POLLIN;
  5394. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5395. pfd[num_sock].fd =
  5396. conn->phys_ctx->thread_shutdown_notification_socket;
  5397. pfd[num_sock].events = POLLIN;
  5398. num_sock++;
  5399. }
  5400. to_read = len;
  5401. pollres = mg_poll(pfd,
  5402. num_sock,
  5403. (int)(timeout * 1000.0),
  5404. &(conn->phys_ctx->stop_flag));
  5405. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5406. return -2;
  5407. }
  5408. }
  5409. if (pollres > 0) {
  5410. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5411. if (nread <= 0) {
  5412. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5413. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5414. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5415. nread = 0;
  5416. } else {
  5417. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5418. return -2;
  5419. }
  5420. } else {
  5421. err = 0;
  5422. }
  5423. } else if (pollres < 0) {
  5424. /* Error */
  5425. return -2;
  5426. } else {
  5427. /* pollres = 0 means timeout */
  5428. nread = 0;
  5429. }
  5430. #elif defined(USE_GNUTLS)
  5431. } else if (conn->ssl != NULL) {
  5432. struct mg_pollfd pfd[2];
  5433. size_t to_read;
  5434. int pollres;
  5435. unsigned int num_sock = 1;
  5436. to_read = gnutls_record_check_pending(conn->ssl->sess);
  5437. if (to_read > 0) {
  5438. /* We already know there is no more data buffered in conn->buf
  5439. * but there is more available in the SSL layer. So don't poll
  5440. * conn->client.sock yet. */
  5441. pollres = 1;
  5442. if (to_read > (size_t)len)
  5443. to_read = (size_t)len;
  5444. } else {
  5445. pfd[0].fd = conn->client.sock;
  5446. pfd[0].events = POLLIN;
  5447. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5448. pfd[num_sock].fd =
  5449. conn->phys_ctx->thread_shutdown_notification_socket;
  5450. pfd[num_sock].events = POLLIN;
  5451. num_sock++;
  5452. }
  5453. to_read = (size_t)len;
  5454. pollres = mg_poll(pfd,
  5455. num_sock,
  5456. (int)(timeout * 1000.0),
  5457. &(conn->phys_ctx->stop_flag));
  5458. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5459. return -2;
  5460. }
  5461. }
  5462. if (pollres > 0) {
  5463. nread = gtls_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5464. if (nread < 0) {
  5465. fprintf(stderr, "SSL read failed (%d): %s", nread, gnutls_strerror(nread));
  5466. return -2;
  5467. } else {
  5468. err = 0;
  5469. }
  5470. } else if (pollres < 0) {
  5471. /* Error */
  5472. return -2;
  5473. } else {
  5474. /* pollres = 0 means timeout */
  5475. nread = 0;
  5476. }
  5477. #elif !defined(NO_SSL)
  5478. } else if (conn->ssl != NULL) {
  5479. int ssl_pending;
  5480. struct mg_pollfd pfd[2];
  5481. int pollres;
  5482. unsigned int num_sock = 1;
  5483. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5484. /* We already know there is no more data buffered in conn->buf
  5485. * but there is more available in the SSL layer. So don't poll
  5486. * conn->client.sock yet. */
  5487. if (ssl_pending > len) {
  5488. ssl_pending = len;
  5489. }
  5490. pollres = 1;
  5491. } else {
  5492. pfd[0].fd = conn->client.sock;
  5493. pfd[0].events = POLLIN;
  5494. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5495. pfd[num_sock].fd =
  5496. conn->phys_ctx->thread_shutdown_notification_socket;
  5497. pfd[num_sock].events = POLLIN;
  5498. num_sock++;
  5499. }
  5500. pollres = mg_poll(pfd,
  5501. num_sock,
  5502. (int)(timeout * 1000.0),
  5503. &(conn->phys_ctx->stop_flag));
  5504. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5505. return -2;
  5506. }
  5507. }
  5508. if (pollres > 0) {
  5509. ERR_clear_error();
  5510. nread =
  5511. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5512. if (nread <= 0) {
  5513. err = SSL_get_error(conn->ssl, nread);
  5514. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5515. err = ERRNO;
  5516. } else if ((err == SSL_ERROR_WANT_READ)
  5517. || (err == SSL_ERROR_WANT_WRITE)) {
  5518. nread = 0;
  5519. } else {
  5520. /* All errors should return -2 */
  5521. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5522. ERR_clear_error();
  5523. return -2;
  5524. }
  5525. ERR_clear_error();
  5526. } else {
  5527. err = 0;
  5528. }
  5529. } else if (pollres < 0) {
  5530. /* Error */
  5531. return -2;
  5532. } else {
  5533. /* pollres = 0 means timeout */
  5534. nread = 0;
  5535. }
  5536. #endif
  5537. } else {
  5538. struct mg_pollfd pfd[2];
  5539. int pollres;
  5540. unsigned int num_sock = 1;
  5541. pfd[0].fd = conn->client.sock;
  5542. pfd[0].events = POLLIN;
  5543. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5544. pfd[num_sock].fd =
  5545. conn->phys_ctx->thread_shutdown_notification_socket;
  5546. pfd[num_sock].events = POLLIN;
  5547. num_sock++;
  5548. }
  5549. pollres = mg_poll(pfd,
  5550. num_sock,
  5551. (int)(timeout * 1000.0),
  5552. &(conn->phys_ctx->stop_flag));
  5553. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5554. return -2;
  5555. }
  5556. if (pollres > 0) {
  5557. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5558. err = (nread < 0) ? ERRNO : 0;
  5559. if (nread <= 0) {
  5560. /* shutdown of the socket at client side */
  5561. return -2;
  5562. }
  5563. } else if (pollres < 0) {
  5564. /* error calling poll */
  5565. return -2;
  5566. } else {
  5567. /* pollres = 0 means timeout */
  5568. nread = 0;
  5569. }
  5570. }
  5571. if (conn != NULL && !STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5572. return -2;
  5573. }
  5574. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5575. /* some data has been read, or no data was requested */
  5576. return nread;
  5577. }
  5578. if (nread < 0) {
  5579. /* socket error - check errno */
  5580. #if defined(_WIN32)
  5581. if (err == WSAEWOULDBLOCK) {
  5582. /* TODO (low): check if this is still required */
  5583. /* standard case if called from close_socket_gracefully */
  5584. return -2;
  5585. } else if (err == WSAETIMEDOUT) {
  5586. /* TODO (low): check if this is still required */
  5587. /* timeout is handled by the while loop */
  5588. return 0;
  5589. } else if (err == WSAECONNABORTED) {
  5590. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5591. return -2;
  5592. } else {
  5593. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5594. return -2;
  5595. }
  5596. #else
  5597. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5598. * if the timeout is reached and if the socket was set to non-
  5599. * blocking in close_socket_gracefully, so we can not distinguish
  5600. * here. We have to wait for the timeout in both cases for now.
  5601. */
  5602. if (ERROR_TRY_AGAIN(err)) {
  5603. /* TODO (low): check if this is still required */
  5604. /* EAGAIN/EWOULDBLOCK:
  5605. * standard case if called from close_socket_gracefully
  5606. * => should return -1 */
  5607. /* or timeout occurred
  5608. * => the code must stay in the while loop */
  5609. /* EINTR can be generated on a socket with a timeout set even
  5610. * when SA_RESTART is effective for all relevant signals
  5611. * (see signal(7)).
  5612. * => stay in the while loop */
  5613. } else {
  5614. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5615. return -2;
  5616. }
  5617. #endif
  5618. }
  5619. /* Timeout occurred, but no data available. */
  5620. return -1;
  5621. }
  5622. static int
  5623. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5624. {
  5625. int n, nread = 0;
  5626. double timeout = -1.0;
  5627. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5628. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5629. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5630. }
  5631. if (timeout <= 0.0) {
  5632. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5633. / 1000.0;
  5634. }
  5635. start_time = mg_get_current_time_ns();
  5636. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5637. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5638. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5639. if (n == -2) {
  5640. if (nread == 0) {
  5641. nread = -1; /* Propagate the error */
  5642. }
  5643. break;
  5644. } else if (n == -1) {
  5645. /* timeout */
  5646. if (timeout >= 0.0) {
  5647. now = mg_get_current_time_ns();
  5648. if ((now - start_time) <= timeout_ns) {
  5649. continue;
  5650. }
  5651. }
  5652. break;
  5653. } else if (n == 0) {
  5654. break; /* No more data to read */
  5655. } else {
  5656. nread += n;
  5657. len -= n;
  5658. }
  5659. }
  5660. return nread;
  5661. }
  5662. static void
  5663. discard_unread_request_data(struct mg_connection *conn)
  5664. {
  5665. char buf[MG_BUF_LEN];
  5666. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5667. ;
  5668. }
  5669. static int
  5670. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5671. {
  5672. int64_t content_len, n, buffered_len, nread;
  5673. int64_t len64 =
  5674. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5675. * int, we may not read more
  5676. * bytes */
  5677. const char *body;
  5678. if (conn == NULL) {
  5679. return 0;
  5680. }
  5681. /* If Content-Length is not set for a response with body data,
  5682. * we do not know in advance how much data should be read. */
  5683. content_len = conn->content_len;
  5684. if (content_len < 0) {
  5685. /* The body data is completed when the connection is closed. */
  5686. content_len = INT64_MAX;
  5687. }
  5688. nread = 0;
  5689. if (conn->consumed_content < content_len) {
  5690. /* Adjust number of bytes to read. */
  5691. int64_t left_to_read = content_len - conn->consumed_content;
  5692. if (left_to_read < len64) {
  5693. /* Do not read more than the total content length of the
  5694. * request.
  5695. */
  5696. len64 = left_to_read;
  5697. }
  5698. /* Return buffered data */
  5699. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5700. - conn->consumed_content;
  5701. if (buffered_len > 0) {
  5702. if (len64 < buffered_len) {
  5703. buffered_len = len64;
  5704. }
  5705. body = conn->buf + conn->request_len + conn->consumed_content;
  5706. memcpy(buf, body, (size_t)buffered_len);
  5707. len64 -= buffered_len;
  5708. conn->consumed_content += buffered_len;
  5709. nread += buffered_len;
  5710. buf = (char *)buf + buffered_len;
  5711. }
  5712. /* We have returned all buffered data. Read new data from the remote
  5713. * socket.
  5714. */
  5715. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5716. conn->consumed_content += n;
  5717. nread += n;
  5718. } else {
  5719. nread = ((nread > 0) ? nread : n);
  5720. }
  5721. }
  5722. return (int)nread;
  5723. }
  5724. /* Forward declarations */
  5725. static void handle_request(struct mg_connection *);
  5726. static void log_access(const struct mg_connection *);
  5727. /* Handle request, update statistics and call access log */
  5728. static void
  5729. handle_request_stat_log(struct mg_connection *conn)
  5730. {
  5731. #if defined(USE_SERVER_STATS)
  5732. struct timespec tnow;
  5733. conn->conn_state = 4; /* processing */
  5734. #endif
  5735. handle_request(conn);
  5736. #if defined(USE_SERVER_STATS)
  5737. conn->conn_state = 5; /* processed */
  5738. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5739. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5740. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5741. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5742. conn->num_bytes_sent);
  5743. #endif
  5744. DEBUG_TRACE("%s", "handle_request done");
  5745. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5746. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5747. DEBUG_TRACE("%s", "end_request callback done");
  5748. }
  5749. log_access(conn);
  5750. }
  5751. #if defined(USE_HTTP2)
  5752. #if defined(NO_SSL)
  5753. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5754. #endif
  5755. #define USE_ALPN
  5756. #include "http2.inl"
  5757. /* Not supported with HTTP/2 */
  5758. #define HTTP1_only \
  5759. { \
  5760. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5761. http2_must_use_http1(conn); \
  5762. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5763. return; \
  5764. } \
  5765. }
  5766. #else
  5767. #define HTTP1_only
  5768. #endif
  5769. CIVETWEB_API int
  5770. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5771. {
  5772. if (len > INT_MAX) {
  5773. len = INT_MAX;
  5774. }
  5775. if (conn == NULL) {
  5776. return 0;
  5777. }
  5778. if (conn->is_chunked) {
  5779. size_t all_read = 0;
  5780. while (len > 0) {
  5781. if (conn->is_chunked >= 3) {
  5782. /* No more data left to read */
  5783. return 0;
  5784. }
  5785. if (conn->is_chunked != 1) {
  5786. /* Has error */
  5787. return -1;
  5788. }
  5789. if (conn->consumed_content != conn->content_len) {
  5790. /* copy from the current chunk */
  5791. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5792. if (read_ret < 1) {
  5793. /* read error */
  5794. conn->is_chunked = 2;
  5795. return -1;
  5796. }
  5797. all_read += (size_t)read_ret;
  5798. len -= (size_t)read_ret;
  5799. if (conn->consumed_content == conn->content_len) {
  5800. /* Add data bytes in the current chunk have been read,
  5801. * so we are expecting \r\n now. */
  5802. char x[2];
  5803. conn->content_len += 2;
  5804. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5805. || (x[1] != '\n')) {
  5806. /* Protocol violation */
  5807. conn->is_chunked = 2;
  5808. return -1;
  5809. }
  5810. }
  5811. } else {
  5812. /* fetch a new chunk */
  5813. size_t i;
  5814. char lenbuf[64];
  5815. char *end = NULL;
  5816. unsigned long chunkSize = 0;
  5817. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5818. conn->content_len++;
  5819. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5820. lenbuf[i] = 0;
  5821. }
  5822. if ((i > 0) && (lenbuf[i] == ';')) {
  5823. // chunk extension --> skip chars until next CR
  5824. //
  5825. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5826. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5827. //
  5828. // chunk = chunk-size [ chunk-extension ] CRLF
  5829. // chunk-data CRLF
  5830. // ...
  5831. // chunk-extension= *( ";" chunk-ext-name [ "="
  5832. // chunk-ext-val ] )
  5833. do
  5834. ++conn->content_len;
  5835. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5836. && lenbuf[i] != '\r');
  5837. }
  5838. if ((i > 0) && (lenbuf[i] == '\r')
  5839. && (lenbuf[i - 1] != '\r')) {
  5840. continue;
  5841. }
  5842. if ((i > 1) && (lenbuf[i] == '\n')
  5843. && (lenbuf[i - 1] == '\r')) {
  5844. lenbuf[i + 1] = 0;
  5845. chunkSize = strtoul(lenbuf, &end, 16);
  5846. if (chunkSize == 0) {
  5847. /* regular end of content */
  5848. conn->is_chunked = 3;
  5849. }
  5850. break;
  5851. }
  5852. if (!isxdigit((unsigned char)lenbuf[i])) {
  5853. /* illegal character for chunk length */
  5854. conn->is_chunked = 2;
  5855. return -1;
  5856. }
  5857. }
  5858. if ((end == NULL) || (*end != '\r')) {
  5859. /* chunksize not set correctly */
  5860. conn->is_chunked = 2;
  5861. return -1;
  5862. }
  5863. if (conn->is_chunked == 3) {
  5864. /* try discarding trailer for keep-alive */
  5865. // We found the last chunk (length 0) including the
  5866. // CRLF that terminates that chunk. Now follows a possibly
  5867. // empty trailer and a final CRLF.
  5868. //
  5869. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5870. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5871. //
  5872. // Chunked-Body = *chunk
  5873. // last-chunk
  5874. // trailer
  5875. // CRLF
  5876. // ...
  5877. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5878. // ...
  5879. // trailer = *(entity-header CRLF)
  5880. int crlf_count = 2; // one CRLF already determined
  5881. while (crlf_count < 4 && conn->is_chunked == 3) {
  5882. ++conn->content_len;
  5883. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5884. if ((crlf_count == 0 || crlf_count == 2)) {
  5885. if (lenbuf[0] == '\r')
  5886. ++crlf_count;
  5887. else
  5888. crlf_count = 0;
  5889. } else {
  5890. // previous character was a CR
  5891. // --> next character must be LF
  5892. if (lenbuf[0] == '\n')
  5893. ++crlf_count;
  5894. else
  5895. conn->is_chunked = 2;
  5896. }
  5897. } else
  5898. // premature end of trailer
  5899. conn->is_chunked = 2;
  5900. }
  5901. if (conn->is_chunked == 2)
  5902. return -1;
  5903. else
  5904. conn->is_chunked = 4;
  5905. break;
  5906. }
  5907. /* append a new chunk */
  5908. conn->content_len += (int64_t)chunkSize;
  5909. }
  5910. }
  5911. return (int)all_read;
  5912. }
  5913. return mg_read_inner(conn, buf, len);
  5914. }
  5915. CIVETWEB_API int
  5916. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5917. {
  5918. time_t now;
  5919. int n, total, allowed;
  5920. if (conn == NULL) {
  5921. return 0;
  5922. }
  5923. if (len > INT_MAX) {
  5924. return -1;
  5925. }
  5926. /* Mark connection as "data sent" */
  5927. conn->request_state = 10;
  5928. #if defined(USE_HTTP2)
  5929. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5930. http2_data_frame_head(conn, len, 0);
  5931. }
  5932. #endif
  5933. if (conn->throttle > 0) {
  5934. if ((now = time(NULL)) != conn->last_throttle_time) {
  5935. conn->last_throttle_time = now;
  5936. conn->last_throttle_bytes = 0;
  5937. }
  5938. allowed = conn->throttle - conn->last_throttle_bytes;
  5939. if (allowed > (int)len) {
  5940. allowed = (int)len;
  5941. }
  5942. total = push_all(conn->phys_ctx,
  5943. NULL,
  5944. conn->client.sock,
  5945. conn->ssl,
  5946. (const char *)buf,
  5947. allowed);
  5948. if (total == allowed) {
  5949. buf = (const char *)buf + total;
  5950. conn->last_throttle_bytes += total;
  5951. while ((total < (int)len)
  5952. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5953. allowed = (conn->throttle > ((int)len - total))
  5954. ? (int)len - total
  5955. : conn->throttle;
  5956. n = push_all(conn->phys_ctx,
  5957. NULL,
  5958. conn->client.sock,
  5959. conn->ssl,
  5960. (const char *)buf,
  5961. allowed);
  5962. if (n != allowed) {
  5963. break;
  5964. }
  5965. sleep(1);
  5966. conn->last_throttle_bytes = allowed;
  5967. conn->last_throttle_time = time(NULL);
  5968. buf = (const char *)buf + n;
  5969. total += n;
  5970. }
  5971. }
  5972. } else {
  5973. total = push_all(conn->phys_ctx,
  5974. NULL,
  5975. conn->client.sock,
  5976. conn->ssl,
  5977. (const char *)buf,
  5978. (int)len);
  5979. }
  5980. if (total > 0) {
  5981. conn->num_bytes_sent += total;
  5982. }
  5983. return total;
  5984. }
  5985. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5986. CIVETWEB_API int
  5987. mg_send_chunk(struct mg_connection *conn,
  5988. const char *chunk,
  5989. unsigned int chunk_len)
  5990. {
  5991. char lenbuf[16];
  5992. size_t lenbuf_len;
  5993. int ret;
  5994. int t;
  5995. /* First store the length information in a text buffer. */
  5996. sprintf(lenbuf, "%x\r\n", chunk_len);
  5997. lenbuf_len = strlen(lenbuf);
  5998. /* Then send length information, chunk and terminating \r\n. */
  5999. ret = mg_write(conn, lenbuf, lenbuf_len);
  6000. if (ret != (int)lenbuf_len) {
  6001. return -1;
  6002. }
  6003. t = ret;
  6004. ret = mg_write(conn, chunk, chunk_len);
  6005. if (ret != (int)chunk_len) {
  6006. return -1;
  6007. }
  6008. t += ret;
  6009. ret = mg_write(conn, "\r\n", 2);
  6010. if (ret != 2) {
  6011. return -1;
  6012. }
  6013. t += ret;
  6014. return t;
  6015. }
  6016. #if defined(GCC_DIAGNOSTIC)
  6017. /* This block forwards format strings to printf implementations,
  6018. * so we need to disable the format-nonliteral warning. */
  6019. #pragma GCC diagnostic push
  6020. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6021. #endif
  6022. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6023. static int
  6024. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6025. {
  6026. va_list ap_copy;
  6027. size_t size = MG_BUF_LEN / 4;
  6028. int len = -1;
  6029. *buf = NULL;
  6030. while (len < 0) {
  6031. if (*buf) {
  6032. mg_free(*buf);
  6033. }
  6034. size *= 4;
  6035. *buf = (char *)mg_malloc(size);
  6036. if (!*buf) {
  6037. break;
  6038. }
  6039. va_copy(ap_copy, ap);
  6040. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6041. va_end(ap_copy);
  6042. (*buf)[size - 1] = 0;
  6043. }
  6044. return len;
  6045. }
  6046. /* Print message to buffer. If buffer is large enough to hold the message,
  6047. * return buffer. If buffer is to small, allocate large enough buffer on
  6048. * heap,
  6049. * and return allocated buffer. */
  6050. static int
  6051. alloc_vprintf(char **out_buf,
  6052. char *prealloc_buf,
  6053. size_t prealloc_size,
  6054. const char *fmt,
  6055. va_list ap)
  6056. {
  6057. va_list ap_copy;
  6058. int len;
  6059. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6060. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6061. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6062. * Therefore, we make two passes: on first pass, get required message
  6063. * length.
  6064. * On second pass, actually print the message. */
  6065. va_copy(ap_copy, ap);
  6066. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6067. va_end(ap_copy);
  6068. if (len < 0) {
  6069. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6070. * Switch to alternative code path that uses incremental
  6071. * allocations.
  6072. */
  6073. va_copy(ap_copy, ap);
  6074. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6075. va_end(ap_copy);
  6076. } else if ((size_t)(len) >= prealloc_size) {
  6077. /* The pre-allocated buffer not large enough. */
  6078. /* Allocate a new buffer. */
  6079. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6080. if (!*out_buf) {
  6081. /* Allocation failed. Return -1 as "out of memory" error. */
  6082. return -1;
  6083. }
  6084. /* Buffer allocation successful. Store the string there. */
  6085. va_copy(ap_copy, ap);
  6086. IGNORE_UNUSED_RESULT(
  6087. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6088. va_end(ap_copy);
  6089. } else {
  6090. /* The pre-allocated buffer is large enough.
  6091. * Use it to store the string and return the address. */
  6092. va_copy(ap_copy, ap);
  6093. IGNORE_UNUSED_RESULT(
  6094. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6095. va_end(ap_copy);
  6096. *out_buf = prealloc_buf;
  6097. }
  6098. return len;
  6099. }
  6100. static int
  6101. alloc_printf(char **out_buf, const char *fmt, ...)
  6102. {
  6103. va_list ap;
  6104. int result;
  6105. va_start(ap, fmt);
  6106. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6107. va_end(ap);
  6108. return result;
  6109. }
  6110. #if defined(GCC_DIAGNOSTIC)
  6111. /* Enable format-nonliteral warning again. */
  6112. #pragma GCC diagnostic pop
  6113. #endif
  6114. static int
  6115. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6116. {
  6117. char mem[MG_BUF_LEN];
  6118. char *buf = NULL;
  6119. int len;
  6120. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6121. len = mg_write(conn, buf, (size_t)len);
  6122. }
  6123. if (buf != mem) {
  6124. mg_free(buf);
  6125. }
  6126. return len;
  6127. }
  6128. CIVETWEB_API int
  6129. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6130. {
  6131. va_list ap;
  6132. int result;
  6133. va_start(ap, fmt);
  6134. result = mg_vprintf(conn, fmt, ap);
  6135. va_end(ap);
  6136. return result;
  6137. }
  6138. CIVETWEB_API int
  6139. mg_url_decode(const char *src,
  6140. int src_len,
  6141. char *dst,
  6142. int dst_len,
  6143. int is_form_url_encoded)
  6144. {
  6145. int i, j, a, b;
  6146. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6147. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6148. if ((i < src_len - 2) && (src[i] == '%')
  6149. && isxdigit((unsigned char)src[i + 1])
  6150. && isxdigit((unsigned char)src[i + 2])) {
  6151. a = tolower((unsigned char)src[i + 1]);
  6152. b = tolower((unsigned char)src[i + 2]);
  6153. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6154. i += 2;
  6155. } else if (is_form_url_encoded && (src[i] == '+')) {
  6156. dst[j] = ' ';
  6157. } else {
  6158. dst[j] = src[i];
  6159. }
  6160. }
  6161. dst[j] = '\0'; /* Null-terminate the destination */
  6162. return (i >= src_len) ? j : -1;
  6163. }
  6164. /* form url decoding of an entire string */
  6165. static void
  6166. url_decode_in_place(char *buf)
  6167. {
  6168. int len = (int)strlen(buf);
  6169. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6170. }
  6171. CIVETWEB_API int
  6172. mg_get_var(const char *data,
  6173. size_t data_len,
  6174. const char *name,
  6175. char *dst,
  6176. size_t dst_len)
  6177. {
  6178. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6179. }
  6180. CIVETWEB_API int
  6181. mg_get_var2(const char *data,
  6182. size_t data_len,
  6183. const char *name,
  6184. char *dst,
  6185. size_t dst_len,
  6186. size_t occurrence)
  6187. {
  6188. const char *p, *e, *s;
  6189. size_t name_len;
  6190. int len;
  6191. if ((dst == NULL) || (dst_len == 0)) {
  6192. len = -2;
  6193. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6194. len = -1;
  6195. dst[0] = '\0';
  6196. } else {
  6197. name_len = strlen(name);
  6198. e = data + data_len;
  6199. len = -1;
  6200. dst[0] = '\0';
  6201. /* data is "var1=val1&var2=val2...". Find variable first */
  6202. for (p = data; p + name_len < e; p++) {
  6203. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6204. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6205. /* Point p to variable value */
  6206. p += name_len + 1;
  6207. /* Point s to the end of the value */
  6208. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6209. if (s == NULL) {
  6210. s = e;
  6211. }
  6212. DEBUG_ASSERT(s >= p);
  6213. if (s < p) {
  6214. return -3;
  6215. }
  6216. /* Decode variable into destination buffer */
  6217. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6218. /* Redirect error code from -1 to -2 (destination buffer too
  6219. * small). */
  6220. if (len == -1) {
  6221. len = -2;
  6222. }
  6223. break;
  6224. }
  6225. }
  6226. }
  6227. return len;
  6228. }
  6229. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6230. CIVETWEB_API int
  6231. mg_split_form_urlencoded(char *data,
  6232. struct mg_header *form_fields,
  6233. unsigned num_form_fields)
  6234. {
  6235. char *b;
  6236. int i;
  6237. int num = 0;
  6238. if (data == NULL) {
  6239. /* parameter error */
  6240. return -1;
  6241. }
  6242. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6243. /* determine the number of expected fields */
  6244. if (data[0] == 0) {
  6245. return 0;
  6246. }
  6247. /* count number of & to return the number of key-value-pairs */
  6248. num = 1;
  6249. while (*data) {
  6250. if (*data == '&') {
  6251. num++;
  6252. }
  6253. data++;
  6254. }
  6255. return num;
  6256. }
  6257. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6258. /* parameter error */
  6259. return -1;
  6260. }
  6261. for (i = 0; i < (int)num_form_fields; i++) {
  6262. /* extract key-value pairs from input data */
  6263. while ((*data == ' ') || (*data == '\t')) {
  6264. /* skip initial spaces */
  6265. data++;
  6266. }
  6267. if (*data == 0) {
  6268. /* end of string reached */
  6269. break;
  6270. }
  6271. form_fields[num].name = data;
  6272. /* find & or = */
  6273. b = data;
  6274. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6275. b++;
  6276. }
  6277. if (*b == 0) {
  6278. /* last key without value */
  6279. form_fields[num].value = NULL;
  6280. } else if (*b == '&') {
  6281. /* mid key without value */
  6282. form_fields[num].value = NULL;
  6283. } else {
  6284. /* terminate string */
  6285. *b = 0;
  6286. /* value starts after '=' */
  6287. data = b + 1;
  6288. form_fields[num].value = data;
  6289. }
  6290. /* new field is stored */
  6291. num++;
  6292. /* find a next key */
  6293. b = strchr(data, '&');
  6294. if (b == 0) {
  6295. /* no more data */
  6296. break;
  6297. } else {
  6298. /* terminate value of last field at '&' */
  6299. *b = 0;
  6300. /* next key-value-pairs starts after '&' */
  6301. data = b + 1;
  6302. }
  6303. }
  6304. /* Decode all values */
  6305. for (i = 0; i < num; i++) {
  6306. if (form_fields[i].name) {
  6307. url_decode_in_place((char *)form_fields[i].name);
  6308. }
  6309. if (form_fields[i].value) {
  6310. url_decode_in_place((char *)form_fields[i].value);
  6311. }
  6312. }
  6313. /* return number of fields found */
  6314. return num;
  6315. }
  6316. /* HCP24: some changes to compare whole var_name */
  6317. CIVETWEB_API int
  6318. mg_get_cookie(const char *cookie_header,
  6319. const char *var_name,
  6320. char *dst,
  6321. size_t dst_size)
  6322. {
  6323. const char *s, *p, *end;
  6324. int name_len, len = -1;
  6325. if ((dst == NULL) || (dst_size == 0)) {
  6326. return -2;
  6327. }
  6328. dst[0] = '\0';
  6329. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6330. return -1;
  6331. }
  6332. name_len = (int)strlen(var_name);
  6333. end = s + strlen(s);
  6334. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6335. if (s[name_len] == '=') {
  6336. /* HCP24: now check is it a substring or a full cookie name */
  6337. if ((s == cookie_header) || (s[-1] == ' ')) {
  6338. s += name_len + 1;
  6339. if ((p = strchr(s, ' ')) == NULL) {
  6340. p = end;
  6341. }
  6342. if (p[-1] == ';') {
  6343. p--;
  6344. }
  6345. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6346. s++;
  6347. p--;
  6348. }
  6349. if ((size_t)(p - s) < dst_size) {
  6350. len = (int)(p - s);
  6351. mg_strlcpy(dst, s, (size_t)len + 1);
  6352. } else {
  6353. len = -3;
  6354. }
  6355. break;
  6356. }
  6357. }
  6358. }
  6359. return len;
  6360. }
  6361. CIVETWEB_API int
  6362. mg_base64_encode(const unsigned char *src,
  6363. size_t src_len,
  6364. char *dst,
  6365. size_t *dst_len)
  6366. {
  6367. static const char *b64 =
  6368. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6369. size_t i, j;
  6370. int a, b, c;
  6371. if (dst_len != NULL) {
  6372. /* Expected length including 0 termination: */
  6373. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6374. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6375. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6376. if (*dst_len < expected_len) {
  6377. if (*dst_len > 0) {
  6378. dst[0] = '\0';
  6379. }
  6380. *dst_len = expected_len;
  6381. return 0;
  6382. }
  6383. }
  6384. for (i = j = 0; i < src_len; i += 3) {
  6385. a = src[i];
  6386. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6387. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6388. dst[j++] = b64[a >> 2];
  6389. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6390. if (i + 1 < src_len) {
  6391. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6392. }
  6393. if (i + 2 < src_len) {
  6394. dst[j++] = b64[c & 63];
  6395. }
  6396. }
  6397. while (j % 4 != 0) {
  6398. dst[j++] = '=';
  6399. }
  6400. dst[j++] = '\0';
  6401. if (dst_len != NULL) {
  6402. *dst_len = (size_t)j;
  6403. }
  6404. /* Return -1 for "OK" */
  6405. return -1;
  6406. }
  6407. static unsigned char
  6408. b64reverse(char letter)
  6409. {
  6410. if ((letter >= 'A') && (letter <= 'Z')) {
  6411. return (unsigned char)(letter - 'A');
  6412. }
  6413. if ((letter >= 'a') && (letter <= 'z')) {
  6414. return (unsigned char)(letter - 'a' + 26);
  6415. }
  6416. if ((letter >= '0') && (letter <= '9')) {
  6417. return (unsigned char)(letter - '0' + 52);
  6418. }
  6419. if (letter == '+') {
  6420. return 62;
  6421. }
  6422. if (letter == '/') {
  6423. return 63;
  6424. }
  6425. if (letter == '=') {
  6426. return 255; /* normal end */
  6427. }
  6428. return 254; /* error */
  6429. }
  6430. CIVETWEB_API int
  6431. mg_base64_decode(const char *src,
  6432. size_t src_len,
  6433. unsigned char *dst,
  6434. size_t *dst_len)
  6435. {
  6436. size_t i;
  6437. unsigned char a, b, c, d;
  6438. size_t dst_len_limit = (size_t)-1;
  6439. size_t dst_len_used = 0;
  6440. if (dst_len != NULL) {
  6441. dst_len_limit = *dst_len;
  6442. *dst_len = 0;
  6443. }
  6444. for (i = 0; i < src_len; i += 4) {
  6445. /* Read 4 characters from BASE64 string */
  6446. a = b64reverse(src[i]);
  6447. if (a >= 254) {
  6448. return (int)i;
  6449. }
  6450. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6451. if (b >= 254) {
  6452. return (int)i + 1;
  6453. }
  6454. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6455. if (c == 254) {
  6456. return (int)i + 2;
  6457. }
  6458. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6459. if (d == 254) {
  6460. return (int)i + 3;
  6461. }
  6462. /* Add first (of 3) decoded character */
  6463. if (dst_len_used < dst_len_limit) {
  6464. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6465. + (unsigned char)(b >> 4));
  6466. }
  6467. dst_len_used++;
  6468. if (c != 255) {
  6469. if (dst_len_used < dst_len_limit) {
  6470. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6471. + (unsigned char)(c >> 2));
  6472. }
  6473. dst_len_used++;
  6474. if (d != 255) {
  6475. if (dst_len_used < dst_len_limit) {
  6476. dst[dst_len_used] =
  6477. (unsigned char)((unsigned char)(c << 6) + d);
  6478. }
  6479. dst_len_used++;
  6480. }
  6481. }
  6482. }
  6483. /* Add terminating zero */
  6484. if (dst_len_used < dst_len_limit) {
  6485. dst[dst_len_used] = '\0';
  6486. }
  6487. dst_len_used++;
  6488. if (dst_len != NULL) {
  6489. *dst_len = dst_len_used;
  6490. }
  6491. if (dst_len_used > dst_len_limit) {
  6492. /* Out of memory */
  6493. return 0;
  6494. }
  6495. /* Return -1 for "OK" */
  6496. return -1;
  6497. }
  6498. static int
  6499. is_put_or_delete_method(const struct mg_connection *conn)
  6500. {
  6501. if (conn) {
  6502. const char *s = conn->request_info.request_method;
  6503. if (s != NULL) {
  6504. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6505. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6506. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6507. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6508. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6509. || !strcmp(s, "COPY"));
  6510. }
  6511. }
  6512. return 0;
  6513. }
  6514. static int
  6515. is_civetweb_webdav_method(const struct mg_connection *conn)
  6516. {
  6517. /* Note: Here we only have to identify the WebDav methods that need special
  6518. * handling in the CivetWeb code - not all methods used in WebDav. In
  6519. * particular, methods used on directories (when using Windows Explorer as
  6520. * WebDav client).
  6521. */
  6522. if (conn) {
  6523. const char *s = conn->request_info.request_method;
  6524. if (s != NULL) {
  6525. /* These are the civetweb builtin DAV methods */
  6526. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6527. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6528. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6529. }
  6530. }
  6531. return 0;
  6532. }
  6533. #if !defined(NO_FILES)
  6534. static int
  6535. extention_matches_script(
  6536. struct mg_connection *conn, /* in: request (must be valid) */
  6537. const char *filename /* in: filename (must be valid) */
  6538. )
  6539. {
  6540. #if !defined(NO_CGI)
  6541. int cgi_config_idx, inc, max;
  6542. #endif
  6543. #if defined(USE_LUA)
  6544. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6545. filename)
  6546. > 0) {
  6547. return 1;
  6548. }
  6549. #endif
  6550. #if defined(USE_DUKTAPE)
  6551. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6552. filename)
  6553. > 0) {
  6554. return 1;
  6555. }
  6556. #endif
  6557. #if !defined(NO_CGI)
  6558. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6559. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6560. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6561. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6562. && (match_prefix_strlen(
  6563. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6564. filename)
  6565. > 0)) {
  6566. return 1;
  6567. }
  6568. }
  6569. #endif
  6570. /* filename and conn could be unused, if all preocessor conditions
  6571. * are false (no script language supported). */
  6572. (void)filename;
  6573. (void)conn;
  6574. return 0;
  6575. }
  6576. static int
  6577. extention_matches_template_text(
  6578. struct mg_connection *conn, /* in: request (must be valid) */
  6579. const char *filename /* in: filename (must be valid) */
  6580. )
  6581. {
  6582. #if defined(USE_LUA)
  6583. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6584. filename)
  6585. > 0) {
  6586. return 1;
  6587. }
  6588. #endif
  6589. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6590. > 0) {
  6591. return 1;
  6592. }
  6593. return 0;
  6594. }
  6595. /* For given directory path, substitute it to valid index file.
  6596. * Return 1 if index file has been found, 0 if not found.
  6597. * If the file is found, it's stats is returned in stp. */
  6598. static int
  6599. substitute_index_file_aux(struct mg_connection *conn,
  6600. char *path,
  6601. size_t path_len,
  6602. struct mg_file_stat *filestat)
  6603. {
  6604. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6605. struct vec filename_vec;
  6606. size_t n = strlen(path);
  6607. int found = 0;
  6608. /* The 'path' given to us points to the directory. Remove all trailing
  6609. * directory separator characters from the end of the path, and
  6610. * then append single directory separator character. */
  6611. while ((n > 0) && (path[n - 1] == '/')) {
  6612. n--;
  6613. }
  6614. path[n] = '/';
  6615. /* Traverse index files list. For each entry, append it to the given
  6616. * path and see if the file exists. If it exists, break the loop */
  6617. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6618. /* Ignore too long entries that may overflow path buffer */
  6619. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6620. continue;
  6621. }
  6622. /* Prepare full path to the index file */
  6623. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6624. /* Does it exist? */
  6625. if (mg_stat(conn, path, filestat)) {
  6626. /* Yes it does, break the loop */
  6627. found = 1;
  6628. break;
  6629. }
  6630. }
  6631. /* If no index file exists, restore directory path */
  6632. if (!found) {
  6633. path[n] = '\0';
  6634. }
  6635. return found;
  6636. }
  6637. /* Same as above, except if the first try fails and a fallback-root is
  6638. * configured, we'll try there also */
  6639. static int
  6640. substitute_index_file(struct mg_connection *conn,
  6641. char *path,
  6642. size_t path_len,
  6643. struct mg_file_stat *filestat)
  6644. {
  6645. int ret = substitute_index_file_aux(conn, path, path_len, filestat);
  6646. if (ret == 0) {
  6647. const char *root_prefix = conn->dom_ctx->config[DOCUMENT_ROOT];
  6648. const char *fallback_root_prefix =
  6649. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT];
  6650. if ((root_prefix) && (fallback_root_prefix)) {
  6651. const size_t root_prefix_len = strlen(root_prefix);
  6652. if ((strncmp(path, root_prefix, root_prefix_len) == 0)) {
  6653. char scratch_path[UTF8_PATH_MAX]; /* separate storage, to avoid
  6654. side effects if we fail */
  6655. size_t sub_path_len;
  6656. const size_t fallback_root_prefix_len =
  6657. strlen(fallback_root_prefix);
  6658. const char *sub_path = path + root_prefix_len;
  6659. while (*sub_path == '/') {
  6660. sub_path++;
  6661. }
  6662. sub_path_len = strlen(sub_path);
  6663. if (((fallback_root_prefix_len + 1 + sub_path_len + 1)
  6664. < sizeof(scratch_path))) {
  6665. /* The concatenations below are all safe because we
  6666. * pre-verified string lengths above */
  6667. char *nul;
  6668. strcpy(scratch_path, fallback_root_prefix);
  6669. nul = strchr(scratch_path, '\0');
  6670. if ((nul > scratch_path) && (*(nul - 1) != '/')) {
  6671. *nul++ = '/';
  6672. *nul = '\0';
  6673. }
  6674. strcat(scratch_path, sub_path);
  6675. if (substitute_index_file_aux(conn,
  6676. scratch_path,
  6677. sizeof(scratch_path),
  6678. filestat)) {
  6679. mg_strlcpy(path, scratch_path, path_len);
  6680. return 1;
  6681. }
  6682. }
  6683. }
  6684. }
  6685. }
  6686. return ret;
  6687. }
  6688. #endif
  6689. static void
  6690. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6691. char *filename, /* out: filename */
  6692. size_t filename_buf_len, /* in: size of filename buffer */
  6693. struct mg_file_stat *filestat, /* out: file status structure */
  6694. int *is_found, /* out: file found (directly) */
  6695. int *is_script_resource, /* out: handled by a script? */
  6696. int *is_websocket_request, /* out: websocket connection? */
  6697. int *is_put_or_delete_request, /* out: put/delete a file? */
  6698. int *is_webdav_request, /* out: webdav request? */
  6699. int *is_template_text /* out: SSI file or LSP file? */
  6700. )
  6701. {
  6702. char const *accept_encoding;
  6703. #if !defined(NO_FILES)
  6704. const char *uri = conn->request_info.local_uri;
  6705. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT],
  6706. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT],
  6707. NULL};
  6708. int fileExists = 0;
  6709. const char *rewrite;
  6710. struct vec a, b;
  6711. ptrdiff_t match_len;
  6712. char gz_path[UTF8_PATH_MAX];
  6713. int truncated;
  6714. int i;
  6715. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6716. char *tmp_str;
  6717. size_t tmp_str_len, sep_pos;
  6718. int allow_substitute_script_subresources;
  6719. #endif
  6720. #else
  6721. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6722. #endif
  6723. /* Step 1: Set all initially unknown outputs to zero */
  6724. memset(filestat, 0, sizeof(*filestat));
  6725. *filename = 0;
  6726. *is_found = 0;
  6727. *is_script_resource = 0;
  6728. *is_template_text = 0;
  6729. /* Step 2: Classify the request method */
  6730. /* Step 2a: Check if the request attempts to modify the file system */
  6731. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6732. /* Step 2b: Check if the request uses WebDav method that requires special
  6733. * handling */
  6734. *is_webdav_request = is_civetweb_webdav_method(conn);
  6735. /* Step 3: Check if it is a websocket request, and modify the document
  6736. * root if required */
  6737. #if defined(USE_WEBSOCKET)
  6738. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6739. #if !defined(NO_FILES)
  6740. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6741. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6742. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6743. }
  6744. #endif /* !NO_FILES */
  6745. #else /* USE_WEBSOCKET */
  6746. *is_websocket_request = 0;
  6747. #endif /* USE_WEBSOCKET */
  6748. /* Step 4: Check if gzip encoded response is allowed */
  6749. conn->accept_gzip = 0;
  6750. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6751. if (strstr(accept_encoding, "gzip") != NULL) {
  6752. conn->accept_gzip = 1;
  6753. }
  6754. }
  6755. #if !defined(NO_FILES)
  6756. /* Step 5: If there is no root directory, don't look for files. */
  6757. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6758. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6759. * config is not required. */
  6760. if (roots[0] == NULL) {
  6761. /* all file related outputs have already been set to 0, just return
  6762. */
  6763. return;
  6764. }
  6765. for (i = 0; roots[i] != NULL; i++) {
  6766. /* Step 6: Determine the local file path from the root path and the
  6767. * request uri. */
  6768. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6769. * part of the path one byte on the right. */
  6770. truncated = 0;
  6771. mg_snprintf(conn,
  6772. &truncated,
  6773. filename,
  6774. filename_buf_len - 1,
  6775. "%s%s",
  6776. roots[i],
  6777. uri);
  6778. if (truncated) {
  6779. goto interpret_cleanup;
  6780. }
  6781. /* Step 7: URI rewriting */
  6782. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6783. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6784. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6785. mg_snprintf(conn,
  6786. &truncated,
  6787. filename,
  6788. filename_buf_len - 1,
  6789. "%.*s%s",
  6790. (int)b.len,
  6791. b.ptr,
  6792. uri + match_len);
  6793. break;
  6794. }
  6795. }
  6796. if (truncated) {
  6797. goto interpret_cleanup;
  6798. }
  6799. /* Step 8: Check if the file exists at the server */
  6800. /* Local file path and name, corresponding to requested URI
  6801. * is now stored in "filename" variable. */
  6802. if (mg_stat(conn, filename, filestat)) {
  6803. fileExists = 1;
  6804. break;
  6805. }
  6806. }
  6807. if (fileExists) {
  6808. int uri_len = (int)strlen(uri);
  6809. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6810. /* 8.1: File exists. */
  6811. *is_found = 1;
  6812. /* 8.2: Check if it is a script type. */
  6813. if (extention_matches_script(conn, filename)) {
  6814. /* The request addresses a CGI resource, Lua script or
  6815. * server-side javascript.
  6816. * The URI corresponds to the script itself (like
  6817. * /path/script.cgi), and there is no additional resource
  6818. * path (like /path/script.cgi/something).
  6819. * Requests that modify (replace or delete) a resource, like
  6820. * PUT and DELETE requests, should replace/delete the script
  6821. * file.
  6822. * Requests that read or write from/to a resource, like GET and
  6823. * POST requests, should call the script and return the
  6824. * generated response. */
  6825. *is_script_resource = (!*is_put_or_delete_request);
  6826. }
  6827. /* 8.3: Check for SSI and LSP files */
  6828. if (extention_matches_template_text(conn, filename)) {
  6829. /* Same as above, but for *.lsp and *.shtml files. */
  6830. /* A "template text" is a file delivered directly to the client,
  6831. * but with some text tags replaced by dynamic content.
  6832. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6833. * (LP, LSP) file. */
  6834. *is_template_text = (!*is_put_or_delete_request);
  6835. }
  6836. /* 8.4: If the request target is a directory, there could be
  6837. * a substitute file (index.html, index.cgi, ...). */
  6838. /* But do not substitute a directory for a WebDav request */
  6839. if (filestat->is_directory && is_uri_end_slash
  6840. && (!*is_webdav_request)) {
  6841. /* Use a local copy here, since substitute_index_file will
  6842. * change the content of the file status */
  6843. struct mg_file_stat tmp_filestat;
  6844. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6845. if (substitute_index_file(
  6846. conn, filename, filename_buf_len, &tmp_filestat)) {
  6847. /* Substitute file found. Copy stat to the output, then
  6848. * check if the file is a script file */
  6849. *filestat = tmp_filestat;
  6850. if (extention_matches_script(conn, filename)) {
  6851. /* Substitute file is a script file */
  6852. *is_script_resource = 1;
  6853. } else if (extention_matches_template_text(conn, filename)) {
  6854. /* Substitute file is a LSP or SSI file */
  6855. *is_template_text = 1;
  6856. } else {
  6857. /* Substitute file is a regular file */
  6858. *is_script_resource = 0;
  6859. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6860. }
  6861. }
  6862. /* If there is no substitute file, the server could return
  6863. * a directory listing in a later step */
  6864. }
  6865. return;
  6866. }
  6867. /* Step 9: Check for zipped files: */
  6868. /* If we can't find the actual file, look for the file
  6869. * with the same name but a .gz extension. If we find it,
  6870. * use that and set the gzipped flag in the file struct
  6871. * to indicate that the response need to have the content-
  6872. * encoding: gzip header.
  6873. * We can only do this if the browser declares support. */
  6874. if (conn->accept_gzip) {
  6875. mg_snprintf(
  6876. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6877. if (truncated) {
  6878. goto interpret_cleanup;
  6879. }
  6880. if (mg_stat(conn, gz_path, filestat)) {
  6881. if (filestat) {
  6882. filestat->is_gzipped = 1;
  6883. *is_found = 1;
  6884. }
  6885. /* Currently gz files can not be scripts. */
  6886. return;
  6887. }
  6888. }
  6889. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6890. /* Step 10: Script resources may handle sub-resources */
  6891. /* Support PATH_INFO for CGI scripts. */
  6892. tmp_str_len = strlen(filename);
  6893. tmp_str =
  6894. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6895. if (!tmp_str) {
  6896. /* Out of memory */
  6897. goto interpret_cleanup;
  6898. }
  6899. memcpy(tmp_str, filename, tmp_str_len + 1);
  6900. /* Check config, if index scripts may have sub-resources */
  6901. allow_substitute_script_subresources =
  6902. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6903. "yes");
  6904. if (*is_webdav_request) {
  6905. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6906. * PROPFIND for their subresources? */
  6907. /* allow_substitute_script_subresources = 0; */
  6908. }
  6909. sep_pos = tmp_str_len;
  6910. while (sep_pos > 0) {
  6911. sep_pos--;
  6912. if (tmp_str[sep_pos] == '/') {
  6913. int is_script = 0, does_exist = 0;
  6914. tmp_str[sep_pos] = 0;
  6915. if (tmp_str[0]) {
  6916. is_script = extention_matches_script(conn, tmp_str);
  6917. does_exist = mg_stat(conn, tmp_str, filestat);
  6918. }
  6919. if (does_exist && is_script) {
  6920. filename[sep_pos] = 0;
  6921. memmove(filename + sep_pos + 2,
  6922. filename + sep_pos + 1,
  6923. strlen(filename + sep_pos + 1) + 1);
  6924. conn->path_info = filename + sep_pos + 1;
  6925. filename[sep_pos + 1] = '/';
  6926. *is_script_resource = 1;
  6927. *is_found = 1;
  6928. break;
  6929. }
  6930. if (allow_substitute_script_subresources) {
  6931. if (substitute_index_file(
  6932. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6933. /* some intermediate directory has an index file */
  6934. if (extention_matches_script(conn, tmp_str)) {
  6935. size_t script_name_len = strlen(tmp_str);
  6936. /* subres_name read before this memory locatio will be
  6937. overwritten */
  6938. char *subres_name = filename + sep_pos;
  6939. size_t subres_name_len = strlen(subres_name);
  6940. DEBUG_TRACE("Substitute script %s serving path %s",
  6941. tmp_str,
  6942. filename);
  6943. /* this index file is a script */
  6944. if ((script_name_len + subres_name_len + 2)
  6945. >= filename_buf_len) {
  6946. mg_free(tmp_str);
  6947. goto interpret_cleanup;
  6948. }
  6949. conn->path_info =
  6950. filename + script_name_len + 1; /* new target */
  6951. memmove(conn->path_info, subres_name, subres_name_len);
  6952. conn->path_info[subres_name_len] = 0;
  6953. memcpy(filename, tmp_str, script_name_len + 1);
  6954. *is_script_resource = 1;
  6955. *is_found = 1;
  6956. break;
  6957. } else {
  6958. DEBUG_TRACE("Substitute file %s serving path %s",
  6959. tmp_str,
  6960. filename);
  6961. /* non-script files will not have sub-resources */
  6962. filename[sep_pos] = 0;
  6963. conn->path_info = 0;
  6964. *is_script_resource = 0;
  6965. *is_found = 0;
  6966. break;
  6967. }
  6968. }
  6969. }
  6970. tmp_str[sep_pos] = '/';
  6971. }
  6972. }
  6973. mg_free(tmp_str);
  6974. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6975. #endif /* !defined(NO_FILES) */
  6976. return;
  6977. #if !defined(NO_FILES)
  6978. /* Reset all outputs */
  6979. interpret_cleanup:
  6980. memset(filestat, 0, sizeof(*filestat));
  6981. *filename = 0;
  6982. *is_found = 0;
  6983. *is_script_resource = 0;
  6984. *is_websocket_request = 0;
  6985. *is_put_or_delete_request = 0;
  6986. #endif /* !defined(NO_FILES) */
  6987. }
  6988. /* Check whether full request is buffered. Return:
  6989. * -1 if request or response is malformed
  6990. * 0 if request or response is not yet fully buffered
  6991. * >0 actual request length, including last \r\n\r\n */
  6992. static int
  6993. get_http_header_len(const char *buf, int buflen)
  6994. {
  6995. int i;
  6996. for (i = 0; i < buflen; i++) {
  6997. /* Do an unsigned comparison in some conditions below */
  6998. const unsigned char c = (unsigned char)buf[i];
  6999. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7000. && !isprint(c)) {
  7001. /* abort scan as soon as one malformed character is found */
  7002. return -1;
  7003. }
  7004. if (i < buflen - 1) {
  7005. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7006. /* Two newline, no carriage return - not standard compliant,
  7007. * but it should be accepted */
  7008. return i + 2;
  7009. }
  7010. }
  7011. if (i < buflen - 3) {
  7012. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7013. && (buf[i + 3] == '\n')) {
  7014. /* Two \r\n - standard compliant */
  7015. return i + 4;
  7016. }
  7017. }
  7018. }
  7019. return 0;
  7020. }
  7021. #if !defined(NO_CACHING)
  7022. /* Convert month to the month number. Return -1 on error, or month number */
  7023. static int
  7024. get_month_index(const char *s)
  7025. {
  7026. size_t i;
  7027. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7028. if (!strcmp(s, month_names[i])) {
  7029. return (int)i;
  7030. }
  7031. }
  7032. return -1;
  7033. }
  7034. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7035. static time_t
  7036. parse_date_string(const char *datetime)
  7037. {
  7038. char month_str[32] = {0};
  7039. int second, minute, hour, day, month, year;
  7040. time_t result = (time_t)0;
  7041. struct tm tm;
  7042. if ((sscanf(datetime,
  7043. "%d/%3s/%d %d:%d:%d",
  7044. &day,
  7045. month_str,
  7046. &year,
  7047. &hour,
  7048. &minute,
  7049. &second)
  7050. == 6)
  7051. || (sscanf(datetime,
  7052. "%d %3s %d %d:%d:%d",
  7053. &day,
  7054. month_str,
  7055. &year,
  7056. &hour,
  7057. &minute,
  7058. &second)
  7059. == 6)
  7060. || (sscanf(datetime,
  7061. "%*3s, %d %3s %d %d:%d:%d",
  7062. &day,
  7063. month_str,
  7064. &year,
  7065. &hour,
  7066. &minute,
  7067. &second)
  7068. == 6)
  7069. || (sscanf(datetime,
  7070. "%d-%3s-%d %d:%d:%d",
  7071. &day,
  7072. month_str,
  7073. &year,
  7074. &hour,
  7075. &minute,
  7076. &second)
  7077. == 6)) {
  7078. month = get_month_index(month_str);
  7079. if ((month >= 0) && (year >= 1970)) {
  7080. memset(&tm, 0, sizeof(tm));
  7081. tm.tm_year = year - 1900;
  7082. tm.tm_mon = month;
  7083. tm.tm_mday = day;
  7084. tm.tm_hour = hour;
  7085. tm.tm_min = minute;
  7086. tm.tm_sec = second;
  7087. result = timegm(&tm);
  7088. }
  7089. }
  7090. return result;
  7091. }
  7092. #endif /* !NO_CACHING */
  7093. /* Pre-process URIs according to RFC + protect against directory disclosure
  7094. * attacks by removing '..', excessive '/' and '\' characters */
  7095. static void
  7096. remove_dot_segments(char *inout)
  7097. {
  7098. /* Windows backend protection
  7099. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7100. * in URI by slash */
  7101. char *out_end = inout;
  7102. char *in = inout;
  7103. if (!in) {
  7104. /* Param error. */
  7105. return;
  7106. }
  7107. while (*in) {
  7108. if (*in == '\\') {
  7109. *in = '/';
  7110. }
  7111. in++;
  7112. }
  7113. /* Algorithm "remove_dot_segments" from
  7114. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7115. /* Step 1:
  7116. * The input buffer is initialized.
  7117. * The output buffer is initialized to the empty string.
  7118. */
  7119. in = inout;
  7120. /* Step 2:
  7121. * While the input buffer is not empty, loop as follows:
  7122. */
  7123. /* Less than out_end of the inout buffer is used as output, so keep
  7124. * condition: out_end <= in */
  7125. while (*in) {
  7126. /* Step 2a:
  7127. * If the input buffer begins with a prefix of "../" or "./",
  7128. * then remove that prefix from the input buffer;
  7129. */
  7130. if (!strncmp(in, "../", 3)) {
  7131. in += 3;
  7132. } else if (!strncmp(in, "./", 2)) {
  7133. in += 2;
  7134. }
  7135. /* otherwise */
  7136. /* Step 2b:
  7137. * if the input buffer begins with a prefix of "/./" or "/.",
  7138. * where "." is a complete path segment, then replace that
  7139. * prefix with "/" in the input buffer;
  7140. */
  7141. else if (!strncmp(in, "/./", 3)) {
  7142. in += 2;
  7143. } else if (!strcmp(in, "/.")) {
  7144. in[1] = 0;
  7145. }
  7146. /* otherwise */
  7147. /* Step 2c:
  7148. * if the input buffer begins with a prefix of "/../" or "/..",
  7149. * where ".." is a complete path segment, then replace that
  7150. * prefix with "/" in the input buffer and remove the last
  7151. * segment and its preceding "/" (if any) from the output
  7152. * buffer;
  7153. */
  7154. else if (!strncmp(in, "/../", 4)) {
  7155. in += 3;
  7156. if (inout != out_end) {
  7157. /* remove last segment */
  7158. do {
  7159. out_end--;
  7160. } while ((inout != out_end) && (*out_end != '/'));
  7161. }
  7162. } else if (!strcmp(in, "/..")) {
  7163. in[1] = 0;
  7164. if (inout != out_end) {
  7165. /* remove last segment */
  7166. do {
  7167. out_end--;
  7168. } while ((inout != out_end) && (*out_end != '/'));
  7169. }
  7170. }
  7171. /* otherwise */
  7172. /* Step 2d:
  7173. * if the input buffer consists only of "." or "..", then remove
  7174. * that from the input buffer;
  7175. */
  7176. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7177. *in = 0;
  7178. }
  7179. /* otherwise */
  7180. /* Step 2e:
  7181. * move the first path segment in the input buffer to the end of
  7182. * the output buffer, including the initial "/" character (if
  7183. * any) and any subsequent characters up to, but not including,
  7184. * the next "/" character or the end of the input buffer.
  7185. */
  7186. else {
  7187. do {
  7188. *out_end = *in;
  7189. out_end++;
  7190. in++;
  7191. } while ((*in != 0) && (*in != '/'));
  7192. }
  7193. }
  7194. /* Step 3:
  7195. * Finally, the output buffer is returned as the result of
  7196. * remove_dot_segments.
  7197. */
  7198. /* Terminate output */
  7199. *out_end = 0;
  7200. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7201. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7202. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7203. * or "//" anymore.
  7204. */
  7205. out_end = in = inout;
  7206. while (*in) {
  7207. if (*in == '.') {
  7208. /* remove . at the end or preceding of / */
  7209. char *in_ahead = in;
  7210. do {
  7211. in_ahead++;
  7212. } while (*in_ahead == '.');
  7213. if (*in_ahead == '/') {
  7214. in = in_ahead;
  7215. if ((out_end != inout) && (out_end[-1] == '/')) {
  7216. /* remove generated // */
  7217. out_end--;
  7218. }
  7219. } else if (*in_ahead == 0) {
  7220. in = in_ahead;
  7221. } else {
  7222. do {
  7223. *out_end++ = '.';
  7224. in++;
  7225. } while (in != in_ahead);
  7226. }
  7227. } else if (*in == '/') {
  7228. /* replace // by / */
  7229. *out_end++ = '/';
  7230. do {
  7231. in++;
  7232. } while (*in == '/');
  7233. } else {
  7234. *out_end++ = *in;
  7235. in++;
  7236. }
  7237. }
  7238. *out_end = 0;
  7239. }
  7240. static const struct {
  7241. const char *extension;
  7242. size_t ext_len;
  7243. const char *mime_type;
  7244. } builtin_mime_types[] = {
  7245. /* IANA registered MIME types
  7246. * (http://www.iana.org/assignments/media-types)
  7247. * application types */
  7248. {".bin", 4, "application/octet-stream"},
  7249. {".deb", 4, "application/octet-stream"},
  7250. {".dmg", 4, "application/octet-stream"},
  7251. {".dll", 4, "application/octet-stream"},
  7252. {".doc", 4, "application/msword"},
  7253. {".eps", 4, "application/postscript"},
  7254. {".exe", 4, "application/octet-stream"},
  7255. {".iso", 4, "application/octet-stream"},
  7256. {".js", 3, "application/javascript"},
  7257. {".json", 5, "application/json"},
  7258. {".mjs", 4, "application/javascript"},
  7259. {".msi", 4, "application/octet-stream"},
  7260. {".pdf", 4, "application/pdf"},
  7261. {".ps", 3, "application/postscript"},
  7262. {".rtf", 4, "application/rtf"},
  7263. {".wasm", 5, "application/wasm"},
  7264. {".xhtml", 6, "application/xhtml+xml"},
  7265. {".xsl", 4, "application/xml"},
  7266. {".xslt", 5, "application/xml"},
  7267. /* fonts */
  7268. {".ttf", 4, "application/font-sfnt"},
  7269. {".cff", 4, "application/font-sfnt"},
  7270. {".otf", 4, "application/font-sfnt"},
  7271. {".aat", 4, "application/font-sfnt"},
  7272. {".sil", 4, "application/font-sfnt"},
  7273. {".pfr", 4, "application/font-tdpfr"},
  7274. {".woff", 5, "application/font-woff"},
  7275. {".woff2", 6, "application/font-woff2"},
  7276. /* audio */
  7277. {".mp3", 4, "audio/mpeg"},
  7278. {".oga", 4, "audio/ogg"},
  7279. {".ogg", 4, "audio/ogg"},
  7280. /* image */
  7281. {".gif", 4, "image/gif"},
  7282. {".ief", 4, "image/ief"},
  7283. {".jpeg", 5, "image/jpeg"},
  7284. {".jpg", 4, "image/jpeg"},
  7285. {".jpm", 4, "image/jpm"},
  7286. {".jpx", 4, "image/jpx"},
  7287. {".png", 4, "image/png"},
  7288. {".svg", 4, "image/svg+xml"},
  7289. {".tif", 4, "image/tiff"},
  7290. {".tiff", 5, "image/tiff"},
  7291. /* model */
  7292. {".wrl", 4, "model/vrml"},
  7293. /* text */
  7294. {".css", 4, "text/css"},
  7295. {".csv", 4, "text/csv"},
  7296. {".htm", 4, "text/html"},
  7297. {".html", 5, "text/html"},
  7298. {".sgm", 4, "text/sgml"},
  7299. {".shtm", 5, "text/html"},
  7300. {".shtml", 6, "text/html"},
  7301. {".txt", 4, "text/plain"},
  7302. {".xml", 4, "text/xml"},
  7303. /* video */
  7304. {".mov", 4, "video/quicktime"},
  7305. {".mp4", 4, "video/mp4"},
  7306. {".mpeg", 5, "video/mpeg"},
  7307. {".mpg", 4, "video/mpeg"},
  7308. {".ogv", 4, "video/ogg"},
  7309. {".qt", 3, "video/quicktime"},
  7310. /* not registered types
  7311. * (http://reference.sitepoint.com/html/mime-types-full,
  7312. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7313. {".arj", 4, "application/x-arj-compressed"},
  7314. {".gz", 3, "application/x-gunzip"},
  7315. {".rar", 4, "application/x-arj-compressed"},
  7316. {".swf", 4, "application/x-shockwave-flash"},
  7317. {".tar", 4, "application/x-tar"},
  7318. {".tgz", 4, "application/x-tar-gz"},
  7319. {".torrent", 8, "application/x-bittorrent"},
  7320. {".ppt", 4, "application/x-mspowerpoint"},
  7321. {".xls", 4, "application/x-msexcel"},
  7322. {".zip", 4, "application/x-zip-compressed"},
  7323. {".aac",
  7324. 4,
  7325. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7326. {".flac", 5, "audio/flac"},
  7327. {".aif", 4, "audio/x-aif"},
  7328. {".m3u", 4, "audio/x-mpegurl"},
  7329. {".mid", 4, "audio/x-midi"},
  7330. {".ra", 3, "audio/x-pn-realaudio"},
  7331. {".ram", 4, "audio/x-pn-realaudio"},
  7332. {".wav", 4, "audio/x-wav"},
  7333. {".bmp", 4, "image/bmp"},
  7334. {".ico", 4, "image/x-icon"},
  7335. {".pct", 4, "image/x-pct"},
  7336. {".pict", 5, "image/pict"},
  7337. {".rgb", 4, "image/x-rgb"},
  7338. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7339. {".asf", 4, "video/x-ms-asf"},
  7340. {".avi", 4, "video/x-msvideo"},
  7341. {".m4v", 4, "video/x-m4v"},
  7342. {NULL, 0, NULL}};
  7343. CIVETWEB_API const char *
  7344. mg_get_builtin_mime_type(const char *path)
  7345. {
  7346. const char *ext;
  7347. size_t i, path_len;
  7348. path_len = strlen(path);
  7349. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7350. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7351. if ((path_len > builtin_mime_types[i].ext_len)
  7352. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7353. return builtin_mime_types[i].mime_type;
  7354. }
  7355. }
  7356. return "text/plain";
  7357. }
  7358. /* Look at the "path" extension and figure what mime type it has.
  7359. * Store mime type in the vector. */
  7360. static void
  7361. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7362. {
  7363. struct vec ext_vec, mime_vec;
  7364. const char *list, *ext;
  7365. size_t path_len;
  7366. path_len = strlen(path);
  7367. if ((conn == NULL) || (vec == NULL)) {
  7368. if (vec != NULL) {
  7369. memset(vec, '\0', sizeof(struct vec));
  7370. }
  7371. return;
  7372. }
  7373. /* Scan user-defined mime types first, in case user wants to
  7374. * override default mime types. */
  7375. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7376. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7377. /* ext now points to the path suffix */
  7378. ext = path + path_len - ext_vec.len;
  7379. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7380. *vec = mime_vec;
  7381. return;
  7382. }
  7383. }
  7384. vec->ptr = mg_get_builtin_mime_type(path);
  7385. vec->len = strlen(vec->ptr);
  7386. }
  7387. /* Stringify binary data. Output buffer must be twice as big as input,
  7388. * because each byte takes 2 bytes in string representation */
  7389. static void
  7390. bin2str(char *to, const unsigned char *p, size_t len)
  7391. {
  7392. static const char *hex = "0123456789abcdef";
  7393. for (; len--; p++) {
  7394. *to++ = hex[p[0] >> 4];
  7395. *to++ = hex[p[0] & 0x0f];
  7396. }
  7397. *to = '\0';
  7398. }
  7399. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7400. */
  7401. CIVETWEB_API char *
  7402. mg_md5(char buf[33], ...)
  7403. {
  7404. md5_byte_t hash[16];
  7405. const char *p;
  7406. va_list ap;
  7407. md5_state_t ctx;
  7408. md5_init(&ctx);
  7409. va_start(ap, buf);
  7410. while ((p = va_arg(ap, const char *)) != NULL) {
  7411. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7412. }
  7413. va_end(ap);
  7414. md5_finish(&ctx, hash);
  7415. bin2str(buf, hash, sizeof(hash));
  7416. return buf;
  7417. }
  7418. /* Check the user's password, return 1 if OK */
  7419. static int
  7420. check_password_digest(const char *method,
  7421. const char *ha1,
  7422. const char *uri,
  7423. const char *nonce,
  7424. const char *nc,
  7425. const char *cnonce,
  7426. const char *qop,
  7427. const char *response)
  7428. {
  7429. char ha2[32 + 1], expected_response[32 + 1];
  7430. /* Some of the parameters may be NULL */
  7431. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7432. || (qop == NULL) || (response == NULL)) {
  7433. return 0;
  7434. }
  7435. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7436. if (strlen(response) != 32) {
  7437. return 0;
  7438. }
  7439. mg_md5(ha2, method, ":", uri, NULL);
  7440. mg_md5(expected_response,
  7441. ha1,
  7442. ":",
  7443. nonce,
  7444. ":",
  7445. nc,
  7446. ":",
  7447. cnonce,
  7448. ":",
  7449. qop,
  7450. ":",
  7451. ha2,
  7452. NULL);
  7453. return mg_strcasecmp(response, expected_response) == 0;
  7454. }
  7455. #if !defined(NO_FILESYSTEMS)
  7456. /* Use the global passwords file, if specified by auth_gpass option,
  7457. * or search for .htpasswd in the requested directory. */
  7458. static void
  7459. open_auth_file(struct mg_connection *conn,
  7460. const char *path,
  7461. struct mg_file *filep)
  7462. {
  7463. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7464. char name[UTF8_PATH_MAX];
  7465. const char *p, *e,
  7466. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7467. int truncated;
  7468. if (gpass != NULL) {
  7469. /* Use global passwords file */
  7470. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7471. #if defined(DEBUG)
  7472. /* Use mg_cry_internal here, since gpass has been
  7473. * configured. */
  7474. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7475. #endif
  7476. }
  7477. /* Important: using local struct mg_file to test path for
  7478. * is_directory flag. If filep is used, mg_stat() makes it
  7479. * appear as if auth file was opened.
  7480. * TODO(mid): Check if this is still required after rewriting
  7481. * mg_stat */
  7482. } else if (mg_stat(conn, path, &filep->stat)
  7483. && filep->stat.is_directory) {
  7484. mg_snprintf(conn,
  7485. &truncated,
  7486. name,
  7487. sizeof(name),
  7488. "%s/%s",
  7489. path,
  7490. PASSWORDS_FILE_NAME);
  7491. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7492. #if defined(DEBUG)
  7493. /* Don't use mg_cry_internal here, but only a trace, since
  7494. * this is a typical case. It will occur for every directory
  7495. * without a password file. */
  7496. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7497. #endif
  7498. }
  7499. } else {
  7500. /* Try to find .htpasswd in requested directory. */
  7501. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7502. if (e[0] == '/') {
  7503. break;
  7504. }
  7505. }
  7506. mg_snprintf(conn,
  7507. &truncated,
  7508. name,
  7509. sizeof(name),
  7510. "%.*s/%s",
  7511. (int)(e - p),
  7512. p,
  7513. PASSWORDS_FILE_NAME);
  7514. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7515. #if defined(DEBUG)
  7516. /* Don't use mg_cry_internal here, but only a trace, since
  7517. * this is a typical case. It will occur for every directory
  7518. * without a password file. */
  7519. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7520. #endif
  7521. }
  7522. }
  7523. }
  7524. }
  7525. #endif /* NO_FILESYSTEMS */
  7526. /* Parsed Authorization header */
  7527. struct auth_header {
  7528. char *user;
  7529. int type; /* 1 = basic, 2 = digest */
  7530. char *plain_password; /* Basic only */
  7531. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7532. };
  7533. /* Return 1 on success. Always initializes the auth_header structure. */
  7534. static int
  7535. parse_auth_header(struct mg_connection *conn,
  7536. char *buf,
  7537. size_t buf_size,
  7538. struct auth_header *auth_header)
  7539. {
  7540. char *name, *value, *s;
  7541. const char *ah;
  7542. uint64_t nonce;
  7543. if (!auth_header || !conn) {
  7544. return 0;
  7545. }
  7546. (void)memset(auth_header, 0, sizeof(*auth_header));
  7547. ah = mg_get_header(conn, "Authorization");
  7548. if (ah == NULL) {
  7549. /* No Authorization header at all */
  7550. return 0;
  7551. }
  7552. if (0 == mg_strncasecmp(ah, "Basic ", 6)) {
  7553. /* Basic Auth (we never asked for this, but some client may send it) */
  7554. char *split;
  7555. const char *userpw_b64 = ah + 6;
  7556. size_t userpw_b64_len = strlen(userpw_b64);
  7557. size_t buf_len_r = buf_size;
  7558. if (mg_base64_decode(
  7559. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7560. != -1) {
  7561. return 0; /* decode error */
  7562. }
  7563. split = strchr(buf, ':');
  7564. if (!split) {
  7565. return 0; /* Format error */
  7566. }
  7567. /* Separate string at ':' */
  7568. *split = 0;
  7569. /* User name is before ':', Password is after ':' */
  7570. auth_header->user = buf;
  7571. auth_header->type = 1;
  7572. auth_header->plain_password = split + 1;
  7573. return 1;
  7574. } else if (0 == mg_strncasecmp(ah, "Digest ", 7)) {
  7575. /* Digest Auth ... implemented below */
  7576. auth_header->type = 2;
  7577. } else {
  7578. /* Unknown or invalid Auth method */
  7579. return 0;
  7580. }
  7581. /* Make modifiable copy of the auth header */
  7582. (void)mg_strlcpy(buf, ah + 7, buf_size);
  7583. s = buf;
  7584. /* Parse authorization header */
  7585. for (;;) {
  7586. /* Gobble initial spaces */
  7587. while (isspace((unsigned char)*s)) {
  7588. s++;
  7589. }
  7590. name = skip_quoted(&s, "=", " ", 0);
  7591. /* Value is either quote-delimited, or ends at first comma or space.
  7592. */
  7593. if (s[0] == '\"') {
  7594. s++;
  7595. value = skip_quoted(&s, "\"", " ", '\\');
  7596. if (s[0] == ',') {
  7597. s++;
  7598. }
  7599. } else {
  7600. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7601. * uses spaces */
  7602. }
  7603. if (*name == '\0') {
  7604. break;
  7605. }
  7606. if (!strcmp(name, "username")) {
  7607. auth_header->user = value;
  7608. } else if (!strcmp(name, "cnonce")) {
  7609. auth_header->cnonce = value;
  7610. } else if (!strcmp(name, "response")) {
  7611. auth_header->response = value;
  7612. } else if (!strcmp(name, "uri")) {
  7613. auth_header->uri = value;
  7614. } else if (!strcmp(name, "qop")) {
  7615. auth_header->qop = value;
  7616. } else if (!strcmp(name, "nc")) {
  7617. auth_header->nc = value;
  7618. } else if (!strcmp(name, "nonce")) {
  7619. auth_header->nonce = value;
  7620. }
  7621. }
  7622. #if !defined(NO_NONCE_CHECK)
  7623. /* Read the nonce from the response. */
  7624. if (auth_header->nonce == NULL) {
  7625. return 0;
  7626. }
  7627. s = NULL;
  7628. nonce = strtoull(auth_header->nonce, &s, 10);
  7629. if ((s == NULL) || (*s != 0)) {
  7630. return 0;
  7631. }
  7632. /* Convert the nonce from the client to a number. */
  7633. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7634. /* The converted number corresponds to the time the nounce has been
  7635. * created. This should not be earlier than the server start. */
  7636. /* Server side nonce check is valuable in all situations but one:
  7637. * if the server restarts frequently, but the client should not see
  7638. * that, so the server should accept nonces from previous starts. */
  7639. /* However, the reasonable default is to not accept a nonce from a
  7640. * previous start, so if anyone changed the access rights between
  7641. * two restarts, a new login is required. */
  7642. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7643. /* nonce is from a previous start of the server and no longer valid
  7644. * (replay attack?) */
  7645. return 0;
  7646. }
  7647. /* Check if the nonce is too high, so it has not (yet) been used by the
  7648. * server. */
  7649. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7650. + conn->dom_ctx->nonce_count)) {
  7651. return 0;
  7652. }
  7653. #else
  7654. (void)nonce;
  7655. #endif
  7656. return (auth_header->user != NULL);
  7657. }
  7658. static const char *
  7659. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7660. {
  7661. if (!filep) {
  7662. return NULL;
  7663. }
  7664. if (filep->access.fp != NULL) {
  7665. return fgets(buf, (int)size, filep->access.fp);
  7666. } else {
  7667. return NULL;
  7668. }
  7669. }
  7670. /* Define the initial recursion depth for procesesing htpasswd files that
  7671. * include other htpasswd
  7672. * (or even the same) files. It is not difficult to provide a file or files
  7673. * s.t. they force civetweb
  7674. * to infinitely recurse and then crash.
  7675. */
  7676. #define INITIAL_DEPTH 9
  7677. #if INITIAL_DEPTH <= 0
  7678. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7679. #endif
  7680. #if !defined(NO_FILESYSTEMS)
  7681. struct read_auth_file_struct {
  7682. struct mg_connection *conn;
  7683. struct auth_header auth_header;
  7684. const char *domain;
  7685. char buf[256 + 256 + 40];
  7686. const char *f_user;
  7687. const char *f_domain;
  7688. const char *f_ha1;
  7689. };
  7690. static int
  7691. read_auth_file(struct mg_file *filep,
  7692. struct read_auth_file_struct *workdata,
  7693. int depth)
  7694. {
  7695. int is_authorized = 0;
  7696. struct mg_file fp;
  7697. size_t l;
  7698. if (!filep || !workdata || (0 == depth)) {
  7699. return 0;
  7700. }
  7701. /* Loop over passwords file */
  7702. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7703. l = strlen(workdata->buf);
  7704. while (l > 0) {
  7705. if (isspace((unsigned char)workdata->buf[l - 1])
  7706. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7707. l--;
  7708. workdata->buf[l] = 0;
  7709. } else
  7710. break;
  7711. }
  7712. if (l < 1) {
  7713. continue;
  7714. }
  7715. workdata->f_user = workdata->buf;
  7716. if (workdata->f_user[0] == ':') {
  7717. /* user names may not contain a ':' and may not be empty,
  7718. * so lines starting with ':' may be used for a special purpose
  7719. */
  7720. if (workdata->f_user[1] == '#') {
  7721. /* :# is a comment */
  7722. continue;
  7723. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7724. if (mg_fopen(workdata->conn,
  7725. workdata->f_user + 9,
  7726. MG_FOPEN_MODE_READ,
  7727. &fp)) {
  7728. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7729. (void)mg_fclose(
  7730. &fp.access); /* ignore error on read only file */
  7731. /* No need to continue processing files once we have a
  7732. * match, since nothing will reset it back
  7733. * to 0.
  7734. */
  7735. if (is_authorized) {
  7736. return is_authorized;
  7737. }
  7738. } else {
  7739. mg_cry_internal(workdata->conn,
  7740. "%s: cannot open authorization file: %s",
  7741. __func__,
  7742. workdata->buf);
  7743. }
  7744. continue;
  7745. }
  7746. /* everything is invalid for the moment (might change in the
  7747. * future) */
  7748. mg_cry_internal(workdata->conn,
  7749. "%s: syntax error in authorization file: %s",
  7750. __func__,
  7751. workdata->buf);
  7752. continue;
  7753. }
  7754. workdata->f_domain = strchr(workdata->f_user, ':');
  7755. if (workdata->f_domain == NULL) {
  7756. mg_cry_internal(workdata->conn,
  7757. "%s: syntax error in authorization file: %s",
  7758. __func__,
  7759. workdata->buf);
  7760. continue;
  7761. }
  7762. *(char *)(workdata->f_domain) = 0;
  7763. (workdata->f_domain)++;
  7764. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7765. if (workdata->f_ha1 == NULL) {
  7766. mg_cry_internal(workdata->conn,
  7767. "%s: syntax error in authorization file: %s",
  7768. __func__,
  7769. workdata->buf);
  7770. continue;
  7771. }
  7772. *(char *)(workdata->f_ha1) = 0;
  7773. (workdata->f_ha1)++;
  7774. if (!strcmp(workdata->auth_header.user, workdata->f_user)
  7775. && !strcmp(workdata->domain, workdata->f_domain)) {
  7776. switch (workdata->auth_header.type) {
  7777. case 1: /* Basic */
  7778. {
  7779. char md5[33];
  7780. mg_md5(md5,
  7781. workdata->f_user,
  7782. ":",
  7783. workdata->domain,
  7784. ":",
  7785. workdata->auth_header.plain_password,
  7786. NULL);
  7787. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7788. }
  7789. case 2: /* Digest */
  7790. return check_password_digest(
  7791. workdata->conn->request_info.request_method,
  7792. workdata->f_ha1,
  7793. workdata->auth_header.uri,
  7794. workdata->auth_header.nonce,
  7795. workdata->auth_header.nc,
  7796. workdata->auth_header.cnonce,
  7797. workdata->auth_header.qop,
  7798. workdata->auth_header.response);
  7799. default: /* None/Other/Unknown */
  7800. return 0;
  7801. }
  7802. }
  7803. }
  7804. return is_authorized;
  7805. }
  7806. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7807. static int
  7808. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7809. {
  7810. struct read_auth_file_struct workdata;
  7811. char buf[MG_BUF_LEN];
  7812. if (!conn || !conn->dom_ctx) {
  7813. return 0;
  7814. }
  7815. memset(&workdata, 0, sizeof(workdata));
  7816. workdata.conn = conn;
  7817. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.auth_header)) {
  7818. return 0;
  7819. }
  7820. /* CGI needs it as REMOTE_USER */
  7821. conn->request_info.remote_user =
  7822. mg_strdup_ctx(workdata.auth_header.user, conn->phys_ctx);
  7823. if (realm) {
  7824. workdata.domain = realm;
  7825. } else {
  7826. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7827. }
  7828. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7829. }
  7830. /* Public function to check http digest authentication header */
  7831. CIVETWEB_API int
  7832. mg_check_digest_access_authentication(struct mg_connection *conn,
  7833. const char *realm,
  7834. const char *filename)
  7835. {
  7836. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7837. int auth;
  7838. if (!conn || !filename) {
  7839. return -1;
  7840. }
  7841. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7842. return -2;
  7843. }
  7844. auth = authorize(conn, &file, realm);
  7845. mg_fclose(&file.access);
  7846. return auth;
  7847. }
  7848. #endif /* NO_FILESYSTEMS */
  7849. /* Return 1 if request is authorised, 0 otherwise. */
  7850. static int
  7851. check_authorization(struct mg_connection *conn, const char *path)
  7852. {
  7853. #if !defined(NO_FILESYSTEMS)
  7854. char fname[UTF8_PATH_MAX];
  7855. struct vec uri_vec, filename_vec;
  7856. const char *list;
  7857. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7858. int authorized = 1, truncated;
  7859. if (!conn || !conn->dom_ctx) {
  7860. return 0;
  7861. }
  7862. list = conn->dom_ctx->config[PROTECT_URI];
  7863. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7864. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7865. mg_snprintf(conn,
  7866. &truncated,
  7867. fname,
  7868. sizeof(fname),
  7869. "%.*s",
  7870. (int)filename_vec.len,
  7871. filename_vec.ptr);
  7872. if (truncated
  7873. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7874. mg_cry_internal(conn,
  7875. "%s: cannot open %s: %s",
  7876. __func__,
  7877. fname,
  7878. strerror(errno));
  7879. }
  7880. break;
  7881. }
  7882. }
  7883. if (!is_file_opened(&file.access)) {
  7884. open_auth_file(conn, path, &file);
  7885. }
  7886. if (is_file_opened(&file.access)) {
  7887. authorized = authorize(conn, &file, NULL);
  7888. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7889. }
  7890. return authorized;
  7891. #else
  7892. (void)conn;
  7893. (void)path;
  7894. return 1;
  7895. #endif /* NO_FILESYSTEMS */
  7896. }
  7897. /* Internal function. Assumes conn is valid */
  7898. static void
  7899. send_authorization_request(struct mg_connection *conn, const char *realm)
  7900. {
  7901. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7902. int trunc = 0;
  7903. char buf[128];
  7904. if (!realm) {
  7905. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7906. }
  7907. mg_lock_context(conn->phys_ctx);
  7908. nonce += conn->dom_ctx->nonce_count;
  7909. ++conn->dom_ctx->nonce_count;
  7910. mg_unlock_context(conn->phys_ctx);
  7911. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7912. conn->must_close = 1;
  7913. /* Create 401 response */
  7914. mg_response_header_start(conn, 401);
  7915. send_no_cache_header(conn);
  7916. send_additional_header(conn);
  7917. mg_response_header_add(conn, "Content-Length", "0", -1);
  7918. /* Content for "WWW-Authenticate" header */
  7919. mg_snprintf(conn,
  7920. &trunc,
  7921. buf,
  7922. sizeof(buf),
  7923. "Digest qop=\"auth\", realm=\"%s\", "
  7924. "nonce=\"%" UINT64_FMT "\"",
  7925. realm,
  7926. nonce);
  7927. if (!trunc) {
  7928. /* !trunc should always be true */
  7929. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7930. }
  7931. /* Send all headers */
  7932. mg_response_header_send(conn);
  7933. }
  7934. /* Interface function. Parameters are provided by the user, so do
  7935. * at least some basic checks.
  7936. */
  7937. CIVETWEB_API int
  7938. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7939. const char *realm)
  7940. {
  7941. if (conn && conn->dom_ctx) {
  7942. send_authorization_request(conn, realm);
  7943. return 0;
  7944. }
  7945. return -1;
  7946. }
  7947. #if !defined(NO_FILES)
  7948. static int
  7949. is_authorized_for_put(struct mg_connection *conn)
  7950. {
  7951. int ret = 0;
  7952. if (conn) {
  7953. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7954. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7955. if (passfile != NULL
  7956. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7957. ret = authorize(conn, &file, NULL);
  7958. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7959. }
  7960. }
  7961. DEBUG_TRACE("file write authorization: %i", ret);
  7962. return ret;
  7963. }
  7964. #endif
  7965. CIVETWEB_API int
  7966. mg_modify_passwords_file_ha1(const char *fname,
  7967. const char *domain,
  7968. const char *user,
  7969. const char *ha1)
  7970. {
  7971. int found = 0, i, result = 1;
  7972. char line[512], u[256], d[256], h[256];
  7973. struct stat st = {0};
  7974. FILE *fp = NULL;
  7975. char *temp_file = NULL;
  7976. int temp_file_offs = 0;
  7977. /* Regard empty password as no password - remove user record. */
  7978. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7979. ha1 = NULL;
  7980. }
  7981. /* Other arguments must not be empty */
  7982. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7983. return 0;
  7984. }
  7985. /* Using the given file format, user name and domain must not contain
  7986. * the ':' character */
  7987. if (strchr(user, ':') != NULL) {
  7988. return 0;
  7989. }
  7990. if (strchr(domain, ':') != NULL) {
  7991. return 0;
  7992. }
  7993. /* Do not allow control characters like newline in user name and domain.
  7994. * Do not allow excessively long names either. */
  7995. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7996. if (iscntrl((unsigned char)user[i])) {
  7997. return 0;
  7998. }
  7999. }
  8000. if (user[i]) {
  8001. return 0; /* user name too long */
  8002. }
  8003. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  8004. if (iscntrl((unsigned char)domain[i])) {
  8005. return 0;
  8006. }
  8007. }
  8008. if (domain[i]) {
  8009. return 0; /* domain name too long */
  8010. }
  8011. /* The maximum length of the path to the password file is limited */
  8012. if (strlen(fname) >= UTF8_PATH_MAX) {
  8013. return 0;
  8014. }
  8015. /* Check if the file exists, and get file size */
  8016. if (0 == stat(fname, &st)) {
  8017. int temp_buf_len;
  8018. if (st.st_size > 10485760) {
  8019. /* Some funster provided a >10 MB text file */
  8020. return 0;
  8021. }
  8022. /* Add enough space for one more line */
  8023. temp_buf_len = (int)st.st_size + 1024;
  8024. /* Allocate memory (instead of using a temporary file) */
  8025. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  8026. if (!temp_file) {
  8027. /* Out of memory */
  8028. return 0;
  8029. }
  8030. /* File exists. Read it into a memory buffer. */
  8031. fp = fopen(fname, "r");
  8032. if (fp == NULL) {
  8033. /* Cannot read file. No permission? */
  8034. mg_free(temp_file);
  8035. return 0;
  8036. }
  8037. /* Read content and store in memory */
  8038. while ((fgets(line, sizeof(line), fp) != NULL)
  8039. && ((temp_file_offs + 600) < temp_buf_len)) {
  8040. /* file format is "user:domain:hash\n" */
  8041. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  8042. continue;
  8043. }
  8044. u[255] = 0;
  8045. d[255] = 0;
  8046. h[255] = 0;
  8047. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8048. /* Found the user: change the password hash or drop the user
  8049. */
  8050. if ((ha1 != NULL) && (!found)) {
  8051. i = sprintf(temp_file + temp_file_offs,
  8052. "%s:%s:%s\n",
  8053. user,
  8054. domain,
  8055. ha1);
  8056. if (i < 1) {
  8057. fclose(fp);
  8058. mg_free(temp_file);
  8059. return 0;
  8060. }
  8061. temp_file_offs += i;
  8062. }
  8063. found = 1;
  8064. } else {
  8065. /* Copy existing user, including password hash */
  8066. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  8067. if (i < 1) {
  8068. fclose(fp);
  8069. mg_free(temp_file);
  8070. return 0;
  8071. }
  8072. temp_file_offs += i;
  8073. }
  8074. }
  8075. fclose(fp);
  8076. }
  8077. /* Create new file */
  8078. fp = fopen(fname, "w");
  8079. if (!fp) {
  8080. mg_free(temp_file);
  8081. return 0;
  8082. }
  8083. #if !defined(_WIN32)
  8084. /* On Linux & co., restrict file read/write permissions to the owner */
  8085. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  8086. result = 0;
  8087. }
  8088. #endif
  8089. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  8090. /* Store buffered content of old file */
  8091. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  8092. != (size_t)temp_file_offs) {
  8093. result = 0;
  8094. }
  8095. }
  8096. /* If new user, just add it */
  8097. if ((ha1 != NULL) && (!found)) {
  8098. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  8099. result = 0;
  8100. }
  8101. }
  8102. /* All data written */
  8103. if (fclose(fp) != 0) {
  8104. result = 0;
  8105. }
  8106. mg_free(temp_file);
  8107. return result;
  8108. }
  8109. CIVETWEB_API int
  8110. mg_modify_passwords_file(const char *fname,
  8111. const char *domain,
  8112. const char *user,
  8113. const char *pass)
  8114. {
  8115. char ha1buf[33];
  8116. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8117. return 0;
  8118. }
  8119. if ((pass == NULL) || (pass[0] == 0)) {
  8120. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  8121. }
  8122. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  8123. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  8124. }
  8125. static int
  8126. is_valid_port(unsigned long port)
  8127. {
  8128. return (port <= 0xffff);
  8129. }
  8130. static int
  8131. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8132. {
  8133. struct addrinfo hints, *res, *ressave;
  8134. int func_ret = 0;
  8135. int gai_ret;
  8136. memset(&hints, 0, sizeof(struct addrinfo));
  8137. hints.ai_family = af;
  8138. if (!resolve_src) {
  8139. hints.ai_flags = AI_NUMERICHOST;
  8140. }
  8141. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8142. if (gai_ret != 0) {
  8143. /* gai_strerror could be used to convert gai_ret to a string */
  8144. /* POSIX return values: see
  8145. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8146. */
  8147. /* Windows return values: see
  8148. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8149. */
  8150. return 0;
  8151. }
  8152. ressave = res;
  8153. while (res) {
  8154. if ((dstlen >= (size_t)res->ai_addrlen)
  8155. && (res->ai_addr->sa_family == af)) {
  8156. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8157. func_ret = 1;
  8158. }
  8159. res = res->ai_next;
  8160. }
  8161. freeaddrinfo(ressave);
  8162. return func_ret;
  8163. }
  8164. static int
  8165. connect_socket(
  8166. struct mg_context *ctx /* may be NULL */,
  8167. const char *host,
  8168. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  8169. int use_ssl, /* 0 or 1 */
  8170. struct mg_error_data *error,
  8171. SOCKET *sock /* output: socket, must not be NULL */,
  8172. union usa *sa /* output: socket address, must not be NULL */
  8173. )
  8174. {
  8175. int ip_ver = 0;
  8176. int conn_ret = -1;
  8177. int sockerr = 0;
  8178. *sock = INVALID_SOCKET;
  8179. memset(sa, 0, sizeof(*sa));
  8180. if (host == NULL) {
  8181. if (error != NULL) {
  8182. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8183. mg_snprintf(NULL,
  8184. NULL, /* No truncation check for ebuf */
  8185. error->text,
  8186. error->text_buffer_size,
  8187. "%s",
  8188. "NULL host");
  8189. }
  8190. return 0;
  8191. }
  8192. #if defined(USE_X_DOM_SOCKET)
  8193. if (port == -99) {
  8194. /* Unix domain socket */
  8195. size_t hostlen = strlen(host);
  8196. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8197. if (error != NULL) {
  8198. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8199. mg_snprintf(NULL,
  8200. NULL, /* No truncation check for ebuf */
  8201. error->text,
  8202. error->text_buffer_size,
  8203. "%s",
  8204. "host length exceeds limit");
  8205. }
  8206. return 0;
  8207. }
  8208. } else
  8209. #endif
  8210. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8211. if (error != NULL) {
  8212. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8213. mg_snprintf(NULL,
  8214. NULL, /* No truncation check for ebuf */
  8215. error->text,
  8216. error->text_buffer_size,
  8217. "%s",
  8218. "invalid port");
  8219. }
  8220. return 0;
  8221. }
  8222. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) && !defined(NO_SSL_DL)
  8223. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8224. if (use_ssl && (TLS_client_method == NULL)) {
  8225. if (error != NULL) {
  8226. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8227. mg_snprintf(NULL,
  8228. NULL, /* No truncation check for ebuf */
  8229. error->text,
  8230. error->text_buffer_size,
  8231. "%s",
  8232. "SSL is not initialized");
  8233. }
  8234. return 0;
  8235. }
  8236. #else
  8237. if (use_ssl && (SSLv23_client_method == NULL)) {
  8238. if (error != 0) {
  8239. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8240. mg_snprintf(NULL,
  8241. NULL, /* No truncation check for ebuf */
  8242. error->text,
  8243. error->text_buffer_size,
  8244. "%s",
  8245. "SSL is not initialized");
  8246. }
  8247. return 0;
  8248. }
  8249. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8250. #else
  8251. (void)use_ssl;
  8252. #endif /* NO SSL */
  8253. #if defined(USE_X_DOM_SOCKET)
  8254. if (port == -99) {
  8255. size_t hostlen = strlen(host);
  8256. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8257. ip_ver = -99;
  8258. sa->sun.sun_family = AF_UNIX;
  8259. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8260. memcpy(sa->sun.sun_path, host, hostlen);
  8261. } else
  8262. #endif
  8263. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8264. sa->sin.sin_port = htons((uint16_t)port);
  8265. ip_ver = 4;
  8266. #if defined(USE_IPV6)
  8267. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8268. sa->sin6.sin6_port = htons((uint16_t)port);
  8269. ip_ver = 6;
  8270. } else if (host[0] == '[') {
  8271. /* While getaddrinfo on Windows will work with [::1],
  8272. * getaddrinfo on Linux only works with ::1 (without []). */
  8273. size_t l = strlen(host + 1);
  8274. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8275. if (h) {
  8276. h[l - 1] = 0;
  8277. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8278. sa->sin6.sin6_port = htons((uint16_t)port);
  8279. ip_ver = 6;
  8280. }
  8281. mg_free(h);
  8282. }
  8283. #endif
  8284. }
  8285. if (ip_ver == 0) {
  8286. if (error != NULL) {
  8287. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8288. mg_snprintf(NULL,
  8289. NULL, /* No truncation check for ebuf */
  8290. error->text,
  8291. error->text_buffer_size,
  8292. "%s",
  8293. "host not found");
  8294. }
  8295. return 0;
  8296. }
  8297. if (ip_ver == 4) {
  8298. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8299. }
  8300. #if defined(USE_IPV6)
  8301. else if (ip_ver == 6) {
  8302. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8303. }
  8304. #endif
  8305. #if defined(USE_X_DOM_SOCKET)
  8306. else if (ip_ver == -99) {
  8307. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8308. }
  8309. #endif
  8310. if (*sock == INVALID_SOCKET) {
  8311. if (error != NULL) {
  8312. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8313. error->code_sub = (unsigned)ERRNO;
  8314. mg_snprintf(NULL,
  8315. NULL, /* No truncation check for ebuf */
  8316. error->text,
  8317. error->text_buffer_size,
  8318. "socket(): %s",
  8319. strerror(ERRNO));
  8320. }
  8321. return 0;
  8322. }
  8323. if (0 != set_non_blocking_mode(*sock)) {
  8324. if (error != NULL) {
  8325. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8326. error->code_sub = (unsigned)ERRNO;
  8327. mg_snprintf(NULL,
  8328. NULL, /* No truncation check for ebuf */
  8329. error->text,
  8330. error->text_buffer_size,
  8331. "Cannot set socket to non-blocking: %s",
  8332. strerror(ERRNO));
  8333. }
  8334. closesocket(*sock);
  8335. *sock = INVALID_SOCKET;
  8336. return 0;
  8337. }
  8338. set_close_on_exec(*sock, NULL, ctx);
  8339. if (ip_ver == 4) {
  8340. /* connected with IPv4 */
  8341. conn_ret = connect(*sock,
  8342. (struct sockaddr *)((void *)&sa->sin),
  8343. sizeof(sa->sin));
  8344. }
  8345. #if defined(USE_IPV6)
  8346. else if (ip_ver == 6) {
  8347. /* connected with IPv6 */
  8348. conn_ret = connect(*sock,
  8349. (struct sockaddr *)((void *)&sa->sin6),
  8350. sizeof(sa->sin6));
  8351. }
  8352. #endif
  8353. #if defined(USE_X_DOM_SOCKET)
  8354. else if (ip_ver == -99) {
  8355. /* connected to domain socket */
  8356. conn_ret = connect(*sock,
  8357. (struct sockaddr *)((void *)&sa->sun),
  8358. sizeof(sa->sun));
  8359. }
  8360. #endif
  8361. if (conn_ret != 0) {
  8362. sockerr = ERRNO;
  8363. }
  8364. #if defined(_WIN32)
  8365. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8366. #else
  8367. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8368. #endif
  8369. /* Data for getsockopt */
  8370. void *psockerr = &sockerr;
  8371. int ret;
  8372. #if defined(_WIN32)
  8373. int len = (int)sizeof(sockerr);
  8374. #else
  8375. socklen_t len = (socklen_t)sizeof(sockerr);
  8376. #endif
  8377. /* Data for poll */
  8378. struct mg_pollfd pfd[2];
  8379. int pollres;
  8380. int ms_wait = 10000; /* 10 second timeout */
  8381. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8382. unsigned int num_sock = 1; /* use one or two sockets */
  8383. /* For a non-blocking socket, the connect sequence is:
  8384. * 1) call connect (will not block)
  8385. * 2) wait until the socket is ready for writing (select or poll)
  8386. * 3) check connection state with getsockopt
  8387. */
  8388. pfd[0].fd = *sock;
  8389. pfd[0].events = POLLOUT;
  8390. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  8391. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  8392. pfd[num_sock].events = POLLIN;
  8393. num_sock++;
  8394. }
  8395. pollres =
  8396. mg_poll(pfd, num_sock, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8397. if (pollres != 1) {
  8398. /* Not connected */
  8399. if (error != NULL) {
  8400. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8401. mg_snprintf(NULL,
  8402. NULL, /* No truncation check for ebuf */
  8403. error->text,
  8404. error->text_buffer_size,
  8405. "connect(%s:%d): timeout",
  8406. host,
  8407. port);
  8408. }
  8409. closesocket(*sock);
  8410. *sock = INVALID_SOCKET;
  8411. return 0;
  8412. }
  8413. #if defined(_WIN32)
  8414. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8415. #else
  8416. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8417. #endif
  8418. if ((ret == 0) && (sockerr == 0)) {
  8419. conn_ret = 0;
  8420. }
  8421. }
  8422. if (conn_ret != 0) {
  8423. /* Not connected */
  8424. if (error != NULL) {
  8425. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8426. error->code_sub = (unsigned)ERRNO;
  8427. mg_snprintf(NULL,
  8428. NULL, /* No truncation check for ebuf */
  8429. error->text,
  8430. error->text_buffer_size,
  8431. "connect(%s:%d): error %s",
  8432. host,
  8433. port,
  8434. strerror(sockerr));
  8435. }
  8436. closesocket(*sock);
  8437. *sock = INVALID_SOCKET;
  8438. return 0;
  8439. }
  8440. return 1;
  8441. }
  8442. CIVETWEB_API int
  8443. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8444. {
  8445. static const char *dont_escape = "._-$,;~()";
  8446. static const char *hex = "0123456789abcdef";
  8447. char *pos = dst;
  8448. const char *end = dst + dst_len - 1;
  8449. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8450. if (isalnum((unsigned char)*src)
  8451. || (strchr(dont_escape, *src) != NULL)) {
  8452. *pos = *src;
  8453. } else if (pos + 2 < end) {
  8454. pos[0] = '%';
  8455. pos[1] = hex[(unsigned char)*src >> 4];
  8456. pos[2] = hex[(unsigned char)*src & 0xf];
  8457. pos += 2;
  8458. } else {
  8459. break;
  8460. }
  8461. }
  8462. *pos = '\0';
  8463. return (*src == '\0') ? (int)(pos - dst) : -1;
  8464. }
  8465. /* Return 0 on success, non-zero if an error occurs. */
  8466. static int
  8467. print_dir_entry(struct mg_connection *conn, struct de *de)
  8468. {
  8469. size_t namesize, escsize, i;
  8470. char *href, *esc, *p;
  8471. char size[64], mod[64];
  8472. #if defined(REENTRANT_TIME)
  8473. struct tm _tm;
  8474. struct tm *tm = &_tm;
  8475. #else
  8476. struct tm *tm;
  8477. #endif
  8478. /* Estimate worst case size for encoding and escaping */
  8479. namesize = strlen(de->file_name) + 1;
  8480. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8481. href = (char *)mg_malloc(namesize * 3 + escsize);
  8482. if (href == NULL) {
  8483. return -1;
  8484. }
  8485. mg_url_encode(de->file_name, href, namesize * 3);
  8486. esc = NULL;
  8487. if (escsize > 0) {
  8488. /* HTML escaping needed */
  8489. esc = href + namesize * 3;
  8490. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8491. mg_strlcpy(p, de->file_name + i, 2);
  8492. if (*p == '&') {
  8493. strcpy(p, "&amp;");
  8494. } else if (*p == '<') {
  8495. strcpy(p, "&lt;");
  8496. } else if (*p == '>') {
  8497. strcpy(p, "&gt;");
  8498. }
  8499. }
  8500. }
  8501. if (de->file.is_directory) {
  8502. mg_snprintf(conn,
  8503. NULL, /* Buffer is big enough */
  8504. size,
  8505. sizeof(size),
  8506. "%s",
  8507. "[DIRECTORY]");
  8508. } else {
  8509. /* We use (signed) cast below because MSVC 6 compiler cannot
  8510. * convert unsigned __int64 to double. Sigh. */
  8511. if (de->file.size < 1024) {
  8512. mg_snprintf(conn,
  8513. NULL, /* Buffer is big enough */
  8514. size,
  8515. sizeof(size),
  8516. "%d",
  8517. (int)de->file.size);
  8518. } else if (de->file.size < 0x100000) {
  8519. mg_snprintf(conn,
  8520. NULL, /* Buffer is big enough */
  8521. size,
  8522. sizeof(size),
  8523. "%.1fk",
  8524. (double)de->file.size / 1024.0);
  8525. } else if (de->file.size < 0x40000000) {
  8526. mg_snprintf(conn,
  8527. NULL, /* Buffer is big enough */
  8528. size,
  8529. sizeof(size),
  8530. "%.1fM",
  8531. (double)de->file.size / 1048576);
  8532. } else {
  8533. mg_snprintf(conn,
  8534. NULL, /* Buffer is big enough */
  8535. size,
  8536. sizeof(size),
  8537. "%.1fG",
  8538. (double)de->file.size / 1073741824);
  8539. }
  8540. }
  8541. /* Note: mg_snprintf will not cause a buffer overflow above.
  8542. * So, string truncation checks are not required here. */
  8543. #if defined(REENTRANT_TIME)
  8544. localtime_r(&de->file.last_modified, tm);
  8545. #else
  8546. tm = localtime(&de->file.last_modified);
  8547. #endif
  8548. if (tm != NULL) {
  8549. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8550. } else {
  8551. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8552. }
  8553. mg_printf(conn,
  8554. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8555. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8556. href,
  8557. de->file.is_directory ? "/" : "",
  8558. esc ? esc : de->file_name,
  8559. de->file.is_directory ? "/" : "",
  8560. mod,
  8561. size);
  8562. mg_free(href);
  8563. return 0;
  8564. }
  8565. /* This function is called from send_directory() and used for
  8566. * sorting directory entries by size, name, or modification time. */
  8567. static int
  8568. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8569. {
  8570. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8571. if (p1 && p2) {
  8572. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8573. int cmp_result = 0;
  8574. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8575. query_string = "n";
  8576. }
  8577. /* Sort Directories vs Files */
  8578. if (a->file.is_directory && !b->file.is_directory) {
  8579. return -1; /* Always put directories on top */
  8580. } else if (!a->file.is_directory && b->file.is_directory) {
  8581. return 1; /* Always put directories on top */
  8582. }
  8583. /* Sort by size or date */
  8584. if (*query_string == 's') {
  8585. cmp_result = (a->file.size == b->file.size)
  8586. ? 0
  8587. : ((a->file.size > b->file.size) ? 1 : -1);
  8588. } else if (*query_string == 'd') {
  8589. cmp_result =
  8590. (a->file.last_modified == b->file.last_modified)
  8591. ? 0
  8592. : ((a->file.last_modified > b->file.last_modified) ? 1
  8593. : -1);
  8594. }
  8595. /* Sort by name:
  8596. * if (*query_string == 'n') ...
  8597. * but also sort files of same size/date by name as secondary criterion.
  8598. */
  8599. if (cmp_result == 0) {
  8600. cmp_result = strcmp(a->file_name, b->file_name);
  8601. }
  8602. /* For descending order, invert result */
  8603. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8604. }
  8605. return 0;
  8606. }
  8607. static int
  8608. must_hide_file(struct mg_connection *conn, const char *path)
  8609. {
  8610. if (conn && conn->dom_ctx) {
  8611. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8612. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8613. return (match_prefix_strlen(pw_pattern, path) > 0)
  8614. || (match_prefix_strlen(pattern, path) > 0);
  8615. }
  8616. return 0;
  8617. }
  8618. #if !defined(NO_FILESYSTEMS)
  8619. static int
  8620. scan_directory(struct mg_connection *conn,
  8621. const char *dir,
  8622. void *data,
  8623. int (*cb)(struct de *, void *))
  8624. {
  8625. char path[UTF8_PATH_MAX];
  8626. struct dirent *dp;
  8627. DIR *dirp;
  8628. struct de de;
  8629. int truncated;
  8630. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8631. return 0;
  8632. } else {
  8633. while ((dp = mg_readdir(dirp)) != NULL) {
  8634. /* Do not show current dir and hidden files */
  8635. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8636. || must_hide_file(conn, dp->d_name)) {
  8637. continue;
  8638. }
  8639. mg_snprintf(
  8640. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8641. /* If we don't memset stat structure to zero, mtime will have
  8642. * garbage and strftime() will segfault later on in
  8643. * print_dir_entry(). memset is required only if mg_stat()
  8644. * fails. For more details, see
  8645. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8646. memset(&de.file, 0, sizeof(de.file));
  8647. if (truncated) {
  8648. /* If the path is not complete, skip processing. */
  8649. continue;
  8650. }
  8651. if (!mg_stat(conn, path, &de.file)) {
  8652. mg_cry_internal(conn,
  8653. "%s: mg_stat(%s) failed: %s",
  8654. __func__,
  8655. path,
  8656. strerror(ERRNO));
  8657. }
  8658. de.file_name = dp->d_name;
  8659. if (cb(&de, data)) {
  8660. /* stopped */
  8661. break;
  8662. }
  8663. }
  8664. (void)mg_closedir(dirp);
  8665. }
  8666. return 1;
  8667. }
  8668. #endif /* NO_FILESYSTEMS */
  8669. #if !defined(NO_FILES)
  8670. static int
  8671. remove_directory(struct mg_connection *conn, const char *dir)
  8672. {
  8673. char path[UTF8_PATH_MAX];
  8674. struct dirent *dp;
  8675. DIR *dirp;
  8676. struct de de;
  8677. int truncated;
  8678. int ok = 1;
  8679. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8680. return 0;
  8681. } else {
  8682. while ((dp = mg_readdir(dirp)) != NULL) {
  8683. /* Do not show current dir (but show hidden files as they will
  8684. * also be removed) */
  8685. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8686. continue;
  8687. }
  8688. mg_snprintf(
  8689. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8690. /* If we don't memset stat structure to zero, mtime will have
  8691. * garbage and strftime() will segfault later on in
  8692. * print_dir_entry(). memset is required only if mg_stat()
  8693. * fails. For more details, see
  8694. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8695. memset(&de.file, 0, sizeof(de.file));
  8696. if (truncated) {
  8697. /* Do not delete anything shorter */
  8698. ok = 0;
  8699. continue;
  8700. }
  8701. if (!mg_stat(conn, path, &de.file)) {
  8702. mg_cry_internal(conn,
  8703. "%s: mg_stat(%s) failed: %s",
  8704. __func__,
  8705. path,
  8706. strerror(ERRNO));
  8707. ok = 0;
  8708. }
  8709. if (de.file.is_directory) {
  8710. if (remove_directory(conn, path) == 0) {
  8711. ok = 0;
  8712. }
  8713. } else {
  8714. /* This will fail file is the file is in memory */
  8715. if (mg_remove(conn, path) == 0) {
  8716. ok = 0;
  8717. }
  8718. }
  8719. }
  8720. (void)mg_closedir(dirp);
  8721. IGNORE_UNUSED_RESULT(rmdir(dir));
  8722. }
  8723. return ok;
  8724. }
  8725. #endif
  8726. struct dir_scan_data {
  8727. struct de *entries;
  8728. size_t num_entries;
  8729. size_t arr_size;
  8730. };
  8731. #if !defined(NO_FILESYSTEMS)
  8732. static int
  8733. dir_scan_callback(struct de *de, void *data)
  8734. {
  8735. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8736. struct de *entries = dsd->entries;
  8737. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8738. /* Here "entries" is a temporary pointer and can be replaced,
  8739. * "dsd->entries" is the original pointer */
  8740. entries =
  8741. (struct de *)mg_realloc(entries,
  8742. dsd->arr_size * 2 * sizeof(entries[0]));
  8743. if (entries == NULL) {
  8744. /* stop scan */
  8745. return 1;
  8746. }
  8747. dsd->entries = entries;
  8748. dsd->arr_size *= 2;
  8749. }
  8750. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8751. if (entries[dsd->num_entries].file_name == NULL) {
  8752. /* stop scan */
  8753. return 1;
  8754. }
  8755. entries[dsd->num_entries].file = de->file;
  8756. dsd->num_entries++;
  8757. return 0;
  8758. }
  8759. static void
  8760. handle_directory_request(struct mg_connection *conn, const char *dir)
  8761. {
  8762. size_t i;
  8763. int sort_direction;
  8764. struct dir_scan_data data = {NULL, 0, 128};
  8765. char date[64], *esc, *p;
  8766. const char *title;
  8767. time_t curtime = time(NULL);
  8768. if (!conn) {
  8769. return;
  8770. }
  8771. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8772. mg_send_http_error(conn,
  8773. 500,
  8774. "Error: Cannot open directory\nopendir(%s): %s",
  8775. dir,
  8776. strerror(ERRNO));
  8777. return;
  8778. }
  8779. gmt_time_string(date, sizeof(date), &curtime);
  8780. esc = NULL;
  8781. title = conn->request_info.local_uri;
  8782. if (title[strcspn(title, "&<>")]) {
  8783. /* HTML escaping needed */
  8784. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8785. if (esc) {
  8786. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8787. mg_strlcpy(p, title + i, 2);
  8788. if (*p == '&') {
  8789. strcpy(p, "&amp;");
  8790. } else if (*p == '<') {
  8791. strcpy(p, "&lt;");
  8792. } else if (*p == '>') {
  8793. strcpy(p, "&gt;");
  8794. }
  8795. }
  8796. } else {
  8797. title = "";
  8798. }
  8799. }
  8800. sort_direction = ((conn->request_info.query_string != NULL)
  8801. && (conn->request_info.query_string[0] != '\0')
  8802. && (conn->request_info.query_string[1] == 'd'))
  8803. ? 'a'
  8804. : 'd';
  8805. conn->must_close = 1;
  8806. /* Create 200 OK response */
  8807. mg_response_header_start(conn, 200);
  8808. send_static_cache_header(conn);
  8809. send_additional_header(conn);
  8810. mg_response_header_add(conn,
  8811. "Content-Type",
  8812. "text/html; charset=utf-8",
  8813. -1);
  8814. /* Send all headers */
  8815. mg_response_header_send(conn);
  8816. /* Body */
  8817. mg_printf(conn,
  8818. "<!DOCTYPE html>"
  8819. "<html><head><title>Index of %s</title>"
  8820. "<style>th {text-align: left;}</style></head>"
  8821. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8822. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8823. "<th><a href=\"?d%c\">Modified</a></th>"
  8824. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8825. "<tr><td colspan=\"3\"><hr></td></tr>",
  8826. esc ? esc : title,
  8827. esc ? esc : title,
  8828. sort_direction,
  8829. sort_direction,
  8830. sort_direction);
  8831. mg_free(esc);
  8832. /* Print first entry - link to a parent directory */
  8833. mg_printf(conn,
  8834. "<tr><td><a href=\"%s\">%s</a></td>"
  8835. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8836. "..",
  8837. "Parent directory",
  8838. "-",
  8839. "-");
  8840. /* Sort and print directory entries */
  8841. if (data.entries != NULL) {
  8842. mg_sort(data.entries,
  8843. data.num_entries,
  8844. sizeof(data.entries[0]),
  8845. compare_dir_entries,
  8846. (void *)conn->request_info.query_string);
  8847. for (i = 0; i < data.num_entries; i++) {
  8848. print_dir_entry(conn, &data.entries[i]);
  8849. mg_free(data.entries[i].file_name);
  8850. }
  8851. mg_free(data.entries);
  8852. }
  8853. mg_printf(conn, "%s", "</table></pre></body></html>");
  8854. conn->status_code = 200;
  8855. }
  8856. #endif /* NO_FILESYSTEMS */
  8857. /* Send len bytes from the opened file to the client. */
  8858. static void
  8859. send_file_data(struct mg_connection *conn,
  8860. struct mg_file *filep,
  8861. int64_t offset,
  8862. int64_t len,
  8863. int no_buffering)
  8864. {
  8865. char buf[MG_BUF_LEN];
  8866. int to_read, num_read, num_written;
  8867. int64_t size;
  8868. if (!filep || !conn) {
  8869. return;
  8870. }
  8871. /* Sanity check the offset */
  8872. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8873. : (int64_t)(filep->stat.size);
  8874. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8875. if (len > 0 && filep->access.fp != NULL) {
  8876. /* file stored on disk */
  8877. #if defined(__linux__)
  8878. /* sendfile is only available for Linux */
  8879. if ((conn->ssl == 0) && (conn->throttle == 0)
  8880. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8881. "yes"))) {
  8882. off_t sf_offs = (off_t)offset;
  8883. ssize_t sf_sent;
  8884. int sf_file = fileno(filep->access.fp);
  8885. int loop_cnt = 0;
  8886. do {
  8887. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8888. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8889. size_t sf_tosend =
  8890. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8891. sf_sent =
  8892. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8893. if (sf_sent > 0) {
  8894. len -= sf_sent;
  8895. offset += sf_sent;
  8896. } else if (loop_cnt == 0) {
  8897. /* This file can not be sent using sendfile.
  8898. * This might be the case for pseudo-files in the
  8899. * /sys/ and /proc/ file system.
  8900. * Use the regular user mode copy code instead. */
  8901. break;
  8902. } else if (sf_sent == 0) {
  8903. /* No error, but 0 bytes sent. May be EOF? */
  8904. return;
  8905. }
  8906. loop_cnt++;
  8907. } while ((len > 0) && (sf_sent >= 0));
  8908. if (sf_sent > 0) {
  8909. return; /* OK */
  8910. }
  8911. /* sf_sent<0 means error, thus fall back to the classic way */
  8912. /* This is always the case, if sf_file is not a "normal" file,
  8913. * e.g., for sending data from the output of a CGI process. */
  8914. offset = (int64_t)sf_offs;
  8915. }
  8916. #endif
  8917. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8918. mg_cry_internal(conn,
  8919. "%s: fseeko() failed: %s",
  8920. __func__,
  8921. strerror(ERRNO));
  8922. mg_send_http_error(
  8923. conn,
  8924. 500,
  8925. "%s",
  8926. "Error: Unable to access file at requested position.");
  8927. } else {
  8928. while (len > 0) {
  8929. /* Calculate how much to read from the file into the buffer. */
  8930. /* If no_buffering is set, we should not wait until the
  8931. * CGI->Server buffer is filled, but send everything
  8932. * immediately. In theory buffering could be turned off using
  8933. * setbuf(filep->access.fp, NULL);
  8934. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8935. * but in practice this does not work. A "Linux only" solution
  8936. * may be to use select(). The only portable way is to read byte
  8937. * by byte, but this is quite inefficient from a performance
  8938. * point of view. */
  8939. to_read = no_buffering ? 1 : sizeof(buf);
  8940. if ((int64_t)to_read > len) {
  8941. to_read = (int)len;
  8942. }
  8943. /* Read from file, exit the loop on error */
  8944. if ((num_read = pull_inner(filep->access.fp,
  8945. NULL,
  8946. buf,
  8947. to_read,
  8948. /* unused */ 0.0))
  8949. <= 0) {
  8950. break;
  8951. }
  8952. /* Send read bytes to the client, exit the loop on error */
  8953. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8954. != num_read) {
  8955. break;
  8956. }
  8957. /* Both read and were successful, adjust counters */
  8958. len -= num_written;
  8959. }
  8960. }
  8961. }
  8962. }
  8963. static int
  8964. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8965. {
  8966. return sscanf(header,
  8967. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8968. a,
  8969. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8970. // to an integer value, but function will not report
  8971. // conversion errors; consider using 'strtol' instead
  8972. }
  8973. static void
  8974. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8975. {
  8976. if ((filestat != NULL) && (buf != NULL)) {
  8977. mg_snprintf(NULL,
  8978. NULL, /* All calls to construct_etag use 64 byte buffer */
  8979. buf,
  8980. buf_len,
  8981. "\"%lx.%" INT64_FMT "\"",
  8982. (unsigned long)filestat->last_modified,
  8983. filestat->size);
  8984. }
  8985. }
  8986. static void
  8987. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8988. {
  8989. if (filep != NULL && filep->fp != NULL) {
  8990. #if defined(_WIN32)
  8991. (void)conn; /* Unused. */
  8992. #else
  8993. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8994. mg_cry_internal(conn,
  8995. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8996. __func__,
  8997. strerror(ERRNO));
  8998. }
  8999. #endif
  9000. }
  9001. }
  9002. #if defined(USE_ZLIB)
  9003. #include "mod_zlib.inl"
  9004. #endif
  9005. #if !defined(NO_FILESYSTEMS)
  9006. static void
  9007. handle_static_file_request(struct mg_connection *conn,
  9008. const char *path,
  9009. struct mg_file *filep,
  9010. const char *mime_type,
  9011. const char *additional_headers)
  9012. {
  9013. char lm[64], etag[64];
  9014. char range[128]; /* large enough, so there will be no overflow */
  9015. const char *range_hdr;
  9016. int64_t cl, r1, r2;
  9017. struct vec mime_vec;
  9018. int n, truncated;
  9019. char gz_path[UTF8_PATH_MAX];
  9020. const char *encoding = 0;
  9021. int is_head_request;
  9022. #if defined(USE_ZLIB)
  9023. /* Compression is allowed, unless there is a reason not to use
  9024. * compression. If the file is already compressed, too small or a
  9025. * "range" request was made, on the fly compression is not possible. */
  9026. int allow_on_the_fly_compression = 1;
  9027. #endif
  9028. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  9029. return;
  9030. }
  9031. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  9032. if (mime_type == NULL) {
  9033. get_mime_type(conn, path, &mime_vec);
  9034. } else {
  9035. mime_vec.ptr = mime_type;
  9036. mime_vec.len = strlen(mime_type);
  9037. }
  9038. if (filep->stat.size > INT64_MAX) {
  9039. mg_send_http_error(conn,
  9040. 500,
  9041. "Error: File size is too large to send\n%" INT64_FMT,
  9042. filep->stat.size);
  9043. return;
  9044. }
  9045. cl = (int64_t)filep->stat.size;
  9046. conn->status_code = 200;
  9047. range[0] = '\0';
  9048. #if defined(USE_ZLIB)
  9049. /* if this file is in fact a pre-gzipped file, rewrite its filename
  9050. * it's important to rewrite the filename after resolving
  9051. * the mime type from it, to preserve the actual file's type */
  9052. if (!conn->accept_gzip) {
  9053. allow_on_the_fly_compression = 0;
  9054. }
  9055. #endif
  9056. /* Check if there is a range header */
  9057. range_hdr = mg_get_header(conn, "Range");
  9058. /* For gzipped files, add *.gz */
  9059. if (filep->stat.is_gzipped) {
  9060. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9061. if (truncated) {
  9062. mg_send_http_error(conn,
  9063. 500,
  9064. "Error: Path of zipped file too long (%s)",
  9065. path);
  9066. return;
  9067. }
  9068. path = gz_path;
  9069. encoding = "gzip";
  9070. #if defined(USE_ZLIB)
  9071. /* File is already compressed. No "on the fly" compression. */
  9072. allow_on_the_fly_compression = 0;
  9073. #endif
  9074. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  9075. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  9076. struct mg_file_stat file_stat;
  9077. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9078. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  9079. && !file_stat.is_directory) {
  9080. file_stat.is_gzipped = 1;
  9081. filep->stat = file_stat;
  9082. cl = (int64_t)filep->stat.size;
  9083. path = gz_path;
  9084. encoding = "gzip";
  9085. #if defined(USE_ZLIB)
  9086. /* File is already compressed. No "on the fly" compression. */
  9087. allow_on_the_fly_compression = 0;
  9088. #endif
  9089. }
  9090. }
  9091. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9092. mg_send_http_error(conn,
  9093. 500,
  9094. "Error: Cannot open file\nfopen(%s): %s",
  9095. path,
  9096. strerror(ERRNO));
  9097. return;
  9098. }
  9099. fclose_on_exec(&filep->access, conn);
  9100. /* If "Range" request was made: parse header, send only selected part
  9101. * of the file. */
  9102. r1 = r2 = 0;
  9103. if ((range_hdr != NULL)
  9104. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  9105. && (r2 >= 0)) {
  9106. /* actually, range requests don't play well with a pre-gzipped
  9107. * file (since the range is specified in the uncompressed space) */
  9108. if (filep->stat.is_gzipped) {
  9109. mg_send_http_error(
  9110. conn,
  9111. 416, /* 416 = Range Not Satisfiable */
  9112. "%s",
  9113. "Error: Range requests in gzipped files are not supported");
  9114. (void)mg_fclose(
  9115. &filep->access); /* ignore error on read only file */
  9116. return;
  9117. }
  9118. conn->status_code = 206;
  9119. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  9120. mg_snprintf(conn,
  9121. NULL, /* range buffer is big enough */
  9122. range,
  9123. sizeof(range),
  9124. "bytes "
  9125. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  9126. r1,
  9127. r1 + cl - 1,
  9128. filep->stat.size);
  9129. #if defined(USE_ZLIB)
  9130. /* Do not compress ranges. */
  9131. allow_on_the_fly_compression = 0;
  9132. #endif
  9133. }
  9134. /* Do not compress small files. Small files do not benefit from file
  9135. * compression, but there is still some overhead. */
  9136. #if defined(USE_ZLIB)
  9137. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  9138. /* File is below the size limit. */
  9139. allow_on_the_fly_compression = 0;
  9140. }
  9141. #endif
  9142. /* Prepare Etag, and Last-Modified headers. */
  9143. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9144. construct_etag(etag, sizeof(etag), &filep->stat);
  9145. /* Create 2xx (200, 206) response */
  9146. mg_response_header_start(conn, conn->status_code);
  9147. send_static_cache_header(conn);
  9148. send_additional_header(conn);
  9149. send_cors_header(conn);
  9150. mg_response_header_add(conn,
  9151. "Content-Type",
  9152. mime_vec.ptr,
  9153. (int)mime_vec.len);
  9154. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9155. mg_response_header_add(conn, "Etag", etag, -1);
  9156. #if defined(USE_ZLIB)
  9157. /* On the fly compression allowed */
  9158. if (allow_on_the_fly_compression) {
  9159. /* For on the fly compression, we don't know the content size in
  9160. * advance, so we have to use chunked encoding */
  9161. encoding = "gzip";
  9162. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9163. /* HTTP/2 is always using "chunks" (frames) */
  9164. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9165. }
  9166. } else
  9167. #endif
  9168. {
  9169. /* Without on-the-fly compression, we know the content-length
  9170. * and we can use ranges (with on-the-fly compression we cannot).
  9171. * So we send these response headers only in this case. */
  9172. char len[32];
  9173. int trunc = 0;
  9174. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9175. if (!trunc) {
  9176. mg_response_header_add(conn, "Content-Length", len, -1);
  9177. }
  9178. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9179. }
  9180. if (encoding) {
  9181. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9182. }
  9183. if (range[0] != 0) {
  9184. mg_response_header_add(conn, "Content-Range", range, -1);
  9185. }
  9186. /* The code above does not add any header starting with X- to make
  9187. * sure no one of the additional_headers is included twice */
  9188. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9189. mg_response_header_add_lines(conn, additional_headers);
  9190. }
  9191. /* Send all headers */
  9192. mg_response_header_send(conn);
  9193. if (!is_head_request) {
  9194. #if defined(USE_ZLIB)
  9195. if (allow_on_the_fly_compression) {
  9196. /* Compress and send */
  9197. send_compressed_data(conn, filep);
  9198. } else
  9199. #endif
  9200. {
  9201. /* Send file directly */
  9202. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9203. }
  9204. }
  9205. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9206. }
  9207. CIVETWEB_API int
  9208. mg_send_file_body(struct mg_connection *conn, const char *path)
  9209. {
  9210. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9211. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9212. return -1;
  9213. }
  9214. fclose_on_exec(&file.access, conn);
  9215. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9216. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9217. return 0; /* >= 0 for OK */
  9218. }
  9219. #endif /* NO_FILESYSTEMS */
  9220. #if !defined(NO_CACHING)
  9221. /* Return True if we should reply 304 Not Modified. */
  9222. static int
  9223. is_not_modified(const struct mg_connection *conn,
  9224. const struct mg_file_stat *filestat)
  9225. {
  9226. char etag[64];
  9227. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9228. const char *inm = mg_get_header(conn, "If-None-Match");
  9229. construct_etag(etag, sizeof(etag), filestat);
  9230. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9231. || ((ims != NULL)
  9232. && (filestat->last_modified <= parse_date_string(ims)));
  9233. }
  9234. static void
  9235. handle_not_modified_static_file_request(struct mg_connection *conn,
  9236. struct mg_file *filep)
  9237. {
  9238. char lm[64], etag[64];
  9239. if ((conn == NULL) || (filep == NULL)) {
  9240. return;
  9241. }
  9242. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9243. construct_etag(etag, sizeof(etag), &filep->stat);
  9244. /* Create 304 "not modified" response */
  9245. mg_response_header_start(conn, 304);
  9246. send_static_cache_header(conn);
  9247. send_additional_header(conn);
  9248. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9249. mg_response_header_add(conn, "Etag", etag, -1);
  9250. /* Send all headers */
  9251. mg_response_header_send(conn);
  9252. }
  9253. #endif
  9254. #if !defined(NO_FILESYSTEMS)
  9255. CIVETWEB_API void
  9256. mg_send_file(struct mg_connection *conn, const char *path)
  9257. {
  9258. mg_send_mime_file2(conn, path, NULL, NULL);
  9259. }
  9260. CIVETWEB_API void
  9261. mg_send_mime_file(struct mg_connection *conn,
  9262. const char *path,
  9263. const char *mime_type)
  9264. {
  9265. mg_send_mime_file2(conn, path, mime_type, NULL);
  9266. }
  9267. CIVETWEB_API void
  9268. mg_send_mime_file2(struct mg_connection *conn,
  9269. const char *path,
  9270. const char *mime_type,
  9271. const char *additional_headers)
  9272. {
  9273. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9274. if (!conn) {
  9275. /* No conn */
  9276. return;
  9277. }
  9278. if (mg_stat(conn, path, &file.stat)) {
  9279. #if !defined(NO_CACHING)
  9280. if (is_not_modified(conn, &file.stat)) {
  9281. /* Send 304 "Not Modified" - this must not send any body data */
  9282. handle_not_modified_static_file_request(conn, &file);
  9283. } else
  9284. #endif /* NO_CACHING */
  9285. if (file.stat.is_directory) {
  9286. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9287. "yes")) {
  9288. handle_directory_request(conn, path);
  9289. } else {
  9290. mg_send_http_error(conn,
  9291. 403,
  9292. "%s",
  9293. "Error: Directory listing denied");
  9294. }
  9295. } else {
  9296. handle_static_file_request(
  9297. conn, path, &file, mime_type, additional_headers);
  9298. }
  9299. } else {
  9300. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9301. }
  9302. }
  9303. /* For a given PUT path, create all intermediate subdirectories.
  9304. * Return 0 if the path itself is a directory.
  9305. * Return 1 if the path leads to a file.
  9306. * Return -1 for if the path is too long.
  9307. * Return -2 if path can not be created.
  9308. */
  9309. static int
  9310. put_dir(struct mg_connection *conn, const char *path)
  9311. {
  9312. char buf[UTF8_PATH_MAX];
  9313. const char *s, *p;
  9314. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9315. size_t len;
  9316. int res = 1;
  9317. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9318. len = (size_t)(p - path);
  9319. if (len >= sizeof(buf)) {
  9320. /* path too long */
  9321. res = -1;
  9322. break;
  9323. }
  9324. memcpy(buf, path, len);
  9325. buf[len] = '\0';
  9326. /* Try to create intermediate directory */
  9327. DEBUG_TRACE("mkdir(%s)", buf);
  9328. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9329. /* path does not exist and can not be created */
  9330. res = -2;
  9331. break;
  9332. }
  9333. /* Is path itself a directory? */
  9334. if (p[1] == '\0') {
  9335. res = 0;
  9336. }
  9337. }
  9338. return res;
  9339. }
  9340. static void
  9341. remove_bad_file(const struct mg_connection *conn, const char *path)
  9342. {
  9343. int r = mg_remove(conn, path);
  9344. if (r != 0) {
  9345. mg_cry_internal(conn,
  9346. "%s: Cannot remove invalid file %s",
  9347. __func__,
  9348. path);
  9349. }
  9350. }
  9351. CIVETWEB_API long long
  9352. mg_store_body(struct mg_connection *conn, const char *path)
  9353. {
  9354. char buf[MG_BUF_LEN];
  9355. long long len = 0;
  9356. int ret, n;
  9357. struct mg_file fi;
  9358. if (conn->consumed_content != 0) {
  9359. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9360. return -11;
  9361. }
  9362. ret = put_dir(conn, path);
  9363. if (ret < 0) {
  9364. /* -1 for path too long,
  9365. * -2 for path can not be created. */
  9366. return ret;
  9367. }
  9368. if (ret != 1) {
  9369. /* Return 0 means, path itself is a directory. */
  9370. return 0;
  9371. }
  9372. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9373. return -12;
  9374. }
  9375. ret = mg_read(conn, buf, sizeof(buf));
  9376. while (ret > 0) {
  9377. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9378. if (n != ret) {
  9379. (void)mg_fclose(
  9380. &fi.access); /* File is bad and will be removed anyway. */
  9381. remove_bad_file(conn, path);
  9382. return -13;
  9383. }
  9384. len += ret;
  9385. ret = mg_read(conn, buf, sizeof(buf));
  9386. }
  9387. /* File is open for writing. If fclose fails, there was probably an
  9388. * error flushing the buffer to disk, so the file on disk might be
  9389. * broken. Delete it and return an error to the caller. */
  9390. if (mg_fclose(&fi.access) != 0) {
  9391. remove_bad_file(conn, path);
  9392. return -14;
  9393. }
  9394. return len;
  9395. }
  9396. #endif /* NO_FILESYSTEMS */
  9397. /* Parse a buffer:
  9398. * Forward the string pointer till the end of a word, then
  9399. * terminate it and forward till the begin of the next word.
  9400. */
  9401. static int
  9402. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9403. {
  9404. /* Forward until a space is found - use isgraph here */
  9405. /* Extended ASCII characters are also treated as word characters. */
  9406. /* See http://www.cplusplus.com/reference/cctype/ */
  9407. while ((unsigned char)**ppw > 127 || isgraph((unsigned char)**ppw)) {
  9408. (*ppw)++;
  9409. }
  9410. /* Check end of word */
  9411. if (eol) {
  9412. /* must be a end of line */
  9413. if ((**ppw != '\r') && (**ppw != '\n')) {
  9414. return -1;
  9415. }
  9416. } else {
  9417. /* must be a end of a word, but not a line */
  9418. if (**ppw != ' ') {
  9419. return -1;
  9420. }
  9421. }
  9422. /* Terminate and forward to the next word */
  9423. do {
  9424. **ppw = 0;
  9425. (*ppw)++;
  9426. } while (isspace((unsigned char)**ppw));
  9427. /* Check after term */
  9428. if (!eol) {
  9429. /* if it's not the end of line, there must be a next word */
  9430. if (!isgraph((unsigned char)**ppw)) {
  9431. return -1;
  9432. }
  9433. }
  9434. /* ok */
  9435. return 1;
  9436. }
  9437. /* Parse HTTP headers from the given buffer, advance buf pointer
  9438. * to the point where parsing stopped.
  9439. * All parameters must be valid pointers (not NULL).
  9440. * Return <0 on error. */
  9441. static int
  9442. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9443. {
  9444. int i;
  9445. int num_headers = 0;
  9446. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9447. char *dp = *buf;
  9448. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9449. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9450. dp++;
  9451. }
  9452. if (dp == *buf) {
  9453. /* End of headers reached. */
  9454. break;
  9455. }
  9456. /* Drop all spaces after header name before : */
  9457. while (*dp == ' ') {
  9458. *dp = 0;
  9459. dp++;
  9460. }
  9461. if (*dp != ':') {
  9462. /* This is not a valid field. */
  9463. return -1;
  9464. }
  9465. /* End of header key (*dp == ':') */
  9466. /* Truncate here and set the key name */
  9467. *dp = 0;
  9468. hdr[i].name = *buf;
  9469. /* Skip all spaces */
  9470. do {
  9471. dp++;
  9472. } while ((*dp == ' ') || (*dp == '\t'));
  9473. /* The rest of the line is the value */
  9474. hdr[i].value = dp;
  9475. /* Find end of line */
  9476. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9477. dp++;
  9478. };
  9479. /* eliminate \r */
  9480. if (*dp == '\r') {
  9481. *dp = 0;
  9482. dp++;
  9483. if (*dp != '\n') {
  9484. /* This is not a valid line. */
  9485. return -1;
  9486. }
  9487. }
  9488. /* here *dp is either 0 or '\n' */
  9489. /* in any case, we have found a complete header */
  9490. num_headers = i + 1;
  9491. if (*dp) {
  9492. *dp = 0;
  9493. dp++;
  9494. *buf = dp;
  9495. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9496. /* We've had CRLF twice in a row
  9497. * This is the end of the headers */
  9498. break;
  9499. }
  9500. /* continue within the loop, find the next header */
  9501. } else {
  9502. *buf = dp;
  9503. break;
  9504. }
  9505. }
  9506. return num_headers;
  9507. }
  9508. struct mg_http_method_info {
  9509. const char *name;
  9510. int request_has_body;
  9511. int response_has_body;
  9512. int is_safe;
  9513. int is_idempotent;
  9514. int is_cacheable;
  9515. };
  9516. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9517. static const struct mg_http_method_info http_methods[] = {
  9518. /* HTTP (RFC 2616) */
  9519. {"GET", 0, 1, 1, 1, 1},
  9520. {"POST", 1, 1, 0, 0, 0},
  9521. {"PUT", 1, 0, 0, 1, 0},
  9522. {"DELETE", 0, 0, 0, 1, 0},
  9523. {"HEAD", 0, 0, 1, 1, 1},
  9524. {"OPTIONS", 0, 0, 1, 1, 0},
  9525. {"CONNECT", 1, 1, 0, 0, 0},
  9526. /* TRACE method (RFC 2616) is not supported for security reasons */
  9527. /* PATCH method (RFC 5789) */
  9528. {"PATCH", 1, 0, 0, 0, 0},
  9529. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9530. /* WEBDAV (RFC 2518) */
  9531. {"PROPFIND", 0, 1, 1, 1, 0},
  9532. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9533. * Some PROPFIND results MAY be cached, with care,
  9534. * as there is no cache validation mechanism for
  9535. * most properties. This method is both safe and
  9536. * idempotent (see Section 9.1 of [RFC2616]). */
  9537. {"MKCOL", 0, 0, 0, 1, 0},
  9538. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9539. * When MKCOL is invoked without a request body,
  9540. * the newly created collection SHOULD have no
  9541. * members. A MKCOL request message may contain
  9542. * a message body. The precise behavior of a MKCOL
  9543. * request when the body is present is undefined,
  9544. * ... ==> We do not support MKCOL with body data.
  9545. * This method is idempotent, but not safe (see
  9546. * Section 9.1 of [RFC2616]). Responses to this
  9547. * method MUST NOT be cached. */
  9548. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9549. {"LOCK", 1, 1, 0, 0, 0},
  9550. {"UNLOCK", 1, 0, 0, 0, 0},
  9551. {"PROPPATCH", 1, 1, 0, 0, 0},
  9552. {"COPY", 1, 0, 0, 0, 0},
  9553. {"MOVE", 1, 1, 0, 0, 0},
  9554. /* Unsupported WEBDAV Methods: */
  9555. /* + 11 methods from RFC 3253 */
  9556. /* ORDERPATCH (RFC 3648) */
  9557. /* ACL (RFC 3744) */
  9558. /* SEARCH (RFC 5323) */
  9559. /* + MicroSoft extensions
  9560. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9561. /* REPORT method (RFC 3253) */
  9562. {"REPORT", 1, 1, 1, 1, 1},
  9563. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9564. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9565. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9566. * to be useful for REST in case a "GET request with body" is
  9567. * required. */
  9568. {NULL, 0, 0, 0, 0, 0}
  9569. /* end of list */
  9570. };
  9571. /* All method names */
  9572. static char *all_methods = NULL; /* Built by mg_init_library */
  9573. static const struct mg_http_method_info *
  9574. get_http_method_info(const char *method)
  9575. {
  9576. /* Check if the method is known to the server. The list of all known
  9577. * HTTP methods can be found here at
  9578. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9579. */
  9580. const struct mg_http_method_info *m = http_methods;
  9581. while (m->name) {
  9582. if (!strcmp(m->name, method)) {
  9583. return m;
  9584. }
  9585. m++;
  9586. }
  9587. return NULL;
  9588. }
  9589. static int
  9590. is_valid_http_method(const char *method)
  9591. {
  9592. return (get_http_method_info(method) != NULL);
  9593. }
  9594. /* Parse HTTP request, fill in mg_request_info structure.
  9595. * This function modifies the buffer by NUL-terminating
  9596. * HTTP request components, header names and header values.
  9597. * Parameters:
  9598. * buf (in/out): pointer to the HTTP header to parse and split
  9599. * len (in): length of HTTP header buffer
  9600. * re (out): parsed header as mg_request_info
  9601. * buf and ri must be valid pointers (not NULL), len>0.
  9602. * Returns <0 on error. */
  9603. static int
  9604. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9605. {
  9606. int request_length;
  9607. int init_skip = 0;
  9608. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9609. * remote_port */
  9610. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9611. NULL;
  9612. ri->num_headers = 0;
  9613. /* RFC says that all initial whitespaces should be ignored */
  9614. /* This included all leading \r and \n (isspace) */
  9615. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9616. while ((len > 0) && isspace((unsigned char)*buf)) {
  9617. buf++;
  9618. len--;
  9619. init_skip++;
  9620. }
  9621. if (len == 0) {
  9622. /* Incomplete request */
  9623. return 0;
  9624. }
  9625. /* Control characters are not allowed, including zero */
  9626. if (iscntrl((unsigned char)*buf)) {
  9627. return -1;
  9628. }
  9629. /* Find end of HTTP header */
  9630. request_length = get_http_header_len(buf, len);
  9631. if (request_length <= 0) {
  9632. return request_length;
  9633. }
  9634. buf[request_length - 1] = '\0';
  9635. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9636. return -1;
  9637. }
  9638. /* The first word has to be the HTTP method */
  9639. ri->request_method = buf;
  9640. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9641. return -1;
  9642. }
  9643. /* The second word is the URI */
  9644. ri->request_uri = buf;
  9645. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9646. return -1;
  9647. }
  9648. /* Next would be the HTTP version */
  9649. ri->http_version = buf;
  9650. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9651. return -1;
  9652. }
  9653. /* Check for a valid HTTP version key */
  9654. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9655. /* Invalid request */
  9656. return -1;
  9657. }
  9658. ri->http_version += 5;
  9659. /* Check for a valid http method */
  9660. if (!is_valid_http_method(ri->request_method)) {
  9661. return -1;
  9662. }
  9663. /* Parse all HTTP headers */
  9664. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9665. if (ri->num_headers < 0) {
  9666. /* Error while parsing headers */
  9667. return -1;
  9668. }
  9669. return request_length + init_skip;
  9670. }
  9671. static int
  9672. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9673. {
  9674. int response_length;
  9675. int init_skip = 0;
  9676. char *tmp, *tmp2;
  9677. long l;
  9678. /* Initialize elements. */
  9679. ri->http_version = ri->status_text = NULL;
  9680. ri->num_headers = ri->status_code = 0;
  9681. /* RFC says that all initial whitespaces should be ignored */
  9682. /* This included all leading \r and \n (isspace) */
  9683. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9684. while ((len > 0) && isspace((unsigned char)*buf)) {
  9685. buf++;
  9686. len--;
  9687. init_skip++;
  9688. }
  9689. if (len == 0) {
  9690. /* Incomplete request */
  9691. return 0;
  9692. }
  9693. /* Control characters are not allowed, including zero */
  9694. if (iscntrl((unsigned char)*buf)) {
  9695. return -1;
  9696. }
  9697. /* Find end of HTTP header */
  9698. response_length = get_http_header_len(buf, len);
  9699. if (response_length <= 0) {
  9700. return response_length;
  9701. }
  9702. buf[response_length - 1] = '\0';
  9703. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9704. return -1;
  9705. }
  9706. /* The first word is the HTTP version */
  9707. /* Check for a valid HTTP version key */
  9708. if (strncmp(buf, "HTTP/", 5) != 0) {
  9709. /* Invalid request */
  9710. return -1;
  9711. }
  9712. buf += 5;
  9713. if (!isgraph((unsigned char)buf[0])) {
  9714. /* Invalid request */
  9715. return -1;
  9716. }
  9717. ri->http_version = buf;
  9718. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9719. return -1;
  9720. }
  9721. /* The second word is the status as a number */
  9722. tmp = buf;
  9723. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9724. return -1;
  9725. }
  9726. l = strtol(tmp, &tmp2, 10);
  9727. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9728. /* Everything else but a 3 digit code is invalid */
  9729. return -1;
  9730. }
  9731. ri->status_code = (int)l;
  9732. /* The rest of the line is the status text */
  9733. ri->status_text = buf;
  9734. /* Find end of status text */
  9735. /* isgraph or isspace = isprint */
  9736. while (isprint((unsigned char)*buf)) {
  9737. buf++;
  9738. }
  9739. if ((*buf != '\r') && (*buf != '\n')) {
  9740. return -1;
  9741. }
  9742. /* Terminate string and forward buf to next line */
  9743. do {
  9744. *buf = 0;
  9745. buf++;
  9746. } while (isspace((unsigned char)*buf));
  9747. /* Parse all HTTP headers */
  9748. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9749. if (ri->num_headers < 0) {
  9750. /* Error while parsing headers */
  9751. return -1;
  9752. }
  9753. return response_length + init_skip;
  9754. }
  9755. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9756. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9757. * buffer (which marks the end of HTTP request). Buffer buf may already
  9758. * have some data. The length of the data is stored in nread.
  9759. * Upon every read operation, increase nread by the number of bytes read. */
  9760. static int
  9761. read_message(FILE *fp,
  9762. struct mg_connection *conn,
  9763. char *buf,
  9764. int bufsiz,
  9765. int *nread)
  9766. {
  9767. int request_len, n = 0;
  9768. struct timespec last_action_time;
  9769. double request_timeout;
  9770. if (!conn) {
  9771. return 0;
  9772. }
  9773. memset(&last_action_time, 0, sizeof(last_action_time));
  9774. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9775. /* value of request_timeout is in seconds, config in milliseconds */
  9776. request_timeout =
  9777. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9778. } else {
  9779. request_timeout =
  9780. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9781. / 1000.0;
  9782. }
  9783. if (conn->handled_requests > 0) {
  9784. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9785. request_timeout =
  9786. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9787. / 1000.0;
  9788. }
  9789. }
  9790. request_len = get_http_header_len(buf, *nread);
  9791. while (request_len == 0) {
  9792. /* Full request not yet received */
  9793. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9794. /* Server is to be stopped. */
  9795. return -1;
  9796. }
  9797. if (*nread >= bufsiz) {
  9798. /* Request too long */
  9799. return -2;
  9800. }
  9801. n = pull_inner(
  9802. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9803. if (n == -2) {
  9804. /* Receive error */
  9805. return -1;
  9806. }
  9807. /* update clock after every read request */
  9808. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9809. if (n > 0) {
  9810. *nread += n;
  9811. request_len = get_http_header_len(buf, *nread);
  9812. }
  9813. if ((n <= 0) && (request_timeout >= 0)) {
  9814. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9815. > request_timeout) {
  9816. /* Timeout */
  9817. return -3;
  9818. }
  9819. }
  9820. }
  9821. return request_len;
  9822. }
  9823. #if !defined(NO_CGI) || !defined(NO_FILES)
  9824. static int
  9825. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9826. {
  9827. const char *expect;
  9828. char buf[MG_BUF_LEN];
  9829. int success = 0;
  9830. if (!conn) {
  9831. return 0;
  9832. }
  9833. expect = mg_get_header(conn, "Expect");
  9834. DEBUG_ASSERT(fp != NULL);
  9835. if (!fp) {
  9836. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9837. return 0;
  9838. }
  9839. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9840. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9841. */
  9842. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9843. } else {
  9844. if (expect != NULL) {
  9845. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9846. conn->status_code = 100;
  9847. } else {
  9848. conn->status_code = 200;
  9849. }
  9850. DEBUG_ASSERT(conn->consumed_content == 0);
  9851. if (conn->consumed_content != 0) {
  9852. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9853. return 0;
  9854. }
  9855. for (;;) {
  9856. int nread = mg_read(conn, buf, sizeof(buf));
  9857. if (nread <= 0) {
  9858. success = (nread == 0);
  9859. break;
  9860. }
  9861. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9862. break;
  9863. }
  9864. }
  9865. /* Each error code path in this function must send an error */
  9866. if (!success) {
  9867. /* NOTE: Maybe some data has already been sent. */
  9868. /* TODO (low): If some data has been sent, a correct error
  9869. * reply can no longer be sent, so just close the connection */
  9870. mg_send_http_error(conn, 500, "%s", "");
  9871. }
  9872. }
  9873. return success;
  9874. }
  9875. #endif
  9876. #if defined(USE_TIMERS)
  9877. #define TIMER_API static
  9878. #include "timer.inl"
  9879. #endif /* USE_TIMERS */
  9880. #if !defined(NO_CGI)
  9881. /* This structure helps to create an environment for the spawned CGI
  9882. * program.
  9883. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9884. * last element must be NULL.
  9885. * However, on Windows there is a requirement that all these
  9886. * VARIABLE=VALUE\0
  9887. * strings must reside in a contiguous buffer. The end of the buffer is
  9888. * marked by two '\0' characters.
  9889. * We satisfy both worlds: we create an envp array (which is vars), all
  9890. * entries are actually pointers inside buf. */
  9891. struct cgi_environment {
  9892. struct mg_connection *conn;
  9893. /* Data block */
  9894. char *buf; /* Environment buffer */
  9895. size_t buflen; /* Space available in buf */
  9896. size_t bufused; /* Space taken in buf */
  9897. /* Index block */
  9898. char **var; /* char **envp */
  9899. size_t varlen; /* Number of variables available in var */
  9900. size_t varused; /* Number of variables stored in var */
  9901. };
  9902. static void addenv(struct cgi_environment *env,
  9903. PRINTF_FORMAT_STRING(const char *fmt),
  9904. ...) PRINTF_ARGS(2, 3);
  9905. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9906. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9907. static void
  9908. addenv(struct cgi_environment *env, const char *fmt, ...)
  9909. {
  9910. size_t i, n, space;
  9911. int truncated = 0;
  9912. char *added;
  9913. va_list ap;
  9914. if ((env->varlen - env->varused) < 2) {
  9915. mg_cry_internal(env->conn,
  9916. "%s: Cannot register CGI variable [%s]",
  9917. __func__,
  9918. fmt);
  9919. return;
  9920. }
  9921. /* Calculate how much space is left in the buffer */
  9922. space = (env->buflen - env->bufused);
  9923. do {
  9924. /* Space for "\0\0" is always needed. */
  9925. if (space <= 2) {
  9926. /* Allocate new buffer */
  9927. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9928. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9929. if (!added) {
  9930. /* Out of memory */
  9931. mg_cry_internal(
  9932. env->conn,
  9933. "%s: Cannot allocate memory for CGI variable [%s]",
  9934. __func__,
  9935. fmt);
  9936. return;
  9937. }
  9938. /* Retarget pointers */
  9939. env->buf = added;
  9940. env->buflen = n;
  9941. for (i = 0, n = 0; i < env->varused; i++) {
  9942. env->var[i] = added + n;
  9943. n += strlen(added + n) + 1;
  9944. }
  9945. space = (env->buflen - env->bufused);
  9946. }
  9947. /* Make a pointer to the free space int the buffer */
  9948. added = env->buf + env->bufused;
  9949. /* Copy VARIABLE=VALUE\0 string into the free space */
  9950. va_start(ap, fmt);
  9951. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9952. va_end(ap);
  9953. /* Do not add truncated strings to the environment */
  9954. if (truncated) {
  9955. /* Reallocate the buffer */
  9956. space = 0;
  9957. }
  9958. } while (truncated);
  9959. /* Calculate number of bytes added to the environment */
  9960. n = strlen(added) + 1;
  9961. env->bufused += n;
  9962. /* Append a pointer to the added string into the envp array */
  9963. env->var[env->varused] = added;
  9964. env->varused++;
  9965. }
  9966. /* Return 0 on success, non-zero if an error occurs. */
  9967. static int
  9968. prepare_cgi_environment(struct mg_connection *conn,
  9969. const char *prog,
  9970. struct cgi_environment *env,
  9971. int cgi_config_idx)
  9972. {
  9973. const char *s;
  9974. struct vec var_vec;
  9975. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9976. int i, truncated, uri_len;
  9977. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9978. return -1;
  9979. }
  9980. env->conn = conn;
  9981. env->buflen = CGI_ENVIRONMENT_SIZE;
  9982. env->bufused = 0;
  9983. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9984. if (env->buf == NULL) {
  9985. mg_cry_internal(conn,
  9986. "%s: Not enough memory for environmental buffer",
  9987. __func__);
  9988. return -1;
  9989. }
  9990. env->varlen = MAX_CGI_ENVIR_VARS;
  9991. env->varused = 0;
  9992. env->var =
  9993. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9994. if (env->var == NULL) {
  9995. mg_cry_internal(conn,
  9996. "%s: Not enough memory for environmental variables",
  9997. __func__);
  9998. mg_free(env->buf);
  9999. return -1;
  10000. }
  10001. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  10002. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10003. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10004. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  10005. addenv(env,
  10006. "FALLBACK_DOCUMENT_ROOT=%s",
  10007. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  10008. }
  10009. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  10010. /* Prepare the environment block */
  10011. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  10012. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  10013. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  10014. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  10015. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10016. addenv(env, "REMOTE_ADDR=%s", src_addr);
  10017. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  10018. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  10019. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  10020. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  10021. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  10022. /* SCRIPT_NAME */
  10023. uri_len = (int)strlen(conn->request_info.local_uri);
  10024. if (conn->path_info == NULL) {
  10025. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  10026. /* URI: /path_to_script/script.cgi */
  10027. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  10028. } else {
  10029. /* URI: /path_to_script/ ... using index.cgi */
  10030. const char *index_file = strrchr(prog, '/');
  10031. if (index_file) {
  10032. addenv(env,
  10033. "SCRIPT_NAME=%s%s",
  10034. conn->request_info.local_uri,
  10035. index_file + 1);
  10036. }
  10037. }
  10038. } else {
  10039. /* URI: /path_to_script/script.cgi/path_info */
  10040. addenv(env,
  10041. "SCRIPT_NAME=%.*s",
  10042. uri_len - (int)strlen(conn->path_info),
  10043. conn->request_info.local_uri);
  10044. }
  10045. addenv(env, "SCRIPT_FILENAME=%s", prog);
  10046. if (conn->path_info == NULL) {
  10047. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10048. } else {
  10049. addenv(env,
  10050. "PATH_TRANSLATED=%s%s",
  10051. conn->dom_ctx->config[DOCUMENT_ROOT],
  10052. conn->path_info);
  10053. }
  10054. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  10055. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  10056. addenv(env, "CONTENT_TYPE=%s", s);
  10057. }
  10058. if (conn->request_info.query_string != NULL) {
  10059. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  10060. }
  10061. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  10062. addenv(env, "CONTENT_LENGTH=%s", s);
  10063. }
  10064. if ((s = getenv("PATH")) != NULL) {
  10065. addenv(env, "PATH=%s", s);
  10066. }
  10067. if (conn->path_info != NULL) {
  10068. addenv(env, "PATH_INFO=%s", conn->path_info);
  10069. }
  10070. if (conn->status_code > 0) {
  10071. /* CGI error handler should show the status code */
  10072. addenv(env, "STATUS=%d", conn->status_code);
  10073. }
  10074. #if defined(_WIN32)
  10075. if ((s = getenv("COMSPEC")) != NULL) {
  10076. addenv(env, "COMSPEC=%s", s);
  10077. }
  10078. if ((s = getenv("SYSTEMROOT")) != NULL) {
  10079. addenv(env, "SYSTEMROOT=%s", s);
  10080. }
  10081. if ((s = getenv("SystemDrive")) != NULL) {
  10082. addenv(env, "SystemDrive=%s", s);
  10083. }
  10084. if ((s = getenv("ProgramFiles")) != NULL) {
  10085. addenv(env, "ProgramFiles=%s", s);
  10086. }
  10087. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  10088. addenv(env, "ProgramFiles(x86)=%s", s);
  10089. }
  10090. #else
  10091. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  10092. addenv(env, "LD_LIBRARY_PATH=%s", s);
  10093. }
  10094. #endif /* _WIN32 */
  10095. if ((s = getenv("PERLLIB")) != NULL) {
  10096. addenv(env, "PERLLIB=%s", s);
  10097. }
  10098. if (conn->request_info.remote_user != NULL) {
  10099. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  10100. addenv(env, "%s", "AUTH_TYPE=Digest");
  10101. }
  10102. /* Add all headers as HTTP_* variables */
  10103. for (i = 0; i < conn->request_info.num_headers; i++) {
  10104. (void)mg_snprintf(conn,
  10105. &truncated,
  10106. http_var_name,
  10107. sizeof(http_var_name),
  10108. "HTTP_%s",
  10109. conn->request_info.http_headers[i].name);
  10110. if (truncated) {
  10111. mg_cry_internal(conn,
  10112. "%s: HTTP header variable too long [%s]",
  10113. __func__,
  10114. conn->request_info.http_headers[i].name);
  10115. continue;
  10116. }
  10117. /* Convert variable name into uppercase, and change - to _ */
  10118. for (p = http_var_name; *p != '\0'; p++) {
  10119. if (*p == '-') {
  10120. *p = '_';
  10121. }
  10122. *p = (char)toupper((unsigned char)*p);
  10123. }
  10124. addenv(env,
  10125. "%s=%s",
  10126. http_var_name,
  10127. conn->request_info.http_headers[i].value);
  10128. }
  10129. /* Add user-specified variables */
  10130. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  10131. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  10132. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  10133. }
  10134. env->var[env->varused] = NULL;
  10135. env->buf[env->bufused] = '\0';
  10136. return 0;
  10137. }
  10138. /* Data for CGI process control: PID and number of references */
  10139. struct process_control_data {
  10140. pid_t pid;
  10141. ptrdiff_t references;
  10142. };
  10143. static int
  10144. abort_cgi_process(void *data)
  10145. {
  10146. /* Waitpid checks for child status and won't work for a pid that does
  10147. * not identify a child of the current process. Thus, if the pid is
  10148. * reused, we will not affect a different process. */
  10149. struct process_control_data *proc = (struct process_control_data *)data;
  10150. int status = 0;
  10151. ptrdiff_t refs;
  10152. pid_t ret_pid;
  10153. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  10154. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  10155. /* Stop child process */
  10156. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  10157. kill(proc->pid, SIGABRT);
  10158. /* Wait until process is terminated (don't leave zombies) */
  10159. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  10160. ;
  10161. } else {
  10162. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10163. }
  10164. /* Dec reference counter */
  10165. refs = mg_atomic_dec(&proc->references);
  10166. if (refs == 0) {
  10167. /* no more references - free data */
  10168. mg_free(data);
  10169. }
  10170. return 0;
  10171. }
  10172. /* Local (static) function assumes all arguments are valid. */
  10173. static void
  10174. handle_cgi_request(struct mg_connection *conn,
  10175. const char *prog,
  10176. int cgi_config_idx)
  10177. {
  10178. char *buf;
  10179. size_t buflen;
  10180. int headers_len, data_len, i, truncated;
  10181. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10182. const char *status, *status_text;
  10183. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10184. struct mg_request_info ri;
  10185. struct cgi_environment blk;
  10186. FILE *in = NULL, *out = NULL, *err = NULL;
  10187. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10188. pid_t pid = (pid_t)-1;
  10189. struct process_control_data *proc = NULL;
  10190. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  10191. int no_buffering = 0;
  10192. #if defined(USE_TIMERS)
  10193. double cgi_timeout;
  10194. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  10195. /* Get timeout in seconds */
  10196. cgi_timeout =
  10197. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  10198. } else {
  10199. cgi_timeout =
  10200. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10201. }
  10202. #endif
  10203. if (cfg_buffering != NULL) {
  10204. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10205. no_buffering = 1;
  10206. }
  10207. }
  10208. buf = NULL;
  10209. buflen = conn->phys_ctx->max_request_size;
  10210. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10211. if (i != 0) {
  10212. blk.buf = NULL;
  10213. blk.var = NULL;
  10214. goto done;
  10215. }
  10216. /* CGI must be executed in its own directory. 'dir' must point to the
  10217. * directory containing executable program, 'p' must point to the
  10218. * executable program name relative to 'dir'. */
  10219. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10220. if (truncated) {
  10221. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10222. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10223. goto done;
  10224. }
  10225. if ((p = strrchr(dir, '/')) != NULL) {
  10226. *p++ = '\0';
  10227. } else {
  10228. dir[0] = '.';
  10229. dir[1] = '\0';
  10230. p = (char *)prog;
  10231. }
  10232. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10233. status = strerror(ERRNO);
  10234. mg_cry_internal(
  10235. conn,
  10236. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10237. prog,
  10238. status);
  10239. mg_send_http_error(conn,
  10240. 500,
  10241. "Error: Cannot create CGI pipe: %s",
  10242. status);
  10243. goto done;
  10244. }
  10245. proc = (struct process_control_data *)
  10246. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10247. if (proc == NULL) {
  10248. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10249. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10250. goto done;
  10251. }
  10252. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10253. pid = spawn_process(
  10254. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10255. if (pid == (pid_t)-1) {
  10256. status = strerror(ERRNO);
  10257. mg_cry_internal(
  10258. conn,
  10259. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10260. prog,
  10261. status);
  10262. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10263. mg_free(proc);
  10264. proc = NULL;
  10265. goto done;
  10266. }
  10267. /* Store data in shared process_control_data */
  10268. proc->pid = pid;
  10269. proc->references = 1;
  10270. #if defined(USE_TIMERS)
  10271. if (cgi_timeout > 0.0) {
  10272. proc->references = 2;
  10273. // Start a timer for CGI
  10274. timer_add(conn->phys_ctx,
  10275. cgi_timeout /* in seconds */,
  10276. 0.0,
  10277. 1,
  10278. abort_cgi_process,
  10279. (void *)proc,
  10280. NULL);
  10281. }
  10282. #endif
  10283. /* Parent closes only one side of the pipes.
  10284. * If we don't mark them as closed, close() attempt before
  10285. * return from this function throws an exception on Windows.
  10286. * Windows does not like when closed descriptor is closed again. */
  10287. (void)close(fdin[0]);
  10288. (void)close(fdout[1]);
  10289. (void)close(fderr[1]);
  10290. fdin[0] = fdout[1] = fderr[1] = -1;
  10291. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10292. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10293. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10294. status = strerror(ERRNO);
  10295. mg_cry_internal(conn,
  10296. "Error: CGI program \"%s\": Can not open fd: %s",
  10297. prog,
  10298. status);
  10299. mg_send_http_error(conn,
  10300. 500,
  10301. "Error: CGI can not open fd\nfdopen: %s",
  10302. status);
  10303. goto done;
  10304. }
  10305. setbuf(in, NULL);
  10306. setbuf(out, NULL);
  10307. setbuf(err, NULL);
  10308. fout.access.fp = out;
  10309. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10310. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10311. conn->content_len);
  10312. /* This is a POST/PUT request, or another request with body data. */
  10313. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10314. /* Error sending the body data */
  10315. mg_cry_internal(
  10316. conn,
  10317. "Error: CGI program \"%s\": Forward body data failed",
  10318. prog);
  10319. goto done;
  10320. }
  10321. }
  10322. /* Close so child gets an EOF. */
  10323. fclose(in);
  10324. in = NULL;
  10325. fdin[1] = -1;
  10326. /* Now read CGI reply into a buffer. We need to set correct
  10327. * status code, thus we need to see all HTTP headers first.
  10328. * Do not send anything back to client, until we buffer in all
  10329. * HTTP headers. */
  10330. data_len = 0;
  10331. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10332. if (buf == NULL) {
  10333. mg_send_http_error(conn,
  10334. 500,
  10335. "Error: Not enough memory for CGI buffer (%u bytes)",
  10336. (unsigned int)buflen);
  10337. mg_cry_internal(
  10338. conn,
  10339. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10340. "bytes)",
  10341. prog,
  10342. (unsigned int)buflen);
  10343. goto done;
  10344. }
  10345. DEBUG_TRACE("CGI: %s", "wait for response");
  10346. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10347. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10348. if (headers_len <= 0) {
  10349. /* Could not parse the CGI response. Check if some error message on
  10350. * stderr. */
  10351. i = pull_all(err, conn, buf, (int)buflen);
  10352. if (i > 0) {
  10353. /* CGI program explicitly sent an error */
  10354. /* Write the error message to the internal log */
  10355. mg_cry_internal(conn,
  10356. "Error: CGI program \"%s\" sent error "
  10357. "message: [%.*s]",
  10358. prog,
  10359. i,
  10360. buf);
  10361. /* Don't send the error message back to the client */
  10362. mg_send_http_error(conn,
  10363. 500,
  10364. "Error: CGI program \"%s\" failed.",
  10365. prog);
  10366. } else {
  10367. /* CGI program did not explicitly send an error, but a broken
  10368. * respon header */
  10369. mg_cry_internal(conn,
  10370. "Error: CGI program sent malformed or too big "
  10371. "(>%u bytes) HTTP headers: [%.*s]",
  10372. (unsigned)buflen,
  10373. data_len,
  10374. buf);
  10375. mg_send_http_error(conn,
  10376. 500,
  10377. "Error: CGI program sent malformed or too big "
  10378. "(>%u bytes) HTTP headers: [%.*s]",
  10379. (unsigned)buflen,
  10380. data_len,
  10381. buf);
  10382. }
  10383. /* in both cases, abort processing CGI */
  10384. goto done;
  10385. }
  10386. pbuf = buf;
  10387. buf[headers_len - 1] = '\0';
  10388. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10389. /* Make up and send the status line */
  10390. status_text = "OK";
  10391. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10392. != NULL) {
  10393. conn->status_code = atoi(status);
  10394. status_text = status;
  10395. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10396. status_text++;
  10397. }
  10398. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10399. != NULL) {
  10400. conn->status_code = 307;
  10401. } else {
  10402. conn->status_code = 200;
  10403. }
  10404. if (!should_keep_alive(conn)) {
  10405. conn->must_close = 1;
  10406. }
  10407. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10408. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10409. /* Send headers */
  10410. for (i = 0; i < ri.num_headers; i++) {
  10411. DEBUG_TRACE("CGI header: %s: %s",
  10412. ri.http_headers[i].name,
  10413. ri.http_headers[i].value);
  10414. mg_printf(conn,
  10415. "%s: %s\r\n",
  10416. ri.http_headers[i].name,
  10417. ri.http_headers[i].value);
  10418. }
  10419. mg_write(conn, "\r\n", 2);
  10420. /* Send chunk of data that may have been read after the headers */
  10421. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10422. /* Read the rest of CGI output and send to the client */
  10423. DEBUG_TRACE("CGI: %s", "forward all data");
  10424. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10425. DEBUG_TRACE("CGI: %s", "all data sent");
  10426. done:
  10427. mg_free(blk.var);
  10428. mg_free(blk.buf);
  10429. if (pid != (pid_t)-1) {
  10430. abort_cgi_process((void *)proc);
  10431. }
  10432. if (fdin[0] != -1) {
  10433. close(fdin[0]);
  10434. }
  10435. if (fdout[1] != -1) {
  10436. close(fdout[1]);
  10437. }
  10438. if (fderr[1] != -1) {
  10439. close(fderr[1]);
  10440. }
  10441. if (in != NULL) {
  10442. fclose(in);
  10443. } else if (fdin[1] != -1) {
  10444. close(fdin[1]);
  10445. }
  10446. if (out != NULL) {
  10447. fclose(out);
  10448. } else if (fdout[0] != -1) {
  10449. close(fdout[0]);
  10450. }
  10451. if (err != NULL) {
  10452. fclose(err);
  10453. } else if (fderr[0] != -1) {
  10454. close(fderr[0]);
  10455. }
  10456. mg_free(buf);
  10457. }
  10458. #endif /* !NO_CGI */
  10459. #if !defined(NO_FILES)
  10460. static void
  10461. dav_mkcol(struct mg_connection *conn, const char *path)
  10462. {
  10463. int rc, body_len;
  10464. struct de de;
  10465. if (conn == NULL) {
  10466. return;
  10467. }
  10468. /* TODO (mid): Check the mg_send_http_error situations in this function
  10469. */
  10470. memset(&de.file, 0, sizeof(de.file));
  10471. if (!mg_stat(conn, path, &de.file)) {
  10472. mg_cry_internal(conn,
  10473. "%s: mg_stat(%s) failed: %s",
  10474. __func__,
  10475. path,
  10476. strerror(ERRNO));
  10477. }
  10478. if (de.file.last_modified) {
  10479. /* TODO (mid): This check does not seem to make any sense ! */
  10480. /* TODO (mid): Add a webdav unit test first, before changing
  10481. * anything here. */
  10482. mg_send_http_error(
  10483. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10484. return;
  10485. }
  10486. body_len = conn->data_len - conn->request_len;
  10487. if (body_len > 0) {
  10488. mg_send_http_error(
  10489. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10490. return;
  10491. }
  10492. rc = mg_mkdir(conn, path, 0755);
  10493. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10494. if (rc == 0) {
  10495. /* Create 201 "Created" response */
  10496. mg_response_header_start(conn, 201);
  10497. send_static_cache_header(conn);
  10498. send_additional_header(conn);
  10499. mg_response_header_add(conn, "Content-Length", "0", -1);
  10500. /* Send all headers - there is no body */
  10501. mg_response_header_send(conn);
  10502. } else {
  10503. int http_status = 500;
  10504. switch (errno) {
  10505. case EEXIST:
  10506. http_status = 405;
  10507. break;
  10508. case EACCES:
  10509. http_status = 403;
  10510. break;
  10511. case ENOENT:
  10512. http_status = 409;
  10513. break;
  10514. }
  10515. mg_send_http_error(conn,
  10516. http_status,
  10517. "Error processing %s: %s",
  10518. path,
  10519. strerror(ERRNO));
  10520. }
  10521. }
  10522. /* Forward decrlaration */
  10523. static int get_uri_type(const char *uri);
  10524. static const char *
  10525. get_rel_url_at_current_server(const char *uri,
  10526. const struct mg_connection *conn);
  10527. static void
  10528. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10529. {
  10530. const char *overwrite_hdr;
  10531. const char *destination_hdr;
  10532. const char *root;
  10533. int rc, dest_uri_type;
  10534. int http_status = 400;
  10535. int do_overwrite = 0;
  10536. int destination_ok = 0;
  10537. char dest_path[UTF8_PATH_MAX];
  10538. struct mg_file_stat ignored;
  10539. if (conn == NULL) {
  10540. return;
  10541. }
  10542. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10543. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10544. destination_hdr = mg_get_header(conn, "Destination");
  10545. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10546. do_overwrite = 1;
  10547. }
  10548. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10549. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10550. return;
  10551. }
  10552. if (root != NULL) {
  10553. char *local_dest = NULL;
  10554. dest_uri_type = get_uri_type(destination_hdr);
  10555. if (dest_uri_type == 2) {
  10556. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10557. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10558. const char *h =
  10559. get_rel_url_at_current_server(destination_hdr, conn);
  10560. if (h) {
  10561. size_t len = strlen(h);
  10562. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10563. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10564. }
  10565. }
  10566. if (local_dest != NULL) {
  10567. remove_dot_segments(local_dest);
  10568. if (local_dest[0] == '/') {
  10569. int trunc_check = 0;
  10570. mg_snprintf(conn,
  10571. &trunc_check,
  10572. dest_path,
  10573. sizeof(dest_path),
  10574. "%s/%s",
  10575. root,
  10576. local_dest);
  10577. if (trunc_check == 0) {
  10578. destination_ok = 1;
  10579. }
  10580. }
  10581. mg_free(local_dest);
  10582. }
  10583. }
  10584. if (!destination_ok) {
  10585. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10586. return;
  10587. }
  10588. /* Check now if this file exists */
  10589. if (mg_stat(conn, dest_path, &ignored)) {
  10590. /* File exists */
  10591. if (do_overwrite) {
  10592. /* Overwrite allowed: delete the file first */
  10593. if (0 != remove(dest_path)) {
  10594. /* No overwrite: return error */
  10595. mg_send_http_error(conn,
  10596. 403,
  10597. "Cannot overwrite file: %s",
  10598. dest_path);
  10599. return;
  10600. }
  10601. } else {
  10602. /* No overwrite: return error */
  10603. mg_send_http_error(conn,
  10604. 412,
  10605. "Destination already exists: %s",
  10606. dest_path);
  10607. return;
  10608. }
  10609. }
  10610. /* Copy / Move / Rename operation. */
  10611. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10612. #if defined(_WIN32)
  10613. {
  10614. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10615. wchar_t wSource[UTF16_PATH_MAX];
  10616. wchar_t wDest[UTF16_PATH_MAX];
  10617. BOOL ok;
  10618. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10619. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10620. if (do_copy) {
  10621. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10622. } else {
  10623. ok = MoveFileExW(wSource,
  10624. wDest,
  10625. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10626. }
  10627. if (ok) {
  10628. rc = 0;
  10629. } else {
  10630. DWORD lastErr = GetLastError();
  10631. if (lastErr == ERROR_ALREADY_EXISTS) {
  10632. mg_send_http_error(conn,
  10633. 412,
  10634. "Destination already exists: %s",
  10635. dest_path);
  10636. return;
  10637. }
  10638. rc = -1;
  10639. http_status = 400;
  10640. }
  10641. }
  10642. #else
  10643. {
  10644. /* Linux uses already UTF-8, we don't need to convert file names. */
  10645. if (do_copy) {
  10646. /* TODO: COPY for Linux. */
  10647. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10648. return;
  10649. }
  10650. rc = rename(path, dest_path);
  10651. if (rc) {
  10652. switch (errno) {
  10653. case EEXIST:
  10654. http_status = 412;
  10655. break;
  10656. case EACCES:
  10657. http_status = 403;
  10658. break;
  10659. case ENOENT:
  10660. http_status = 409;
  10661. break;
  10662. }
  10663. }
  10664. }
  10665. #endif
  10666. if (rc == 0) {
  10667. /* Create 204 "No Content" response */
  10668. mg_response_header_start(conn, 204);
  10669. mg_response_header_add(conn, "Content-Length", "0", -1);
  10670. /* Send all headers - there is no body */
  10671. mg_response_header_send(conn);
  10672. } else {
  10673. mg_send_http_error(conn, http_status, "Operation failed");
  10674. }
  10675. }
  10676. static void
  10677. put_file(struct mg_connection *conn, const char *path)
  10678. {
  10679. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10680. const char *range;
  10681. int64_t r1, r2;
  10682. int rc;
  10683. if (conn == NULL) {
  10684. return;
  10685. }
  10686. DEBUG_TRACE("store %s", path);
  10687. if (mg_stat(conn, path, &file.stat)) {
  10688. /* File already exists */
  10689. conn->status_code = 200;
  10690. if (file.stat.is_directory) {
  10691. /* This is an already existing directory,
  10692. * so there is nothing to do for the server. */
  10693. rc = 0;
  10694. } else {
  10695. /* File exists and is not a directory. */
  10696. /* Can it be replaced? */
  10697. /* Check if the server may write this file */
  10698. if (access(path, W_OK) == 0) {
  10699. /* Access granted */
  10700. rc = 1;
  10701. } else {
  10702. mg_send_http_error(
  10703. conn,
  10704. 403,
  10705. "Error: Put not possible\nReplacing %s is not allowed",
  10706. path);
  10707. return;
  10708. }
  10709. }
  10710. } else {
  10711. /* File should be created */
  10712. conn->status_code = 201;
  10713. rc = put_dir(conn, path);
  10714. }
  10715. if (rc == 0) {
  10716. /* put_dir returns 0 if path is a directory */
  10717. /* Create response */
  10718. mg_response_header_start(conn, conn->status_code);
  10719. send_no_cache_header(conn);
  10720. send_additional_header(conn);
  10721. mg_response_header_add(conn, "Content-Length", "0", -1);
  10722. /* Send all headers - there is no body */
  10723. mg_response_header_send(conn);
  10724. /* Request to create a directory has been fulfilled successfully.
  10725. * No need to put a file. */
  10726. return;
  10727. }
  10728. if (rc == -1) {
  10729. /* put_dir returns -1 if the path is too long */
  10730. mg_send_http_error(conn,
  10731. 414,
  10732. "Error: Path too long\nput_dir(%s): %s",
  10733. path,
  10734. strerror(ERRNO));
  10735. return;
  10736. }
  10737. if (rc == -2) {
  10738. /* put_dir returns -2 if the directory can not be created */
  10739. mg_send_http_error(conn,
  10740. 500,
  10741. "Error: Can not create directory\nput_dir(%s): %s",
  10742. path,
  10743. strerror(ERRNO));
  10744. return;
  10745. }
  10746. /* A file should be created or overwritten. */
  10747. /* Currently CivetWeb does not need read+write access. */
  10748. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10749. || file.access.fp == NULL) {
  10750. (void)mg_fclose(&file.access);
  10751. mg_send_http_error(conn,
  10752. 500,
  10753. "Error: Can not create file\nfopen(%s): %s",
  10754. path,
  10755. strerror(ERRNO));
  10756. return;
  10757. }
  10758. fclose_on_exec(&file.access, conn);
  10759. range = mg_get_header(conn, "Content-Range");
  10760. r1 = r2 = 0;
  10761. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10762. conn->status_code = 206; /* Partial content */
  10763. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10764. mg_send_http_error(conn,
  10765. 500,
  10766. "Error: Internal error processing file %s",
  10767. path);
  10768. return;
  10769. }
  10770. }
  10771. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10772. /* forward_body_data failed.
  10773. * The error code has already been sent to the client,
  10774. * and conn->status_code is already set. */
  10775. (void)mg_fclose(&file.access);
  10776. return;
  10777. }
  10778. if (mg_fclose(&file.access) != 0) {
  10779. /* fclose failed. This might have different reasons, but a likely
  10780. * one is "no space on disk", http 507. */
  10781. conn->status_code = 507;
  10782. }
  10783. /* Create response (status_code has been set before) */
  10784. mg_response_header_start(conn, conn->status_code);
  10785. send_no_cache_header(conn);
  10786. send_additional_header(conn);
  10787. mg_response_header_add(conn, "Content-Length", "0", -1);
  10788. /* Send all headers - there is no body */
  10789. mg_response_header_send(conn);
  10790. }
  10791. static void
  10792. delete_file(struct mg_connection *conn, const char *path)
  10793. {
  10794. struct de de;
  10795. memset(&de.file, 0, sizeof(de.file));
  10796. if (!mg_stat(conn, path, &de.file)) {
  10797. /* mg_stat returns 0 if the file does not exist */
  10798. mg_send_http_error(conn,
  10799. 404,
  10800. "Error: Cannot delete file\nFile %s not found",
  10801. path);
  10802. return;
  10803. }
  10804. DEBUG_TRACE("delete %s", path);
  10805. if (de.file.is_directory) {
  10806. if (remove_directory(conn, path)) {
  10807. /* Delete is successful: Return 204 without content. */
  10808. mg_send_http_error(conn, 204, "%s", "");
  10809. } else {
  10810. /* Delete is not successful: Return 500 (Server error). */
  10811. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10812. }
  10813. return;
  10814. }
  10815. /* This is an existing file (not a directory).
  10816. * Check if write permission is granted. */
  10817. if (access(path, W_OK) != 0) {
  10818. /* File is read only */
  10819. mg_send_http_error(
  10820. conn,
  10821. 403,
  10822. "Error: Delete not possible\nDeleting %s is not allowed",
  10823. path);
  10824. return;
  10825. }
  10826. /* Try to delete it. */
  10827. if (mg_remove(conn, path) == 0) {
  10828. /* Delete was successful: Return 204 without content. */
  10829. mg_response_header_start(conn, 204);
  10830. send_no_cache_header(conn);
  10831. send_additional_header(conn);
  10832. mg_response_header_add(conn, "Content-Length", "0", -1);
  10833. mg_response_header_send(conn);
  10834. } else {
  10835. /* Delete not successful (file locked). */
  10836. mg_send_http_error(conn,
  10837. 423,
  10838. "Error: Cannot delete file\nremove(%s): %s",
  10839. path,
  10840. strerror(ERRNO));
  10841. }
  10842. }
  10843. #endif /* !NO_FILES */
  10844. #if !defined(NO_FILESYSTEMS)
  10845. static void
  10846. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10847. static void
  10848. do_ssi_include(struct mg_connection *conn,
  10849. const char *ssi,
  10850. char *tag,
  10851. int include_level)
  10852. {
  10853. char file_name[MG_BUF_LEN], path[512], *p;
  10854. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10855. size_t len;
  10856. int truncated = 0;
  10857. if (conn == NULL) {
  10858. return;
  10859. }
  10860. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10861. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10862. * always < MG_BUF_LEN. */
  10863. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10864. /* File name is relative to the webserver root */
  10865. file_name[511] = 0;
  10866. (void)mg_snprintf(conn,
  10867. &truncated,
  10868. path,
  10869. sizeof(path),
  10870. "%s/%s",
  10871. conn->dom_ctx->config[DOCUMENT_ROOT],
  10872. file_name);
  10873. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10874. /* File name is relative to the webserver working directory
  10875. * or it is absolute system path */
  10876. file_name[511] = 0;
  10877. (void)
  10878. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10879. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10880. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10881. /* File name is relative to the current document */
  10882. file_name[511] = 0;
  10883. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10884. if (!truncated) {
  10885. if ((p = strrchr(path, '/')) != NULL) {
  10886. p[1] = '\0';
  10887. }
  10888. len = strlen(path);
  10889. (void)mg_snprintf(conn,
  10890. &truncated,
  10891. path + len,
  10892. sizeof(path) - len,
  10893. "%s",
  10894. file_name);
  10895. }
  10896. } else {
  10897. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10898. return;
  10899. }
  10900. if (truncated) {
  10901. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10902. return;
  10903. }
  10904. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10905. mg_cry_internal(conn,
  10906. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10907. tag,
  10908. path,
  10909. strerror(ERRNO));
  10910. } else {
  10911. fclose_on_exec(&file.access, conn);
  10912. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10913. > 0) {
  10914. send_ssi_file(conn, path, &file, include_level + 1);
  10915. } else {
  10916. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10917. }
  10918. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10919. }
  10920. }
  10921. #if !defined(NO_POPEN)
  10922. static void
  10923. do_ssi_exec(struct mg_connection *conn, char *tag)
  10924. {
  10925. char cmd[1024] = "";
  10926. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10927. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10928. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10929. } else {
  10930. cmd[1023] = 0;
  10931. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10932. mg_cry_internal(conn,
  10933. "Cannot SSI #exec: [%s]: %s",
  10934. cmd,
  10935. strerror(ERRNO));
  10936. } else {
  10937. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10938. pclose(file.access.fp);
  10939. }
  10940. }
  10941. }
  10942. #endif /* !NO_POPEN */
  10943. static int
  10944. mg_fgetc(struct mg_file *filep)
  10945. {
  10946. if (filep == NULL) {
  10947. return EOF;
  10948. }
  10949. if (filep->access.fp != NULL) {
  10950. return fgetc(filep->access.fp);
  10951. } else {
  10952. return EOF;
  10953. }
  10954. }
  10955. static void
  10956. send_ssi_file(struct mg_connection *conn,
  10957. const char *path,
  10958. struct mg_file *filep,
  10959. int include_level)
  10960. {
  10961. char buf[MG_BUF_LEN];
  10962. int ch, len, in_tag, in_ssi_tag;
  10963. if (include_level > 10) {
  10964. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10965. return;
  10966. }
  10967. in_tag = in_ssi_tag = len = 0;
  10968. /* Read file, byte by byte, and look for SSI include tags */
  10969. while ((ch = mg_fgetc(filep)) != EOF) {
  10970. if (in_tag) {
  10971. /* We are in a tag, either SSI tag or html tag */
  10972. if (ch == '>') {
  10973. /* Tag is closing */
  10974. buf[len++] = '>';
  10975. if (in_ssi_tag) {
  10976. /* Handle SSI tag */
  10977. buf[len] = 0;
  10978. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10979. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10980. #if !defined(NO_POPEN)
  10981. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10982. do_ssi_exec(conn, buf + 9);
  10983. #endif /* !NO_POPEN */
  10984. } else {
  10985. mg_cry_internal(conn,
  10986. "%s: unknown SSI "
  10987. "command: \"%s\"",
  10988. path,
  10989. buf);
  10990. }
  10991. len = 0;
  10992. in_ssi_tag = in_tag = 0;
  10993. } else {
  10994. /* Not an SSI tag */
  10995. /* Flush buffer */
  10996. (void)mg_write(conn, buf, (size_t)len);
  10997. len = 0;
  10998. in_tag = 0;
  10999. }
  11000. } else {
  11001. /* Tag is still open */
  11002. buf[len++] = (char)(ch & 0xff);
  11003. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  11004. /* All SSI tags start with <!--# */
  11005. in_ssi_tag = 1;
  11006. }
  11007. if ((len + 2) > (int)sizeof(buf)) {
  11008. /* Tag to long for buffer */
  11009. mg_cry_internal(conn, "%s: tag is too large", path);
  11010. return;
  11011. }
  11012. }
  11013. } else {
  11014. /* We are not in a tag yet. */
  11015. if (ch == '<') {
  11016. /* Tag is opening */
  11017. in_tag = 1;
  11018. if (len > 0) {
  11019. /* Flush current buffer.
  11020. * Buffer is filled with "len" bytes. */
  11021. (void)mg_write(conn, buf, (size_t)len);
  11022. }
  11023. /* Store the < */
  11024. len = 1;
  11025. buf[0] = '<';
  11026. } else {
  11027. /* No Tag */
  11028. /* Add data to buffer */
  11029. buf[len++] = (char)(ch & 0xff);
  11030. /* Flush if buffer is full */
  11031. if (len == (int)sizeof(buf)) {
  11032. mg_write(conn, buf, (size_t)len);
  11033. len = 0;
  11034. }
  11035. }
  11036. }
  11037. }
  11038. /* Send the rest of buffered data */
  11039. if (len > 0) {
  11040. mg_write(conn, buf, (size_t)len);
  11041. }
  11042. }
  11043. static void
  11044. handle_ssi_file_request(struct mg_connection *conn,
  11045. const char *path,
  11046. struct mg_file *filep)
  11047. {
  11048. char date[64];
  11049. time_t curtime = time(NULL);
  11050. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  11051. return;
  11052. }
  11053. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  11054. /* File exists (precondition for calling this function),
  11055. * but can not be opened by the server. */
  11056. mg_send_http_error(conn,
  11057. 500,
  11058. "Error: Cannot read file\nfopen(%s): %s",
  11059. path,
  11060. strerror(ERRNO));
  11061. } else {
  11062. /* Set "must_close" for HTTP/1.x, since we do not know the
  11063. * content length */
  11064. conn->must_close = 1;
  11065. gmt_time_string(date, sizeof(date), &curtime);
  11066. fclose_on_exec(&filep->access, conn);
  11067. /* 200 OK response */
  11068. mg_response_header_start(conn, 200);
  11069. send_no_cache_header(conn);
  11070. send_additional_header(conn);
  11071. send_cors_header(conn);
  11072. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11073. mg_response_header_send(conn);
  11074. /* Header sent, now send body */
  11075. send_ssi_file(conn, path, filep, 0);
  11076. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  11077. }
  11078. }
  11079. #endif /* NO_FILESYSTEMS */
  11080. #if !defined(NO_FILES)
  11081. static void
  11082. send_options(struct mg_connection *conn)
  11083. {
  11084. if (!conn || !all_methods) {
  11085. return;
  11086. }
  11087. /* We do not set a "Cache-Control" header here, but leave the default.
  11088. * Since browsers do not send an OPTIONS request, we can not test the
  11089. * effect anyway. */
  11090. mg_response_header_start(conn, 200);
  11091. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11092. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  11093. /* Use the same as before */
  11094. mg_response_header_add(conn, "Allow", all_methods, -1);
  11095. mg_response_header_add(conn, "DAV", "1", -1);
  11096. } else {
  11097. /* TODO: Check this later for HTTP/2 */
  11098. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  11099. }
  11100. send_additional_header(conn);
  11101. mg_response_header_send(conn);
  11102. }
  11103. /* Writes PROPFIND properties for a collection element */
  11104. static int
  11105. print_props(struct mg_connection *conn,
  11106. const char *uri,
  11107. const char *name,
  11108. struct mg_file_stat *filep)
  11109. {
  11110. size_t i;
  11111. char mtime[64];
  11112. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11113. char *link_concat;
  11114. size_t link_concat_len;
  11115. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  11116. return 0;
  11117. }
  11118. link_concat_len = strlen(uri) + strlen(name) + 1;
  11119. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  11120. if (!link_concat) {
  11121. return 0;
  11122. }
  11123. strcpy(link_concat, uri);
  11124. strcat(link_concat, name);
  11125. /* Get full link used in request */
  11126. mg_construct_local_link(
  11127. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  11128. /*
  11129. OutputDebugStringA("print_props:\n uri: ");
  11130. OutputDebugStringA(uri);
  11131. OutputDebugStringA("\n name: ");
  11132. OutputDebugStringA(name);
  11133. OutputDebugStringA("\n link: ");
  11134. OutputDebugStringA(link_buf);
  11135. OutputDebugStringA("\n");
  11136. */
  11137. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  11138. mg_printf(conn,
  11139. "<d:response>"
  11140. "<d:href>%s</d:href>"
  11141. "<d:propstat>"
  11142. "<d:prop>"
  11143. "<d:resourcetype>%s</d:resourcetype>"
  11144. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  11145. "<d:getlastmodified>%s</d:getlastmodified>"
  11146. "<d:lockdiscovery>",
  11147. link_buf,
  11148. filep->is_directory ? "<d:collection/>" : "",
  11149. filep->size,
  11150. mtime);
  11151. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11152. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11153. if (!strcmp(dav_lock[i].path, link_buf)) {
  11154. mg_printf(conn,
  11155. "<d:activelock>"
  11156. "<d:locktype><d:write/></d:locktype>"
  11157. "<d:lockscope><d:exclusive/></d:lockscope>"
  11158. "<d:depth>0</d:depth>"
  11159. "<d:owner>%s</d:owner>"
  11160. "<d:timeout>Second-%u</d:timeout>"
  11161. "<d:locktoken>"
  11162. "<d:href>%s</d:href>"
  11163. "</d:locktoken>"
  11164. "</d:activelock>\n",
  11165. dav_lock[i].user,
  11166. (unsigned)LOCK_DURATION_S,
  11167. dav_lock[i].token);
  11168. }
  11169. }
  11170. mg_printf(conn,
  11171. "</d:lockdiscovery>"
  11172. "</d:prop>"
  11173. "<d:status>HTTP/1.1 200 OK</d:status>"
  11174. "</d:propstat>"
  11175. "</d:response>\n");
  11176. mg_free(link_concat);
  11177. return 1;
  11178. }
  11179. static int
  11180. print_dav_dir_entry(struct de *de, void *data)
  11181. {
  11182. struct mg_connection *conn = (struct mg_connection *)data;
  11183. if (!de || !conn
  11184. || !print_props(
  11185. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  11186. /* stop scan */
  11187. return 1;
  11188. }
  11189. return 0;
  11190. }
  11191. static void
  11192. handle_propfind(struct mg_connection *conn,
  11193. const char *path,
  11194. struct mg_file_stat *filep)
  11195. {
  11196. const char *depth = mg_get_header(conn, "Depth");
  11197. if (!conn || !path || !filep || !conn->dom_ctx) {
  11198. return;
  11199. }
  11200. /* return 207 "Multi-Status" */
  11201. conn->must_close = 1;
  11202. mg_response_header_start(conn, 207);
  11203. send_static_cache_header(conn);
  11204. send_additional_header(conn);
  11205. mg_response_header_add(conn,
  11206. "Content-Type",
  11207. "application/xml; charset=utf-8",
  11208. -1);
  11209. mg_response_header_send(conn);
  11210. /* Content */
  11211. mg_printf(conn,
  11212. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11213. "<d:multistatus xmlns:d='DAV:'>\n");
  11214. /* Print properties for the requested resource itself */
  11215. print_props(conn, conn->request_info.local_uri, "", filep);
  11216. /* If it is a directory, print directory entries too if Depth is not 0
  11217. */
  11218. if (filep->is_directory
  11219. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11220. "yes")
  11221. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11222. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11223. }
  11224. mg_printf(conn, "%s\n", "</d:multistatus>");
  11225. }
  11226. static void
  11227. dav_lock_file(struct mg_connection *conn, const char *path)
  11228. {
  11229. /* internal function - therefore conn is assumed to be valid */
  11230. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11231. uint64_t new_locktime;
  11232. int lock_index = -1;
  11233. int i;
  11234. uint64_t LOCK_DURATION_NS =
  11235. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11236. struct twebdav_lock *dav_lock = NULL;
  11237. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11238. || !conn->phys_ctx) {
  11239. return;
  11240. }
  11241. dav_lock = conn->phys_ctx->webdav_lock;
  11242. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11243. /* const char *refresh = mg_get_header(conn, "If"); */
  11244. /* Link refresh should have an "If" header:
  11245. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11246. * But it seems Windows Explorer does not send them.
  11247. */
  11248. mg_lock_context(conn->phys_ctx);
  11249. new_locktime = mg_get_current_time_ns();
  11250. /* Find a slot for a lock */
  11251. while (lock_index < 0) {
  11252. /* find existing lock */
  11253. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11254. if (!strcmp(dav_lock[i].path, link_buf)) {
  11255. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11256. /* locked by the same user */
  11257. dav_lock[i].locktime = new_locktime;
  11258. lock_index = i;
  11259. break;
  11260. } else {
  11261. /* already locked by someone else */
  11262. if (new_locktime
  11263. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11264. /* Lock expired */
  11265. dav_lock[i].path[0] = 0;
  11266. } else {
  11267. /* Lock still valid */
  11268. mg_unlock_context(conn->phys_ctx);
  11269. mg_send_http_error(conn, 423, "%s", "Already locked");
  11270. return;
  11271. }
  11272. }
  11273. }
  11274. }
  11275. /* create new lock token */
  11276. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11277. if (dav_lock[i].path[0] == 0) {
  11278. char s[32];
  11279. dav_lock[i].locktime = mg_get_current_time_ns();
  11280. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11281. mg_md5(dav_lock[i].token,
  11282. link_buf,
  11283. "\x01",
  11284. s,
  11285. "\x01",
  11286. conn->request_info.remote_user,
  11287. NULL);
  11288. mg_strlcpy(dav_lock[i].path,
  11289. link_buf,
  11290. sizeof(dav_lock[i].path));
  11291. mg_strlcpy(dav_lock[i].user,
  11292. conn->request_info.remote_user,
  11293. sizeof(dav_lock[i].user));
  11294. lock_index = i;
  11295. break;
  11296. }
  11297. }
  11298. if (lock_index < 0) {
  11299. /* too many locks. Find oldest lock */
  11300. uint64_t oldest_locktime = dav_lock[0].locktime;
  11301. lock_index = 0;
  11302. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11303. if (dav_lock[i].locktime < oldest_locktime) {
  11304. oldest_locktime = dav_lock[i].locktime;
  11305. lock_index = i;
  11306. }
  11307. }
  11308. /* invalidate oldest lock */
  11309. dav_lock[lock_index].path[0] = 0;
  11310. }
  11311. }
  11312. mg_unlock_context(conn->phys_ctx);
  11313. /* return 200 "OK" */
  11314. conn->must_close = 1;
  11315. mg_response_header_start(conn, 200);
  11316. send_static_cache_header(conn);
  11317. send_additional_header(conn);
  11318. mg_response_header_add(conn,
  11319. "Content-Type",
  11320. "application/xml; charset=utf-8",
  11321. -1);
  11322. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11323. mg_response_header_send(conn);
  11324. /* Content */
  11325. mg_printf(conn,
  11326. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11327. "<d:prop xmlns:d=\"DAV:\">\n"
  11328. " <d:lockdiscovery>\n"
  11329. " <d:activelock>\n"
  11330. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11331. " <d:locktype><d:write/></d:locktype>\n"
  11332. " <d:owner>\n"
  11333. " <d:href>%s</d:href>\n"
  11334. " </d:owner>\n"
  11335. " <d:timeout>Second-%u</d:timeout>\n"
  11336. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11337. " <d:lockroot>\n"
  11338. " <d:href>%s</d:href>\n"
  11339. " </d:lockroot>\n"
  11340. " </d:activelock>\n"
  11341. " </d:lockdiscovery>\n"
  11342. " </d:prop>\n",
  11343. dav_lock[lock_index].user,
  11344. (LOCK_DURATION_S),
  11345. dav_lock[lock_index].token,
  11346. dav_lock[lock_index].path);
  11347. }
  11348. static void
  11349. dav_unlock_file(struct mg_connection *conn, const char *path)
  11350. {
  11351. /* internal function - therefore conn is assumed to be valid */
  11352. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11353. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11354. int lock_index;
  11355. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11356. return;
  11357. }
  11358. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11359. mg_lock_context(conn->phys_ctx);
  11360. /* find existing lock */
  11361. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11362. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11363. /* Success: return 204 "No Content" */
  11364. mg_unlock_context(conn->phys_ctx);
  11365. conn->must_close = 1;
  11366. mg_response_header_start(conn, 204);
  11367. mg_response_header_send(conn);
  11368. return;
  11369. }
  11370. }
  11371. mg_unlock_context(conn->phys_ctx);
  11372. /* Error: Cannot unlock a resource that is not locked */
  11373. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11374. }
  11375. static void
  11376. dav_proppatch(struct mg_connection *conn, const char *path)
  11377. {
  11378. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11379. if (!conn || !path || !conn->dom_ctx) {
  11380. return;
  11381. }
  11382. /* return 207 "Multi-Status" */
  11383. conn->must_close = 1;
  11384. mg_response_header_start(conn, 207);
  11385. send_static_cache_header(conn);
  11386. send_additional_header(conn);
  11387. mg_response_header_add(conn,
  11388. "Content-Type",
  11389. "application/xml; charset=utf-8",
  11390. -1);
  11391. mg_response_header_send(conn);
  11392. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11393. /* Content */
  11394. mg_printf(conn,
  11395. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11396. "<d:multistatus xmlns:d='DAV:'>\n"
  11397. "<d:response>\n<d:href>%s</d:href>\n",
  11398. link_buf);
  11399. mg_printf(conn,
  11400. "<d:propstat><d:status>HTTP/1.1 403 "
  11401. "Forbidden</d:status></d:propstat>\n");
  11402. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11403. }
  11404. #endif
  11405. CIVETWEB_API void
  11406. mg_lock_connection(struct mg_connection *conn)
  11407. {
  11408. if (conn) {
  11409. (void)pthread_mutex_lock(&conn->mutex);
  11410. }
  11411. }
  11412. CIVETWEB_API void
  11413. mg_unlock_connection(struct mg_connection *conn)
  11414. {
  11415. if (conn) {
  11416. (void)pthread_mutex_unlock(&conn->mutex);
  11417. }
  11418. }
  11419. CIVETWEB_API void
  11420. mg_lock_context(struct mg_context *ctx)
  11421. {
  11422. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11423. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11424. }
  11425. }
  11426. CIVETWEB_API void
  11427. mg_unlock_context(struct mg_context *ctx)
  11428. {
  11429. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11430. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11431. }
  11432. }
  11433. #if defined(USE_LUA)
  11434. #include "mod_lua.inl"
  11435. #endif /* USE_LUA */
  11436. #if defined(USE_DUKTAPE)
  11437. #include "mod_duktape.inl"
  11438. #endif /* USE_DUKTAPE */
  11439. #if defined(USE_WEBSOCKET)
  11440. #if !defined(NO_SSL_DL)
  11441. #if !defined(OPENSSL_API_3_0)
  11442. #define SHA_API static
  11443. #include "sha1.inl"
  11444. #endif
  11445. #endif
  11446. static int
  11447. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11448. {
  11449. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11450. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11451. size_t dst_len = sizeof(b64_sha);
  11452. #if !defined(OPENSSL_API_3_0)
  11453. SHA_CTX sha_ctx;
  11454. #endif
  11455. int truncated;
  11456. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11457. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11458. if (truncated) {
  11459. conn->must_close = 1;
  11460. return 0;
  11461. }
  11462. DEBUG_TRACE("%s", "Send websocket handshake");
  11463. #if defined(OPENSSL_API_3_0)
  11464. EVP_Digest((unsigned char *)buf,
  11465. (uint32_t)strlen(buf),
  11466. (unsigned char *)sha,
  11467. NULL,
  11468. EVP_get_digestbyname("sha1"),
  11469. NULL);
  11470. #else
  11471. SHA1_Init(&sha_ctx);
  11472. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11473. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11474. #endif
  11475. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11476. mg_printf(conn,
  11477. "HTTP/1.1 101 Switching Protocols\r\n"
  11478. "Upgrade: websocket\r\n"
  11479. "Connection: Upgrade\r\n"
  11480. "Sec-WebSocket-Accept: %s\r\n",
  11481. b64_sha);
  11482. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11483. // Send negotiated compression extension parameters
  11484. websocket_deflate_response(conn);
  11485. #endif
  11486. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11487. mg_printf(conn,
  11488. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11489. conn->request_info.acceptedWebSocketSubprotocol);
  11490. } else {
  11491. mg_printf(conn, "%s", "\r\n");
  11492. }
  11493. return 1;
  11494. }
  11495. #if !defined(MG_MAX_UNANSWERED_PING)
  11496. /* Configuration of the maximum number of websocket PINGs that might
  11497. * stay unanswered before the connection is considered broken.
  11498. * Note: The name of this define may still change (until it is
  11499. * defined as a compile parameter in a documentation).
  11500. */
  11501. #define MG_MAX_UNANSWERED_PING (5)
  11502. #endif
  11503. static void
  11504. read_websocket(struct mg_connection *conn,
  11505. mg_websocket_data_handler ws_data_handler,
  11506. void *callback_data)
  11507. {
  11508. /* Pointer to the beginning of the portion of the incoming websocket
  11509. * message queue.
  11510. * The original websocket upgrade request is never removed, so the queue
  11511. * begins after it. */
  11512. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11513. int n, error, exit_by_callback;
  11514. int ret;
  11515. /* body_len is the length of the entire queue in bytes
  11516. * len is the length of the current message
  11517. * data_len is the length of the current message's data payload
  11518. * header_len is the length of the current message's header */
  11519. size_t i, len, mask_len = 0, header_len, body_len;
  11520. uint64_t data_len = 0;
  11521. /* "The masking key is a 32-bit value chosen at random by the client."
  11522. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11523. */
  11524. unsigned char mask[4];
  11525. /* data points to the place where the message is stored when passed to
  11526. * the websocket_data callback. This is either mem on the stack, or a
  11527. * dynamically allocated buffer if it is too large. */
  11528. unsigned char mem[4096];
  11529. unsigned char mop; /* mask flag and opcode */
  11530. /* Variables used for connection monitoring */
  11531. double timeout = -1.0;
  11532. int enable_ping_pong = 0;
  11533. int ping_count = 0;
  11534. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11535. enable_ping_pong =
  11536. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11537. "yes");
  11538. }
  11539. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11540. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11541. }
  11542. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11543. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11544. }
  11545. if (timeout <= 0.0) {
  11546. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11547. }
  11548. /* Enter data processing loop */
  11549. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11550. conn->request_info.remote_addr,
  11551. conn->request_info.remote_port);
  11552. conn->in_websocket_handling = 1;
  11553. mg_set_thread_name("wsock");
  11554. /* Loop continuously, reading messages from the socket, invoking the
  11555. * callback, and waiting repeatedly until an error occurs. */
  11556. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11557. && (!conn->must_close)) {
  11558. header_len = 0;
  11559. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11560. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11561. len = buf[1] & 127;
  11562. mask_len = (buf[1] & 128) ? 4 : 0;
  11563. if ((len < 126) && (body_len >= mask_len)) {
  11564. /* inline 7-bit length field */
  11565. data_len = len;
  11566. header_len = 2 + mask_len;
  11567. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11568. /* 16-bit length field */
  11569. header_len = 4 + mask_len;
  11570. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11571. } else if (body_len >= (10 + mask_len)) {
  11572. /* 64-bit length field */
  11573. uint32_t l1, l2;
  11574. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11575. memcpy(&l2, &buf[6], 4);
  11576. header_len = 10 + mask_len;
  11577. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11578. if (data_len > (uint64_t)0x7FFF0000ul) {
  11579. /* no can do */
  11580. mg_cry_internal(
  11581. conn,
  11582. "%s",
  11583. "websocket out of memory; closing connection");
  11584. break;
  11585. }
  11586. }
  11587. }
  11588. if ((header_len > 0) && (body_len >= header_len)) {
  11589. /* Allocate space to hold websocket payload */
  11590. unsigned char *data = mem;
  11591. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11592. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11593. conn->phys_ctx);
  11594. if (data == NULL) {
  11595. /* Allocation failed, exit the loop and then close the
  11596. * connection */
  11597. mg_cry_internal(
  11598. conn,
  11599. "%s",
  11600. "websocket out of memory; closing connection");
  11601. break;
  11602. }
  11603. }
  11604. /* Copy the mask before we shift the queue and destroy it */
  11605. if (mask_len > 0) {
  11606. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11607. } else {
  11608. memset(mask, 0, sizeof(mask));
  11609. }
  11610. /* Read frame payload from the first message in the queue into
  11611. * data and advance the queue by moving the memory in place. */
  11612. DEBUG_ASSERT(body_len >= header_len);
  11613. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11614. mop = buf[0]; /* current mask and opcode */
  11615. /* Overflow case */
  11616. len = body_len - header_len;
  11617. memcpy(data, buf + header_len, len);
  11618. error = 0;
  11619. while ((uint64_t)len < data_len) {
  11620. n = pull_inner(NULL,
  11621. conn,
  11622. (char *)(data + len),
  11623. (int)(data_len - len),
  11624. timeout);
  11625. if (n <= -2) {
  11626. error = 1;
  11627. break;
  11628. } else if (n > 0) {
  11629. len += (size_t)n;
  11630. } else {
  11631. /* Timeout: should retry */
  11632. /* TODO: retry condition */
  11633. }
  11634. }
  11635. if (error) {
  11636. mg_cry_internal(
  11637. conn,
  11638. "%s",
  11639. "Websocket pull failed; closing connection");
  11640. if (data != mem) {
  11641. mg_free(data);
  11642. }
  11643. break;
  11644. }
  11645. conn->data_len = conn->request_len;
  11646. } else {
  11647. mop = buf[0]; /* current mask and opcode, overwritten by
  11648. * memmove() */
  11649. /* Length of the message being read at the front of the
  11650. * queue. Cast to 31 bit is OK, since we limited
  11651. * data_len before. */
  11652. len = (size_t)data_len + header_len;
  11653. /* Copy the data payload into the data pointer for the
  11654. * callback. Cast to 31 bit is OK, since we
  11655. * limited data_len */
  11656. memcpy(data, buf + header_len, (size_t)data_len);
  11657. /* Move the queue forward len bytes */
  11658. memmove(buf, buf + len, body_len - len);
  11659. /* Mark the queue as advanced */
  11660. conn->data_len -= (int)len;
  11661. }
  11662. /* Apply mask if necessary */
  11663. if (mask_len > 0) {
  11664. for (i = 0; i < (size_t)data_len; i++) {
  11665. data[i] ^= mask[i & 3];
  11666. }
  11667. }
  11668. exit_by_callback = 0;
  11669. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11670. /* filter PONG messages */
  11671. DEBUG_TRACE("PONG from %s:%u",
  11672. conn->request_info.remote_addr,
  11673. conn->request_info.remote_port);
  11674. /* No unanwered PINGs left */
  11675. ping_count = 0;
  11676. } else if (enable_ping_pong
  11677. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11678. /* reply PING messages */
  11679. DEBUG_TRACE("Reply PING from %s:%u",
  11680. conn->request_info.remote_addr,
  11681. conn->request_info.remote_port);
  11682. ret = mg_websocket_write(conn,
  11683. MG_WEBSOCKET_OPCODE_PONG,
  11684. (char *)data,
  11685. (size_t)data_len);
  11686. if (ret <= 0) {
  11687. /* Error: send failed */
  11688. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11689. break;
  11690. }
  11691. } else {
  11692. /* Exit the loop if callback signals to exit (server side),
  11693. * or "connection close" opcode received (client side). */
  11694. if (ws_data_handler != NULL) {
  11695. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11696. if (mop & 0x40) {
  11697. /* Inflate the data received if bit RSV1 is set. */
  11698. if (!conn->websocket_deflate_initialized) {
  11699. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11700. exit_by_callback = 1;
  11701. }
  11702. if (!exit_by_callback) {
  11703. size_t inflate_buf_size_old = 0;
  11704. size_t inflate_buf_size =
  11705. data_len
  11706. * 4; // Initial guess of the inflated message
  11707. // size. We double the memory when needed.
  11708. Bytef *inflated = NULL;
  11709. Bytef *new_mem = NULL;
  11710. conn->websocket_inflate_state.avail_in =
  11711. (uInt)(data_len + 4);
  11712. conn->websocket_inflate_state.next_in = data;
  11713. // Add trailing 0x00 0x00 0xff 0xff bytes
  11714. data[data_len] = '\x00';
  11715. data[data_len + 1] = '\x00';
  11716. data[data_len + 2] = '\xff';
  11717. data[data_len + 3] = '\xff';
  11718. do {
  11719. if (inflate_buf_size_old == 0) {
  11720. new_mem =
  11721. (Bytef *)mg_calloc(inflate_buf_size,
  11722. sizeof(Bytef));
  11723. } else {
  11724. inflate_buf_size *= 2;
  11725. new_mem =
  11726. (Bytef *)mg_realloc(inflated,
  11727. inflate_buf_size);
  11728. }
  11729. if (new_mem == NULL) {
  11730. mg_cry_internal(
  11731. conn,
  11732. "Out of memory: Cannot allocate "
  11733. "inflate buffer of %lu bytes",
  11734. (unsigned long)inflate_buf_size);
  11735. exit_by_callback = 1;
  11736. break;
  11737. }
  11738. inflated = new_mem;
  11739. conn->websocket_inflate_state.avail_out =
  11740. (uInt)(inflate_buf_size
  11741. - inflate_buf_size_old);
  11742. conn->websocket_inflate_state.next_out =
  11743. inflated + inflate_buf_size_old;
  11744. ret = inflate(&conn->websocket_inflate_state,
  11745. Z_SYNC_FLUSH);
  11746. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11747. || ret == Z_MEM_ERROR) {
  11748. mg_cry_internal(
  11749. conn,
  11750. "ZLIB inflate error: %i %s",
  11751. ret,
  11752. (conn->websocket_inflate_state.msg
  11753. ? conn->websocket_inflate_state.msg
  11754. : "<no error message>"));
  11755. exit_by_callback = 1;
  11756. break;
  11757. }
  11758. inflate_buf_size_old = inflate_buf_size;
  11759. } while (conn->websocket_inflate_state.avail_out
  11760. == 0);
  11761. inflate_buf_size -=
  11762. conn->websocket_inflate_state.avail_out;
  11763. if (!ws_data_handler(conn,
  11764. mop,
  11765. (char *)inflated,
  11766. inflate_buf_size,
  11767. callback_data)) {
  11768. exit_by_callback = 1;
  11769. }
  11770. mg_free(inflated);
  11771. }
  11772. } else
  11773. #endif
  11774. if (!ws_data_handler(conn,
  11775. mop,
  11776. (char *)data,
  11777. (size_t)data_len,
  11778. callback_data)) {
  11779. exit_by_callback = 1;
  11780. }
  11781. }
  11782. }
  11783. /* It a buffer has been allocated, free it again */
  11784. if (data != mem) {
  11785. mg_free(data);
  11786. }
  11787. if (exit_by_callback) {
  11788. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11789. conn->request_info.remote_addr,
  11790. conn->request_info.remote_port);
  11791. break;
  11792. }
  11793. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11794. /* Opcode == 8, connection close */
  11795. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11796. conn->request_info.remote_addr,
  11797. conn->request_info.remote_port);
  11798. break;
  11799. }
  11800. /* Not breaking the loop, process next websocket frame. */
  11801. } else {
  11802. /* Read from the socket into the next available location in the
  11803. * message queue. */
  11804. n = pull_inner(NULL,
  11805. conn,
  11806. conn->buf + conn->data_len,
  11807. conn->buf_size - conn->data_len,
  11808. timeout);
  11809. if (n <= -2) {
  11810. /* Error, no bytes read */
  11811. DEBUG_TRACE("PULL from %s:%u failed",
  11812. conn->request_info.remote_addr,
  11813. conn->request_info.remote_port);
  11814. break;
  11815. }
  11816. if (n > 0) {
  11817. conn->data_len += n;
  11818. /* Reset open PING count */
  11819. ping_count = 0;
  11820. } else {
  11821. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11822. && (!conn->must_close)) {
  11823. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11824. /* Stop sending PING */
  11825. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11826. "- closing connection",
  11827. ping_count,
  11828. conn->request_info.remote_addr,
  11829. conn->request_info.remote_port);
  11830. break;
  11831. }
  11832. if (enable_ping_pong) {
  11833. /* Send Websocket PING message */
  11834. DEBUG_TRACE("PING to %s:%u",
  11835. conn->request_info.remote_addr,
  11836. conn->request_info.remote_port);
  11837. ret = mg_websocket_write(conn,
  11838. MG_WEBSOCKET_OPCODE_PING,
  11839. NULL,
  11840. 0);
  11841. if (ret <= 0) {
  11842. /* Error: send failed */
  11843. DEBUG_TRACE("Send PING failed (%i)", ret);
  11844. break;
  11845. }
  11846. ping_count++;
  11847. }
  11848. }
  11849. /* Timeout: should retry */
  11850. /* TODO: get timeout def */
  11851. }
  11852. }
  11853. }
  11854. /* Leave data processing loop */
  11855. mg_set_thread_name("worker");
  11856. conn->in_websocket_handling = 0;
  11857. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11858. conn->request_info.remote_addr,
  11859. conn->request_info.remote_port);
  11860. }
  11861. static int
  11862. mg_websocket_write_exec(struct mg_connection *conn,
  11863. int opcode,
  11864. const char *data,
  11865. size_t dataLen,
  11866. uint32_t masking_key)
  11867. {
  11868. unsigned char header[14];
  11869. size_t headerLen;
  11870. int retval;
  11871. #if defined(GCC_DIAGNOSTIC)
  11872. /* Disable spurious conversion warning for GCC */
  11873. #pragma GCC diagnostic push
  11874. #pragma GCC diagnostic ignored "-Wconversion"
  11875. #endif
  11876. /* Note that POSIX/Winsock's send() is threadsafe
  11877. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11878. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11879. * push(), although that is only a problem if the packet is large or
  11880. * outgoing buffer is full). */
  11881. /* TODO: Check if this lock should be moved to user land.
  11882. * Currently the server sets this lock for websockets, but
  11883. * not for any other connection. It must be set for every
  11884. * conn read/written by more than one thread, no matter if
  11885. * it is a websocket or regular connection. */
  11886. (void)mg_lock_connection(conn);
  11887. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11888. size_t deflated_size = 0;
  11889. Bytef *deflated = 0;
  11890. // Deflate websocket messages over 100kb
  11891. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11892. if (use_deflate) {
  11893. if (!conn->websocket_deflate_initialized) {
  11894. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11895. return 0;
  11896. }
  11897. // Deflating the message
  11898. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11899. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11900. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11901. deflated_size = (size_t)compressBound((uLong)dataLen);
  11902. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11903. if (deflated == NULL) {
  11904. mg_cry_internal(
  11905. conn,
  11906. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11907. (unsigned long)deflated_size);
  11908. mg_unlock_connection(conn);
  11909. return -1;
  11910. }
  11911. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11912. conn->websocket_deflate_state.next_out = deflated;
  11913. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11914. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11915. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11916. } else
  11917. #endif
  11918. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11919. #if defined(GCC_DIAGNOSTIC)
  11920. #pragma GCC diagnostic pop
  11921. #endif
  11922. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11923. if (dataLen < 126) {
  11924. /* inline 7-bit length field */
  11925. header[1] = (unsigned char)dataLen;
  11926. headerLen = 2;
  11927. } else if (dataLen <= 0xFFFF) {
  11928. /* 16-bit length field */
  11929. uint16_t len = htons((uint16_t)dataLen);
  11930. header[1] = 126;
  11931. memcpy(header + 2, &len, 2);
  11932. headerLen = 4;
  11933. } else {
  11934. /* 64-bit length field */
  11935. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11936. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11937. header[1] = 127;
  11938. memcpy(header + 2, &len1, 4);
  11939. memcpy(header + 6, &len2, 4);
  11940. headerLen = 10;
  11941. }
  11942. if (masking_key) {
  11943. /* add mask */
  11944. header[1] |= 0x80;
  11945. memcpy(header + headerLen, &masking_key, 4);
  11946. headerLen += 4;
  11947. }
  11948. retval = mg_write(conn, header, headerLen);
  11949. if (retval != (int)headerLen) {
  11950. /* Did not send complete header */
  11951. retval = -1;
  11952. } else {
  11953. if (dataLen > 0) {
  11954. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11955. if (use_deflate) {
  11956. retval = mg_write(conn, deflated, dataLen);
  11957. mg_free(deflated);
  11958. } else
  11959. #endif
  11960. retval = mg_write(conn, data, dataLen);
  11961. }
  11962. /* if dataLen == 0, the header length (2) is returned */
  11963. }
  11964. /* TODO: Remove this unlock as well, when lock is removed. */
  11965. mg_unlock_connection(conn);
  11966. return retval;
  11967. }
  11968. CIVETWEB_API int
  11969. mg_websocket_write(struct mg_connection *conn,
  11970. int opcode,
  11971. const char *data,
  11972. size_t dataLen)
  11973. {
  11974. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11975. }
  11976. static void
  11977. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11978. {
  11979. size_t i = 0;
  11980. i = 0;
  11981. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11982. /* Convert in 32 bit words, if data is 4 byte aligned */
  11983. while (i < (in_len - 3)) {
  11984. *(uint32_t *)(void *)(out + i) =
  11985. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11986. i += 4;
  11987. }
  11988. }
  11989. if (i != in_len) {
  11990. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11991. while (i < in_len) {
  11992. *(uint8_t *)(void *)(out + i) =
  11993. *(uint8_t *)(void *)(in + i)
  11994. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11995. i++;
  11996. }
  11997. }
  11998. }
  11999. CIVETWEB_API int
  12000. mg_websocket_client_write(struct mg_connection *conn,
  12001. int opcode,
  12002. const char *data,
  12003. size_t dataLen)
  12004. {
  12005. int retval = -1;
  12006. char *masked_data =
  12007. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  12008. uint32_t masking_key = 0;
  12009. if (masked_data == NULL) {
  12010. /* Return -1 in an error case */
  12011. mg_cry_internal(conn,
  12012. "%s",
  12013. "Cannot allocate buffer for masked websocket response: "
  12014. "Out of memory");
  12015. return -1;
  12016. }
  12017. do {
  12018. /* Get a masking key - but not 0 */
  12019. masking_key = (uint32_t)get_random();
  12020. } while (masking_key == 0);
  12021. mask_data(data, dataLen, masking_key, masked_data);
  12022. retval = mg_websocket_write_exec(
  12023. conn, opcode, masked_data, dataLen, masking_key);
  12024. mg_free(masked_data);
  12025. return retval;
  12026. }
  12027. static void
  12028. handle_websocket_request(struct mg_connection *conn,
  12029. const char *path,
  12030. int is_callback_resource,
  12031. struct mg_websocket_subprotocols *subprotocols,
  12032. mg_websocket_connect_handler ws_connect_handler,
  12033. mg_websocket_ready_handler ws_ready_handler,
  12034. mg_websocket_data_handler ws_data_handler,
  12035. mg_websocket_close_handler ws_close_handler,
  12036. void *cbData)
  12037. {
  12038. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  12039. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  12040. ptrdiff_t lua_websock = 0;
  12041. #if !defined(USE_LUA)
  12042. (void)path;
  12043. #endif
  12044. /* Step 1: Check websocket protocol version. */
  12045. /* Step 1.1: Check Sec-WebSocket-Key. */
  12046. if (!websock_key) {
  12047. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  12048. * requires a Sec-WebSocket-Key header.
  12049. */
  12050. /* It could be the hixie draft version
  12051. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  12052. */
  12053. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  12054. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  12055. char key3[8];
  12056. if ((key1 != NULL) && (key2 != NULL)) {
  12057. /* This version uses 8 byte body data in a GET request */
  12058. conn->content_len = 8;
  12059. if (8 == mg_read(conn, key3, 8)) {
  12060. /* This is the hixie version */
  12061. mg_send_http_error(conn,
  12062. 426,
  12063. "%s",
  12064. "Protocol upgrade to RFC 6455 required");
  12065. return;
  12066. }
  12067. }
  12068. /* This is an unknown version */
  12069. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  12070. return;
  12071. }
  12072. /* Step 1.2: Check websocket protocol version. */
  12073. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  12074. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  12075. /* Reject wrong versions */
  12076. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  12077. return;
  12078. }
  12079. /* Step 1.3: Could check for "Host", but we do not really need this
  12080. * value for anything, so just ignore it. */
  12081. /* Step 2: If a callback is responsible, call it. */
  12082. if (is_callback_resource) {
  12083. /* Step 2.1 check and select subprotocol */
  12084. const char *protocols[64]; // max 64 headers
  12085. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  12086. "Sec-WebSocket-Protocol",
  12087. protocols,
  12088. 64);
  12089. if ((nbSubprotocolHeader > 0) && subprotocols) {
  12090. int headerNo, idx;
  12091. size_t len;
  12092. const char *sep, *curSubProtocol,
  12093. *acceptedWebSocketSubprotocol = NULL;
  12094. /* look for matching subprotocol */
  12095. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  12096. /* There might be multiple headers ... */
  12097. const char *protocol = protocols[headerNo];
  12098. curSubProtocol = protocol;
  12099. /* ... and in every header there might be a , separated list */
  12100. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  12101. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  12102. curSubProtocol++;
  12103. sep = strchr(curSubProtocol, ',');
  12104. if (sep) {
  12105. len = (size_t)(sep - curSubProtocol);
  12106. } else {
  12107. len = strlen(curSubProtocol);
  12108. }
  12109. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  12110. // COMPARE: curSubProtocol ==
  12111. // subprotocols->subprotocols[idx]
  12112. if ((strlen(subprotocols->subprotocols[idx]) == len)
  12113. && (strncmp(curSubProtocol,
  12114. subprotocols->subprotocols[idx],
  12115. len)
  12116. == 0)) {
  12117. acceptedWebSocketSubprotocol =
  12118. subprotocols->subprotocols[idx];
  12119. break;
  12120. }
  12121. }
  12122. curSubProtocol += len;
  12123. }
  12124. }
  12125. conn->request_info.acceptedWebSocketSubprotocol =
  12126. acceptedWebSocketSubprotocol;
  12127. }
  12128. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12129. websocket_deflate_negotiate(conn);
  12130. #endif
  12131. if ((ws_connect_handler != NULL)
  12132. && (ws_connect_handler(conn, cbData) != 0)) {
  12133. /* C callback has returned non-zero, do not proceed with
  12134. * handshake.
  12135. */
  12136. /* Note that C callbacks are no longer called when Lua is
  12137. * responsible, so C can no longer filter callbacks for Lua. */
  12138. return;
  12139. }
  12140. }
  12141. #if defined(USE_LUA)
  12142. /* Step 3: No callback. Check if Lua is responsible. */
  12143. else {
  12144. /* Step 3.1: Check if Lua is responsible. */
  12145. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  12146. lua_websock = match_prefix_strlen(
  12147. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  12148. }
  12149. if (lua_websock > 0) {
  12150. /* Step 3.2: Lua is responsible: call it. */
  12151. conn->lua_websocket_state = lua_websocket_new(path, conn);
  12152. if (!conn->lua_websocket_state) {
  12153. /* Lua rejected the new client */
  12154. return;
  12155. }
  12156. }
  12157. }
  12158. #endif
  12159. /* Step 4: Check if there is a responsible websocket handler. */
  12160. if (!is_callback_resource && !lua_websock) {
  12161. /* There is no callback, and Lua is not responsible either. */
  12162. /* Reply with a 404 Not Found. We are still at a standard
  12163. * HTTP request here, before the websocket handshake, so
  12164. * we can still send standard HTTP error replies. */
  12165. mg_send_http_error(conn, 404, "%s", "Not found");
  12166. return;
  12167. }
  12168. /* Step 5: The websocket connection has been accepted */
  12169. if (!send_websocket_handshake(conn, websock_key)) {
  12170. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  12171. return;
  12172. }
  12173. /* Step 6: Call the ready handler */
  12174. if (is_callback_resource) {
  12175. if (ws_ready_handler != NULL) {
  12176. ws_ready_handler(conn, cbData);
  12177. }
  12178. #if defined(USE_LUA)
  12179. } else if (lua_websock) {
  12180. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  12181. /* the ready handler returned false */
  12182. return;
  12183. }
  12184. #endif
  12185. }
  12186. /* Step 7: Enter the read loop */
  12187. if (is_callback_resource) {
  12188. read_websocket(conn, ws_data_handler, cbData);
  12189. #if defined(USE_LUA)
  12190. } else if (lua_websock) {
  12191. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  12192. #endif
  12193. }
  12194. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12195. /* Step 8: Close the deflate & inflate buffers */
  12196. if (conn->websocket_deflate_initialized) {
  12197. deflateEnd(&conn->websocket_deflate_state);
  12198. inflateEnd(&conn->websocket_inflate_state);
  12199. }
  12200. #endif
  12201. /* Step 9: Call the close handler */
  12202. if (ws_close_handler) {
  12203. ws_close_handler(conn, cbData);
  12204. }
  12205. }
  12206. #endif /* !USE_WEBSOCKET */
  12207. /* Is upgrade request:
  12208. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12209. * 1 = upgrade to websocket
  12210. * 2 = upgrade to HTTP/2
  12211. * -1 = upgrade to unknown protocol
  12212. */
  12213. static int
  12214. should_switch_to_protocol(const struct mg_connection *conn)
  12215. {
  12216. const char *connection_headers[8];
  12217. const char *upgrade_to;
  12218. int connection_header_count, i, should_upgrade;
  12219. /* A websocket protocol has the following HTTP headers:
  12220. *
  12221. * Connection: Upgrade
  12222. * Upgrade: Websocket
  12223. *
  12224. * It seems some clients use multiple headers:
  12225. * see https://github.com/civetweb/civetweb/issues/1083
  12226. */
  12227. connection_header_count = get_req_headers(&conn->request_info,
  12228. "Connection",
  12229. connection_headers,
  12230. 8);
  12231. should_upgrade = 0;
  12232. for (i = 0; i < connection_header_count; i++) {
  12233. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12234. should_upgrade = 1;
  12235. }
  12236. }
  12237. if (!should_upgrade) {
  12238. return PROTOCOL_TYPE_HTTP1;
  12239. }
  12240. upgrade_to = mg_get_header(conn, "Upgrade");
  12241. if (upgrade_to == NULL) {
  12242. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12243. return -1;
  12244. }
  12245. /* Upgrade to ... */
  12246. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12247. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12248. * "Sec-WebSocket-Version" are also required.
  12249. * Don't check them here, since even an unsupported websocket protocol
  12250. * request still IS a websocket request (in contrast to a standard HTTP
  12251. * request). It will fail later in handle_websocket_request.
  12252. */
  12253. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12254. }
  12255. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12256. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12257. }
  12258. /* Upgrade to another protocol */
  12259. return -1;
  12260. }
  12261. static int
  12262. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12263. {
  12264. int n;
  12265. unsigned int a, b, c, d, slash;
  12266. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12267. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12268. // integer value, but function will not report conversion
  12269. // errors; consider using 'strtol' instead
  12270. slash = 32;
  12271. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12272. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12273. // an integer value, but function will not report conversion
  12274. // errors; consider using 'strtol' instead
  12275. n = 0;
  12276. }
  12277. }
  12278. if ((n > 0) && ((size_t)n == vec->len)) {
  12279. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12280. /* IPv4 format */
  12281. if (sa->sa.sa_family == AF_INET) {
  12282. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12283. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12284. | ((uint32_t)c << 8) | (uint32_t)d;
  12285. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12286. return (ip & mask) == net;
  12287. }
  12288. return 0;
  12289. }
  12290. }
  12291. #if defined(USE_IPV6)
  12292. else {
  12293. char ad[50];
  12294. const char *p;
  12295. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12296. slash = 128;
  12297. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12298. n = 0;
  12299. }
  12300. }
  12301. if ((n <= 0) && no_strict) {
  12302. /* no square brackets? */
  12303. p = strchr(vec->ptr, '/');
  12304. if (p && (p < (vec->ptr + vec->len))) {
  12305. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12306. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12307. n += (int)(p - vec->ptr);
  12308. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12309. } else {
  12310. n = 0;
  12311. }
  12312. } else if (vec->len < sizeof(ad)) {
  12313. n = (int)vec->len;
  12314. slash = 128;
  12315. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12316. }
  12317. }
  12318. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12319. p = ad;
  12320. c = 0;
  12321. /* zone indexes are unsupported, at least two colons are needed */
  12322. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12323. if (*(p++) == ':') {
  12324. c++;
  12325. }
  12326. }
  12327. if ((*p == '\0') && (c >= 2)) {
  12328. struct sockaddr_in6 sin6;
  12329. unsigned int i;
  12330. /* for strict validation, an actual IPv6 argument is needed */
  12331. if (sa->sa.sa_family != AF_INET6) {
  12332. return 0;
  12333. }
  12334. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12335. /* IPv6 format */
  12336. for (i = 0; i < 16; i++) {
  12337. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12338. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12339. uint8_t mask = 0;
  12340. if (8 * i + 8 < slash) {
  12341. mask = 0xFFu;
  12342. } else if (8 * i < slash) {
  12343. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12344. }
  12345. if ((ip & mask) != net) {
  12346. return 0;
  12347. }
  12348. }
  12349. return 1;
  12350. }
  12351. }
  12352. }
  12353. }
  12354. #else
  12355. (void)no_strict;
  12356. #endif
  12357. /* malformed */
  12358. return -1;
  12359. }
  12360. static int
  12361. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12362. {
  12363. int throttle = 0;
  12364. struct vec vec, val;
  12365. char mult;
  12366. double v;
  12367. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12368. mult = ',';
  12369. if ((val.ptr == NULL)
  12370. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12371. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12372. // to an integer value, but function will not report
  12373. // conversion errors; consider using 'strtol' instead
  12374. || (v < 0)
  12375. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12376. && (mult != ','))) {
  12377. continue;
  12378. }
  12379. v *= (lowercase(&mult) == 'k')
  12380. ? 1024
  12381. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12382. if (vec.len == 1 && vec.ptr[0] == '*') {
  12383. throttle = (int)v;
  12384. } else {
  12385. int matched = parse_match_net(&vec, rsa, 0);
  12386. if (matched >= 0) {
  12387. /* a valid IP subnet */
  12388. if (matched) {
  12389. throttle = (int)v;
  12390. }
  12391. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12392. throttle = (int)v;
  12393. }
  12394. }
  12395. }
  12396. return throttle;
  12397. }
  12398. /* The mg_upload function is superseded by mg_handle_form_request. */
  12399. #include "handle_form.inl"
  12400. static int
  12401. get_first_ssl_listener_index(const struct mg_context *ctx)
  12402. {
  12403. unsigned int i;
  12404. int idx = -1;
  12405. if (ctx) {
  12406. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12407. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12408. }
  12409. }
  12410. return idx;
  12411. }
  12412. /* Return host (without port) */
  12413. static void
  12414. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12415. {
  12416. const char *host_header =
  12417. get_header(ri->http_headers, ri->num_headers, "Host");
  12418. host->ptr = NULL;
  12419. host->len = 0;
  12420. if (host_header != NULL) {
  12421. const char *pos;
  12422. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12423. * is found. */
  12424. if (*host_header == '[') {
  12425. pos = strchr(host_header, ']');
  12426. if (!pos) {
  12427. /* Malformed hostname starts with '[', but no ']' found */
  12428. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12429. return;
  12430. }
  12431. /* terminate after ']' */
  12432. host->ptr = host_header;
  12433. host->len = (size_t)(pos + 1 - host_header);
  12434. } else {
  12435. /* Otherwise, a ':' separates hostname and port number */
  12436. pos = strchr(host_header, ':');
  12437. if (pos != NULL) {
  12438. host->len = (size_t)(pos - host_header);
  12439. } else {
  12440. host->len = strlen(host_header);
  12441. }
  12442. host->ptr = host_header;
  12443. }
  12444. }
  12445. }
  12446. static int
  12447. switch_domain_context(struct mg_connection *conn)
  12448. {
  12449. struct vec host;
  12450. get_host_from_request_info(&host, &conn->request_info);
  12451. if (host.ptr) {
  12452. if (conn->ssl) {
  12453. /* This is a HTTPS connection, maybe we have a hostname
  12454. * from SNI (set in ssl_servername_callback). */
  12455. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12456. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12457. /* We are not using the default domain */
  12458. if ((strlen(sslhost) != host.len)
  12459. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12460. /* Mismatch between SNI domain and HTTP domain */
  12461. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12462. sslhost,
  12463. (int)host.len,
  12464. host.ptr);
  12465. return 0;
  12466. }
  12467. }
  12468. } else {
  12469. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12470. while (dom) {
  12471. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12472. size_t domNameLen = strlen(domName);
  12473. if ((domNameLen == host.len)
  12474. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12475. /* Found matching domain */
  12476. DEBUG_TRACE("HTTP domain %s found",
  12477. dom->config[AUTHENTICATION_DOMAIN]);
  12478. /* TODO: Check if this is a HTTP or HTTPS domain */
  12479. conn->dom_ctx = dom;
  12480. break;
  12481. }
  12482. mg_lock_context(conn->phys_ctx);
  12483. dom = dom->next;
  12484. mg_unlock_context(conn->phys_ctx);
  12485. }
  12486. }
  12487. DEBUG_TRACE("HTTP%s Host: %.*s",
  12488. conn->ssl ? "S" : "",
  12489. (int)host.len,
  12490. host.ptr);
  12491. } else {
  12492. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12493. return 1;
  12494. }
  12495. return 1;
  12496. }
  12497. static void
  12498. redirect_to_https_port(struct mg_connection *conn, int port)
  12499. {
  12500. char target_url[MG_BUF_LEN];
  12501. int truncated = 0;
  12502. const char *expect_proto =
  12503. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12504. /* Use "308 Permanent Redirect" */
  12505. int redirect_code = 308;
  12506. /* In any case, close the current connection */
  12507. conn->must_close = 1;
  12508. /* Send host, port, uri and (if it exists) ?query_string */
  12509. if (mg_construct_local_link(
  12510. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12511. < 0) {
  12512. truncated = 1;
  12513. } else if (conn->request_info.query_string != NULL) {
  12514. size_t slen1 = strlen(target_url);
  12515. size_t slen2 = strlen(conn->request_info.query_string);
  12516. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12517. target_url[slen1] = '?';
  12518. memcpy(target_url + slen1 + 1,
  12519. conn->request_info.query_string,
  12520. slen2);
  12521. target_url[slen1 + slen2 + 1] = 0;
  12522. } else {
  12523. truncated = 1;
  12524. }
  12525. }
  12526. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12527. * is used as buffer size) */
  12528. if (truncated) {
  12529. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12530. return;
  12531. }
  12532. /* Use redirect helper function */
  12533. mg_send_http_redirect(conn, target_url, redirect_code);
  12534. }
  12535. static void
  12536. mg_set_handler_type(struct mg_context *phys_ctx,
  12537. struct mg_domain_context *dom_ctx,
  12538. const char *uri,
  12539. int handler_type,
  12540. int is_delete_request,
  12541. mg_request_handler handler,
  12542. struct mg_websocket_subprotocols *subprotocols,
  12543. mg_websocket_connect_handler connect_handler,
  12544. mg_websocket_ready_handler ready_handler,
  12545. mg_websocket_data_handler data_handler,
  12546. mg_websocket_close_handler close_handler,
  12547. mg_authorization_handler auth_handler,
  12548. void *cbdata)
  12549. {
  12550. struct mg_handler_info *tmp_rh, **lastref;
  12551. size_t urilen = strlen(uri);
  12552. if (handler_type == WEBSOCKET_HANDLER) {
  12553. DEBUG_ASSERT(handler == NULL);
  12554. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12555. || ready_handler != NULL || data_handler != NULL
  12556. || close_handler != NULL);
  12557. DEBUG_ASSERT(auth_handler == NULL);
  12558. if (handler != NULL) {
  12559. return;
  12560. }
  12561. if (!is_delete_request && (connect_handler == NULL)
  12562. && (ready_handler == NULL) && (data_handler == NULL)
  12563. && (close_handler == NULL)) {
  12564. return;
  12565. }
  12566. if (auth_handler != NULL) {
  12567. return;
  12568. }
  12569. } else if (handler_type == REQUEST_HANDLER) {
  12570. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12571. && data_handler == NULL && close_handler == NULL);
  12572. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12573. DEBUG_ASSERT(auth_handler == NULL);
  12574. if ((connect_handler != NULL) || (ready_handler != NULL)
  12575. || (data_handler != NULL) || (close_handler != NULL)) {
  12576. return;
  12577. }
  12578. if (!is_delete_request && (handler == NULL)) {
  12579. return;
  12580. }
  12581. if (auth_handler != NULL) {
  12582. return;
  12583. }
  12584. } else if (handler_type == AUTH_HANDLER) {
  12585. DEBUG_ASSERT(handler == NULL);
  12586. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12587. && data_handler == NULL && close_handler == NULL);
  12588. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12589. if (handler != NULL) {
  12590. return;
  12591. }
  12592. if ((connect_handler != NULL) || (ready_handler != NULL)
  12593. || (data_handler != NULL) || (close_handler != NULL)) {
  12594. return;
  12595. }
  12596. if (!is_delete_request && (auth_handler == NULL)) {
  12597. return;
  12598. }
  12599. } else {
  12600. /* Unknown handler type. */
  12601. return;
  12602. }
  12603. if (!phys_ctx || !dom_ctx) {
  12604. /* no context available */
  12605. return;
  12606. }
  12607. mg_lock_context(phys_ctx);
  12608. /* first try to find an existing handler */
  12609. do {
  12610. lastref = &(dom_ctx->handlers);
  12611. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12612. tmp_rh = tmp_rh->next) {
  12613. if (tmp_rh->handler_type == handler_type
  12614. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12615. if (!is_delete_request) {
  12616. /* update existing handler */
  12617. if (handler_type == REQUEST_HANDLER) {
  12618. /* Wait for end of use before updating */
  12619. if (tmp_rh->refcount) {
  12620. mg_unlock_context(phys_ctx);
  12621. mg_sleep(1);
  12622. mg_lock_context(phys_ctx);
  12623. /* tmp_rh might have been freed, search again. */
  12624. break;
  12625. }
  12626. /* Ok, the handler is no more use -> Update it */
  12627. tmp_rh->handler = handler;
  12628. } else if (handler_type == WEBSOCKET_HANDLER) {
  12629. tmp_rh->subprotocols = subprotocols;
  12630. tmp_rh->connect_handler = connect_handler;
  12631. tmp_rh->ready_handler = ready_handler;
  12632. tmp_rh->data_handler = data_handler;
  12633. tmp_rh->close_handler = close_handler;
  12634. } else { /* AUTH_HANDLER */
  12635. tmp_rh->auth_handler = auth_handler;
  12636. }
  12637. tmp_rh->cbdata = cbdata;
  12638. } else {
  12639. /* remove existing handler */
  12640. if (handler_type == REQUEST_HANDLER) {
  12641. /* Wait for end of use before removing */
  12642. if (tmp_rh->refcount) {
  12643. tmp_rh->removing = 1;
  12644. mg_unlock_context(phys_ctx);
  12645. mg_sleep(1);
  12646. mg_lock_context(phys_ctx);
  12647. /* tmp_rh might have been freed, search again. */
  12648. break;
  12649. }
  12650. /* Ok, the handler is no more used */
  12651. }
  12652. *lastref = tmp_rh->next;
  12653. mg_free(tmp_rh->uri);
  12654. mg_free(tmp_rh);
  12655. }
  12656. mg_unlock_context(phys_ctx);
  12657. return;
  12658. }
  12659. lastref = &(tmp_rh->next);
  12660. }
  12661. } while (tmp_rh != NULL);
  12662. if (is_delete_request) {
  12663. /* no handler to set, this was a remove request to a non-existing
  12664. * handler */
  12665. mg_unlock_context(phys_ctx);
  12666. return;
  12667. }
  12668. tmp_rh =
  12669. (struct mg_handler_info *)mg_calloc_ctx(1,
  12670. sizeof(struct mg_handler_info),
  12671. phys_ctx);
  12672. if (tmp_rh == NULL) {
  12673. mg_unlock_context(phys_ctx);
  12674. mg_cry_ctx_internal(phys_ctx,
  12675. "%s",
  12676. "Cannot create new request handler struct, OOM");
  12677. return;
  12678. }
  12679. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12680. if (!tmp_rh->uri) {
  12681. mg_unlock_context(phys_ctx);
  12682. mg_free(tmp_rh);
  12683. mg_cry_ctx_internal(phys_ctx,
  12684. "%s",
  12685. "Cannot create new request handler struct, OOM");
  12686. return;
  12687. }
  12688. tmp_rh->uri_len = urilen;
  12689. if (handler_type == REQUEST_HANDLER) {
  12690. tmp_rh->refcount = 0;
  12691. tmp_rh->removing = 0;
  12692. tmp_rh->handler = handler;
  12693. } else if (handler_type == WEBSOCKET_HANDLER) {
  12694. tmp_rh->subprotocols = subprotocols;
  12695. tmp_rh->connect_handler = connect_handler;
  12696. tmp_rh->ready_handler = ready_handler;
  12697. tmp_rh->data_handler = data_handler;
  12698. tmp_rh->close_handler = close_handler;
  12699. } else { /* AUTH_HANDLER */
  12700. tmp_rh->auth_handler = auth_handler;
  12701. }
  12702. tmp_rh->cbdata = cbdata;
  12703. tmp_rh->handler_type = handler_type;
  12704. tmp_rh->next = NULL;
  12705. *lastref = tmp_rh;
  12706. mg_unlock_context(phys_ctx);
  12707. }
  12708. CIVETWEB_API void
  12709. mg_set_request_handler(struct mg_context *ctx,
  12710. const char *uri,
  12711. mg_request_handler handler,
  12712. void *cbdata)
  12713. {
  12714. mg_set_handler_type(ctx,
  12715. &(ctx->dd),
  12716. uri,
  12717. REQUEST_HANDLER,
  12718. handler == NULL,
  12719. handler,
  12720. NULL,
  12721. NULL,
  12722. NULL,
  12723. NULL,
  12724. NULL,
  12725. NULL,
  12726. cbdata);
  12727. }
  12728. CIVETWEB_API void
  12729. mg_set_websocket_handler(struct mg_context *ctx,
  12730. const char *uri,
  12731. mg_websocket_connect_handler connect_handler,
  12732. mg_websocket_ready_handler ready_handler,
  12733. mg_websocket_data_handler data_handler,
  12734. mg_websocket_close_handler close_handler,
  12735. void *cbdata)
  12736. {
  12737. mg_set_websocket_handler_with_subprotocols(ctx,
  12738. uri,
  12739. NULL,
  12740. connect_handler,
  12741. ready_handler,
  12742. data_handler,
  12743. close_handler,
  12744. cbdata);
  12745. }
  12746. CIVETWEB_API void
  12747. mg_set_websocket_handler_with_subprotocols(
  12748. struct mg_context *ctx,
  12749. const char *uri,
  12750. struct mg_websocket_subprotocols *subprotocols,
  12751. mg_websocket_connect_handler connect_handler,
  12752. mg_websocket_ready_handler ready_handler,
  12753. mg_websocket_data_handler data_handler,
  12754. mg_websocket_close_handler close_handler,
  12755. void *cbdata)
  12756. {
  12757. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12758. && (data_handler == NULL)
  12759. && (close_handler == NULL);
  12760. mg_set_handler_type(ctx,
  12761. &(ctx->dd),
  12762. uri,
  12763. WEBSOCKET_HANDLER,
  12764. is_delete_request,
  12765. NULL,
  12766. subprotocols,
  12767. connect_handler,
  12768. ready_handler,
  12769. data_handler,
  12770. close_handler,
  12771. NULL,
  12772. cbdata);
  12773. }
  12774. CIVETWEB_API void
  12775. mg_set_auth_handler(struct mg_context *ctx,
  12776. const char *uri,
  12777. mg_authorization_handler handler,
  12778. void *cbdata)
  12779. {
  12780. mg_set_handler_type(ctx,
  12781. &(ctx->dd),
  12782. uri,
  12783. AUTH_HANDLER,
  12784. handler == NULL,
  12785. NULL,
  12786. NULL,
  12787. NULL,
  12788. NULL,
  12789. NULL,
  12790. NULL,
  12791. handler,
  12792. cbdata);
  12793. }
  12794. static int
  12795. get_request_handler(struct mg_connection *conn,
  12796. int handler_type,
  12797. mg_request_handler *handler,
  12798. struct mg_websocket_subprotocols **subprotocols,
  12799. mg_websocket_connect_handler *connect_handler,
  12800. mg_websocket_ready_handler *ready_handler,
  12801. mg_websocket_data_handler *data_handler,
  12802. mg_websocket_close_handler *close_handler,
  12803. mg_authorization_handler *auth_handler,
  12804. void **cbdata,
  12805. struct mg_handler_info **handler_info)
  12806. {
  12807. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12808. if (request_info) {
  12809. const char *uri = request_info->local_uri;
  12810. size_t urilen = strlen(uri);
  12811. struct mg_handler_info *tmp_rh;
  12812. int step, matched;
  12813. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12814. return 0;
  12815. }
  12816. mg_lock_context(conn->phys_ctx);
  12817. for (step = 0; step < 3; step++) {
  12818. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12819. tmp_rh = tmp_rh->next) {
  12820. if (tmp_rh->handler_type != handler_type) {
  12821. continue;
  12822. }
  12823. if (step == 0) {
  12824. /* first try for an exact match */
  12825. matched = (tmp_rh->uri_len == urilen)
  12826. && (strcmp(tmp_rh->uri, uri) == 0);
  12827. } else if (step == 1) {
  12828. /* next try for a partial match, we will accept
  12829. uri/something */
  12830. matched =
  12831. (tmp_rh->uri_len < urilen)
  12832. && (uri[tmp_rh->uri_len] == '/')
  12833. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12834. } else {
  12835. /* finally try for pattern match */
  12836. matched =
  12837. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12838. }
  12839. if (matched) {
  12840. if (handler_type == WEBSOCKET_HANDLER) {
  12841. *subprotocols = tmp_rh->subprotocols;
  12842. *connect_handler = tmp_rh->connect_handler;
  12843. *ready_handler = tmp_rh->ready_handler;
  12844. *data_handler = tmp_rh->data_handler;
  12845. *close_handler = tmp_rh->close_handler;
  12846. } else if (handler_type == REQUEST_HANDLER) {
  12847. if (tmp_rh->removing) {
  12848. /* Treat as none found */
  12849. step = 2;
  12850. break;
  12851. }
  12852. *handler = tmp_rh->handler;
  12853. /* Acquire handler and give it back */
  12854. tmp_rh->refcount++;
  12855. *handler_info = tmp_rh;
  12856. } else { /* AUTH_HANDLER */
  12857. *auth_handler = tmp_rh->auth_handler;
  12858. }
  12859. *cbdata = tmp_rh->cbdata;
  12860. mg_unlock_context(conn->phys_ctx);
  12861. return 1;
  12862. }
  12863. }
  12864. }
  12865. mg_unlock_context(conn->phys_ctx);
  12866. }
  12867. return 0; /* none found */
  12868. }
  12869. /* Check if the script file is in a path, allowed for script files.
  12870. * This can be used if uploading files is possible not only for the server
  12871. * admin, and the upload mechanism does not check the file extension.
  12872. */
  12873. static int
  12874. is_in_script_path(const struct mg_connection *conn, const char *path)
  12875. {
  12876. /* TODO (Feature): Add config value for allowed script path.
  12877. * Default: All allowed. */
  12878. (void)conn;
  12879. (void)path;
  12880. return 1;
  12881. }
  12882. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12883. static int
  12884. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12885. int bits,
  12886. char *data,
  12887. size_t len,
  12888. void *cbdata)
  12889. {
  12890. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12891. if (pcallbacks->websocket_data) {
  12892. return pcallbacks->websocket_data(conn, bits, data, len);
  12893. }
  12894. /* No handler set - assume "OK" */
  12895. return 1;
  12896. }
  12897. static void
  12898. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12899. void *cbdata)
  12900. {
  12901. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12902. if (pcallbacks->connection_close) {
  12903. pcallbacks->connection_close(conn);
  12904. }
  12905. }
  12906. #endif
  12907. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12908. */
  12909. static void
  12910. release_handler_ref(struct mg_connection *conn,
  12911. struct mg_handler_info *handler_info)
  12912. {
  12913. if (handler_info != NULL) {
  12914. /* Use context lock for ref counter */
  12915. mg_lock_context(conn->phys_ctx);
  12916. handler_info->refcount--;
  12917. mg_unlock_context(conn->phys_ctx);
  12918. }
  12919. }
  12920. /* This is the heart of the Civetweb's logic.
  12921. * This function is called when the request is read, parsed and validated,
  12922. * and Civetweb must decide what action to take: serve a file, or
  12923. * a directory, or call embedded function, etcetera. */
  12924. static void
  12925. handle_request(struct mg_connection *conn)
  12926. {
  12927. struct mg_request_info *ri = &conn->request_info;
  12928. char path[UTF8_PATH_MAX];
  12929. int uri_len, ssl_index;
  12930. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12931. is_put_or_delete_request = 0, is_callback_resource = 0,
  12932. is_template_text_file = 0, is_webdav_request = 0;
  12933. int i;
  12934. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12935. mg_request_handler callback_handler = NULL;
  12936. struct mg_handler_info *handler_info = NULL;
  12937. struct mg_websocket_subprotocols *subprotocols;
  12938. mg_websocket_connect_handler ws_connect_handler = NULL;
  12939. mg_websocket_ready_handler ws_ready_handler = NULL;
  12940. mg_websocket_data_handler ws_data_handler = NULL;
  12941. mg_websocket_close_handler ws_close_handler = NULL;
  12942. void *callback_data = NULL;
  12943. mg_authorization_handler auth_handler = NULL;
  12944. void *auth_callback_data = NULL;
  12945. int handler_type;
  12946. time_t curtime = time(NULL);
  12947. char date[64];
  12948. char *tmp;
  12949. path[0] = 0;
  12950. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12951. conn->request_state = 0;
  12952. /* 1. get the request url */
  12953. /* 1.1. split into url and query string */
  12954. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12955. != NULL) {
  12956. *((char *)conn->request_info.query_string++) = '\0';
  12957. }
  12958. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12959. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12960. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12961. if (ssl_index >= 0) {
  12962. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12963. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12964. redirect_to_https_port(conn, port);
  12965. } else {
  12966. /* A http to https forward port has been specified,
  12967. * but no https port to forward to. */
  12968. mg_send_http_error(conn,
  12969. 503,
  12970. "%s",
  12971. "Error: SSL forward not configured properly");
  12972. mg_cry_internal(conn,
  12973. "%s",
  12974. "Can not redirect to SSL, no SSL port available");
  12975. }
  12976. return;
  12977. }
  12978. uri_len = (int)strlen(ri->local_uri);
  12979. /* 1.3. decode url (if config says so) */
  12980. if (should_decode_url(conn)) {
  12981. url_decode_in_place((char *)ri->local_uri);
  12982. }
  12983. /* URL decode the query-string only if explicitly set in the configuration
  12984. */
  12985. if (conn->request_info.query_string) {
  12986. if (should_decode_query_string(conn)) {
  12987. url_decode_in_place((char *)conn->request_info.query_string);
  12988. }
  12989. }
  12990. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12991. * possible. The fact that we cleaned the URI is stored in that the
  12992. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12993. * ri->local_uri_raw still points to memory allocated in
  12994. * worker_thread_run(). ri->local_uri is private to the request so we
  12995. * don't have to use preallocated memory here. */
  12996. tmp = mg_strdup(ri->local_uri_raw);
  12997. if (!tmp) {
  12998. /* Out of memory. We cannot do anything reasonable here. */
  12999. return;
  13000. }
  13001. remove_dot_segments(tmp);
  13002. ri->local_uri = tmp;
  13003. /* step 1. completed, the url is known now */
  13004. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  13005. /* 2. if this ip has limited speed, set it for this connection */
  13006. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  13007. &conn->client.rsa,
  13008. ri->local_uri);
  13009. /* 3. call a "handle everything" callback, if registered */
  13010. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  13011. /* Note that since V1.7 the "begin_request" function is called
  13012. * before an authorization check. If an authorization check is
  13013. * required, use a request_handler instead. */
  13014. i = conn->phys_ctx->callbacks.begin_request(conn);
  13015. if (i > 0) {
  13016. /* callback already processed the request. Store the
  13017. return value as a status code for the access log. */
  13018. conn->status_code = i;
  13019. if (!conn->must_close) {
  13020. discard_unread_request_data(conn);
  13021. }
  13022. DEBUG_TRACE("%s", "begin_request handled request");
  13023. return;
  13024. } else if (i == 0) {
  13025. /* civetweb should process the request */
  13026. } else {
  13027. /* unspecified - may change with the next version */
  13028. DEBUG_TRACE("%s", "done (undocumented behavior)");
  13029. return;
  13030. }
  13031. }
  13032. /* request not yet handled by a handler or redirect, so the request
  13033. * is processed here */
  13034. /* 4. Check for CORS preflight requests and handle them (if configured).
  13035. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  13036. */
  13037. if (!strcmp(ri->request_method, "OPTIONS")) {
  13038. /* Send a response to CORS preflights only if
  13039. * access_control_allow_methods is not NULL and not an empty string.
  13040. * In this case, scripts can still handle CORS. */
  13041. const char *cors_meth_cfg =
  13042. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  13043. const char *cors_orig_cfg =
  13044. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  13045. const char *cors_origin =
  13046. get_header(ri->http_headers, ri->num_headers, "Origin");
  13047. const char *cors_acrm = get_header(ri->http_headers,
  13048. ri->num_headers,
  13049. "Access-Control-Request-Method");
  13050. /* Todo: check if cors_origin is in cors_orig_cfg.
  13051. * Or, let the client check this. */
  13052. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  13053. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  13054. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  13055. /* This is a valid CORS preflight, and the server is configured
  13056. * to handle it automatically. */
  13057. const char *cors_acrh =
  13058. get_header(ri->http_headers,
  13059. ri->num_headers,
  13060. "Access-Control-Request-Headers");
  13061. const char *cors_cred_cfg =
  13062. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  13063. const char *cors_exphdr_cfg =
  13064. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  13065. gmt_time_string(date, sizeof(date), &curtime);
  13066. mg_printf(conn,
  13067. "HTTP/1.1 200 OK\r\n"
  13068. "Date: %s\r\n"
  13069. "Access-Control-Allow-Origin: %s\r\n"
  13070. "Access-Control-Allow-Methods: %s\r\n"
  13071. "Content-Length: 0\r\n"
  13072. "Connection: %s\r\n",
  13073. date,
  13074. cors_orig_cfg,
  13075. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  13076. suggest_connection_header(conn));
  13077. if (cors_cred_cfg && *cors_cred_cfg) {
  13078. mg_printf(conn,
  13079. "Access-Control-Allow-Credentials: %s\r\n",
  13080. cors_cred_cfg);
  13081. }
  13082. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  13083. mg_printf(conn,
  13084. "Access-Control-Expose-Headers: %s\r\n",
  13085. cors_exphdr_cfg);
  13086. }
  13087. if (cors_acrh || (cors_cred_cfg && *cors_cred_cfg)) {
  13088. /* CORS request is asking for additional headers */
  13089. const char *cors_hdr_cfg =
  13090. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  13091. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  13092. /* Allow only if access_control_allow_headers is
  13093. * not NULL and not an empty string. If this
  13094. * configuration is set to *, allow everything.
  13095. * Otherwise this configuration must be a list
  13096. * of allowed HTTP header names. */
  13097. mg_printf(conn,
  13098. "Access-Control-Allow-Headers: %s\r\n",
  13099. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  13100. : cors_hdr_cfg));
  13101. }
  13102. }
  13103. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  13104. mg_printf(conn, "\r\n");
  13105. DEBUG_TRACE("%s", "OPTIONS done");
  13106. return;
  13107. }
  13108. }
  13109. /* 5. interpret the url to find out how the request must be handled
  13110. */
  13111. /* 5.1. first test, if the request targets the regular http(s)://
  13112. * protocol namespace or the websocket ws(s):// protocol namespace.
  13113. */
  13114. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  13115. #if defined(USE_WEBSOCKET)
  13116. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  13117. #else
  13118. handler_type = REQUEST_HANDLER;
  13119. #endif /* defined(USE_WEBSOCKET) */
  13120. if (is_websocket_request) {
  13121. HTTP1_only;
  13122. }
  13123. /* 5.2. check if the request will be handled by a callback */
  13124. if (get_request_handler(conn,
  13125. handler_type,
  13126. &callback_handler,
  13127. &subprotocols,
  13128. &ws_connect_handler,
  13129. &ws_ready_handler,
  13130. &ws_data_handler,
  13131. &ws_close_handler,
  13132. NULL,
  13133. &callback_data,
  13134. &handler_info)) {
  13135. /* 5.2.1. A callback will handle this request. All requests
  13136. * handled by a callback have to be considered as requests
  13137. * to a script resource. */
  13138. is_callback_resource = 1;
  13139. is_script_resource = 1;
  13140. is_put_or_delete_request = is_put_or_delete_method(conn);
  13141. /* Never handle a C callback according to File WebDav rules,
  13142. * even if it is a webdav method */
  13143. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  13144. } else {
  13145. no_callback_resource:
  13146. /* 5.2.2. No callback is responsible for this request. The URI
  13147. * addresses a file based resource (static content or Lua/cgi
  13148. * scripts in the file system). */
  13149. is_callback_resource = 0;
  13150. interpret_uri(conn,
  13151. path,
  13152. sizeof(path),
  13153. &file.stat,
  13154. &is_found,
  13155. &is_script_resource,
  13156. &is_websocket_request,
  13157. &is_put_or_delete_request,
  13158. &is_webdav_request,
  13159. &is_template_text_file);
  13160. }
  13161. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  13162. if (is_webdav_request) {
  13163. /* TODO: Do we need a config option? */
  13164. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  13165. if (webdav_enable[0] != 'y') {
  13166. mg_send_http_error(conn,
  13167. 405,
  13168. "%s method not allowed",
  13169. conn->request_info.request_method);
  13170. DEBUG_TRACE("%s", "webdav rejected");
  13171. return;
  13172. }
  13173. }
  13174. /* 6. authorization check */
  13175. /* 6.1. a custom authorization handler is installed */
  13176. if (get_request_handler(conn,
  13177. AUTH_HANDLER,
  13178. NULL,
  13179. NULL,
  13180. NULL,
  13181. NULL,
  13182. NULL,
  13183. NULL,
  13184. &auth_handler,
  13185. &auth_callback_data,
  13186. NULL)) {
  13187. if (!auth_handler(conn, auth_callback_data)) {
  13188. /* Callback handler will not be used anymore. Release it */
  13189. release_handler_ref(conn, handler_info);
  13190. DEBUG_TRACE("%s", "auth handler rejected request");
  13191. return;
  13192. }
  13193. } else if (is_put_or_delete_request && !is_script_resource
  13194. && !is_callback_resource) {
  13195. HTTP1_only;
  13196. /* 6.2. this request is a PUT/DELETE to a real file */
  13197. /* 6.2.1. thus, the server must have real files */
  13198. #if defined(NO_FILES)
  13199. if (1) {
  13200. #else
  13201. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  13202. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  13203. #endif
  13204. /* This code path will not be called for request handlers */
  13205. DEBUG_ASSERT(handler_info == NULL);
  13206. /* This server does not have any real files, thus the
  13207. * PUT/DELETE methods are not valid. */
  13208. mg_send_http_error(conn,
  13209. 405,
  13210. "%s method not allowed",
  13211. conn->request_info.request_method);
  13212. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  13213. return;
  13214. }
  13215. #if !defined(NO_FILES)
  13216. /* 6.2.2. Check if put authorization for static files is
  13217. * available.
  13218. */
  13219. if (!is_authorized_for_put(conn)) {
  13220. send_authorization_request(conn, NULL);
  13221. DEBUG_TRACE("%s", "file write needs authorization");
  13222. return;
  13223. }
  13224. #endif
  13225. } else {
  13226. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13227. * or it is a PUT or DELETE request to a resource that does not
  13228. * correspond to a file. Check authorization. */
  13229. if (!check_authorization(conn, path)) {
  13230. send_authorization_request(conn, NULL);
  13231. /* Callback handler will not be used anymore. Release it */
  13232. release_handler_ref(conn, handler_info);
  13233. DEBUG_TRACE("%s", "access authorization required");
  13234. return;
  13235. }
  13236. }
  13237. /* request is authorized or does not need authorization */
  13238. /* 7. check if there are request handlers for this uri */
  13239. if (is_callback_resource) {
  13240. HTTP1_only;
  13241. if (!is_websocket_request) {
  13242. i = callback_handler(conn, callback_data);
  13243. /* Callback handler will not be used anymore. Release it */
  13244. release_handler_ref(conn, handler_info);
  13245. if (i > 0) {
  13246. /* Do nothing, callback has served the request. Store
  13247. * then return value as status code for the log and discard
  13248. * all data from the client not used by the callback. */
  13249. conn->status_code = i;
  13250. if (!conn->must_close) {
  13251. discard_unread_request_data(conn);
  13252. }
  13253. } else {
  13254. /* The handler did NOT handle the request. */
  13255. /* Some proper reactions would be:
  13256. * a) close the connections without sending anything
  13257. * b) send a 404 not found
  13258. * c) try if there is a file matching the URI
  13259. * It would be possible to do a, b or c in the callback
  13260. * implementation, and return 1 - we cannot do anything
  13261. * here, that is not possible in the callback.
  13262. *
  13263. * TODO: What would be the best reaction here?
  13264. * (Note: The reaction may change, if there is a better
  13265. * idea.)
  13266. */
  13267. /* For the moment, use option c: We look for a proper file,
  13268. * but since a file request is not always a script resource,
  13269. * the authorization check might be different. */
  13270. callback_handler = NULL;
  13271. /* Here we are at a dead end:
  13272. * According to URI matching, a callback should be
  13273. * responsible for handling the request,
  13274. * we called it, but the callback declared itself
  13275. * not responsible.
  13276. * We use a goto here, to get out of this dead end,
  13277. * and continue with the default handling.
  13278. * A goto here is simpler and better to understand
  13279. * than some curious loop. */
  13280. goto no_callback_resource;
  13281. }
  13282. } else {
  13283. #if defined(USE_WEBSOCKET)
  13284. handle_websocket_request(conn,
  13285. path,
  13286. is_callback_resource,
  13287. subprotocols,
  13288. ws_connect_handler,
  13289. ws_ready_handler,
  13290. ws_data_handler,
  13291. ws_close_handler,
  13292. callback_data);
  13293. #endif
  13294. }
  13295. DEBUG_TRACE("%s", "websocket handling done");
  13296. return;
  13297. }
  13298. /* 8. handle websocket requests */
  13299. #if defined(USE_WEBSOCKET)
  13300. if (is_websocket_request) {
  13301. HTTP1_only;
  13302. if (is_script_resource) {
  13303. if (is_in_script_path(conn, path)) {
  13304. /* Websocket Lua script */
  13305. handle_websocket_request(conn,
  13306. path,
  13307. 0 /* Lua Script */,
  13308. NULL,
  13309. NULL,
  13310. NULL,
  13311. NULL,
  13312. NULL,
  13313. conn->phys_ctx->user_data);
  13314. } else {
  13315. /* Script was in an illegal path */
  13316. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13317. }
  13318. } else {
  13319. mg_send_http_error(conn, 404, "%s", "Not found");
  13320. }
  13321. DEBUG_TRACE("%s", "websocket script done");
  13322. return;
  13323. } else
  13324. #endif
  13325. #if defined(NO_FILES)
  13326. /* 9a. In case the server uses only callbacks, this uri is
  13327. * unknown.
  13328. * Then, all request handling ends here. */
  13329. mg_send_http_error(conn, 404, "%s", "Not Found");
  13330. #else
  13331. /* 9b. This request is either for a static file or resource handled
  13332. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13333. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13334. mg_send_http_error(conn, 404, "%s", "Not Found");
  13335. DEBUG_TRACE("%s", "no document root available");
  13336. return;
  13337. }
  13338. /* 10. Request is handled by a script */
  13339. if (is_script_resource) {
  13340. HTTP1_only;
  13341. handle_file_based_request(conn, path, &file);
  13342. DEBUG_TRACE("%s", "script handling done");
  13343. return;
  13344. }
  13345. /* Request was not handled by a callback or script. It will be
  13346. * handled by a server internal method. */
  13347. /* 11. Handle put/delete/mkcol requests */
  13348. if (is_put_or_delete_request) {
  13349. HTTP1_only;
  13350. /* 11.1. PUT method */
  13351. if (!strcmp(ri->request_method, "PUT")) {
  13352. put_file(conn, path);
  13353. DEBUG_TRACE("handling %s request to %s done",
  13354. ri->request_method,
  13355. path);
  13356. return;
  13357. }
  13358. /* 11.2. DELETE method */
  13359. if (!strcmp(ri->request_method, "DELETE")) {
  13360. delete_file(conn, path);
  13361. DEBUG_TRACE("handling %s request to %s done",
  13362. ri->request_method,
  13363. path);
  13364. return;
  13365. }
  13366. /* 11.3. MKCOL method */
  13367. if (!strcmp(ri->request_method, "MKCOL")) {
  13368. dav_mkcol(conn, path);
  13369. DEBUG_TRACE("handling %s request to %s done",
  13370. ri->request_method,
  13371. path);
  13372. return;
  13373. }
  13374. /* 11.4. MOVE method */
  13375. if (!strcmp(ri->request_method, "MOVE")) {
  13376. dav_move_file(conn, path, 0);
  13377. DEBUG_TRACE("handling %s request to %s done",
  13378. ri->request_method,
  13379. path);
  13380. return;
  13381. }
  13382. if (!strcmp(ri->request_method, "COPY")) {
  13383. dav_move_file(conn, path, 1);
  13384. DEBUG_TRACE("handling %s request to %s done",
  13385. ri->request_method,
  13386. path);
  13387. return;
  13388. }
  13389. /* 11.5. LOCK method */
  13390. if (!strcmp(ri->request_method, "LOCK")) {
  13391. dav_lock_file(conn, path);
  13392. DEBUG_TRACE("handling %s request to %s done",
  13393. ri->request_method,
  13394. path);
  13395. return;
  13396. }
  13397. /* 11.6. UNLOCK method */
  13398. if (!strcmp(ri->request_method, "UNLOCK")) {
  13399. dav_unlock_file(conn, path);
  13400. DEBUG_TRACE("handling %s request to %s done",
  13401. ri->request_method,
  13402. path);
  13403. return;
  13404. }
  13405. /* 11.7. PROPPATCH method */
  13406. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13407. dav_proppatch(conn, path);
  13408. DEBUG_TRACE("handling %s request to %s done",
  13409. ri->request_method,
  13410. path);
  13411. return;
  13412. }
  13413. /* 11.8. Other methods, e.g.: PATCH
  13414. * This method is not supported for static resources,
  13415. * only for scripts (Lua, CGI) and callbacks. */
  13416. mg_send_http_error(conn,
  13417. 405,
  13418. "%s method not allowed",
  13419. conn->request_info.request_method);
  13420. DEBUG_TRACE("method %s on %s is not supported",
  13421. ri->request_method,
  13422. path);
  13423. return;
  13424. }
  13425. /* 11. File does not exist, or it was configured that it should be
  13426. * hidden */
  13427. if (!is_found || (must_hide_file(conn, path))) {
  13428. mg_send_http_error(conn, 404, "%s", "Not found");
  13429. DEBUG_TRACE("handling %s request to %s: file not found",
  13430. ri->request_method,
  13431. path);
  13432. return;
  13433. }
  13434. /* 12. Directory uris should end with a slash */
  13435. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13436. && (ri->local_uri[uri_len - 1] != '/')) {
  13437. /* Path + server root */
  13438. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13439. char *new_path;
  13440. if (ri->query_string) {
  13441. buflen += strlen(ri->query_string);
  13442. }
  13443. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13444. if (!new_path) {
  13445. mg_send_http_error(conn, 500, "out or memory");
  13446. } else {
  13447. mg_get_request_link(conn, new_path, buflen - 1);
  13448. strcat(new_path, "/");
  13449. if (ri->query_string) {
  13450. /* Append ? and query string */
  13451. strcat(new_path, "?");
  13452. strcat(new_path, ri->query_string);
  13453. }
  13454. mg_send_http_redirect(conn, new_path, 301);
  13455. mg_free(new_path);
  13456. }
  13457. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13458. ri->request_method,
  13459. path);
  13460. return;
  13461. }
  13462. /* 13. Handle other methods than GET/HEAD */
  13463. /* 13.1. Handle PROPFIND */
  13464. if (!strcmp(ri->request_method, "PROPFIND")) {
  13465. handle_propfind(conn, path, &file.stat);
  13466. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13467. return;
  13468. }
  13469. /* 13.2. Handle OPTIONS for files */
  13470. if (!strcmp(ri->request_method, "OPTIONS")) {
  13471. /* This standard handler is only used for real files.
  13472. * Scripts should support the OPTIONS method themselves, to allow a
  13473. * maximum flexibility.
  13474. * Lua and CGI scripts may fully support CORS this way (including
  13475. * preflights). */
  13476. send_options(conn);
  13477. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13478. return;
  13479. }
  13480. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13481. if ((0 != strcmp(ri->request_method, "GET"))
  13482. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13483. mg_send_http_error(conn,
  13484. 405,
  13485. "%s method not allowed",
  13486. conn->request_info.request_method);
  13487. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13488. return;
  13489. }
  13490. /* 14. directories */
  13491. if (file.stat.is_directory) {
  13492. /* Substitute files have already been handled above. */
  13493. /* Here we can either generate and send a directory listing,
  13494. * or send an "access denied" error. */
  13495. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13496. "yes")) {
  13497. handle_directory_request(conn, path);
  13498. } else {
  13499. mg_send_http_error(conn,
  13500. 403,
  13501. "%s",
  13502. "Error: Directory listing denied");
  13503. }
  13504. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13505. return;
  13506. }
  13507. /* 15. Files with search/replace patterns: LSP and SSI */
  13508. if (is_template_text_file) {
  13509. HTTP1_only;
  13510. handle_file_based_request(conn, path, &file);
  13511. DEBUG_TRACE("handling %s request to %s done (template)",
  13512. ri->request_method,
  13513. path);
  13514. return;
  13515. }
  13516. /* 16. Static file - maybe cached */
  13517. #if !defined(NO_CACHING)
  13518. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13519. /* Send 304 "Not Modified" - this must not send any body data */
  13520. handle_not_modified_static_file_request(conn, &file);
  13521. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13522. ri->request_method,
  13523. path);
  13524. return;
  13525. }
  13526. #endif /* !NO_CACHING */
  13527. /* 17. Static file - not cached */
  13528. handle_static_file_request(conn, path, &file, NULL, NULL);
  13529. DEBUG_TRACE("handling %s request to %s done (static)",
  13530. ri->request_method,
  13531. path);
  13532. #endif /* !defined(NO_FILES) */
  13533. }
  13534. #if !defined(NO_FILESYSTEMS)
  13535. static void
  13536. handle_file_based_request(struct mg_connection *conn,
  13537. const char *path,
  13538. struct mg_file *file)
  13539. {
  13540. #if !defined(NO_CGI)
  13541. int cgi_config_idx, inc, max;
  13542. #endif
  13543. if (!conn || !conn->dom_ctx) {
  13544. return;
  13545. }
  13546. #if defined(USE_LUA)
  13547. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13548. path)
  13549. > 0) {
  13550. if (is_in_script_path(conn, path)) {
  13551. /* Lua server page: an SSI like page containing mostly plain
  13552. * html code plus some tags with server generated contents. */
  13553. handle_lsp_request(conn, path, file, NULL);
  13554. } else {
  13555. /* Script was in an illegal path */
  13556. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13557. }
  13558. return;
  13559. }
  13560. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13561. > 0) {
  13562. if (is_in_script_path(conn, path)) {
  13563. /* Lua in-server module script: a CGI like script used to
  13564. * generate the entire reply. */
  13565. mg_exec_lua_script(conn, path, NULL);
  13566. } else {
  13567. /* Script was in an illegal path */
  13568. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13569. }
  13570. return;
  13571. }
  13572. #endif
  13573. #if defined(USE_DUKTAPE)
  13574. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13575. path)
  13576. > 0) {
  13577. if (is_in_script_path(conn, path)) {
  13578. /* Call duktape to generate the page */
  13579. mg_exec_duktape_script(conn, path);
  13580. } else {
  13581. /* Script was in an illegal path */
  13582. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13583. }
  13584. return;
  13585. }
  13586. #endif
  13587. #if !defined(NO_CGI)
  13588. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13589. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13590. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13591. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13592. if (match_prefix_strlen(
  13593. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13594. path)
  13595. > 0) {
  13596. if (is_in_script_path(conn, path)) {
  13597. /* CGI scripts may support all HTTP methods */
  13598. handle_cgi_request(conn, path, cgi_config_idx);
  13599. } else {
  13600. /* Script was in an illegal path */
  13601. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13602. }
  13603. return;
  13604. }
  13605. }
  13606. }
  13607. #endif /* !NO_CGI */
  13608. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13609. if (is_in_script_path(conn, path)) {
  13610. handle_ssi_file_request(conn, path, file);
  13611. } else {
  13612. /* Script was in an illegal path */
  13613. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13614. }
  13615. return;
  13616. }
  13617. #if !defined(NO_CACHING)
  13618. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13619. /* Send 304 "Not Modified" - this must not send any body data */
  13620. handle_not_modified_static_file_request(conn, file);
  13621. return;
  13622. }
  13623. #endif /* !NO_CACHING */
  13624. handle_static_file_request(conn, path, file, NULL, NULL);
  13625. }
  13626. #endif /* NO_FILESYSTEMS */
  13627. static void
  13628. close_all_listening_sockets(struct mg_context *ctx)
  13629. {
  13630. unsigned int i;
  13631. if (!ctx) {
  13632. return;
  13633. }
  13634. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13635. closesocket(ctx->listening_sockets[i].sock);
  13636. #if defined(USE_X_DOM_SOCKET)
  13637. /* For unix domain sockets, the socket name represents a file that has
  13638. * to be deleted. */
  13639. /* See
  13640. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13641. */
  13642. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13643. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13644. IGNORE_UNUSED_RESULT(
  13645. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13646. }
  13647. #endif
  13648. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13649. }
  13650. mg_free(ctx->listening_sockets);
  13651. ctx->listening_sockets = NULL;
  13652. mg_free(ctx->listening_socket_fds);
  13653. ctx->listening_socket_fds = NULL;
  13654. }
  13655. /* Valid listening port specification is: [ip_address:]port[s]
  13656. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13657. * Examples for IPv6: [::]:80, [::1]:80,
  13658. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13659. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13660. * In order to bind to both, IPv4 and IPv6, you can either add
  13661. * both ports using 8080,[::]:8080, or the short form +8080.
  13662. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13663. * one only accepting IPv4 the other only IPv6. +8080 creates
  13664. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13665. * environment, they might work differently, or might not work
  13666. * at all - it must be tested what options work best in the
  13667. * relevant network environment.
  13668. */
  13669. static int
  13670. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13671. {
  13672. unsigned int a, b, c, d;
  13673. unsigned port;
  13674. unsigned long portUL;
  13675. int len;
  13676. const char *cb;
  13677. char *endptr;
  13678. #if defined(USE_IPV6)
  13679. char buf[100] = {0};
  13680. #endif
  13681. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13682. * Also, all-zeroes in the socket address means binding to all addresses
  13683. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13684. memset(so, 0, sizeof(*so));
  13685. so->lsa.sin.sin_family = AF_INET;
  13686. *ip_version = 0;
  13687. /* Initialize len as invalid. */
  13688. port = 0;
  13689. len = 0;
  13690. /* Test for different ways to format this string */
  13691. if (sscanf(vec->ptr,
  13692. "%u.%u.%u.%u:%u%n",
  13693. &a,
  13694. &b,
  13695. &c,
  13696. &d,
  13697. &port,
  13698. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13699. // to an integer value, but function will not report
  13700. // conversion errors; consider using 'strtol' instead
  13701. == 5) {
  13702. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13703. so->lsa.sin.sin_addr.s_addr =
  13704. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13705. so->lsa.sin.sin_port = htons((uint16_t)port);
  13706. *ip_version = 4;
  13707. #if defined(USE_IPV6)
  13708. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13709. && ((size_t)len <= vec->len)
  13710. && mg_inet_pton(
  13711. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13712. /* IPv6 address, examples: see above */
  13713. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13714. */
  13715. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13716. *ip_version = 6;
  13717. #endif
  13718. } else if ((vec->ptr[0] == '+')
  13719. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13720. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13721. // string to an integer value, but function will not
  13722. // report conversion errors; consider using 'strtol'
  13723. // instead
  13724. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13725. /* Add 1 to len for the + character we skipped before */
  13726. len++;
  13727. #if defined(USE_IPV6)
  13728. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13729. so->lsa.sin6.sin6_family = AF_INET6;
  13730. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13731. *ip_version = 4 + 6;
  13732. #else
  13733. /* Bind to IPv4 only, since IPv6 is not built in. */
  13734. so->lsa.sin.sin_port = htons((uint16_t)port);
  13735. *ip_version = 4;
  13736. #endif
  13737. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13738. && (vec->ptr != endptr)) {
  13739. len = (int)(endptr - vec->ptr);
  13740. port = (uint16_t)portUL;
  13741. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13742. so->lsa.sin.sin_port = htons((uint16_t)port);
  13743. *ip_version = 4;
  13744. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13745. /* String could be a hostname. This check algorithm
  13746. * will only work for RFC 952 compliant hostnames,
  13747. * starting with a letter, containing only letters,
  13748. * digits and hyphen ('-'). Newer specs may allow
  13749. * more, but this is not guaranteed here, since it
  13750. * may interfere with rules for port option lists. */
  13751. /* According to RFC 1035, hostnames are restricted to 255 characters
  13752. * in total (63 between two dots). */
  13753. char hostname[256];
  13754. size_t hostnlen = (size_t)(cb - vec->ptr);
  13755. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13756. /* This would be invalid in any case */
  13757. *ip_version = 0;
  13758. return 0;
  13759. }
  13760. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13761. if (mg_inet_pton(
  13762. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13763. if (sscanf(cb + 1, "%u%n", &port, &len)
  13764. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13765. // string to an integer value, but function will not
  13766. // report conversion errors; consider using 'strtol'
  13767. // instead
  13768. *ip_version = 4;
  13769. so->lsa.sin.sin_port = htons((uint16_t)port);
  13770. len += (int)(hostnlen + 1);
  13771. } else {
  13772. len = 0;
  13773. }
  13774. #if defined(USE_IPV6)
  13775. } else if (mg_inet_pton(AF_INET6,
  13776. hostname,
  13777. &so->lsa.sin6,
  13778. sizeof(so->lsa.sin6),
  13779. 1)) {
  13780. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13781. *ip_version = 6;
  13782. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13783. len += (int)(hostnlen + 1);
  13784. } else {
  13785. len = 0;
  13786. }
  13787. #endif
  13788. } else {
  13789. len = 0;
  13790. }
  13791. #if defined(USE_X_DOM_SOCKET)
  13792. } else if (vec->ptr[0] == 'x') {
  13793. /* unix (linux) domain socket */
  13794. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13795. len = vec->len;
  13796. so->lsa.sun.sun_family = AF_UNIX;
  13797. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13798. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13799. port = 0;
  13800. *ip_version = 99;
  13801. } else {
  13802. /* String too long */
  13803. len = 0;
  13804. }
  13805. #endif
  13806. } else {
  13807. /* Parsing failure. */
  13808. len = 0;
  13809. }
  13810. /* sscanf and the option splitting code ensure the following condition
  13811. * Make sure the port is valid and vector ends with the port, 'o', 's', or
  13812. * 'r' */
  13813. if ((len > 0) && (is_valid_port(port))) {
  13814. int bad_suffix = 0;
  13815. size_t i;
  13816. /* Parse any suffix character(s) after the port number */
  13817. for (i = len; i < vec->len; i++) {
  13818. unsigned char *opt = NULL;
  13819. switch (vec->ptr[i]) {
  13820. case 'o':
  13821. opt = &so->is_optional;
  13822. break;
  13823. case 'r':
  13824. opt = &so->ssl_redir;
  13825. break;
  13826. case 's':
  13827. opt = &so->is_ssl;
  13828. break;
  13829. default: /* empty */
  13830. break;
  13831. }
  13832. if ((opt) && (*opt == 0))
  13833. *opt = 1;
  13834. else {
  13835. bad_suffix = 1;
  13836. break;
  13837. }
  13838. }
  13839. if ((bad_suffix == 0) && ((so->is_ssl == 0) || (so->ssl_redir == 0))) {
  13840. return 1;
  13841. }
  13842. }
  13843. /* Reset ip_version to 0 if there is an error */
  13844. *ip_version = 0;
  13845. return 0;
  13846. }
  13847. /* Is there any SSL port in use? */
  13848. static int
  13849. is_ssl_port_used(const char *ports)
  13850. {
  13851. if (ports) {
  13852. /* There are several different allowed syntax variants:
  13853. * - "80" for a single port using every network interface
  13854. * - "localhost:80" for a single port using only localhost
  13855. * - "80,localhost:8080" for two ports, one bound to localhost
  13856. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13857. * to IPv4 localhost, one to IPv6 localhost
  13858. * - "+80" use port 80 for IPv4 and IPv6
  13859. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13860. * for both: IPv4 and IPv4
  13861. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13862. * additionally port 8080 bound to localhost connections
  13863. *
  13864. * If we just look for 's' anywhere in the string, "localhost:80"
  13865. * will be detected as SSL (false positive).
  13866. * Looking for 's' after a digit may cause false positives in
  13867. * "my24service:8080".
  13868. * Looking from 's' backward if there are only ':' and numbers
  13869. * before will not work for "24service:8080" (non SSL, port 8080)
  13870. * or "24s" (SSL, port 24).
  13871. *
  13872. * Remark: Initially hostnames were not allowed to start with a
  13873. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13874. * Section 2.1).
  13875. *
  13876. * To get this correct, the entire string must be parsed as a whole,
  13877. * reading it as a list element for element and parsing with an
  13878. * algorithm equivalent to parse_port_string.
  13879. *
  13880. * In fact, we use local interface names here, not arbitrary
  13881. * hostnames, so in most cases the only name will be "localhost".
  13882. *
  13883. * So, for now, we use this simple algorithm, that may still return
  13884. * a false positive in bizarre cases.
  13885. */
  13886. int i;
  13887. int portslen = (int)strlen(ports);
  13888. char prevIsNumber = 0;
  13889. for (i = 0; i < portslen; i++) {
  13890. if (prevIsNumber) {
  13891. int suffixCharIdx = (ports[i] == 'o')
  13892. ? (i + 1)
  13893. : i; /* allow "os" and "or" suffixes */
  13894. if (ports[suffixCharIdx] == 's'
  13895. || ports[suffixCharIdx] == 'r') {
  13896. return 1;
  13897. }
  13898. }
  13899. if (ports[i] >= '0' && ports[i] <= '9') {
  13900. prevIsNumber = 1;
  13901. } else {
  13902. prevIsNumber = 0;
  13903. }
  13904. }
  13905. }
  13906. return 0;
  13907. }
  13908. static int
  13909. set_ports_option(struct mg_context *phys_ctx)
  13910. {
  13911. const char *list;
  13912. int on = 1;
  13913. #if defined(USE_IPV6)
  13914. int off = 0;
  13915. #endif
  13916. struct vec vec;
  13917. struct socket so, *ptr;
  13918. struct mg_pollfd *pfd;
  13919. union usa usa;
  13920. socklen_t len;
  13921. int ip_version;
  13922. int portsTotal = 0;
  13923. int portsOk = 0;
  13924. const char *opt_txt;
  13925. long opt_listen_backlog;
  13926. if (!phys_ctx) {
  13927. return 0;
  13928. }
  13929. memset(&so, 0, sizeof(so));
  13930. memset(&usa, 0, sizeof(usa));
  13931. len = sizeof(usa);
  13932. list = phys_ctx->dd.config[LISTENING_PORTS];
  13933. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13934. portsTotal++;
  13935. if (!parse_port_string(&vec, &so, &ip_version)) {
  13936. mg_cry_ctx_internal(
  13937. phys_ctx,
  13938. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13939. (int)vec.len,
  13940. vec.ptr,
  13941. portsTotal,
  13942. "[IP_ADDRESS:]PORT[s|r]");
  13943. continue;
  13944. }
  13945. #if !defined(NO_SSL)
  13946. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13947. mg_cry_ctx_internal(phys_ctx,
  13948. "Cannot add SSL socket (entry %i)",
  13949. portsTotal);
  13950. continue;
  13951. }
  13952. #endif
  13953. /* Create socket. */
  13954. /* For a list of protocol numbers (e.g., TCP==6) see:
  13955. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13956. */
  13957. if ((so.sock =
  13958. socket(so.lsa.sa.sa_family,
  13959. SOCK_STREAM,
  13960. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13961. == INVALID_SOCKET) {
  13962. mg_cry_ctx_internal(phys_ctx,
  13963. "cannot create socket (entry %i)",
  13964. portsTotal);
  13965. continue;
  13966. }
  13967. #if defined(_WIN32)
  13968. /* Windows SO_REUSEADDR lets many procs binds to a
  13969. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13970. * if someone already has the socket -- DTL */
  13971. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13972. * Windows might need a few seconds before
  13973. * the same port can be used again in the
  13974. * same process, so a short Sleep may be
  13975. * required between mg_stop and mg_start.
  13976. */
  13977. if (setsockopt(so.sock,
  13978. SOL_SOCKET,
  13979. SO_EXCLUSIVEADDRUSE,
  13980. (SOCK_OPT_TYPE)&on,
  13981. sizeof(on))
  13982. != 0) {
  13983. /* Set reuse option, but don't abort on errors. */
  13984. mg_cry_ctx_internal(
  13985. phys_ctx,
  13986. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13987. portsTotal);
  13988. }
  13989. #else
  13990. if (setsockopt(so.sock,
  13991. SOL_SOCKET,
  13992. SO_REUSEADDR,
  13993. (SOCK_OPT_TYPE)&on,
  13994. sizeof(on))
  13995. != 0) {
  13996. /* Set reuse option, but don't abort on errors. */
  13997. mg_cry_ctx_internal(
  13998. phys_ctx,
  13999. "cannot set socket option SO_REUSEADDR (entry %i)",
  14000. portsTotal);
  14001. }
  14002. #endif
  14003. #if defined(USE_X_DOM_SOCKET)
  14004. if (ip_version == 99) {
  14005. /* Unix domain socket */
  14006. } else
  14007. #endif
  14008. if (ip_version > 4) {
  14009. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  14010. #if defined(USE_IPV6)
  14011. if (ip_version > 6) {
  14012. if (so.lsa.sa.sa_family == AF_INET6
  14013. && setsockopt(so.sock,
  14014. IPPROTO_IPV6,
  14015. IPV6_V6ONLY,
  14016. (void *)&off,
  14017. sizeof(off))
  14018. != 0) {
  14019. /* Set IPv6 only option, but don't abort on errors. */
  14020. mg_cry_ctx_internal(phys_ctx,
  14021. "cannot set socket option "
  14022. "IPV6_V6ONLY=off (entry %i)",
  14023. portsTotal);
  14024. }
  14025. } else {
  14026. if (so.lsa.sa.sa_family == AF_INET6
  14027. && setsockopt(so.sock,
  14028. IPPROTO_IPV6,
  14029. IPV6_V6ONLY,
  14030. (void *)&on,
  14031. sizeof(on))
  14032. != 0) {
  14033. /* Set IPv6 only option, but don't abort on errors. */
  14034. mg_cry_ctx_internal(phys_ctx,
  14035. "cannot set socket option "
  14036. "IPV6_V6ONLY=on (entry %i)",
  14037. portsTotal);
  14038. }
  14039. }
  14040. #else
  14041. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  14042. closesocket(so.sock);
  14043. so.sock = INVALID_SOCKET;
  14044. continue;
  14045. #endif
  14046. }
  14047. if (so.lsa.sa.sa_family == AF_INET) {
  14048. len = sizeof(so.lsa.sin);
  14049. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14050. mg_cry_ctx_internal(phys_ctx,
  14051. "cannot bind to %.*s: %d (%s)",
  14052. (int)vec.len,
  14053. vec.ptr,
  14054. (int)ERRNO,
  14055. strerror(errno));
  14056. closesocket(so.sock);
  14057. so.sock = INVALID_SOCKET;
  14058. if (so.is_optional) {
  14059. portsOk++; /* it's okay if we couldn't bind, this port is
  14060. optional anyway */
  14061. }
  14062. continue;
  14063. }
  14064. }
  14065. #if defined(USE_IPV6)
  14066. else if (so.lsa.sa.sa_family == AF_INET6) {
  14067. len = sizeof(so.lsa.sin6);
  14068. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14069. mg_cry_ctx_internal(phys_ctx,
  14070. "cannot bind to IPv6 %.*s: %d (%s)",
  14071. (int)vec.len,
  14072. vec.ptr,
  14073. (int)ERRNO,
  14074. strerror(errno));
  14075. closesocket(so.sock);
  14076. so.sock = INVALID_SOCKET;
  14077. if (so.is_optional) {
  14078. portsOk++; /* it's okay if we couldn't bind, this port is
  14079. optional anyway */
  14080. }
  14081. continue;
  14082. }
  14083. }
  14084. #endif
  14085. #if defined(USE_X_DOM_SOCKET)
  14086. else if (so.lsa.sa.sa_family == AF_UNIX) {
  14087. len = sizeof(so.lsa.sun);
  14088. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14089. mg_cry_ctx_internal(phys_ctx,
  14090. "cannot bind to unix socket %s: %d (%s)",
  14091. so.lsa.sun.sun_path,
  14092. (int)ERRNO,
  14093. strerror(errno));
  14094. closesocket(so.sock);
  14095. so.sock = INVALID_SOCKET;
  14096. if (so.is_optional) {
  14097. portsOk++; /* it's okay if we couldn't bind, this port is
  14098. optional anyway */
  14099. }
  14100. continue;
  14101. }
  14102. }
  14103. #endif
  14104. else {
  14105. mg_cry_ctx_internal(
  14106. phys_ctx,
  14107. "cannot bind: address family not supported (entry %i)",
  14108. portsTotal);
  14109. closesocket(so.sock);
  14110. so.sock = INVALID_SOCKET;
  14111. continue;
  14112. }
  14113. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  14114. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  14115. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  14116. mg_cry_ctx_internal(phys_ctx,
  14117. "%s value \"%s\" is invalid",
  14118. config_options[LISTEN_BACKLOG_SIZE].name,
  14119. opt_txt);
  14120. closesocket(so.sock);
  14121. so.sock = INVALID_SOCKET;
  14122. continue;
  14123. }
  14124. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  14125. mg_cry_ctx_internal(phys_ctx,
  14126. "cannot listen to %.*s: %d (%s)",
  14127. (int)vec.len,
  14128. vec.ptr,
  14129. (int)ERRNO,
  14130. strerror(errno));
  14131. closesocket(so.sock);
  14132. so.sock = INVALID_SOCKET;
  14133. continue;
  14134. }
  14135. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  14136. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  14137. int err = (int)ERRNO;
  14138. mg_cry_ctx_internal(phys_ctx,
  14139. "call to getsockname failed %.*s: %d (%s)",
  14140. (int)vec.len,
  14141. vec.ptr,
  14142. err,
  14143. strerror(errno));
  14144. closesocket(so.sock);
  14145. so.sock = INVALID_SOCKET;
  14146. continue;
  14147. }
  14148. /* Update lsa port in case of random free ports */
  14149. #if defined(USE_IPV6)
  14150. if (so.lsa.sa.sa_family == AF_INET6) {
  14151. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  14152. } else
  14153. #endif
  14154. {
  14155. so.lsa.sin.sin_port = usa.sin.sin_port;
  14156. }
  14157. if ((ptr = (struct socket *)
  14158. mg_realloc_ctx(phys_ctx->listening_sockets,
  14159. (phys_ctx->num_listening_sockets + 1)
  14160. * sizeof(phys_ctx->listening_sockets[0]),
  14161. phys_ctx))
  14162. == NULL) {
  14163. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14164. closesocket(so.sock);
  14165. so.sock = INVALID_SOCKET;
  14166. continue;
  14167. }
  14168. /* The +2 below includes the original +1 (for the socket we're about to
  14169. * add), plus another +1 for the thread_shutdown_notification_socket
  14170. * that we'll also want to poll() on so that mg_stop() can return
  14171. * quickly
  14172. */
  14173. if ((pfd = (struct mg_pollfd *)
  14174. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  14175. (phys_ctx->num_listening_sockets + 2)
  14176. * sizeof(phys_ctx->listening_socket_fds[0]),
  14177. phys_ctx))
  14178. == NULL) {
  14179. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14180. closesocket(so.sock);
  14181. so.sock = INVALID_SOCKET;
  14182. mg_free(ptr);
  14183. continue;
  14184. }
  14185. set_close_on_exec(so.sock, NULL, phys_ctx);
  14186. phys_ctx->listening_sockets = ptr;
  14187. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  14188. phys_ctx->listening_socket_fds = pfd;
  14189. phys_ctx->num_listening_sockets++;
  14190. portsOk++;
  14191. }
  14192. if (portsOk != portsTotal) {
  14193. close_all_listening_sockets(phys_ctx);
  14194. portsOk = 0;
  14195. }
  14196. return portsOk;
  14197. }
  14198. static const char *
  14199. header_val(const struct mg_connection *conn, const char *header)
  14200. {
  14201. const char *header_value;
  14202. if ((header_value = mg_get_header(conn, header)) == NULL) {
  14203. return "-";
  14204. } else {
  14205. return header_value;
  14206. }
  14207. }
  14208. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  14209. #include "external_log_access.inl"
  14210. #elif !defined(NO_FILESYSTEMS)
  14211. static void
  14212. log_access(const struct mg_connection *conn)
  14213. {
  14214. const struct mg_request_info *ri;
  14215. struct mg_file fi;
  14216. char date[64], src_addr[IP_ADDR_STR_LEN];
  14217. #if defined(REENTRANT_TIME)
  14218. struct tm _tm;
  14219. struct tm *tm = &_tm;
  14220. #else
  14221. struct tm *tm;
  14222. #endif
  14223. const char *referer;
  14224. const char *user_agent;
  14225. char log_buf[4096];
  14226. if (!conn || !conn->dom_ctx) {
  14227. return;
  14228. }
  14229. /* Set log message to "empty" */
  14230. log_buf[0] = 0;
  14231. #if defined(USE_LUA)
  14232. if (conn->phys_ctx->lua_bg_log_available) {
  14233. int ret;
  14234. struct mg_context *ctx = conn->phys_ctx;
  14235. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14236. pthread_mutex_lock(&ctx->lua_bg_mutex);
  14237. /* call "log()" in Lua */
  14238. lua_getglobal(lstate, "log");
  14239. prepare_lua_request_info_inner(conn, lstate);
  14240. push_lua_response_log_data(conn, lstate);
  14241. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  14242. if (ret == 0) {
  14243. int t = lua_type(lstate, -1);
  14244. if (t == LUA_TBOOLEAN) {
  14245. if (lua_toboolean(lstate, -1) == 0) {
  14246. /* log() returned false: do not log */
  14247. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14248. return;
  14249. }
  14250. /* log returned true: continue logging */
  14251. } else if (t == LUA_TSTRING) {
  14252. size_t len;
  14253. const char *txt = lua_tolstring(lstate, -1, &len);
  14254. if ((len == 0) || (*txt == 0)) {
  14255. /* log() returned empty string: do not log */
  14256. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14257. return;
  14258. }
  14259. /* Copy test from Lua into log_buf */
  14260. if (len >= sizeof(log_buf)) {
  14261. len = sizeof(log_buf) - 1;
  14262. }
  14263. memcpy(log_buf, txt, len);
  14264. log_buf[len] = 0;
  14265. }
  14266. } else {
  14267. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14268. }
  14269. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14270. }
  14271. #endif
  14272. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14273. if (mg_fopen(conn,
  14274. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14275. MG_FOPEN_MODE_APPEND,
  14276. &fi)
  14277. == 0) {
  14278. fi.access.fp = NULL;
  14279. }
  14280. } else {
  14281. fi.access.fp = NULL;
  14282. }
  14283. /* Log is written to a file and/or a callback. If both are not set,
  14284. * executing the rest of the function is pointless. */
  14285. if ((fi.access.fp == NULL)
  14286. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14287. return;
  14288. }
  14289. /* If we did not get a log message from Lua, create it here. */
  14290. if (!log_buf[0]) {
  14291. #if defined(REENTRANT_TIME)
  14292. localtime_r(&conn->conn_birth_time, tm);
  14293. #else
  14294. tm = localtime(&conn->conn_birth_time);
  14295. #endif
  14296. if (tm != NULL) {
  14297. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14298. } else {
  14299. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14300. }
  14301. ri = &conn->request_info;
  14302. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14303. referer = header_val(conn, "Referer");
  14304. user_agent = header_val(conn, "User-Agent");
  14305. mg_snprintf(conn,
  14306. NULL, /* Ignore truncation in access log */
  14307. log_buf,
  14308. sizeof(log_buf),
  14309. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14310. " %s %s",
  14311. src_addr,
  14312. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14313. date,
  14314. ri->request_method ? ri->request_method : "-",
  14315. ri->request_uri ? ri->request_uri : "-",
  14316. ri->query_string ? "?" : "",
  14317. ri->query_string ? ri->query_string : "",
  14318. ri->http_version,
  14319. conn->status_code,
  14320. conn->num_bytes_sent,
  14321. referer,
  14322. user_agent);
  14323. }
  14324. /* Here we have a log message in log_buf. Call the callback */
  14325. if (conn->phys_ctx->callbacks.log_access) {
  14326. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14327. /* do not log if callback returns non-zero */
  14328. if (fi.access.fp) {
  14329. mg_fclose(&fi.access);
  14330. }
  14331. return;
  14332. }
  14333. }
  14334. /* Store in file */
  14335. if (fi.access.fp) {
  14336. int ok = 1;
  14337. flockfile(fi.access.fp);
  14338. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14339. ok = 0;
  14340. }
  14341. if (fflush(fi.access.fp) != 0) {
  14342. ok = 0;
  14343. }
  14344. funlockfile(fi.access.fp);
  14345. if (mg_fclose(&fi.access) != 0) {
  14346. ok = 0;
  14347. }
  14348. if (!ok) {
  14349. mg_cry_internal(conn,
  14350. "Error writing log file %s",
  14351. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14352. }
  14353. }
  14354. }
  14355. #else
  14356. #error "Either enable filesystems or provide a custom log_access implementation"
  14357. #endif /* Externally provided function */
  14358. /* Verify given socket address against the ACL.
  14359. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14360. */
  14361. static int
  14362. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14363. {
  14364. int allowed, flag, matched;
  14365. struct vec vec;
  14366. if (phys_ctx) {
  14367. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14368. /* If any ACL is set, deny by default */
  14369. allowed = (list == NULL) ? '+' : '-';
  14370. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14371. flag = vec.ptr[0];
  14372. matched = -1;
  14373. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14374. vec.ptr++;
  14375. vec.len--;
  14376. matched = parse_match_net(&vec, sa, 1);
  14377. }
  14378. if (matched < 0) {
  14379. mg_cry_ctx_internal(phys_ctx,
  14380. "%s: subnet must be [+|-]IP-addr[/x]",
  14381. __func__);
  14382. return -1;
  14383. }
  14384. if (matched) {
  14385. allowed = flag;
  14386. }
  14387. }
  14388. return allowed == '+';
  14389. }
  14390. return -1;
  14391. }
  14392. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14393. static int
  14394. set_uid_option(struct mg_context *phys_ctx)
  14395. {
  14396. int success = 0;
  14397. if (phys_ctx) {
  14398. /* We are currently running as curr_uid. */
  14399. const uid_t curr_uid = getuid();
  14400. /* If set, we want to run as run_as_user. */
  14401. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14402. const struct passwd *to_pw = NULL;
  14403. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14404. /* run_as_user does not exist on the system. We can't proceed
  14405. * further. */
  14406. mg_cry_ctx_internal(phys_ctx,
  14407. "%s: unknown user [%s]",
  14408. __func__,
  14409. run_as_user);
  14410. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14411. /* There was either no request to change user, or we're already
  14412. * running as run_as_user. Nothing else to do.
  14413. */
  14414. success = 1;
  14415. } else {
  14416. /* Valid change request. */
  14417. if (setgid(to_pw->pw_gid) == -1) {
  14418. mg_cry_ctx_internal(phys_ctx,
  14419. "%s: setgid(%s): %s",
  14420. __func__,
  14421. run_as_user,
  14422. strerror(errno));
  14423. } else if (setgroups(0, NULL) == -1) {
  14424. mg_cry_ctx_internal(phys_ctx,
  14425. "%s: setgroups(): %s",
  14426. __func__,
  14427. strerror(errno));
  14428. } else if (setuid(to_pw->pw_uid) == -1) {
  14429. mg_cry_ctx_internal(phys_ctx,
  14430. "%s: setuid(%s): %s",
  14431. __func__,
  14432. run_as_user,
  14433. strerror(errno));
  14434. } else {
  14435. success = 1;
  14436. }
  14437. }
  14438. }
  14439. return success;
  14440. }
  14441. #endif /* !_WIN32 */
  14442. static void
  14443. tls_dtor(void *key)
  14444. {
  14445. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14446. /* key == pthread_getspecific(sTlsKey); */
  14447. if (tls) {
  14448. if (tls->is_master == 2) {
  14449. tls->is_master = -3; /* Mark memory as dead */
  14450. mg_free(tls);
  14451. }
  14452. }
  14453. pthread_setspecific(sTlsKey, NULL);
  14454. }
  14455. #if defined(USE_MBEDTLS)
  14456. /* Check if SSL is required.
  14457. * If so, set up ctx->ssl_ctx pointer. */
  14458. static int
  14459. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14460. {
  14461. if (!phys_ctx) {
  14462. return 0;
  14463. }
  14464. if (!dom_ctx) {
  14465. dom_ctx = &(phys_ctx->dd);
  14466. }
  14467. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14468. /* No SSL port is set. No need to setup SSL. */
  14469. return 1;
  14470. }
  14471. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14472. if (dom_ctx->ssl_ctx == NULL) {
  14473. fprintf(stderr, "ssl_ctx malloc failed\n");
  14474. return 0;
  14475. }
  14476. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14477. == 0
  14478. ? 1
  14479. : 0;
  14480. }
  14481. #elif defined(USE_GNUTLS)
  14482. /* Check if SSL is required.
  14483. * If so, set up ctx->ssl_ctx pointer. */
  14484. static int
  14485. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14486. {
  14487. if (!phys_ctx) {
  14488. return 0;
  14489. }
  14490. if (!dom_ctx) {
  14491. dom_ctx = &(phys_ctx->dd);
  14492. }
  14493. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14494. /* No SSL port is set. No need to setup SSL. */
  14495. return 1;
  14496. }
  14497. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14498. if (dom_ctx->ssl_ctx == NULL) {
  14499. fprintf(stderr, "ssl_ctx malloc failed\n");
  14500. return 0;
  14501. }
  14502. return gtls_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14503. == 0
  14504. ? 1
  14505. : 0;
  14506. }
  14507. #elif !defined(NO_SSL)
  14508. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14509. struct mg_domain_context *dom_ctx,
  14510. const char *pem,
  14511. const char *chain);
  14512. static const char *ssl_error(void);
  14513. static int
  14514. refresh_trust(struct mg_connection *conn)
  14515. {
  14516. struct stat cert_buf;
  14517. int64_t t = 0;
  14518. const char *pem;
  14519. const char *chain;
  14520. int should_verify_peer;
  14521. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14522. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14523. * refresh_trust still can not work. */
  14524. return 0;
  14525. }
  14526. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14527. if (chain == NULL) {
  14528. /* pem is not NULL here */
  14529. chain = pem;
  14530. }
  14531. if (*chain == 0) {
  14532. chain = NULL;
  14533. }
  14534. if (stat(pem, &cert_buf) != -1) {
  14535. t = (int64_t)cert_buf.st_mtime;
  14536. }
  14537. mg_lock_context(conn->phys_ctx);
  14538. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14539. conn->dom_ctx->ssl_cert_last_mtime = t;
  14540. should_verify_peer = 0;
  14541. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14542. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14543. == 0) {
  14544. should_verify_peer = 1;
  14545. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14546. "optional")
  14547. == 0) {
  14548. should_verify_peer = 1;
  14549. }
  14550. }
  14551. if (should_verify_peer) {
  14552. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14553. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14554. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14555. ca_file,
  14556. ca_path)
  14557. != 1) {
  14558. mg_unlock_context(conn->phys_ctx);
  14559. mg_cry_ctx_internal(
  14560. conn->phys_ctx,
  14561. "SSL_CTX_load_verify_locations error: %s "
  14562. "ssl_verify_peer requires setting "
  14563. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14564. "present in "
  14565. "the .conf file?",
  14566. ssl_error());
  14567. return 0;
  14568. }
  14569. }
  14570. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14571. mg_unlock_context(conn->phys_ctx);
  14572. return 0;
  14573. }
  14574. }
  14575. mg_unlock_context(conn->phys_ctx);
  14576. return 1;
  14577. }
  14578. #if defined(OPENSSL_API_1_1)
  14579. #else
  14580. static pthread_mutex_t *ssl_mutexes;
  14581. #endif /* OPENSSL_API_1_1 */
  14582. static int
  14583. sslize(struct mg_connection *conn,
  14584. int (*func)(SSL *),
  14585. const struct mg_client_options *client_options)
  14586. {
  14587. int ret, err;
  14588. int short_trust;
  14589. unsigned timeout = 1024;
  14590. unsigned i;
  14591. if (!conn) {
  14592. return 0;
  14593. }
  14594. short_trust =
  14595. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14596. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14597. if (short_trust) {
  14598. int trust_ret = refresh_trust(conn);
  14599. if (!trust_ret) {
  14600. return trust_ret;
  14601. }
  14602. }
  14603. mg_lock_context(conn->phys_ctx);
  14604. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14605. mg_unlock_context(conn->phys_ctx);
  14606. if (conn->ssl == NULL) {
  14607. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14608. OPENSSL_REMOVE_THREAD_STATE();
  14609. return 0;
  14610. }
  14611. SSL_set_app_data(conn->ssl, (char *)conn);
  14612. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14613. if (ret != 1) {
  14614. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14615. SSL_free(conn->ssl);
  14616. conn->ssl = NULL;
  14617. OPENSSL_REMOVE_THREAD_STATE();
  14618. return 0;
  14619. }
  14620. if (client_options) {
  14621. if (client_options->host_name) {
  14622. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14623. }
  14624. }
  14625. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14626. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14627. /* NOTE: The loop below acts as a back-off, so we can end
  14628. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14629. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14630. if (to >= 0) {
  14631. timeout = (unsigned)to;
  14632. }
  14633. }
  14634. /* SSL functions may fail and require to be called again:
  14635. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14636. * Here "func" could be SSL_connect or SSL_accept. */
  14637. for (i = 0; i <= timeout; i += 50) {
  14638. ERR_clear_error();
  14639. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14640. ret = func(conn->ssl);
  14641. if (ret != 1) {
  14642. err = SSL_get_error(conn->ssl, ret);
  14643. if ((err == SSL_ERROR_WANT_CONNECT)
  14644. || (err == SSL_ERROR_WANT_ACCEPT)
  14645. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14646. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14647. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14648. /* Don't wait if the server is going to be stopped. */
  14649. break;
  14650. }
  14651. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14652. /* Simply retry the function call. */
  14653. mg_sleep(50);
  14654. } else {
  14655. /* Need to retry the function call "later".
  14656. * See https://linux.die.net/man/3/ssl_get_error
  14657. * This is typical for non-blocking sockets. */
  14658. struct mg_pollfd pfd[2];
  14659. int pollres;
  14660. unsigned int num_sock = 1;
  14661. pfd[0].fd = conn->client.sock;
  14662. pfd[0].events = ((err == SSL_ERROR_WANT_CONNECT)
  14663. || (err == SSL_ERROR_WANT_WRITE))
  14664. ? POLLOUT
  14665. : POLLIN;
  14666. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14667. pfd[num_sock].fd =
  14668. conn->phys_ctx->thread_shutdown_notification_socket;
  14669. pfd[num_sock].events = POLLIN;
  14670. num_sock++;
  14671. }
  14672. pollres = mg_poll(pfd,
  14673. num_sock,
  14674. 50,
  14675. &(conn->phys_ctx->stop_flag));
  14676. if (pollres < 0) {
  14677. /* Break if error occurred (-1)
  14678. * or server shutdown (-2) */
  14679. break;
  14680. }
  14681. }
  14682. } else if (err == SSL_ERROR_SYSCALL) {
  14683. /* This is an IO error. Look at errno. */
  14684. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14685. break;
  14686. } else {
  14687. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14688. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14689. break;
  14690. }
  14691. } else {
  14692. /* success */
  14693. break;
  14694. }
  14695. }
  14696. ERR_clear_error();
  14697. if (ret != 1) {
  14698. SSL_free(conn->ssl);
  14699. conn->ssl = NULL;
  14700. OPENSSL_REMOVE_THREAD_STATE();
  14701. return 0;
  14702. }
  14703. return 1;
  14704. }
  14705. /* Return OpenSSL error message (from CRYPTO lib) */
  14706. static const char *
  14707. ssl_error(void)
  14708. {
  14709. unsigned long err;
  14710. err = ERR_get_error();
  14711. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14712. }
  14713. static int
  14714. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14715. {
  14716. int i;
  14717. const char hexdigit[] = "0123456789abcdef";
  14718. if ((memlen <= 0) || (buflen <= 0)) {
  14719. return 0;
  14720. }
  14721. if (buflen < (3 * memlen)) {
  14722. return 0;
  14723. }
  14724. for (i = 0; i < memlen; i++) {
  14725. if (i > 0) {
  14726. buf[3 * i - 1] = ' ';
  14727. }
  14728. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14729. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14730. }
  14731. buf[3 * memlen - 1] = 0;
  14732. return 1;
  14733. }
  14734. static int
  14735. ssl_get_client_cert_info(const struct mg_connection *conn,
  14736. struct mg_client_cert *client_cert)
  14737. {
  14738. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14739. if (cert) {
  14740. char str_buf[1024];
  14741. unsigned char buf[256];
  14742. char *str_serial = NULL;
  14743. unsigned int ulen;
  14744. int ilen;
  14745. unsigned char *tmp_buf;
  14746. unsigned char *tmp_p;
  14747. /* Handle to algorithm used for fingerprint */
  14748. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14749. /* Get Subject and issuer */
  14750. X509_NAME *subj = X509_get_subject_name(cert);
  14751. X509_NAME *iss = X509_get_issuer_name(cert);
  14752. /* Get serial number */
  14753. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14754. /* Translate serial number to a hex string */
  14755. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14756. if (serial_bn) {
  14757. str_serial = BN_bn2hex(serial_bn);
  14758. BN_free(serial_bn);
  14759. }
  14760. client_cert->serial =
  14761. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14762. /* Translate subject and issuer to a string */
  14763. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14764. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14765. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14766. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14767. /* Calculate SHA1 fingerprint and store as a hex string */
  14768. ulen = 0;
  14769. /* ASN1_digest is deprecated. Do the calculation manually,
  14770. * using EVP_Digest. */
  14771. ilen = i2d_X509(cert, NULL);
  14772. tmp_buf = (ilen > 0)
  14773. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14774. conn->phys_ctx)
  14775. : NULL;
  14776. if (tmp_buf) {
  14777. tmp_p = tmp_buf;
  14778. (void)i2d_X509(cert, &tmp_p);
  14779. if (!EVP_Digest(
  14780. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14781. ulen = 0;
  14782. }
  14783. mg_free(tmp_buf);
  14784. }
  14785. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14786. *str_buf = 0;
  14787. }
  14788. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14789. client_cert->peer_cert = (void *)cert;
  14790. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14791. * see https://linux.die.net/man/3/bn_bn2hex */
  14792. OPENSSL_free(str_serial);
  14793. return 1;
  14794. }
  14795. return 0;
  14796. }
  14797. #if defined(OPENSSL_API_1_1)
  14798. #else
  14799. static void
  14800. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14801. {
  14802. (void)line;
  14803. (void)file;
  14804. if (mode & 1) {
  14805. /* 1 is CRYPTO_LOCK */
  14806. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14807. } else {
  14808. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14809. }
  14810. }
  14811. #endif /* OPENSSL_API_1_1 */
  14812. #if !defined(NO_SSL_DL)
  14813. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14814. static void *
  14815. load_tls_dll(char *ebuf,
  14816. size_t ebuf_len,
  14817. const char *dll_name,
  14818. struct ssl_func *sw,
  14819. int *feature_missing)
  14820. {
  14821. union {
  14822. void *p;
  14823. void (*fp)(void);
  14824. } u;
  14825. void *dll_handle;
  14826. struct ssl_func *fp;
  14827. int ok;
  14828. int truncated = 0;
  14829. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14830. mg_snprintf(NULL,
  14831. NULL, /* No truncation check for ebuf */
  14832. ebuf,
  14833. ebuf_len,
  14834. "%s: cannot load %s",
  14835. __func__,
  14836. dll_name);
  14837. return NULL;
  14838. }
  14839. ok = 1;
  14840. for (fp = sw; fp->name != NULL; fp++) {
  14841. #if defined(_WIN32)
  14842. /* GetProcAddress() returns pointer to function */
  14843. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14844. #else
  14845. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14846. * pointers to function pointers. We need to use a union to make a
  14847. * cast. */
  14848. u.p = dlsym(dll_handle, fp->name);
  14849. #endif /* _WIN32 */
  14850. /* Set pointer (might be NULL) */
  14851. fp->ptr = u.fp;
  14852. if (u.fp == NULL) {
  14853. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14854. if (feature_missing) {
  14855. feature_missing[fp->required]++;
  14856. }
  14857. if (fp->required == TLS_Mandatory) {
  14858. /* Mandatory function is missing */
  14859. if (ok) {
  14860. /* This is the first missing function.
  14861. * Create a new error message. */
  14862. mg_snprintf(NULL,
  14863. &truncated,
  14864. ebuf,
  14865. ebuf_len,
  14866. "%s: %s: cannot find %s",
  14867. __func__,
  14868. dll_name,
  14869. fp->name);
  14870. ok = 0;
  14871. } else {
  14872. /* This is yet anothermissing function.
  14873. * Append existing error message. */
  14874. size_t cur_len = strlen(ebuf);
  14875. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14876. mg_snprintf(NULL,
  14877. &truncated,
  14878. ebuf + cur_len,
  14879. ebuf_len - cur_len - 3,
  14880. ", %s",
  14881. fp->name);
  14882. if (truncated) {
  14883. /* If truncated, add "..." */
  14884. strcat(ebuf, "...");
  14885. }
  14886. }
  14887. }
  14888. }
  14889. }
  14890. }
  14891. if (!ok) {
  14892. (void)dlclose(dll_handle);
  14893. return NULL;
  14894. }
  14895. return dll_handle;
  14896. }
  14897. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14898. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14899. #endif /* NO_SSL_DL */
  14900. #if defined(SSL_ALREADY_INITIALIZED)
  14901. static volatile ptrdiff_t cryptolib_users =
  14902. 1; /* Reference counter for crypto library. */
  14903. #else
  14904. static volatile ptrdiff_t cryptolib_users =
  14905. 0; /* Reference counter for crypto library. */
  14906. #endif
  14907. static int
  14908. initialize_openssl(char *ebuf, size_t ebuf_len)
  14909. {
  14910. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14911. int i, num_locks;
  14912. size_t size;
  14913. #endif
  14914. if (ebuf_len > 0) {
  14915. ebuf[0] = 0;
  14916. }
  14917. #if !defined(NO_SSL_DL)
  14918. if (!cryptolib_dll_handle) {
  14919. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14920. cryptolib_dll_handle = load_tls_dll(
  14921. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14922. if (!cryptolib_dll_handle) {
  14923. mg_snprintf(NULL,
  14924. NULL, /* No truncation check for ebuf */
  14925. ebuf,
  14926. ebuf_len,
  14927. "%s: error loading library %s",
  14928. __func__,
  14929. CRYPTO_LIB);
  14930. DEBUG_TRACE("%s", ebuf);
  14931. return 0;
  14932. }
  14933. }
  14934. #endif /* NO_SSL_DL */
  14935. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14936. return 1;
  14937. }
  14938. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14939. /* Initialize locking callbacks, needed for thread safety.
  14940. * http://www.openssl.org/support/faq.html#PROG1
  14941. */
  14942. num_locks = CRYPTO_num_locks();
  14943. if (num_locks < 0) {
  14944. num_locks = 0;
  14945. }
  14946. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14947. /* allocate mutex array, if required */
  14948. if (num_locks == 0) {
  14949. /* No mutex array required */
  14950. ssl_mutexes = NULL;
  14951. } else {
  14952. /* Mutex array required - allocate it */
  14953. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14954. /* Check OOM */
  14955. if (ssl_mutexes == NULL) {
  14956. mg_snprintf(NULL,
  14957. NULL, /* No truncation check for ebuf */
  14958. ebuf,
  14959. ebuf_len,
  14960. "%s: cannot allocate mutexes: %s",
  14961. __func__,
  14962. ssl_error());
  14963. DEBUG_TRACE("%s", ebuf);
  14964. return 0;
  14965. }
  14966. /* initialize mutex array */
  14967. for (i = 0; i < num_locks; i++) {
  14968. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14969. mg_snprintf(NULL,
  14970. NULL, /* No truncation check for ebuf */
  14971. ebuf,
  14972. ebuf_len,
  14973. "%s: error initializing mutex %i of %i",
  14974. __func__,
  14975. i,
  14976. num_locks);
  14977. DEBUG_TRACE("%s", ebuf);
  14978. mg_free(ssl_mutexes);
  14979. return 0;
  14980. }
  14981. }
  14982. }
  14983. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14984. CRYPTO_set_id_callback(&mg_current_thread_id);
  14985. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14986. #if !defined(NO_SSL_DL)
  14987. if (!ssllib_dll_handle) {
  14988. ssllib_dll_handle =
  14989. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14990. if (!ssllib_dll_handle) {
  14991. #if !defined(OPENSSL_API_1_1)
  14992. mg_free(ssl_mutexes);
  14993. #endif
  14994. DEBUG_TRACE("%s", ebuf);
  14995. return 0;
  14996. }
  14997. }
  14998. #endif /* NO_SSL_DL */
  14999. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15000. && !defined(NO_SSL_DL)
  15001. /* Initialize SSL library */
  15002. OPENSSL_init_ssl(0, NULL);
  15003. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  15004. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  15005. NULL);
  15006. #else
  15007. /* Initialize SSL library */
  15008. SSL_library_init();
  15009. SSL_load_error_strings();
  15010. #endif
  15011. return 1;
  15012. }
  15013. static int
  15014. ssl_use_pem_file(struct mg_context *phys_ctx,
  15015. struct mg_domain_context *dom_ctx,
  15016. const char *pem,
  15017. const char *chain)
  15018. {
  15019. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15020. mg_cry_ctx_internal(phys_ctx,
  15021. "%s: cannot open certificate file %s: %s",
  15022. __func__,
  15023. pem,
  15024. ssl_error());
  15025. return 0;
  15026. }
  15027. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  15028. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15029. mg_cry_ctx_internal(phys_ctx,
  15030. "%s: cannot open private key file %s: %s",
  15031. __func__,
  15032. pem,
  15033. ssl_error());
  15034. return 0;
  15035. }
  15036. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  15037. mg_cry_ctx_internal(phys_ctx,
  15038. "%s: certificate and private key do not match: %s",
  15039. __func__,
  15040. pem);
  15041. return 0;
  15042. }
  15043. /* In contrast to OpenSSL, wolfSSL does not support certificate
  15044. * chain files that contain private keys and certificates in
  15045. * SSL_CTX_use_certificate_chain_file.
  15046. * The CivetWeb-Server used pem-Files that contained both information.
  15047. * In order to make wolfSSL work, it is split in two files.
  15048. * One file that contains key and certificate used by the server and
  15049. * an optional chain file for the ssl stack.
  15050. */
  15051. if (chain) {
  15052. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  15053. mg_cry_ctx_internal(phys_ctx,
  15054. "%s: cannot use certificate chain file %s: %s",
  15055. __func__,
  15056. chain,
  15057. ssl_error());
  15058. return 0;
  15059. }
  15060. }
  15061. return 1;
  15062. }
  15063. #if defined(OPENSSL_API_1_1)
  15064. static unsigned long
  15065. ssl_get_protocol(int version_id)
  15066. {
  15067. long unsigned ret = (long unsigned)SSL_OP_ALL;
  15068. if (version_id > 0)
  15069. ret |= SSL_OP_NO_SSLv2;
  15070. if (version_id > 1)
  15071. ret |= SSL_OP_NO_SSLv3;
  15072. if (version_id > 2)
  15073. ret |= SSL_OP_NO_TLSv1;
  15074. if (version_id > 3)
  15075. ret |= SSL_OP_NO_TLSv1_1;
  15076. if (version_id > 4)
  15077. ret |= SSL_OP_NO_TLSv1_2;
  15078. #if defined(SSL_OP_NO_TLSv1_3)
  15079. if (version_id > 5)
  15080. ret |= SSL_OP_NO_TLSv1_3;
  15081. #endif
  15082. return ret;
  15083. }
  15084. #else
  15085. static long
  15086. ssl_get_protocol(int version_id)
  15087. {
  15088. unsigned long ret = (unsigned long)SSL_OP_ALL;
  15089. if (version_id > 0)
  15090. ret |= SSL_OP_NO_SSLv2;
  15091. if (version_id > 1)
  15092. ret |= SSL_OP_NO_SSLv3;
  15093. if (version_id > 2)
  15094. ret |= SSL_OP_NO_TLSv1;
  15095. if (version_id > 3)
  15096. ret |= SSL_OP_NO_TLSv1_1;
  15097. if (version_id > 4)
  15098. ret |= SSL_OP_NO_TLSv1_2;
  15099. #if defined(SSL_OP_NO_TLSv1_3)
  15100. if (version_id > 5)
  15101. ret |= SSL_OP_NO_TLSv1_3;
  15102. #endif
  15103. return (long)ret;
  15104. }
  15105. #endif /* OPENSSL_API_1_1 */
  15106. /* SSL callback documentation:
  15107. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  15108. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  15109. * https://linux.die.net/man/3/ssl_set_info_callback */
  15110. /* Note: There is no "const" for the first argument in the documentation
  15111. * examples, however some (maybe most, but not all) headers of OpenSSL
  15112. * versions / OpenSSL compatibility layers have it. Having a different
  15113. * definition will cause a warning in C and an error in C++. Use "const SSL
  15114. * *", while automatic conversion from "SSL *" works for all compilers,
  15115. * but not other way around */
  15116. static void
  15117. ssl_info_callback(const SSL *ssl, int what, int ret)
  15118. {
  15119. (void)ret;
  15120. if (what & SSL_CB_HANDSHAKE_START) {
  15121. SSL_get_app_data(ssl);
  15122. }
  15123. if (what & SSL_CB_HANDSHAKE_DONE) {
  15124. /* TODO: check for openSSL 1.1 */
  15125. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  15126. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  15127. }
  15128. }
  15129. static int
  15130. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  15131. {
  15132. #if defined(GCC_DIAGNOSTIC)
  15133. #pragma GCC diagnostic push
  15134. #pragma GCC diagnostic ignored "-Wcast-align"
  15135. #endif /* defined(GCC_DIAGNOSTIC) */
  15136. /* We used an aligned pointer in SSL_set_app_data */
  15137. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  15138. #if defined(GCC_DIAGNOSTIC)
  15139. #pragma GCC diagnostic pop
  15140. #endif /* defined(GCC_DIAGNOSTIC) */
  15141. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15142. (void)ad;
  15143. (void)arg;
  15144. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15145. DEBUG_ASSERT(0);
  15146. return SSL_TLSEXT_ERR_NOACK;
  15147. }
  15148. conn->dom_ctx = &(conn->phys_ctx->dd);
  15149. /* Old clients (Win XP) will not support SNI. Then, there
  15150. * is no server name available in the request - we can
  15151. * only work with the default certificate.
  15152. * Multiple HTTPS hosts on one IP+port are only possible
  15153. * with a certificate containing all alternative names.
  15154. */
  15155. if ((servername == NULL) || (*servername == 0)) {
  15156. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  15157. mg_lock_context(conn->phys_ctx);
  15158. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15159. mg_unlock_context(conn->phys_ctx);
  15160. return SSL_TLSEXT_ERR_NOACK;
  15161. }
  15162. DEBUG_TRACE("TLS connection to host %s", servername);
  15163. while (conn->dom_ctx) {
  15164. if (!mg_strcasecmp(servername,
  15165. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  15166. /* Found matching domain */
  15167. DEBUG_TRACE("TLS domain %s found",
  15168. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  15169. break;
  15170. }
  15171. mg_lock_context(conn->phys_ctx);
  15172. conn->dom_ctx = conn->dom_ctx->next;
  15173. mg_unlock_context(conn->phys_ctx);
  15174. }
  15175. if (conn->dom_ctx == NULL) {
  15176. /* Default domain */
  15177. DEBUG_TRACE("TLS default domain %s used",
  15178. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  15179. conn->dom_ctx = &(conn->phys_ctx->dd);
  15180. }
  15181. mg_lock_context(conn->phys_ctx);
  15182. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15183. mg_unlock_context(conn->phys_ctx);
  15184. return SSL_TLSEXT_ERR_OK;
  15185. }
  15186. #if defined(USE_ALPN)
  15187. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  15188. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  15189. alpn_proto_list + 3 + 8,
  15190. NULL};
  15191. #if defined(USE_HTTP2)
  15192. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  15193. alpn_proto_list + 3,
  15194. alpn_proto_list + 3 + 8,
  15195. NULL};
  15196. #endif
  15197. static int
  15198. alpn_select_cb(SSL *ssl,
  15199. const unsigned char **out,
  15200. unsigned char *outlen,
  15201. const unsigned char *in,
  15202. unsigned int inlen,
  15203. void *arg)
  15204. {
  15205. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15206. unsigned int i, j, enable_http2 = 0;
  15207. const char **alpn_proto_order = alpn_proto_order_http1;
  15208. struct mg_workerTLS *tls =
  15209. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  15210. (void)ssl;
  15211. if (tls == NULL) {
  15212. /* Need to store protocol in Thread Local Storage */
  15213. /* If there is no Thread Local Storage, don't use ALPN */
  15214. return SSL_TLSEXT_ERR_NOACK;
  15215. }
  15216. #if defined(USE_HTTP2)
  15217. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  15218. if (enable_http2) {
  15219. alpn_proto_order = alpn_proto_order_http2;
  15220. }
  15221. #endif
  15222. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  15223. /* check all accepted protocols in this order */
  15224. const char *alpn_proto = alpn_proto_order[j];
  15225. /* search input for matching protocol */
  15226. for (i = 0; i < inlen; i++) {
  15227. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  15228. *out = in + i + 1;
  15229. *outlen = in[i];
  15230. tls->alpn_proto = alpn_proto;
  15231. return SSL_TLSEXT_ERR_OK;
  15232. }
  15233. }
  15234. }
  15235. /* Nothing found */
  15236. return SSL_TLSEXT_ERR_NOACK;
  15237. }
  15238. static int
  15239. next_protos_advertised_cb(SSL *ssl,
  15240. const unsigned char **data,
  15241. unsigned int *len,
  15242. void *arg)
  15243. {
  15244. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15245. *data = (const unsigned char *)alpn_proto_list;
  15246. *len = (unsigned int)strlen((const char *)data);
  15247. (void)ssl;
  15248. (void)dom_ctx;
  15249. return SSL_TLSEXT_ERR_OK;
  15250. }
  15251. static int
  15252. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15253. {
  15254. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  15255. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  15256. (const unsigned char *)alpn_proto_list,
  15257. alpn_len);
  15258. if (ret != 0) {
  15259. mg_cry_ctx_internal(phys_ctx,
  15260. "SSL_CTX_set_alpn_protos error: %s",
  15261. ssl_error());
  15262. }
  15263. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  15264. alpn_select_cb,
  15265. (void *)dom_ctx);
  15266. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  15267. next_protos_advertised_cb,
  15268. (void *)dom_ctx);
  15269. return ret;
  15270. }
  15271. #endif
  15272. /* Setup SSL CTX as required by CivetWeb */
  15273. static int
  15274. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  15275. struct mg_domain_context *dom_ctx,
  15276. const char *pem,
  15277. const char *chain)
  15278. {
  15279. int callback_ret;
  15280. int should_verify_peer;
  15281. int peer_certificate_optional;
  15282. const char *ca_path;
  15283. const char *ca_file;
  15284. int use_default_verify_paths;
  15285. int verify_depth;
  15286. struct timespec now_mt;
  15287. md5_byte_t ssl_context_id[16];
  15288. md5_state_t md5state;
  15289. int protocol_ver;
  15290. int ssl_cache_timeout;
  15291. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15292. && !defined(NO_SSL_DL)
  15293. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15294. mg_cry_ctx_internal(phys_ctx,
  15295. "SSL_CTX_new (server) error: %s",
  15296. ssl_error());
  15297. return 0;
  15298. }
  15299. #else
  15300. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15301. mg_cry_ctx_internal(phys_ctx,
  15302. "SSL_CTX_new (server) error: %s",
  15303. ssl_error());
  15304. return 0;
  15305. }
  15306. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15307. #if defined(SSL_OP_NO_TLSv1_3)
  15308. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15309. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15310. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15311. | SSL_OP_NO_TLSv1_3);
  15312. #else
  15313. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15314. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15315. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15316. #endif
  15317. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15318. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15319. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15320. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15321. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15322. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15323. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15324. #if defined(SSL_OP_NO_RENEGOTIATION)
  15325. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15326. #endif
  15327. #if !defined(NO_SSL_DL)
  15328. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15329. #endif /* NO_SSL_DL */
  15330. /* In SSL documentation examples callback defined without const
  15331. * specifier 'void (*)(SSL *, int, int)' See:
  15332. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15333. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15334. * But in the source code const SSL is used:
  15335. * 'void (*)(const SSL *, int, int)' See:
  15336. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15337. * Problem about wrong documentation described, but not resolved:
  15338. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15339. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15340. * But when compiled with modern C++ compiler, correct const should be
  15341. * provided
  15342. */
  15343. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15344. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15345. ssl_servername_callback);
  15346. /* If a callback has been specified, call it. */
  15347. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15348. ? 0
  15349. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15350. phys_ctx->user_data));
  15351. /* If callback returns 0, civetweb sets up the SSL certificate.
  15352. * If it returns 1, civetweb assumes the callback already did this.
  15353. * If it returns -1, initializing ssl fails. */
  15354. if (callback_ret < 0) {
  15355. mg_cry_ctx_internal(phys_ctx,
  15356. "SSL callback returned error: %i",
  15357. callback_ret);
  15358. return 0;
  15359. }
  15360. if (callback_ret > 0) {
  15361. /* Callback did everything. */
  15362. return 1;
  15363. }
  15364. /* If a domain callback has been specified, call it. */
  15365. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15366. ? 0
  15367. : (phys_ctx->callbacks.init_ssl_domain(
  15368. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15369. dom_ctx->ssl_ctx,
  15370. phys_ctx->user_data));
  15371. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15372. * If it returns 1, civetweb assumes the callback already did this.
  15373. * If it returns -1, initializing ssl fails. */
  15374. if (callback_ret < 0) {
  15375. mg_cry_ctx_internal(phys_ctx,
  15376. "Domain SSL callback returned error: %i",
  15377. callback_ret);
  15378. return 0;
  15379. }
  15380. if (callback_ret > 0) {
  15381. /* Domain callback did everything. */
  15382. return 1;
  15383. }
  15384. /* Use some combination of start time, domain and port as a SSL
  15385. * context ID. This should be unique on the current machine. */
  15386. md5_init(&md5state);
  15387. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15388. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15389. md5_append(&md5state,
  15390. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15391. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15392. md5_append(&md5state,
  15393. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15394. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15395. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15396. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15397. md5_finish(&md5state, ssl_context_id);
  15398. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15399. (unsigned char *)ssl_context_id,
  15400. sizeof(ssl_context_id));
  15401. if (pem != NULL) {
  15402. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15403. return 0;
  15404. }
  15405. }
  15406. /* Should we support client certificates? */
  15407. /* Default is "no". */
  15408. should_verify_peer = 0;
  15409. peer_certificate_optional = 0;
  15410. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15411. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15412. /* Yes, they are mandatory */
  15413. should_verify_peer = 1;
  15414. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15415. "optional")
  15416. == 0) {
  15417. /* Yes, they are optional */
  15418. should_verify_peer = 1;
  15419. peer_certificate_optional = 1;
  15420. }
  15421. }
  15422. use_default_verify_paths =
  15423. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15424. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15425. == 0);
  15426. if (should_verify_peer) {
  15427. ca_path = dom_ctx->config[SSL_CA_PATH];
  15428. ca_file = dom_ctx->config[SSL_CA_FILE];
  15429. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15430. != 1) {
  15431. mg_cry_ctx_internal(phys_ctx,
  15432. "SSL_CTX_load_verify_locations error: %s "
  15433. "ssl_verify_peer requires setting "
  15434. "either ssl_ca_path or ssl_ca_file. "
  15435. "Is any of them present in the "
  15436. ".conf file?",
  15437. ssl_error());
  15438. return 0;
  15439. }
  15440. if (peer_certificate_optional) {
  15441. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15442. } else {
  15443. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15444. SSL_VERIFY_PEER
  15445. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15446. NULL);
  15447. }
  15448. if (use_default_verify_paths
  15449. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15450. mg_cry_ctx_internal(phys_ctx,
  15451. "SSL_CTX_set_default_verify_paths error: %s",
  15452. ssl_error());
  15453. return 0;
  15454. }
  15455. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15456. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15457. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15458. }
  15459. }
  15460. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15461. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15462. dom_ctx->config[SSL_CIPHER_LIST])
  15463. != 1) {
  15464. mg_cry_ctx_internal(phys_ctx,
  15465. "SSL_CTX_set_cipher_list error: %s",
  15466. ssl_error());
  15467. }
  15468. }
  15469. /* SSL session caching */
  15470. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15471. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15472. : 0);
  15473. if (ssl_cache_timeout > 0) {
  15474. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15475. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15476. * default */
  15477. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15478. }
  15479. #if defined(USE_ALPN)
  15480. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15481. #if !defined(NO_SSL_DL)
  15482. if (!tls_feature_missing[TLS_ALPN])
  15483. #endif
  15484. {
  15485. init_alpn(phys_ctx, dom_ctx);
  15486. }
  15487. #endif
  15488. return 1;
  15489. }
  15490. /* Check if SSL is required.
  15491. * If so, dynamically load SSL library
  15492. * and set up ctx->ssl_ctx pointer. */
  15493. static int
  15494. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15495. {
  15496. void *ssl_ctx = 0;
  15497. int callback_ret;
  15498. const char *pem;
  15499. const char *chain;
  15500. char ebuf[128];
  15501. if (!phys_ctx) {
  15502. return 0;
  15503. }
  15504. if (!dom_ctx) {
  15505. dom_ctx = &(phys_ctx->dd);
  15506. }
  15507. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15508. /* No SSL port is set. No need to setup SSL. */
  15509. return 1;
  15510. }
  15511. /* Check for external SSL_CTX */
  15512. callback_ret =
  15513. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15514. ? 0
  15515. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15516. phys_ctx->user_data));
  15517. if (callback_ret < 0) {
  15518. /* Callback exists and returns <0: Initializing failed. */
  15519. mg_cry_ctx_internal(phys_ctx,
  15520. "external_ssl_ctx callback returned error: %i",
  15521. callback_ret);
  15522. return 0;
  15523. } else if (callback_ret > 0) {
  15524. /* Callback exists and returns >0: Initializing complete,
  15525. * civetweb should not modify the SSL context. */
  15526. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15527. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15528. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15529. return 0;
  15530. }
  15531. return 1;
  15532. }
  15533. /* If the callback does not exist or return 0, civetweb must initialize
  15534. * the SSL context. Handle "domain" callback next. */
  15535. /* Check for external domain SSL_CTX callback. */
  15536. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15537. ? 0
  15538. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15539. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15540. &ssl_ctx,
  15541. phys_ctx->user_data));
  15542. if (callback_ret < 0) {
  15543. /* Callback < 0: Error. Abort init. */
  15544. mg_cry_ctx_internal(
  15545. phys_ctx,
  15546. "external_ssl_ctx_domain callback returned error: %i",
  15547. callback_ret);
  15548. return 0;
  15549. } else if (callback_ret > 0) {
  15550. /* Callback > 0: Consider init done. */
  15551. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15552. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15553. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15554. return 0;
  15555. }
  15556. return 1;
  15557. }
  15558. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15559. * 0, CivetWeb should continue initializing SSL */
  15560. /* If PEM file is not specified and the init_ssl callbacks
  15561. * are not specified, setup will fail. */
  15562. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15563. && (phys_ctx->callbacks.init_ssl == NULL)
  15564. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15565. /* No certificate and no init_ssl callbacks:
  15566. * Essential data to set up TLS is missing.
  15567. */
  15568. mg_cry_ctx_internal(phys_ctx,
  15569. "Initializing SSL failed: -%s is not set",
  15570. config_options[SSL_CERTIFICATE].name);
  15571. return 0;
  15572. }
  15573. /* If a certificate chain is configured, use it. */
  15574. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15575. if (chain == NULL) {
  15576. /* Default: certificate chain in PEM file */
  15577. chain = pem;
  15578. }
  15579. if ((chain != NULL) && (*chain == 0)) {
  15580. /* If the chain is an empty string, don't use it. */
  15581. chain = NULL;
  15582. }
  15583. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15584. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15585. return 0;
  15586. }
  15587. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15588. }
  15589. static void
  15590. uninitialize_openssl(void)
  15591. {
  15592. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15593. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15594. /* Shutdown according to
  15595. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15596. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15597. */
  15598. CONF_modules_unload(1);
  15599. #else
  15600. int i;
  15601. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15602. /* Shutdown according to
  15603. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15604. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15605. */
  15606. CRYPTO_set_locking_callback(NULL);
  15607. CRYPTO_set_id_callback(NULL);
  15608. ENGINE_cleanup();
  15609. CONF_modules_unload(1);
  15610. ERR_free_strings();
  15611. EVP_cleanup();
  15612. CRYPTO_cleanup_all_ex_data();
  15613. OPENSSL_REMOVE_THREAD_STATE();
  15614. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15615. pthread_mutex_destroy(&ssl_mutexes[i]);
  15616. }
  15617. mg_free(ssl_mutexes);
  15618. ssl_mutexes = NULL;
  15619. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15620. }
  15621. }
  15622. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) */
  15623. #if !defined(NO_FILESYSTEMS)
  15624. static int
  15625. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15626. {
  15627. if (phys_ctx) {
  15628. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15629. const char *path;
  15630. struct mg_connection fc;
  15631. if (!dom_ctx) {
  15632. dom_ctx = &(phys_ctx->dd);
  15633. }
  15634. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15635. if ((path != NULL)
  15636. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15637. mg_cry_ctx_internal(phys_ctx,
  15638. "Cannot open %s: %s",
  15639. path,
  15640. strerror(ERRNO));
  15641. return 0;
  15642. }
  15643. return 1;
  15644. }
  15645. return 0;
  15646. }
  15647. #endif /* NO_FILESYSTEMS */
  15648. static int
  15649. set_acl_option(struct mg_context *phys_ctx)
  15650. {
  15651. union usa sa;
  15652. memset(&sa, 0, sizeof(sa));
  15653. #if defined(USE_IPV6)
  15654. sa.sin6.sin6_family = AF_INET6;
  15655. #else
  15656. sa.sin.sin_family = AF_INET;
  15657. #endif
  15658. return check_acl(phys_ctx, &sa) != -1;
  15659. }
  15660. static void
  15661. reset_per_request_attributes(struct mg_connection *conn)
  15662. {
  15663. if (!conn) {
  15664. return;
  15665. }
  15666. conn->num_bytes_sent = conn->consumed_content = 0;
  15667. conn->path_info = NULL;
  15668. conn->status_code = -1;
  15669. conn->content_len = -1;
  15670. conn->is_chunked = 0;
  15671. conn->must_close = 0;
  15672. conn->request_len = 0;
  15673. conn->request_state = 0;
  15674. conn->throttle = 0;
  15675. conn->accept_gzip = 0;
  15676. conn->response_info.content_length = conn->request_info.content_length = -1;
  15677. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15678. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15679. conn->response_info.status_text = NULL;
  15680. conn->response_info.status_code = 0;
  15681. conn->request_info.remote_user = NULL;
  15682. conn->request_info.request_method = NULL;
  15683. conn->request_info.request_uri = NULL;
  15684. /* Free cleaned local URI (if any) */
  15685. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15686. mg_free((void *)conn->request_info.local_uri);
  15687. conn->request_info.local_uri = NULL;
  15688. }
  15689. conn->request_info.local_uri = NULL;
  15690. #if defined(USE_SERVER_STATS)
  15691. conn->processing_time = 0;
  15692. #endif
  15693. }
  15694. static int
  15695. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15696. {
  15697. if ((so->lsa.sa.sa_family == AF_INET)
  15698. || (so->lsa.sa.sa_family == AF_INET6)) {
  15699. /* Only for TCP sockets */
  15700. if (setsockopt(so->sock,
  15701. IPPROTO_TCP,
  15702. TCP_NODELAY,
  15703. (SOCK_OPT_TYPE)&nodelay_on,
  15704. sizeof(nodelay_on))
  15705. != 0) {
  15706. /* Error */
  15707. return 1;
  15708. }
  15709. }
  15710. /* OK */
  15711. return 0;
  15712. }
  15713. #if !defined(__ZEPHYR__)
  15714. static void
  15715. close_socket_gracefully(struct mg_connection *conn)
  15716. {
  15717. #if defined(_WIN32)
  15718. char buf[MG_BUF_LEN];
  15719. int n;
  15720. #endif
  15721. struct linger linger;
  15722. int error_code = 0;
  15723. int linger_timeout = -2;
  15724. socklen_t opt_len = sizeof(error_code);
  15725. if (!conn) {
  15726. return;
  15727. }
  15728. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15729. * "Note that enabling a nonzero timeout on a nonblocking socket
  15730. * is not recommended.", so set it to blocking now */
  15731. set_blocking_mode(conn->client.sock);
  15732. /* Send FIN to the client */
  15733. shutdown(conn->client.sock, SHUTDOWN_WR);
  15734. #if defined(_WIN32)
  15735. /* Read and discard pending incoming data. If we do not do that and
  15736. * close
  15737. * the socket, the data in the send buffer may be discarded. This
  15738. * behaviour is seen on Windows, when client keeps sending data
  15739. * when server decides to close the connection; then when client
  15740. * does recv() it gets no data back. */
  15741. do {
  15742. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15743. } while (n > 0);
  15744. #endif
  15745. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15746. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15747. }
  15748. /* Set linger option according to configuration */
  15749. if (linger_timeout >= 0) {
  15750. /* Set linger option to avoid socket hanging out after close. This
  15751. * prevent ephemeral port exhaust problem under high QPS. */
  15752. linger.l_onoff = 1;
  15753. #if defined(_MSC_VER)
  15754. #pragma warning(push)
  15755. #pragma warning(disable : 4244)
  15756. #endif
  15757. #if defined(GCC_DIAGNOSTIC)
  15758. #pragma GCC diagnostic push
  15759. #pragma GCC diagnostic ignored "-Wconversion"
  15760. #endif
  15761. /* Data type of linger structure elements may differ,
  15762. * so we don't know what cast we need here.
  15763. * Disable type conversion warnings. */
  15764. linger.l_linger = (linger_timeout + 999) / 1000;
  15765. #if defined(GCC_DIAGNOSTIC)
  15766. #pragma GCC diagnostic pop
  15767. #endif
  15768. #if defined(_MSC_VER)
  15769. #pragma warning(pop)
  15770. #endif
  15771. } else {
  15772. linger.l_onoff = 0;
  15773. linger.l_linger = 0;
  15774. }
  15775. if (linger_timeout < -1) {
  15776. /* Default: don't configure any linger */
  15777. } else if (getsockopt(conn->client.sock,
  15778. SOL_SOCKET,
  15779. SO_ERROR,
  15780. #if defined(_WIN32) /* WinSock uses different data type here */
  15781. (char *)&error_code,
  15782. #else
  15783. &error_code,
  15784. #endif
  15785. &opt_len)
  15786. != 0) {
  15787. /* Cannot determine if socket is already closed. This should
  15788. * not occur and never did in a test. Log an error message
  15789. * and continue. */
  15790. mg_cry_internal(conn,
  15791. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15792. __func__,
  15793. strerror(ERRNO));
  15794. #if defined(_WIN32)
  15795. } else if (error_code == WSAECONNRESET) {
  15796. #else
  15797. } else if (error_code == ECONNRESET) {
  15798. #endif
  15799. /* Socket already closed by client/peer, close socket without linger
  15800. */
  15801. } else {
  15802. /* Set linger timeout */
  15803. if (setsockopt(conn->client.sock,
  15804. SOL_SOCKET,
  15805. SO_LINGER,
  15806. (char *)&linger,
  15807. sizeof(linger))
  15808. != 0) {
  15809. mg_cry_internal(
  15810. conn,
  15811. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15812. __func__,
  15813. linger.l_onoff,
  15814. linger.l_linger,
  15815. strerror(ERRNO));
  15816. }
  15817. }
  15818. /* Now we know that our FIN is ACK-ed, safe to close */
  15819. closesocket(conn->client.sock);
  15820. conn->client.sock = INVALID_SOCKET;
  15821. }
  15822. #endif
  15823. static void
  15824. close_connection(struct mg_connection *conn)
  15825. {
  15826. #if defined(USE_SERVER_STATS)
  15827. conn->conn_state = 6; /* to close */
  15828. #endif
  15829. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15830. if (conn->lua_websocket_state) {
  15831. lua_websocket_close(conn, conn->lua_websocket_state);
  15832. conn->lua_websocket_state = NULL;
  15833. }
  15834. #endif
  15835. mg_lock_connection(conn);
  15836. /* Set close flag, so keep-alive loops will stop */
  15837. conn->must_close = 1;
  15838. /* call the connection_close callback if assigned */
  15839. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15840. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15841. conn->phys_ctx->callbacks.connection_close(conn);
  15842. }
  15843. }
  15844. /* Reset user data, after close callback is called.
  15845. * Do not reuse it. If the user needs a destructor,
  15846. * it must be done in the connection_close callback. */
  15847. mg_set_user_connection_data(conn, NULL);
  15848. #if defined(USE_SERVER_STATS)
  15849. conn->conn_state = 7; /* closing */
  15850. #endif
  15851. #if defined(USE_MBEDTLS)
  15852. if (conn->ssl != NULL) {
  15853. mbed_ssl_close(conn->ssl);
  15854. conn->ssl = NULL;
  15855. }
  15856. #elif defined(USE_GNUTLS)
  15857. if (conn->ssl != NULL) {
  15858. gtls_ssl_close(conn->ssl);
  15859. conn->ssl = NULL;
  15860. }
  15861. #elif !defined(NO_SSL)
  15862. if (conn->ssl != NULL) {
  15863. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15864. */
  15865. SSL_shutdown(conn->ssl);
  15866. SSL_free(conn->ssl);
  15867. OPENSSL_REMOVE_THREAD_STATE();
  15868. conn->ssl = NULL;
  15869. }
  15870. #endif
  15871. if (conn->client.sock != INVALID_SOCKET) {
  15872. #if defined(__ZEPHYR__)
  15873. closesocket(conn->client.sock);
  15874. #else
  15875. close_socket_gracefully(conn);
  15876. #endif
  15877. conn->client.sock = INVALID_SOCKET;
  15878. }
  15879. /* call the connection_closed callback if assigned */
  15880. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15881. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15882. conn->phys_ctx->callbacks.connection_closed(conn);
  15883. }
  15884. }
  15885. mg_unlock_connection(conn);
  15886. #if defined(USE_SERVER_STATS)
  15887. conn->conn_state = 8; /* closed */
  15888. #endif
  15889. }
  15890. CIVETWEB_API void
  15891. mg_close_connection(struct mg_connection *conn)
  15892. {
  15893. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15894. return;
  15895. }
  15896. #if defined(USE_WEBSOCKET)
  15897. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15898. if (conn->in_websocket_handling) {
  15899. /* Set close flag, so the server thread can exit. */
  15900. conn->must_close = 1;
  15901. return;
  15902. }
  15903. }
  15904. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15905. unsigned int i;
  15906. /* client context: loops must end */
  15907. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15908. conn->must_close = 1;
  15909. /* We need to get the client thread out of the select/recv call
  15910. * here. */
  15911. /* Since we use a sleep quantum of some seconds to check for recv
  15912. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15913. /* join worker thread */
  15914. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15915. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15916. }
  15917. }
  15918. #endif /* defined(USE_WEBSOCKET) */
  15919. close_connection(conn);
  15920. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) // TODO: mbedTLS client
  15921. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15922. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15923. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15924. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15925. }
  15926. #endif
  15927. #if defined(USE_WEBSOCKET)
  15928. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15929. mg_free(conn->phys_ctx->worker_threadids);
  15930. (void)pthread_mutex_destroy(&conn->mutex);
  15931. mg_free(conn);
  15932. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15933. (void)pthread_mutex_destroy(&conn->mutex);
  15934. mg_free(conn);
  15935. }
  15936. #else
  15937. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15938. (void)pthread_mutex_destroy(&conn->mutex);
  15939. mg_free(conn);
  15940. }
  15941. #endif /* defined(USE_WEBSOCKET) */
  15942. }
  15943. static struct mg_connection *
  15944. mg_connect_client_impl(const struct mg_client_options *client_options,
  15945. int use_ssl,
  15946. struct mg_init_data *init,
  15947. struct mg_error_data *error)
  15948. {
  15949. struct mg_connection *conn = NULL;
  15950. SOCKET sock;
  15951. union usa sa;
  15952. struct sockaddr *psa;
  15953. socklen_t len;
  15954. unsigned max_req_size =
  15955. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15956. /* Size of structures, aligned to 8 bytes */
  15957. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15958. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15959. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15960. (void)init; /* TODO: Implement required options */
  15961. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15962. if (error != NULL) {
  15963. error->code = MG_ERROR_DATA_CODE_OK;
  15964. error->code_sub = 0;
  15965. if (error->text_buffer_size > 0) {
  15966. error->text[0] = 0;
  15967. }
  15968. }
  15969. if (conn == NULL) {
  15970. if (error != NULL) {
  15971. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15972. error->code_sub = (unsigned)alloc_size;
  15973. mg_snprintf(NULL,
  15974. NULL, /* No truncation check for ebuf */
  15975. error->text,
  15976. error->text_buffer_size,
  15977. "calloc(): %s",
  15978. strerror(ERRNO));
  15979. }
  15980. return NULL;
  15981. }
  15982. #if defined(GCC_DIAGNOSTIC)
  15983. #pragma GCC diagnostic push
  15984. #pragma GCC diagnostic ignored "-Wcast-align"
  15985. #endif /* defined(GCC_DIAGNOSTIC) */
  15986. /* conn_size is aligned to 8 bytes */
  15987. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15988. #if defined(GCC_DIAGNOSTIC)
  15989. #pragma GCC diagnostic pop
  15990. #endif /* defined(GCC_DIAGNOSTIC) */
  15991. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15992. conn->buf_size = (int)max_req_size;
  15993. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15994. conn->dom_ctx = &(conn->phys_ctx->dd);
  15995. if (!connect_socket(conn->phys_ctx,
  15996. client_options->host,
  15997. client_options->port,
  15998. use_ssl,
  15999. error,
  16000. &sock,
  16001. &sa)) {
  16002. /* "error" will be set by connect_socket. */
  16003. /* free all memory and return NULL; */
  16004. mg_free(conn);
  16005. return NULL;
  16006. }
  16007. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16008. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  16009. && !defined(NO_SSL_DL)
  16010. if (use_ssl
  16011. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  16012. == NULL) {
  16013. if (error != NULL) {
  16014. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16015. mg_snprintf(NULL,
  16016. NULL, /* No truncation check for ebuf */
  16017. error->text,
  16018. error->text_buffer_size,
  16019. "SSL_CTX_new error: %s",
  16020. ssl_error());
  16021. }
  16022. closesocket(sock);
  16023. mg_free(conn);
  16024. return NULL;
  16025. }
  16026. #else
  16027. if (use_ssl
  16028. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  16029. == NULL) {
  16030. if (error != NULL) {
  16031. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16032. mg_snprintf(NULL,
  16033. NULL, /* No truncation check for ebuf */
  16034. error->text,
  16035. error->text_buffer_size,
  16036. "SSL_CTX_new error: %s",
  16037. ssl_error());
  16038. }
  16039. closesocket(sock);
  16040. mg_free(conn);
  16041. return NULL;
  16042. }
  16043. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  16044. #endif /* NO_SSL */
  16045. #if defined(USE_IPV6)
  16046. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  16047. : sizeof(conn->client.rsa.sin6);
  16048. psa = (sa.sa.sa_family == AF_INET)
  16049. ? (struct sockaddr *)&(conn->client.rsa.sin)
  16050. : (struct sockaddr *)&(conn->client.rsa.sin6);
  16051. #else
  16052. len = sizeof(conn->client.rsa.sin);
  16053. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  16054. #endif
  16055. conn->client.sock = sock;
  16056. conn->client.lsa = sa;
  16057. if (getsockname(sock, psa, &len) != 0) {
  16058. mg_cry_internal(conn,
  16059. "%s: getsockname() failed: %s",
  16060. __func__,
  16061. strerror(ERRNO));
  16062. }
  16063. conn->client.is_ssl = use_ssl ? 1 : 0;
  16064. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16065. if (error != NULL) {
  16066. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  16067. error->code_sub = (unsigned)ERRNO;
  16068. mg_snprintf(NULL,
  16069. NULL, /* No truncation check for ebuf */
  16070. error->text,
  16071. error->text_buffer_size,
  16072. "Can not create mutex");
  16073. }
  16074. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16075. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16076. #endif
  16077. closesocket(sock);
  16078. mg_free(conn);
  16079. return NULL;
  16080. }
  16081. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16082. if (use_ssl) {
  16083. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  16084. * SSL_CTX_set_verify call is needed to switch off server
  16085. * certificate checking, which is off by default in OpenSSL and
  16086. * on in yaSSL. */
  16087. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  16088. * SSL_VERIFY_PEER, verify_ssl_server); */
  16089. if (client_options->client_cert) {
  16090. if (!ssl_use_pem_file(conn->phys_ctx,
  16091. conn->dom_ctx,
  16092. client_options->client_cert,
  16093. NULL)) {
  16094. if (error != NULL) {
  16095. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  16096. mg_snprintf(NULL,
  16097. NULL, /* No truncation check for ebuf */
  16098. error->text,
  16099. error->text_buffer_size,
  16100. "Can not use SSL client certificate");
  16101. }
  16102. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16103. closesocket(sock);
  16104. mg_free(conn);
  16105. return NULL;
  16106. }
  16107. }
  16108. if (client_options->server_cert) {
  16109. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  16110. client_options->server_cert,
  16111. NULL)
  16112. != 1) {
  16113. if (error != NULL) {
  16114. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  16115. mg_snprintf(NULL,
  16116. NULL, /* No truncation check for ebuf */
  16117. error->text,
  16118. error->text_buffer_size,
  16119. "SSL_CTX_load_verify_locations error: %s",
  16120. ssl_error());
  16121. }
  16122. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16123. closesocket(sock);
  16124. mg_free(conn);
  16125. return NULL;
  16126. }
  16127. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  16128. } else {
  16129. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  16130. }
  16131. if (!sslize(conn, SSL_connect, client_options)) {
  16132. if (error != NULL) {
  16133. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  16134. mg_snprintf(NULL,
  16135. NULL, /* No truncation check for ebuf */
  16136. error->text,
  16137. error->text_buffer_size,
  16138. "SSL connection error");
  16139. }
  16140. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16141. closesocket(sock);
  16142. mg_free(conn);
  16143. return NULL;
  16144. }
  16145. }
  16146. #endif
  16147. return conn;
  16148. }
  16149. CIVETWEB_API struct mg_connection *
  16150. mg_connect_client_secure(const struct mg_client_options *client_options,
  16151. char *error_buffer,
  16152. size_t error_buffer_size)
  16153. {
  16154. struct mg_init_data init;
  16155. struct mg_error_data error;
  16156. memset(&init, 0, sizeof(init));
  16157. memset(&error, 0, sizeof(error));
  16158. error.text_buffer_size = error_buffer_size;
  16159. error.text = error_buffer;
  16160. return mg_connect_client_impl(client_options, 1, &init, &error);
  16161. }
  16162. CIVETWEB_API struct mg_connection *
  16163. mg_connect_client(const char *host,
  16164. int port,
  16165. int use_ssl,
  16166. char *error_buffer,
  16167. size_t error_buffer_size)
  16168. {
  16169. struct mg_client_options opts;
  16170. struct mg_init_data init;
  16171. struct mg_error_data error;
  16172. memset(&init, 0, sizeof(init));
  16173. memset(&error, 0, sizeof(error));
  16174. error.text_buffer_size = error_buffer_size;
  16175. error.text = error_buffer;
  16176. memset(&opts, 0, sizeof(opts));
  16177. opts.host = host;
  16178. opts.port = port;
  16179. if (use_ssl) {
  16180. opts.host_name = host;
  16181. }
  16182. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  16183. }
  16184. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16185. CIVETWEB_API struct mg_connection *
  16186. mg_connect_client2(const char *host,
  16187. const char *protocol,
  16188. int port,
  16189. const char *path,
  16190. struct mg_init_data *init,
  16191. struct mg_error_data *error)
  16192. {
  16193. (void)path;
  16194. int is_ssl, is_ws;
  16195. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  16196. if (error != NULL) {
  16197. error->code = MG_ERROR_DATA_CODE_OK;
  16198. error->code_sub = 0;
  16199. if (error->text_buffer_size > 0) {
  16200. *error->text = 0;
  16201. }
  16202. }
  16203. if ((host == NULL) || (protocol == NULL)) {
  16204. if (error != NULL) {
  16205. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16206. mg_snprintf(NULL,
  16207. NULL, /* No truncation check for error buffers */
  16208. error->text,
  16209. error->text_buffer_size,
  16210. "%s",
  16211. "Invalid parameters");
  16212. }
  16213. return NULL;
  16214. }
  16215. /* check all known protocols */
  16216. if (!mg_strcasecmp(protocol, "http")) {
  16217. is_ssl = 0;
  16218. is_ws = 0;
  16219. } else if (!mg_strcasecmp(protocol, "https")) {
  16220. is_ssl = 1;
  16221. is_ws = 0;
  16222. #if defined(USE_WEBSOCKET)
  16223. } else if (!mg_strcasecmp(protocol, "ws")) {
  16224. is_ssl = 0;
  16225. is_ws = 1;
  16226. } else if (!mg_strcasecmp(protocol, "wss")) {
  16227. is_ssl = 1;
  16228. is_ws = 1;
  16229. #endif
  16230. } else {
  16231. if (error != NULL) {
  16232. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16233. mg_snprintf(NULL,
  16234. NULL, /* No truncation check for error buffers */
  16235. error->text,
  16236. error->text_buffer_size,
  16237. "Protocol %s not supported",
  16238. protocol);
  16239. }
  16240. return NULL;
  16241. }
  16242. /* TODO: The current implementation here just calls the old
  16243. * implementations, without using any new options. This is just a first
  16244. * step to test the new interfaces. */
  16245. #if defined(USE_WEBSOCKET)
  16246. if (is_ws) {
  16247. /* TODO: implement all options */
  16248. return mg_connect_websocket_client(
  16249. host,
  16250. port,
  16251. is_ssl,
  16252. ((error != NULL) ? error->text : NULL),
  16253. ((error != NULL) ? error->text_buffer_size : 0),
  16254. (path ? path : ""),
  16255. NULL /* TODO: origin */,
  16256. experimental_websocket_client_data_wrapper,
  16257. experimental_websocket_client_close_wrapper,
  16258. (void *)init->callbacks);
  16259. }
  16260. #else
  16261. (void)is_ws;
  16262. #endif
  16263. /* TODO: all additional options */
  16264. struct mg_client_options opts;
  16265. memset(&opts, 0, sizeof(opts));
  16266. opts.host = host;
  16267. opts.port = port;
  16268. return mg_connect_client_impl(&opts, is_ssl, init, error);
  16269. }
  16270. #endif
  16271. static const struct {
  16272. const char *proto;
  16273. size_t proto_len;
  16274. unsigned default_port;
  16275. } abs_uri_protocols[] = {{"http://", 7, 80},
  16276. {"https://", 8, 443},
  16277. {"ws://", 5, 80},
  16278. {"wss://", 6, 443},
  16279. {NULL, 0, 0}};
  16280. /* Check if the uri is valid.
  16281. * return 0 for invalid uri,
  16282. * return 1 for *,
  16283. * return 2 for relative uri,
  16284. * return 3 for absolute uri without port,
  16285. * return 4 for absolute uri with port */
  16286. static int
  16287. get_uri_type(const char *uri)
  16288. {
  16289. int i;
  16290. const char *hostend, *portbegin;
  16291. char *portend;
  16292. unsigned long port;
  16293. /* According to the HTTP standard
  16294. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  16295. * URI can be an asterisk (*) or should start with slash (relative uri),
  16296. * or it should start with the protocol (absolute uri). */
  16297. if ((uri[0] == '*') && (uri[1] == '\0')) {
  16298. /* asterisk */
  16299. return 1;
  16300. }
  16301. /* Valid URIs according to RFC 3986
  16302. * (https://www.ietf.org/rfc/rfc3986.txt)
  16303. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16304. * and unreserved characters A-Z a-z 0-9 and -._~
  16305. * and % encoded symbols.
  16306. */
  16307. for (i = 0; uri[i] != 0; i++) {
  16308. if ((unsigned char)uri[i] < 33) {
  16309. /* control characters and spaces are invalid */
  16310. return 0;
  16311. }
  16312. /* Allow everything else here (See #894) */
  16313. }
  16314. /* A relative uri starts with a / character */
  16315. if (uri[0] == '/') {
  16316. /* relative uri */
  16317. return 2;
  16318. }
  16319. /* It could be an absolute uri: */
  16320. /* This function only checks if the uri is valid, not if it is
  16321. * addressing the current server. So civetweb can also be used
  16322. * as a proxy server. */
  16323. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16324. if (mg_strncasecmp(uri,
  16325. abs_uri_protocols[i].proto,
  16326. abs_uri_protocols[i].proto_len)
  16327. == 0) {
  16328. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16329. if (!hostend) {
  16330. return 0;
  16331. }
  16332. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16333. if (!portbegin) {
  16334. return 3;
  16335. }
  16336. port = strtoul(portbegin + 1, &portend, 10);
  16337. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16338. return 0;
  16339. }
  16340. return 4;
  16341. }
  16342. }
  16343. return 0;
  16344. }
  16345. /* Return NULL or the relative uri at the current server */
  16346. static const char *
  16347. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16348. {
  16349. const char *server_domain;
  16350. size_t server_domain_len;
  16351. size_t request_domain_len = 0;
  16352. unsigned long port = 0;
  16353. int i, auth_domain_check_enabled;
  16354. const char *hostbegin = NULL;
  16355. const char *hostend = NULL;
  16356. const char *portbegin;
  16357. char *portend;
  16358. auth_domain_check_enabled =
  16359. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16360. /* DNS is case insensitive, so use case insensitive string compare here
  16361. */
  16362. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16363. if (mg_strncasecmp(uri,
  16364. abs_uri_protocols[i].proto,
  16365. abs_uri_protocols[i].proto_len)
  16366. == 0) {
  16367. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16368. hostend = strchr(hostbegin, '/');
  16369. if (!hostend) {
  16370. return 0;
  16371. }
  16372. portbegin = strchr(hostbegin, ':');
  16373. if ((!portbegin) || (portbegin > hostend)) {
  16374. port = abs_uri_protocols[i].default_port;
  16375. request_domain_len = (size_t)(hostend - hostbegin);
  16376. } else {
  16377. port = strtoul(portbegin + 1, &portend, 10);
  16378. if ((portend != hostend) || (port <= 0)
  16379. || !is_valid_port(port)) {
  16380. return 0;
  16381. }
  16382. request_domain_len = (size_t)(portbegin - hostbegin);
  16383. }
  16384. /* protocol found, port set */
  16385. break;
  16386. }
  16387. }
  16388. if (!port) {
  16389. /* port remains 0 if the protocol is not found */
  16390. return 0;
  16391. }
  16392. /* Check if the request is directed to a different server. */
  16393. /* First check if the port is the same. */
  16394. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16395. /* Request is directed to a different port */
  16396. return 0;
  16397. }
  16398. /* Finally check if the server corresponds to the authentication
  16399. * domain of the server (the server domain).
  16400. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16401. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16402. * but do not allow substrings (like
  16403. * http://notmydomain.com/path/file.ext
  16404. * or http://mydomain.com.fake/path/file.ext).
  16405. */
  16406. if (auth_domain_check_enabled) {
  16407. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16408. server_domain_len = strlen(server_domain);
  16409. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16410. return 0;
  16411. }
  16412. if ((request_domain_len == server_domain_len)
  16413. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16414. /* Request is directed to this server - full name match. */
  16415. } else {
  16416. if (request_domain_len < (server_domain_len + 2)) {
  16417. /* Request is directed to another server: The server name
  16418. * is longer than the request name.
  16419. * Drop this case here to avoid overflows in the
  16420. * following checks. */
  16421. return 0;
  16422. }
  16423. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16424. /* Request is directed to another server: It could be a
  16425. * substring
  16426. * like notmyserver.com */
  16427. return 0;
  16428. }
  16429. if (0
  16430. != memcmp(server_domain,
  16431. hostbegin + request_domain_len - server_domain_len,
  16432. server_domain_len)) {
  16433. /* Request is directed to another server:
  16434. * The server name is different. */
  16435. return 0;
  16436. }
  16437. }
  16438. }
  16439. return hostend;
  16440. }
  16441. static int
  16442. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16443. {
  16444. if (ebuf_len > 0) {
  16445. ebuf[0] = '\0';
  16446. }
  16447. *err = 0;
  16448. reset_per_request_attributes(conn);
  16449. if (!conn) {
  16450. mg_snprintf(conn,
  16451. NULL, /* No truncation check for ebuf */
  16452. ebuf,
  16453. ebuf_len,
  16454. "%s",
  16455. "Internal error");
  16456. *err = 500;
  16457. return 0;
  16458. }
  16459. /* Set the time the request was received. This value should be used for
  16460. * timeouts. */
  16461. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16462. conn->request_len =
  16463. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16464. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16465. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16466. mg_snprintf(conn,
  16467. NULL, /* No truncation check for ebuf */
  16468. ebuf,
  16469. ebuf_len,
  16470. "%s",
  16471. "Invalid message size");
  16472. *err = 500;
  16473. return 0;
  16474. }
  16475. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16476. mg_snprintf(conn,
  16477. NULL, /* No truncation check for ebuf */
  16478. ebuf,
  16479. ebuf_len,
  16480. "%s",
  16481. "Message too large");
  16482. *err = 413;
  16483. return 0;
  16484. }
  16485. if (conn->request_len <= 0) {
  16486. if (conn->data_len > 0) {
  16487. mg_snprintf(conn,
  16488. NULL, /* No truncation check for ebuf */
  16489. ebuf,
  16490. ebuf_len,
  16491. "%s",
  16492. conn->request_len == -3 ? "Request timeout"
  16493. : "Malformed message");
  16494. *err = 400;
  16495. } else {
  16496. /* Server did not recv anything -> just close the connection */
  16497. conn->must_close = 1;
  16498. mg_snprintf(conn,
  16499. NULL, /* No truncation check for ebuf */
  16500. ebuf,
  16501. ebuf_len,
  16502. "%s",
  16503. "No data received");
  16504. *err = 0;
  16505. }
  16506. return 0;
  16507. }
  16508. return 1;
  16509. }
  16510. static int
  16511. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16512. {
  16513. const char *cl;
  16514. conn->connection_type =
  16515. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16516. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16517. return 0;
  16518. }
  16519. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16520. <= 0) {
  16521. mg_snprintf(conn,
  16522. NULL, /* No truncation check for ebuf */
  16523. ebuf,
  16524. ebuf_len,
  16525. "%s",
  16526. "Bad request");
  16527. *err = 400;
  16528. return 0;
  16529. }
  16530. /* Message is a valid request */
  16531. if (!switch_domain_context(conn)) {
  16532. mg_snprintf(conn,
  16533. NULL, /* No truncation check for ebuf */
  16534. ebuf,
  16535. ebuf_len,
  16536. "%s",
  16537. "Bad request: Host mismatch");
  16538. *err = 400;
  16539. return 0;
  16540. }
  16541. #if USE_ZLIB
  16542. if (((cl = get_header(conn->request_info.http_headers,
  16543. conn->request_info.num_headers,
  16544. "Accept-Encoding"))
  16545. != NULL)
  16546. && strstr(cl, "gzip")) {
  16547. conn->accept_gzip = 1;
  16548. }
  16549. #endif
  16550. if (((cl = get_header(conn->request_info.http_headers,
  16551. conn->request_info.num_headers,
  16552. "Transfer-Encoding"))
  16553. != NULL)
  16554. && mg_strcasecmp(cl, "identity")) {
  16555. if (mg_strcasecmp(cl, "chunked")) {
  16556. mg_snprintf(conn,
  16557. NULL, /* No truncation check for ebuf */
  16558. ebuf,
  16559. ebuf_len,
  16560. "%s",
  16561. "Bad request");
  16562. *err = 400;
  16563. return 0;
  16564. }
  16565. conn->is_chunked = 1;
  16566. conn->content_len = 0; /* not yet read */
  16567. } else if ((cl = get_header(conn->request_info.http_headers,
  16568. conn->request_info.num_headers,
  16569. "Content-Length"))
  16570. != NULL) {
  16571. /* Request has content length set */
  16572. char *endptr = NULL;
  16573. conn->content_len = strtoll(cl, &endptr, 10);
  16574. if ((endptr == cl) || (conn->content_len < 0)) {
  16575. mg_snprintf(conn,
  16576. NULL, /* No truncation check for ebuf */
  16577. ebuf,
  16578. ebuf_len,
  16579. "%s",
  16580. "Bad request");
  16581. *err = 411;
  16582. return 0;
  16583. }
  16584. /* Publish the content length back to the request info. */
  16585. conn->request_info.content_length = conn->content_len;
  16586. } else {
  16587. /* There is no exception, see RFC7230. */
  16588. conn->content_len = 0;
  16589. }
  16590. return 1;
  16591. }
  16592. /* conn is assumed to be valid in this internal function */
  16593. static int
  16594. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16595. {
  16596. const char *cl;
  16597. conn->connection_type =
  16598. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16599. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16600. return 0;
  16601. }
  16602. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16603. <= 0) {
  16604. mg_snprintf(conn,
  16605. NULL, /* No truncation check for ebuf */
  16606. ebuf,
  16607. ebuf_len,
  16608. "%s",
  16609. "Bad response");
  16610. *err = 400;
  16611. return 0;
  16612. }
  16613. /* Message is a valid response */
  16614. if (((cl = get_header(conn->response_info.http_headers,
  16615. conn->response_info.num_headers,
  16616. "Transfer-Encoding"))
  16617. != NULL)
  16618. && mg_strcasecmp(cl, "identity")) {
  16619. if (mg_strcasecmp(cl, "chunked")) {
  16620. mg_snprintf(conn,
  16621. NULL, /* No truncation check for ebuf */
  16622. ebuf,
  16623. ebuf_len,
  16624. "%s",
  16625. "Bad request");
  16626. *err = 400;
  16627. return 0;
  16628. }
  16629. conn->is_chunked = 1;
  16630. conn->content_len = 0; /* not yet read */
  16631. } else if ((cl = get_header(conn->response_info.http_headers,
  16632. conn->response_info.num_headers,
  16633. "Content-Length"))
  16634. != NULL) {
  16635. char *endptr = NULL;
  16636. conn->content_len = strtoll(cl, &endptr, 10);
  16637. if ((endptr == cl) || (conn->content_len < 0)) {
  16638. mg_snprintf(conn,
  16639. NULL, /* No truncation check for ebuf */
  16640. ebuf,
  16641. ebuf_len,
  16642. "%s",
  16643. "Bad request");
  16644. *err = 411;
  16645. return 0;
  16646. }
  16647. /* Publish the content length back to the response info. */
  16648. conn->response_info.content_length = conn->content_len;
  16649. /* TODO: check if it is still used in response_info */
  16650. conn->request_info.content_length = conn->content_len;
  16651. /* TODO: we should also consider HEAD method */
  16652. if (conn->response_info.status_code == 304) {
  16653. conn->content_len = 0;
  16654. }
  16655. } else {
  16656. /* TODO: we should also consider HEAD method */
  16657. if (((conn->response_info.status_code >= 100)
  16658. && (conn->response_info.status_code <= 199))
  16659. || (conn->response_info.status_code == 204)
  16660. || (conn->response_info.status_code == 304)) {
  16661. conn->content_len = 0;
  16662. } else {
  16663. conn->content_len = -1; /* unknown content length */
  16664. }
  16665. }
  16666. return 1;
  16667. }
  16668. CIVETWEB_API int
  16669. mg_get_response(struct mg_connection *conn,
  16670. char *ebuf,
  16671. size_t ebuf_len,
  16672. int timeout)
  16673. {
  16674. int err, ret;
  16675. char txt[32]; /* will not overflow */
  16676. char *save_timeout;
  16677. char *new_timeout;
  16678. if (ebuf_len > 0) {
  16679. ebuf[0] = '\0';
  16680. }
  16681. if (!conn) {
  16682. mg_snprintf(conn,
  16683. NULL, /* No truncation check for ebuf */
  16684. ebuf,
  16685. ebuf_len,
  16686. "%s",
  16687. "Parameter error");
  16688. return -1;
  16689. }
  16690. /* Reset the previous responses */
  16691. conn->data_len = 0;
  16692. /* Implementation of API function for HTTP clients */
  16693. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16694. if (timeout >= 0) {
  16695. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16696. new_timeout = txt;
  16697. } else {
  16698. new_timeout = NULL;
  16699. }
  16700. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16701. ret = get_response(conn, ebuf, ebuf_len, &err);
  16702. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16703. /* TODO: here, the URI is the http response code */
  16704. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16705. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16706. /* TODO (mid): Define proper return values - maybe return length?
  16707. * For the first test use <0 for error and >0 for OK */
  16708. return (ret == 0) ? -1 : +1;
  16709. }
  16710. CIVETWEB_API struct mg_connection *
  16711. mg_download(const char *host,
  16712. int port,
  16713. int use_ssl,
  16714. char *ebuf,
  16715. size_t ebuf_len,
  16716. const char *fmt,
  16717. ...)
  16718. {
  16719. struct mg_connection *conn;
  16720. va_list ap;
  16721. int i;
  16722. int reqerr;
  16723. if (ebuf_len > 0) {
  16724. ebuf[0] = '\0';
  16725. }
  16726. va_start(ap, fmt);
  16727. /* open a connection */
  16728. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16729. if (conn != NULL) {
  16730. i = mg_vprintf(conn, fmt, ap);
  16731. if (i <= 0) {
  16732. mg_snprintf(conn,
  16733. NULL, /* No truncation check for ebuf */
  16734. ebuf,
  16735. ebuf_len,
  16736. "%s",
  16737. "Error sending request");
  16738. } else {
  16739. /* make sure the buffer is clear */
  16740. conn->data_len = 0;
  16741. get_response(conn, ebuf, ebuf_len, &reqerr);
  16742. /* TODO: here, the URI is the http response code */
  16743. conn->request_info.local_uri = conn->request_info.request_uri;
  16744. }
  16745. }
  16746. /* if an error occurred, close the connection */
  16747. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16748. mg_close_connection(conn);
  16749. conn = NULL;
  16750. }
  16751. va_end(ap);
  16752. return conn;
  16753. }
  16754. struct websocket_client_thread_data {
  16755. struct mg_connection *conn;
  16756. mg_websocket_data_handler data_handler;
  16757. mg_websocket_close_handler close_handler;
  16758. void *callback_data;
  16759. };
  16760. #if defined(USE_WEBSOCKET)
  16761. #if defined(_WIN32)
  16762. static unsigned __stdcall websocket_client_thread(void *data)
  16763. #else
  16764. static void *
  16765. websocket_client_thread(void *data)
  16766. #endif
  16767. {
  16768. struct websocket_client_thread_data *cdata =
  16769. (struct websocket_client_thread_data *)data;
  16770. void *user_thread_ptr = NULL;
  16771. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16772. struct sigaction sa;
  16773. /* Ignore SIGPIPE */
  16774. memset(&sa, 0, sizeof(sa));
  16775. sa.sa_handler = SIG_IGN;
  16776. sigaction(SIGPIPE, &sa, NULL);
  16777. #endif
  16778. mg_set_thread_name("ws-clnt");
  16779. if (cdata->conn->phys_ctx) {
  16780. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16781. /* 3 indicates a websocket client thread */
  16782. /* TODO: check if conn->phys_ctx can be set */
  16783. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16784. cdata->conn->phys_ctx, 3);
  16785. }
  16786. }
  16787. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16788. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16789. if (cdata->close_handler != NULL) {
  16790. cdata->close_handler(cdata->conn, cdata->callback_data);
  16791. }
  16792. /* The websocket_client context has only this thread. If it runs out,
  16793. set the stop_flag to 2 (= "stopped"). */
  16794. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16795. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16796. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16797. 3,
  16798. user_thread_ptr);
  16799. }
  16800. mg_free((void *)cdata);
  16801. #if defined(_WIN32)
  16802. return 0;
  16803. #else
  16804. return NULL;
  16805. #endif
  16806. }
  16807. #endif
  16808. #if defined(USE_WEBSOCKET)
  16809. static void
  16810. generate_websocket_magic(char *magic25)
  16811. {
  16812. uint64_t rnd;
  16813. unsigned char buffer[2 * sizeof(rnd)];
  16814. rnd = get_random();
  16815. memcpy(buffer, &rnd, sizeof(rnd));
  16816. rnd = get_random();
  16817. memcpy(buffer + sizeof(rnd), &rnd, sizeof(rnd));
  16818. size_t dst_len = 24 + 1;
  16819. mg_base64_encode(buffer, sizeof(buffer), magic25, &dst_len);
  16820. }
  16821. #endif
  16822. static struct mg_connection *
  16823. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16824. int use_ssl,
  16825. char *error_buffer,
  16826. size_t error_buffer_size,
  16827. const char *path,
  16828. const char *origin,
  16829. const char *extensions,
  16830. mg_websocket_data_handler data_func,
  16831. mg_websocket_close_handler close_func,
  16832. void *user_data)
  16833. {
  16834. struct mg_connection *conn = NULL;
  16835. #if defined(USE_WEBSOCKET)
  16836. struct websocket_client_thread_data *thread_data;
  16837. char magic[32];
  16838. generate_websocket_magic(magic);
  16839. const char *host = client_options->host;
  16840. int i;
  16841. struct mg_init_data init;
  16842. struct mg_error_data error;
  16843. memset(&init, 0, sizeof(init));
  16844. memset(&error, 0, sizeof(error));
  16845. error.text_buffer_size = error_buffer_size;
  16846. error.text = error_buffer;
  16847. #if defined(__clang__)
  16848. #pragma clang diagnostic push
  16849. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16850. #endif
  16851. /* Establish the client connection and request upgrade */
  16852. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16853. /* Connection object will be null if something goes wrong */
  16854. if (conn == NULL) {
  16855. /* error_buffer should be already filled ... */
  16856. if (!error_buffer[0]) {
  16857. /* ... if not add an error message */
  16858. mg_snprintf(conn,
  16859. NULL, /* No truncation check for ebuf */
  16860. error_buffer,
  16861. error_buffer_size,
  16862. "Unexpected error");
  16863. }
  16864. return NULL;
  16865. }
  16866. if (origin != NULL) {
  16867. if (extensions != NULL) {
  16868. i = mg_printf(conn,
  16869. "GET %s HTTP/1.1\r\n"
  16870. "Host: %s\r\n"
  16871. "Upgrade: websocket\r\n"
  16872. "Connection: Upgrade\r\n"
  16873. "Sec-WebSocket-Key: %s\r\n"
  16874. "Sec-WebSocket-Version: 13\r\n"
  16875. "Sec-WebSocket-Extensions: %s\r\n"
  16876. "Origin: %s\r\n"
  16877. "\r\n",
  16878. path,
  16879. host,
  16880. magic,
  16881. extensions,
  16882. origin);
  16883. } else {
  16884. i = mg_printf(conn,
  16885. "GET %s HTTP/1.1\r\n"
  16886. "Host: %s\r\n"
  16887. "Upgrade: websocket\r\n"
  16888. "Connection: Upgrade\r\n"
  16889. "Sec-WebSocket-Key: %s\r\n"
  16890. "Sec-WebSocket-Version: 13\r\n"
  16891. "Origin: %s\r\n"
  16892. "\r\n",
  16893. path,
  16894. host,
  16895. magic,
  16896. origin);
  16897. }
  16898. } else {
  16899. if (extensions != NULL) {
  16900. i = mg_printf(conn,
  16901. "GET %s HTTP/1.1\r\n"
  16902. "Host: %s\r\n"
  16903. "Upgrade: websocket\r\n"
  16904. "Connection: Upgrade\r\n"
  16905. "Sec-WebSocket-Key: %s\r\n"
  16906. "Sec-WebSocket-Version: 13\r\n"
  16907. "Sec-WebSocket-Extensions: %s\r\n"
  16908. "\r\n",
  16909. path,
  16910. host,
  16911. magic,
  16912. extensions);
  16913. } else {
  16914. i = mg_printf(conn,
  16915. "GET %s HTTP/1.1\r\n"
  16916. "Host: %s\r\n"
  16917. "Upgrade: websocket\r\n"
  16918. "Connection: Upgrade\r\n"
  16919. "Sec-WebSocket-Key: %s\r\n"
  16920. "Sec-WebSocket-Version: 13\r\n"
  16921. "\r\n",
  16922. path,
  16923. host,
  16924. magic);
  16925. }
  16926. }
  16927. if (i <= 0) {
  16928. mg_snprintf(conn,
  16929. NULL, /* No truncation check for ebuf */
  16930. error_buffer,
  16931. error_buffer_size,
  16932. "%s",
  16933. "Error sending request");
  16934. mg_close_connection(conn);
  16935. return NULL;
  16936. }
  16937. conn->data_len = 0;
  16938. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16939. mg_close_connection(conn);
  16940. return NULL;
  16941. }
  16942. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16943. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16944. #if defined(__clang__)
  16945. #pragma clang diagnostic pop
  16946. #endif
  16947. if (conn->response_info.status_code != 101) {
  16948. /* We sent an "upgrade" request. For a correct websocket
  16949. * protocol handshake, we expect a "101 Continue" response.
  16950. * Otherwise it is a protocol violation. Maybe the HTTP
  16951. * Server does not know websockets. */
  16952. if (!*error_buffer) {
  16953. /* set an error, if not yet set */
  16954. mg_snprintf(conn,
  16955. NULL, /* No truncation check for ebuf */
  16956. error_buffer,
  16957. error_buffer_size,
  16958. "Unexpected server reply");
  16959. }
  16960. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16961. mg_close_connection(conn);
  16962. return NULL;
  16963. }
  16964. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16965. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16966. if (!thread_data) {
  16967. DEBUG_TRACE("%s\r\n", "Out of memory");
  16968. mg_close_connection(conn);
  16969. return NULL;
  16970. }
  16971. thread_data->conn = conn;
  16972. thread_data->data_handler = data_func;
  16973. thread_data->close_handler = close_func;
  16974. thread_data->callback_data = user_data;
  16975. conn->phys_ctx->worker_threadids =
  16976. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16977. if (!conn->phys_ctx->worker_threadids) {
  16978. DEBUG_TRACE("%s\r\n", "Out of memory");
  16979. mg_free(thread_data);
  16980. mg_close_connection(conn);
  16981. return NULL;
  16982. }
  16983. /* Now upgrade to ws/wss client context */
  16984. conn->phys_ctx->user_data = user_data;
  16985. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16986. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  16987. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  16988. /* Start a thread to read the websocket client connection
  16989. * This thread will automatically stop when mg_disconnect is
  16990. * called on the client connection */
  16991. if (mg_start_thread_with_id(websocket_client_thread,
  16992. thread_data,
  16993. conn->phys_ctx->worker_threadids)
  16994. != 0) {
  16995. conn->phys_ctx->spawned_worker_threads = 0;
  16996. mg_free(thread_data);
  16997. mg_close_connection(conn);
  16998. conn = NULL;
  16999. DEBUG_TRACE("%s",
  17000. "Websocket client connect thread could not be started\r\n");
  17001. }
  17002. #else
  17003. /* Appease "unused parameter" warnings */
  17004. (void)client_options;
  17005. (void)use_ssl;
  17006. (void)error_buffer;
  17007. (void)error_buffer_size;
  17008. (void)path;
  17009. (void)origin;
  17010. (void)extensions;
  17011. (void)user_data;
  17012. (void)data_func;
  17013. (void)close_func;
  17014. #endif
  17015. return conn;
  17016. }
  17017. CIVETWEB_API struct mg_connection *
  17018. mg_connect_websocket_client(const char *host,
  17019. int port,
  17020. int use_ssl,
  17021. char *error_buffer,
  17022. size_t error_buffer_size,
  17023. const char *path,
  17024. const char *origin,
  17025. mg_websocket_data_handler data_func,
  17026. mg_websocket_close_handler close_func,
  17027. void *user_data)
  17028. {
  17029. struct mg_client_options client_options;
  17030. memset(&client_options, 0, sizeof(client_options));
  17031. client_options.host = host;
  17032. client_options.port = port;
  17033. if (use_ssl) {
  17034. client_options.host_name = host;
  17035. }
  17036. return mg_connect_websocket_client_impl(&client_options,
  17037. use_ssl,
  17038. error_buffer,
  17039. error_buffer_size,
  17040. path,
  17041. origin,
  17042. NULL,
  17043. data_func,
  17044. close_func,
  17045. user_data);
  17046. }
  17047. CIVETWEB_API struct mg_connection *
  17048. mg_connect_websocket_client_secure(
  17049. const struct mg_client_options *client_options,
  17050. char *error_buffer,
  17051. size_t error_buffer_size,
  17052. const char *path,
  17053. const char *origin,
  17054. mg_websocket_data_handler data_func,
  17055. mg_websocket_close_handler close_func,
  17056. void *user_data)
  17057. {
  17058. if (!client_options) {
  17059. return NULL;
  17060. }
  17061. return mg_connect_websocket_client_impl(client_options,
  17062. 1,
  17063. error_buffer,
  17064. error_buffer_size,
  17065. path,
  17066. origin,
  17067. NULL,
  17068. data_func,
  17069. close_func,
  17070. user_data);
  17071. }
  17072. CIVETWEB_API struct mg_connection *
  17073. mg_connect_websocket_client_extensions(const char *host,
  17074. int port,
  17075. int use_ssl,
  17076. char *error_buffer,
  17077. size_t error_buffer_size,
  17078. const char *path,
  17079. const char *origin,
  17080. const char *extensions,
  17081. mg_websocket_data_handler data_func,
  17082. mg_websocket_close_handler close_func,
  17083. void *user_data)
  17084. {
  17085. struct mg_client_options client_options;
  17086. memset(&client_options, 0, sizeof(client_options));
  17087. client_options.host = host;
  17088. client_options.port = port;
  17089. return mg_connect_websocket_client_impl(&client_options,
  17090. use_ssl,
  17091. error_buffer,
  17092. error_buffer_size,
  17093. path,
  17094. origin,
  17095. extensions,
  17096. data_func,
  17097. close_func,
  17098. user_data);
  17099. }
  17100. CIVETWEB_API struct mg_connection *
  17101. mg_connect_websocket_client_secure_extensions(
  17102. const struct mg_client_options *client_options,
  17103. char *error_buffer,
  17104. size_t error_buffer_size,
  17105. const char *path,
  17106. const char *origin,
  17107. const char *extensions,
  17108. mg_websocket_data_handler data_func,
  17109. mg_websocket_close_handler close_func,
  17110. void *user_data)
  17111. {
  17112. if (!client_options) {
  17113. return NULL;
  17114. }
  17115. return mg_connect_websocket_client_impl(client_options,
  17116. 1,
  17117. error_buffer,
  17118. error_buffer_size,
  17119. path,
  17120. origin,
  17121. extensions,
  17122. data_func,
  17123. close_func,
  17124. user_data);
  17125. }
  17126. /* Prepare connection data structure */
  17127. static void
  17128. init_connection(struct mg_connection *conn)
  17129. {
  17130. /* Is keep alive allowed by the server */
  17131. int keep_alive_enabled =
  17132. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  17133. if (!keep_alive_enabled) {
  17134. conn->must_close = 1;
  17135. }
  17136. /* Important: on new connection, reset the receiving buffer. Credit
  17137. * goes to crule42. */
  17138. conn->data_len = 0;
  17139. conn->handled_requests = 0;
  17140. conn->connection_type = CONNECTION_TYPE_INVALID;
  17141. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  17142. mg_set_user_connection_data(conn, NULL);
  17143. #if defined(USE_SERVER_STATS)
  17144. conn->conn_state = 2; /* init */
  17145. #endif
  17146. /* call the init_connection callback if assigned */
  17147. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  17148. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  17149. void *conn_data = NULL;
  17150. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  17151. mg_set_user_connection_data(conn, conn_data);
  17152. }
  17153. }
  17154. }
  17155. /* Process a connection - may handle multiple requests
  17156. * using the same connection.
  17157. * Must be called with a valid connection (conn and
  17158. * conn->phys_ctx must be valid).
  17159. */
  17160. static void
  17161. process_new_connection(struct mg_connection *conn)
  17162. {
  17163. struct mg_request_info *ri = &conn->request_info;
  17164. int keep_alive, discard_len;
  17165. char ebuf[100];
  17166. const char *hostend;
  17167. int reqerr, uri_type;
  17168. #if defined(USE_SERVER_STATS)
  17169. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  17170. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  17171. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  17172. #endif
  17173. DEBUG_TRACE("Start processing connection from %s",
  17174. conn->request_info.remote_addr);
  17175. /* Loop over multiple requests sent using the same connection
  17176. * (while "keep alive"). */
  17177. do {
  17178. DEBUG_TRACE("calling get_request (%i times for this connection)",
  17179. conn->handled_requests + 1);
  17180. #if defined(USE_SERVER_STATS)
  17181. conn->conn_state = 3; /* ready */
  17182. #endif
  17183. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  17184. /* The request sent by the client could not be understood by
  17185. * the server, or it was incomplete or a timeout. Send an
  17186. * error message and close the connection. */
  17187. if (reqerr > 0) {
  17188. DEBUG_ASSERT(ebuf[0] != '\0');
  17189. mg_send_http_error(conn, reqerr, "%s", ebuf);
  17190. }
  17191. } else if (strcmp(ri->http_version, "1.0")
  17192. && strcmp(ri->http_version, "1.1")) {
  17193. /* HTTP/2 is not allowed here */
  17194. mg_snprintf(conn,
  17195. NULL, /* No truncation check for ebuf */
  17196. ebuf,
  17197. sizeof(ebuf),
  17198. "Bad HTTP version: [%s]",
  17199. ri->http_version);
  17200. mg_send_http_error(conn, 505, "%s", ebuf);
  17201. }
  17202. if (ebuf[0] == '\0') {
  17203. uri_type = get_uri_type(conn->request_info.request_uri);
  17204. switch (uri_type) {
  17205. case 1:
  17206. /* Asterisk */
  17207. conn->request_info.local_uri_raw = 0;
  17208. /* TODO: Deal with '*'. */
  17209. break;
  17210. case 2:
  17211. /* relative uri */
  17212. conn->request_info.local_uri_raw =
  17213. conn->request_info.request_uri;
  17214. break;
  17215. case 3:
  17216. case 4:
  17217. /* absolute uri (with/without port) */
  17218. hostend = get_rel_url_at_current_server(
  17219. conn->request_info.request_uri, conn);
  17220. if (hostend) {
  17221. conn->request_info.local_uri_raw = hostend;
  17222. } else {
  17223. conn->request_info.local_uri_raw = NULL;
  17224. }
  17225. break;
  17226. default:
  17227. mg_snprintf(conn,
  17228. NULL, /* No truncation check for ebuf */
  17229. ebuf,
  17230. sizeof(ebuf),
  17231. "Invalid URI");
  17232. mg_send_http_error(conn, 400, "%s", ebuf);
  17233. conn->request_info.local_uri_raw = NULL;
  17234. break;
  17235. }
  17236. conn->request_info.local_uri =
  17237. (char *)conn->request_info.local_uri_raw;
  17238. }
  17239. if (ebuf[0] != '\0') {
  17240. conn->protocol_type = -1;
  17241. } else {
  17242. /* HTTP/1 allows protocol upgrade */
  17243. conn->protocol_type = should_switch_to_protocol(conn);
  17244. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  17245. /* This will occur, if a HTTP/1.1 request should be upgraded
  17246. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  17247. * Since most (all?) major browsers only support HTTP/2 using
  17248. * ALPN, this is hard to test and very low priority.
  17249. * Deactivate it (at least for now).
  17250. */
  17251. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17252. }
  17253. }
  17254. DEBUG_TRACE("http: %s, error: %s",
  17255. (ri->http_version ? ri->http_version : "none"),
  17256. (ebuf[0] ? ebuf : "none"));
  17257. if (ebuf[0] == '\0') {
  17258. if (conn->request_info.local_uri) {
  17259. /* handle request to local server */
  17260. handle_request_stat_log(conn);
  17261. } else {
  17262. /* TODO: handle non-local request (PROXY) */
  17263. conn->must_close = 1;
  17264. }
  17265. } else {
  17266. conn->must_close = 1;
  17267. }
  17268. /* Response complete. Free header buffer */
  17269. free_buffered_response_header_list(conn);
  17270. if (ri->remote_user != NULL) {
  17271. mg_free((void *)ri->remote_user);
  17272. /* Important! When having connections with and without auth
  17273. * would cause double free and then crash */
  17274. ri->remote_user = NULL;
  17275. }
  17276. /* NOTE(lsm): order is important here. should_keep_alive() call
  17277. * is using parsed request, which will be invalid after
  17278. * memmove's below.
  17279. * Therefore, memorize should_keep_alive() result now for later
  17280. * use in loop exit condition. */
  17281. /* Enable it only if this request is completely discardable. */
  17282. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  17283. && should_keep_alive(conn) && (conn->content_len >= 0)
  17284. && (conn->request_len > 0)
  17285. && ((conn->is_chunked == 4)
  17286. || (!conn->is_chunked
  17287. && ((conn->consumed_content == conn->content_len)
  17288. || ((conn->request_len + conn->content_len)
  17289. <= conn->data_len))))
  17290. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  17291. if (keep_alive) {
  17292. /* Discard all buffered data for this request */
  17293. discard_len =
  17294. ((conn->request_len + conn->content_len) < conn->data_len)
  17295. ? (int)(conn->request_len + conn->content_len)
  17296. : conn->data_len;
  17297. conn->data_len -= discard_len;
  17298. if (conn->data_len > 0) {
  17299. DEBUG_TRACE("discard_len = %d", discard_len);
  17300. memmove(conn->buf,
  17301. conn->buf + discard_len,
  17302. (size_t)conn->data_len);
  17303. }
  17304. }
  17305. DEBUG_ASSERT(conn->data_len >= 0);
  17306. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  17307. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  17308. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  17309. (long int)conn->data_len,
  17310. (long int)conn->buf_size);
  17311. break;
  17312. }
  17313. conn->handled_requests++;
  17314. } while (keep_alive);
  17315. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  17316. conn->request_info.remote_addr,
  17317. difftime(time(NULL), conn->conn_birth_time));
  17318. close_connection(conn);
  17319. #if defined(USE_SERVER_STATS)
  17320. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17321. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17322. #endif
  17323. }
  17324. static int
  17325. mg_start_worker_thread(struct mg_context *ctx,
  17326. int only_if_no_idle_threads); /* forward declaration */
  17327. #if defined(ALTERNATIVE_QUEUE)
  17328. static void
  17329. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17330. {
  17331. unsigned int i;
  17332. (void)mg_start_worker_thread(
  17333. ctx, 1); /* will start a worker-thread only if there aren't currently
  17334. any idle worker-threads */
  17335. while (!ctx->stop_flag) {
  17336. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17337. /* find a free worker slot and signal it */
  17338. if (ctx->client_socks[i].in_use == 2) {
  17339. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17340. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17341. ctx->client_socks[i] = *sp;
  17342. ctx->client_socks[i].in_use = 1;
  17343. /* socket has been moved to the consumer */
  17344. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17345. (void)event_signal(ctx->client_wait_events[i]);
  17346. return;
  17347. }
  17348. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17349. }
  17350. }
  17351. /* queue is full */
  17352. mg_sleep(1);
  17353. }
  17354. /* must consume */
  17355. set_blocking_mode(sp->sock);
  17356. closesocket(sp->sock);
  17357. }
  17358. static int
  17359. consume_socket(struct mg_context *ctx,
  17360. struct socket *sp,
  17361. int thread_index,
  17362. int counter_was_preincremented)
  17363. {
  17364. DEBUG_TRACE("%s", "going idle");
  17365. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17366. if (counter_was_preincremented
  17367. == 0) { /* first call only: the master-thread pre-incremented this
  17368. before he spawned us */
  17369. ctx->idle_worker_thread_count++;
  17370. }
  17371. ctx->client_socks[thread_index].in_use = 2;
  17372. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17373. event_wait(ctx->client_wait_events[thread_index]);
  17374. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17375. *sp = ctx->client_socks[thread_index];
  17376. if (ctx->stop_flag) {
  17377. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17378. if (sp->in_use == 1) {
  17379. /* must consume */
  17380. set_blocking_mode(sp->sock);
  17381. closesocket(sp->sock);
  17382. }
  17383. return 0;
  17384. }
  17385. ctx->idle_worker_thread_count--;
  17386. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17387. if (sp->in_use == 1) {
  17388. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17389. return 1;
  17390. }
  17391. /* must not reach here */
  17392. DEBUG_ASSERT(0);
  17393. return 0;
  17394. }
  17395. #else /* ALTERNATIVE_QUEUE */
  17396. /* Worker threads take accepted socket from the queue */
  17397. static int
  17398. consume_socket(struct mg_context *ctx,
  17399. struct socket *sp,
  17400. int thread_index,
  17401. int counter_was_preincremented)
  17402. {
  17403. (void)thread_index;
  17404. DEBUG_TRACE("%s", "going idle");
  17405. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17406. if (counter_was_preincremented
  17407. == 0) { /* first call only: the master-thread pre-incremented this
  17408. before he spawned us */
  17409. ctx->idle_worker_thread_count++;
  17410. }
  17411. /* If the queue is empty, wait. We're idle at this point. */
  17412. while ((ctx->sq_head == ctx->sq_tail)
  17413. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17414. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17415. }
  17416. /* If we're stopping, sq_head may be equal to sq_tail. */
  17417. if (ctx->sq_head > ctx->sq_tail) {
  17418. /* Copy socket from the queue and increment tail */
  17419. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17420. ctx->sq_tail++;
  17421. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17422. /* Wrap pointers if needed */
  17423. while (ctx->sq_tail > ctx->sq_size) {
  17424. ctx->sq_tail -= ctx->sq_size;
  17425. ctx->sq_head -= ctx->sq_size;
  17426. }
  17427. }
  17428. (void)pthread_cond_signal(&ctx->sq_empty);
  17429. ctx->idle_worker_thread_count--;
  17430. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17431. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17432. }
  17433. /* Master thread adds accepted socket to a queue */
  17434. static void
  17435. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17436. {
  17437. int queue_filled;
  17438. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17439. queue_filled = ctx->sq_head - ctx->sq_tail;
  17440. /* If the queue is full, wait */
  17441. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17442. && (queue_filled >= ctx->sq_size)) {
  17443. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17444. #if defined(USE_SERVER_STATS)
  17445. if (queue_filled > ctx->sq_max_fill) {
  17446. ctx->sq_max_fill = queue_filled;
  17447. }
  17448. #endif
  17449. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17450. ctx->sq_blocked = 0; /* Not blocked now */
  17451. queue_filled = ctx->sq_head - ctx->sq_tail;
  17452. }
  17453. if (queue_filled < ctx->sq_size) {
  17454. /* Copy socket to the queue and increment head */
  17455. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17456. ctx->sq_head++;
  17457. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17458. }
  17459. queue_filled = ctx->sq_head - ctx->sq_tail;
  17460. #if defined(USE_SERVER_STATS)
  17461. if (queue_filled > ctx->sq_max_fill) {
  17462. ctx->sq_max_fill = queue_filled;
  17463. }
  17464. #endif
  17465. (void)pthread_cond_signal(&ctx->sq_full);
  17466. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17467. (void)mg_start_worker_thread(
  17468. ctx, 1); /* will start a worker-thread only if there aren't currently
  17469. any idle worker-threads */
  17470. }
  17471. #endif /* ALTERNATIVE_QUEUE */
  17472. static void
  17473. worker_thread_run(struct mg_connection *conn)
  17474. {
  17475. struct mg_context *ctx = conn->phys_ctx;
  17476. int thread_index;
  17477. struct mg_workerTLS tls;
  17478. int first_call_to_consume_socket = 1;
  17479. mg_set_thread_name("worker");
  17480. tls.is_master = 0;
  17481. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17482. #if defined(_WIN32)
  17483. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17484. #endif
  17485. /* Initialize thread local storage before calling any callback */
  17486. pthread_setspecific(sTlsKey, &tls);
  17487. /* Check if there is a user callback */
  17488. if (ctx->callbacks.init_thread) {
  17489. /* call init_thread for a worker thread (type 1), and store the
  17490. * return value */
  17491. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17492. } else {
  17493. /* No callback: set user pointer to NULL */
  17494. tls.user_ptr = NULL;
  17495. }
  17496. /* Connection structure has been pre-allocated */
  17497. thread_index = (int)(conn - ctx->worker_connections);
  17498. if ((thread_index < 0)
  17499. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17500. mg_cry_ctx_internal(ctx,
  17501. "Internal error: Invalid worker index %i",
  17502. thread_index);
  17503. return;
  17504. }
  17505. /* Request buffers are not pre-allocated. They are private to the
  17506. * request and do not contain any state information that might be
  17507. * of interest to anyone observing a server status. */
  17508. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17509. if (conn->buf == NULL) {
  17510. mg_cry_ctx_internal(
  17511. ctx,
  17512. "Out of memory: Cannot allocate buffer for worker %i",
  17513. thread_index);
  17514. return;
  17515. }
  17516. conn->buf_size = (int)ctx->max_request_size;
  17517. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17518. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17519. conn->request_info.user_data = ctx->user_data;
  17520. /* Allocate a mutex for this connection to allow communication both
  17521. * within the request handler and from elsewhere in the application
  17522. */
  17523. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17524. mg_free(conn->buf);
  17525. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17526. return;
  17527. }
  17528. #if defined(USE_SERVER_STATS)
  17529. conn->conn_state = 1; /* not consumed */
  17530. #endif
  17531. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17532. * signal sq_empty condvar to wake up the master waiting in
  17533. * produce_socket() */
  17534. while (consume_socket(
  17535. ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17536. first_call_to_consume_socket = 0;
  17537. /* New connections must start with new protocol negotiation */
  17538. tls.alpn_proto = NULL;
  17539. #if defined(USE_SERVER_STATS)
  17540. conn->conn_close_time = 0;
  17541. #endif
  17542. conn->conn_birth_time = time(NULL);
  17543. /* Fill in IP, port info early so even if SSL setup below fails,
  17544. * error handler would have the corresponding info.
  17545. * Thanks to Johannes Winkelmann for the patch.
  17546. */
  17547. conn->request_info.remote_port =
  17548. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17549. conn->request_info.server_port =
  17550. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17551. sockaddr_to_string(conn->request_info.remote_addr,
  17552. sizeof(conn->request_info.remote_addr),
  17553. &conn->client.rsa);
  17554. DEBUG_TRACE("Incoming %sconnection from %s",
  17555. (conn->client.is_ssl ? "SSL " : ""),
  17556. conn->request_info.remote_addr);
  17557. conn->request_info.is_ssl = conn->client.is_ssl;
  17558. if (conn->client.is_ssl) {
  17559. #if defined(USE_MBEDTLS)
  17560. /* HTTPS connection */
  17561. if (mbed_ssl_accept(&(conn->ssl),
  17562. conn->dom_ctx->ssl_ctx,
  17563. (int *)&(conn->client.sock),
  17564. conn->phys_ctx)
  17565. == 0) {
  17566. /* conn->dom_ctx is set in get_request */
  17567. /* process HTTPS connection */
  17568. init_connection(conn);
  17569. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17570. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17571. process_new_connection(conn);
  17572. } else {
  17573. /* make sure the connection is cleaned up on SSL failure */
  17574. close_connection(conn);
  17575. }
  17576. #elif defined(USE_GNUTLS)
  17577. /* HTTPS connection */
  17578. if (gtls_ssl_accept(&(conn->ssl),
  17579. conn->dom_ctx->ssl_ctx,
  17580. conn->client.sock,
  17581. conn->phys_ctx)
  17582. == 0) {
  17583. /* conn->dom_ctx is set in get_request */
  17584. /* process HTTPS connection */
  17585. init_connection(conn);
  17586. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17587. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17588. process_new_connection(conn);
  17589. } else {
  17590. /* make sure the connection is cleaned up on SSL failure */
  17591. close_connection(conn);
  17592. }
  17593. #elif !defined(NO_SSL)
  17594. /* HTTPS connection */
  17595. if (sslize(conn, SSL_accept, NULL)) {
  17596. /* conn->dom_ctx is set in get_request */
  17597. /* Get SSL client certificate information (if set) */
  17598. struct mg_client_cert client_cert;
  17599. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17600. conn->request_info.client_cert = &client_cert;
  17601. }
  17602. /* process HTTPS connection */
  17603. #if defined(USE_HTTP2)
  17604. if ((tls.alpn_proto != NULL)
  17605. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17606. /* process HTTPS/2 connection */
  17607. init_connection(conn);
  17608. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17609. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17610. conn->content_len =
  17611. -1; /* content length is not predefined */
  17612. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17613. process_new_http2_connection(conn);
  17614. } else
  17615. #endif
  17616. {
  17617. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17618. init_connection(conn);
  17619. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17620. /* Start with HTTP, WS will be an "upgrade" request later */
  17621. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17622. process_new_connection(conn);
  17623. }
  17624. /* Free client certificate info */
  17625. if (conn->request_info.client_cert) {
  17626. mg_free((void *)(conn->request_info.client_cert->subject));
  17627. mg_free((void *)(conn->request_info.client_cert->issuer));
  17628. mg_free((void *)(conn->request_info.client_cert->serial));
  17629. mg_free((void *)(conn->request_info.client_cert->finger));
  17630. /* Free certificate memory */
  17631. X509_free(
  17632. (X509 *)conn->request_info.client_cert->peer_cert);
  17633. conn->request_info.client_cert->peer_cert = 0;
  17634. conn->request_info.client_cert->subject = 0;
  17635. conn->request_info.client_cert->issuer = 0;
  17636. conn->request_info.client_cert->serial = 0;
  17637. conn->request_info.client_cert->finger = 0;
  17638. conn->request_info.client_cert = 0;
  17639. }
  17640. } else {
  17641. /* make sure the connection is cleaned up on SSL failure */
  17642. close_connection(conn);
  17643. }
  17644. #endif
  17645. } else {
  17646. /* process HTTP connection */
  17647. init_connection(conn);
  17648. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17649. /* Start with HTTP, WS will be an "upgrade" request later */
  17650. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17651. process_new_connection(conn);
  17652. }
  17653. DEBUG_TRACE("%s", "Connection closed");
  17654. #if defined(USE_SERVER_STATS)
  17655. conn->conn_close_time = time(NULL);
  17656. #endif
  17657. }
  17658. /* Call exit thread user callback */
  17659. if (ctx->callbacks.exit_thread) {
  17660. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17661. }
  17662. /* delete thread local storage objects */
  17663. pthread_setspecific(sTlsKey, NULL);
  17664. #if defined(_WIN32)
  17665. CloseHandle(tls.pthread_cond_helper_mutex);
  17666. #endif
  17667. pthread_mutex_destroy(&conn->mutex);
  17668. /* Free the request buffer. */
  17669. conn->buf_size = 0;
  17670. mg_free(conn->buf);
  17671. conn->buf = NULL;
  17672. /* Free cleaned URI (if any) */
  17673. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17674. mg_free((void *)conn->request_info.local_uri);
  17675. conn->request_info.local_uri = NULL;
  17676. }
  17677. #if defined(USE_SERVER_STATS)
  17678. conn->conn_state = 9; /* done */
  17679. #endif
  17680. DEBUG_TRACE("%s", "exiting");
  17681. }
  17682. /* Threads have different return types on Windows and Unix. */
  17683. #if defined(_WIN32)
  17684. static unsigned __stdcall worker_thread(void *thread_func_param)
  17685. {
  17686. worker_thread_run((struct mg_connection *)thread_func_param);
  17687. return 0;
  17688. }
  17689. #else
  17690. static void *
  17691. worker_thread(void *thread_func_param)
  17692. {
  17693. #if !defined(__ZEPHYR__)
  17694. struct sigaction sa;
  17695. /* Ignore SIGPIPE */
  17696. memset(&sa, 0, sizeof(sa));
  17697. sa.sa_handler = SIG_IGN;
  17698. sigaction(SIGPIPE, &sa, NULL);
  17699. #endif
  17700. worker_thread_run((struct mg_connection *)thread_func_param);
  17701. return NULL;
  17702. }
  17703. #endif /* _WIN32 */
  17704. /* This is an internal function, thus all arguments are expected to be
  17705. * valid - a NULL check is not required. */
  17706. static void
  17707. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17708. {
  17709. struct socket so;
  17710. char src_addr[IP_ADDR_STR_LEN];
  17711. socklen_t len = sizeof(so.rsa);
  17712. #if !defined(__ZEPHYR__)
  17713. int on = 1;
  17714. #endif
  17715. memset(&so, 0, sizeof(so));
  17716. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17717. == INVALID_SOCKET) {
  17718. } else if (check_acl(ctx, &so.rsa) != 1) {
  17719. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17720. mg_cry_ctx_internal(ctx,
  17721. "%s: %s is not allowed to connect",
  17722. __func__,
  17723. src_addr);
  17724. closesocket(so.sock);
  17725. } else {
  17726. /* Put so socket structure into the queue */
  17727. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17728. set_close_on_exec(so.sock, NULL, ctx);
  17729. so.is_ssl = listener->is_ssl;
  17730. so.ssl_redir = listener->ssl_redir;
  17731. so.is_optional = listener->is_optional;
  17732. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17733. mg_cry_ctx_internal(ctx,
  17734. "%s: getsockname() failed: %s",
  17735. __func__,
  17736. strerror(ERRNO));
  17737. }
  17738. #if !defined(__ZEPHYR__)
  17739. if ((so.lsa.sa.sa_family == AF_INET)
  17740. || (so.lsa.sa.sa_family == AF_INET6)) {
  17741. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17742. * This is needed because if HTTP-level keep-alive
  17743. * is enabled, and client resets the connection, server won't get
  17744. * TCP FIN or RST and will keep the connection open forever. With
  17745. * TCP keep-alive, next keep-alive handshake will figure out that
  17746. * the client is down and will close the server end.
  17747. * Thanks to Igor Klopov who suggested the patch. */
  17748. if (setsockopt(so.sock,
  17749. SOL_SOCKET,
  17750. SO_KEEPALIVE,
  17751. (SOCK_OPT_TYPE)&on,
  17752. sizeof(on))
  17753. != 0) {
  17754. mg_cry_ctx_internal(
  17755. ctx,
  17756. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17757. __func__,
  17758. strerror(ERRNO));
  17759. }
  17760. }
  17761. #endif
  17762. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17763. * to effectively fill up the underlying IP packet payload and
  17764. * reduce the overhead of sending lots of small buffers. However
  17765. * this hurts the server's throughput (ie. operations per second)
  17766. * when HTTP 1.1 persistent connections are used and the responses
  17767. * are relatively small (eg. less than 1400 bytes).
  17768. */
  17769. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17770. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17771. if (set_tcp_nodelay(&so, 1) != 0) {
  17772. mg_cry_ctx_internal(
  17773. ctx,
  17774. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17775. __func__,
  17776. strerror(ERRNO));
  17777. }
  17778. }
  17779. /* The "non blocking" property should already be
  17780. * inherited from the parent socket. Set it for
  17781. * non-compliant socket implementations. */
  17782. set_non_blocking_mode(so.sock);
  17783. so.in_use = 0;
  17784. produce_socket(ctx, &so);
  17785. }
  17786. }
  17787. static void
  17788. master_thread_run(struct mg_context *ctx)
  17789. {
  17790. struct mg_workerTLS tls;
  17791. struct mg_pollfd *pfd;
  17792. unsigned int i;
  17793. unsigned int workerthreadcount;
  17794. if (!ctx) {
  17795. return;
  17796. }
  17797. mg_set_thread_name("master");
  17798. /* Increase priority of the master thread */
  17799. #if defined(_WIN32)
  17800. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17801. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17802. int min_prio = sched_get_priority_min(SCHED_RR);
  17803. int max_prio = sched_get_priority_max(SCHED_RR);
  17804. if ((min_prio >= 0) && (max_prio >= 0)
  17805. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17806. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17807. struct sched_param sched_param = {0};
  17808. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17809. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17810. }
  17811. #endif
  17812. /* Initialize thread local storage */
  17813. #if defined(_WIN32)
  17814. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17815. #endif
  17816. tls.is_master = 1;
  17817. pthread_setspecific(sTlsKey, &tls);
  17818. if (ctx->callbacks.init_thread) {
  17819. /* Callback for the master thread (type 0) */
  17820. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17821. } else {
  17822. tls.user_ptr = NULL;
  17823. }
  17824. /* Lua background script "start" event */
  17825. #if defined(USE_LUA)
  17826. if (ctx->lua_background_state) {
  17827. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17828. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17829. /* call "start()" in Lua */
  17830. lua_getglobal(lstate, "start");
  17831. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17832. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17833. if (ret != 0) {
  17834. struct mg_connection fc;
  17835. lua_cry(fake_connection(&fc, ctx),
  17836. ret,
  17837. lstate,
  17838. "lua_background_script",
  17839. "start");
  17840. }
  17841. } else {
  17842. lua_pop(lstate, 1);
  17843. }
  17844. /* determine if there is a "log()" function in Lua background script */
  17845. lua_getglobal(lstate, "log");
  17846. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17847. ctx->lua_bg_log_available = 1;
  17848. }
  17849. lua_pop(lstate, 1);
  17850. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17851. }
  17852. #endif
  17853. /* Server starts *now* */
  17854. ctx->start_time = time(NULL);
  17855. /* Server accept loop */
  17856. pfd = ctx->listening_socket_fds;
  17857. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17858. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17859. pfd[i].fd = ctx->listening_sockets[i].sock;
  17860. pfd[i].events = POLLIN;
  17861. }
  17862. /* We listen on this socket just so that mg_stop() can cause mg_poll()
  17863. * to return ASAP. Don't worry, we did allocate an extra slot at the end
  17864. * of listening_socket_fds[] just to hold this
  17865. */
  17866. pfd[ctx->num_listening_sockets].fd =
  17867. ctx->thread_shutdown_notification_socket;
  17868. pfd[ctx->num_listening_sockets].events = POLLIN;
  17869. if (mg_poll(pfd,
  17870. ctx->num_listening_sockets
  17871. + 1, // +1 for the thread_shutdown_notification_socket
  17872. SOCKET_TIMEOUT_QUANTUM,
  17873. &(ctx->stop_flag))
  17874. > 0) {
  17875. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17876. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17877. * successful poll, and POLLIN is defined as
  17878. * (POLLRDNORM | POLLRDBAND)
  17879. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17880. * pfd[i].revents == POLLIN. */
  17881. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17882. && (pfd[i].revents & POLLIN)) {
  17883. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17884. }
  17885. }
  17886. }
  17887. }
  17888. /* Here stop_flag is 1 - Initiate shutdown. */
  17889. DEBUG_TRACE("%s", "stopping workers");
  17890. /* Stop signal received: somebody called mg_stop. Quit. */
  17891. close_all_listening_sockets(ctx);
  17892. /* Wakeup workers that are waiting for connections to handle. */
  17893. #if defined(ALTERNATIVE_QUEUE)
  17894. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17895. event_signal(ctx->client_wait_events[i]);
  17896. }
  17897. #else
  17898. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17899. pthread_cond_broadcast(&ctx->sq_full);
  17900. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17901. #endif
  17902. /* Join all worker threads to avoid leaking threads. */
  17903. workerthreadcount = ctx->spawned_worker_threads;
  17904. for (i = 0; i < workerthreadcount; i++) {
  17905. if (ctx->worker_threadids[i] != 0) {
  17906. mg_join_thread(ctx->worker_threadids[i]);
  17907. }
  17908. }
  17909. #if defined(USE_LUA)
  17910. /* Free Lua state of lua background task */
  17911. if (ctx->lua_background_state) {
  17912. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17913. ctx->lua_bg_log_available = 0;
  17914. /* call "stop()" in Lua */
  17915. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17916. lua_getglobal(lstate, "stop");
  17917. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17918. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17919. if (ret != 0) {
  17920. struct mg_connection fc;
  17921. lua_cry(fake_connection(&fc, ctx),
  17922. ret,
  17923. lstate,
  17924. "lua_background_script",
  17925. "stop");
  17926. }
  17927. }
  17928. DEBUG_TRACE("Close Lua background state %p", lstate);
  17929. lua_close(lstate);
  17930. ctx->lua_background_state = 0;
  17931. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17932. }
  17933. #endif
  17934. DEBUG_TRACE("%s", "exiting");
  17935. /* call exit thread callback */
  17936. if (ctx->callbacks.exit_thread) {
  17937. /* Callback for the master thread (type 0) */
  17938. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17939. }
  17940. #if defined(_WIN32)
  17941. CloseHandle(tls.pthread_cond_helper_mutex);
  17942. #endif
  17943. pthread_setspecific(sTlsKey, NULL);
  17944. /* Signal mg_stop() that we're done.
  17945. * WARNING: This must be the very last thing this
  17946. * thread does, as ctx becomes invalid after this line. */
  17947. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17948. }
  17949. /* Threads have different return types on Windows and Unix. */
  17950. #if defined(_WIN32)
  17951. static unsigned __stdcall master_thread(void *thread_func_param)
  17952. {
  17953. master_thread_run((struct mg_context *)thread_func_param);
  17954. return 0;
  17955. }
  17956. #else
  17957. static void *
  17958. master_thread(void *thread_func_param)
  17959. {
  17960. #if !defined(__ZEPHYR__)
  17961. struct sigaction sa;
  17962. /* Ignore SIGPIPE */
  17963. memset(&sa, 0, sizeof(sa));
  17964. sa.sa_handler = SIG_IGN;
  17965. sigaction(SIGPIPE, &sa, NULL);
  17966. #endif
  17967. master_thread_run((struct mg_context *)thread_func_param);
  17968. return NULL;
  17969. }
  17970. #endif /* _WIN32 */
  17971. static void
  17972. free_context(struct mg_context *ctx)
  17973. {
  17974. int i;
  17975. struct mg_handler_info *tmp_rh;
  17976. if (ctx == NULL) {
  17977. return;
  17978. }
  17979. /* Call user callback */
  17980. if (ctx->callbacks.exit_context) {
  17981. ctx->callbacks.exit_context(ctx);
  17982. }
  17983. /* All threads exited, no sync is needed. Destroy thread mutex and
  17984. * condvars
  17985. */
  17986. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17987. #if defined(ALTERNATIVE_QUEUE)
  17988. mg_free(ctx->client_socks);
  17989. if (ctx->client_wait_events != NULL) {
  17990. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  17991. event_destroy(ctx->client_wait_events[i]);
  17992. }
  17993. mg_free(ctx->client_wait_events);
  17994. }
  17995. #else
  17996. (void)pthread_cond_destroy(&ctx->sq_empty);
  17997. (void)pthread_cond_destroy(&ctx->sq_full);
  17998. mg_free(ctx->squeue);
  17999. #endif
  18000. /* Destroy other context global data structures mutex */
  18001. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  18002. #if defined(USE_LUA)
  18003. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  18004. #endif
  18005. /* Deallocate shutdown-triggering socket-pair */
  18006. if (ctx->user_shutdown_notification_socket >= 0) {
  18007. closesocket(ctx->user_shutdown_notification_socket);
  18008. }
  18009. if (ctx->thread_shutdown_notification_socket >= 0) {
  18010. closesocket(ctx->thread_shutdown_notification_socket);
  18011. }
  18012. /* Deallocate config parameters */
  18013. for (i = 0; i < NUM_OPTIONS; i++) {
  18014. if (ctx->dd.config[i] != NULL) {
  18015. #if defined(_MSC_VER)
  18016. #pragma warning(suppress : 6001)
  18017. #endif
  18018. mg_free(ctx->dd.config[i]);
  18019. }
  18020. }
  18021. /* Deallocate request handlers */
  18022. while (ctx->dd.handlers) {
  18023. tmp_rh = ctx->dd.handlers;
  18024. ctx->dd.handlers = tmp_rh->next;
  18025. mg_free(tmp_rh->uri);
  18026. mg_free(tmp_rh);
  18027. }
  18028. #if defined(USE_MBEDTLS)
  18029. if (ctx->dd.ssl_ctx != NULL) {
  18030. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  18031. mg_free(ctx->dd.ssl_ctx);
  18032. ctx->dd.ssl_ctx = NULL;
  18033. }
  18034. #elif defined(USE_GNUTLS)
  18035. if (ctx->dd.ssl_ctx != NULL) {
  18036. gtls_sslctx_uninit(ctx->dd.ssl_ctx);
  18037. mg_free(ctx->dd.ssl_ctx);
  18038. ctx->dd.ssl_ctx = NULL;
  18039. }
  18040. #elif !defined(NO_SSL)
  18041. /* Deallocate SSL context */
  18042. if (ctx->dd.ssl_ctx != NULL) {
  18043. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  18044. int callback_ret =
  18045. (ctx->callbacks.external_ssl_ctx == NULL)
  18046. ? 0
  18047. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  18048. if (callback_ret == 0) {
  18049. SSL_CTX_free(ctx->dd.ssl_ctx);
  18050. }
  18051. /* else: ignore error and omit SSL_CTX_free in case
  18052. * callback_ret is 1 */
  18053. }
  18054. #endif /* !NO_SSL */
  18055. /* Deallocate worker thread ID array */
  18056. mg_free(ctx->worker_threadids);
  18057. /* Deallocate worker thread ID array */
  18058. mg_free(ctx->worker_connections);
  18059. /* deallocate system name string */
  18060. mg_free(ctx->systemName);
  18061. /* Deallocate context itself */
  18062. mg_free(ctx);
  18063. }
  18064. CIVETWEB_API void
  18065. mg_stop(struct mg_context *ctx)
  18066. {
  18067. pthread_t mt;
  18068. if (!ctx) {
  18069. return;
  18070. }
  18071. /* We don't use a lock here. Calling mg_stop with the same ctx from
  18072. * two threads is not allowed. */
  18073. mt = ctx->masterthreadid;
  18074. if (mt == 0) {
  18075. return;
  18076. }
  18077. ctx->masterthreadid = 0;
  18078. /* Set stop flag, so all threads know they have to exit. */
  18079. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  18080. /* Closing this socket will cause mg_poll() in all the I/O threads to return
  18081. * immediately */
  18082. closesocket(ctx->user_shutdown_notification_socket);
  18083. ctx->user_shutdown_notification_socket =
  18084. -1; /* to avoid calling closesocket() again in free_context() */
  18085. /* Join timer thread */
  18086. #if defined(USE_TIMERS)
  18087. timers_exit(ctx);
  18088. #endif
  18089. /* Wait until everything has stopped. */
  18090. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  18091. (void)mg_sleep(10);
  18092. }
  18093. /* Wait to stop master thread */
  18094. mg_join_thread(mt);
  18095. /* Close remaining Lua states */
  18096. #if defined(USE_LUA)
  18097. lua_ctx_exit(ctx);
  18098. #endif
  18099. /* Free memory */
  18100. free_context(ctx);
  18101. }
  18102. static void
  18103. get_system_name(char **sysName)
  18104. {
  18105. #if defined(_WIN32)
  18106. char name[128];
  18107. DWORD dwVersion = 0;
  18108. DWORD dwMajorVersion = 0;
  18109. DWORD dwMinorVersion = 0;
  18110. DWORD dwBuild = 0;
  18111. BOOL wowRet, isWoW = FALSE;
  18112. #if defined(_MSC_VER)
  18113. #pragma warning(push)
  18114. /* GetVersion was declared deprecated */
  18115. #pragma warning(disable : 4996)
  18116. #endif
  18117. dwVersion = GetVersion();
  18118. #if defined(_MSC_VER)
  18119. #pragma warning(pop)
  18120. #endif
  18121. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18122. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18123. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  18124. (void)dwBuild;
  18125. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  18126. sprintf(name,
  18127. "Windows %u.%u%s",
  18128. (unsigned)dwMajorVersion,
  18129. (unsigned)dwMinorVersion,
  18130. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  18131. *sysName = mg_strdup(name);
  18132. #elif defined(__rtems__)
  18133. *sysName = mg_strdup("RTEMS");
  18134. #elif defined(__ZEPHYR__)
  18135. *sysName = mg_strdup("Zephyr OS");
  18136. #else
  18137. struct utsname name;
  18138. memset(&name, 0, sizeof(name));
  18139. uname(&name);
  18140. *sysName = mg_strdup(name.sysname);
  18141. #endif
  18142. }
  18143. static void
  18144. legacy_init(const char **options)
  18145. {
  18146. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  18147. if (options) {
  18148. const char **run_options = options;
  18149. const char *optname = config_options[LISTENING_PORTS].name;
  18150. /* Try to find the "listening_ports" option */
  18151. while (*run_options) {
  18152. if (!strcmp(*run_options, optname)) {
  18153. ports_option = run_options[1];
  18154. }
  18155. run_options += 2;
  18156. }
  18157. }
  18158. if (is_ssl_port_used(ports_option)) {
  18159. /* Initialize with SSL support */
  18160. mg_init_library(MG_FEATURES_TLS);
  18161. } else {
  18162. /* Initialize without SSL support */
  18163. mg_init_library(MG_FEATURES_DEFAULT);
  18164. }
  18165. }
  18166. /* we'll assume it's only Windows that doesn't have socketpair() available */
  18167. #if !defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  18168. #define HAVE_SOCKETPAIR 1
  18169. #endif
  18170. static int
  18171. mg_socketpair(int *sockA, int *sockB)
  18172. {
  18173. int temp[2] = {-1, -1};
  18174. int asock = -1;
  18175. /** Default to unallocated */
  18176. *sockA = -1;
  18177. *sockB = -1;
  18178. #if defined(HAVE_SOCKETPAIR)
  18179. int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, temp);
  18180. if (ret == 0) {
  18181. *sockA = temp[0];
  18182. *sockB = temp[1];
  18183. set_close_on_exec(*sockA, NULL, NULL);
  18184. set_close_on_exec(*sockB, NULL, NULL);
  18185. }
  18186. (void)asock; /* not used */
  18187. return ret;
  18188. #else
  18189. /** No socketpair() call is available, so we'll have to roll our own
  18190. * implementation */
  18191. asock = socket(PF_INET, SOCK_STREAM, 0);
  18192. if (asock >= 0) {
  18193. struct sockaddr_in addr;
  18194. struct sockaddr *pa = (struct sockaddr *)&addr;
  18195. socklen_t addrLen = sizeof(addr);
  18196. memset(&addr, 0, sizeof(addr));
  18197. addr.sin_family = AF_INET;
  18198. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18199. addr.sin_port = 0;
  18200. if ((bind(asock, pa, sizeof(addr)) == 0)
  18201. && (getsockname(asock, pa, &addrLen) == 0)
  18202. && (listen(asock, 1) == 0)) {
  18203. temp[0] = socket(PF_INET, SOCK_STREAM, 0);
  18204. if ((temp[0] >= 0) && (connect(temp[0], pa, sizeof(addr)) == 0)) {
  18205. temp[1] = accept(asock, pa, &addrLen);
  18206. if (temp[1] >= 0) {
  18207. closesocket(asock);
  18208. *sockA = temp[0];
  18209. *sockB = temp[1];
  18210. set_close_on_exec(*sockA, NULL, NULL);
  18211. set_close_on_exec(*sockB, NULL, NULL);
  18212. return 0; /* success! */
  18213. }
  18214. }
  18215. }
  18216. }
  18217. /* Cleanup */
  18218. if (asock >= 0)
  18219. closesocket(asock);
  18220. if (temp[0] >= 0)
  18221. closesocket(temp[0]);
  18222. if (temp[1] >= 0)
  18223. closesocket(temp[1]);
  18224. return -1; /* fail! */
  18225. #endif
  18226. }
  18227. static int
  18228. mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads)
  18229. {
  18230. const unsigned int i = ctx->spawned_worker_threads;
  18231. if (i >= ctx->cfg_max_worker_threads) {
  18232. return -1; /* Oops, we hit our worker-thread limit! No more worker
  18233. threads, ever! */
  18234. }
  18235. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18236. #if defined(ALTERNATIVE_QUEUE)
  18237. if ((only_if_no_idle_threads) && (ctx->idle_worker_thread_count > 0)) {
  18238. #else
  18239. if ((only_if_no_idle_threads)
  18240. && (ctx->idle_worker_thread_count
  18241. > (unsigned)(ctx->sq_head - ctx->sq_tail))) {
  18242. #endif
  18243. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18244. return -2; /* There are idle threads available, so no need to spawn a
  18245. new worker thread now */
  18246. }
  18247. ctx->idle_worker_thread_count++; /* we do this here to avoid a race
  18248. condition while the thread is starting
  18249. up */
  18250. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18251. ctx->worker_connections[i].phys_ctx = ctx;
  18252. int ret = mg_start_thread_with_id(worker_thread,
  18253. &ctx->worker_connections[i],
  18254. &ctx->worker_threadids[i]);
  18255. if (ret == 0) {
  18256. ctx->spawned_worker_threads++; /* note that we've filled another slot in
  18257. the table */
  18258. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  18259. } else {
  18260. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18261. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  18262. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18263. }
  18264. return ret;
  18265. }
  18266. CIVETWEB_API struct mg_context *
  18267. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  18268. {
  18269. struct mg_context *ctx;
  18270. const char *name, *value, *default_value;
  18271. int idx, ok, prespawnthreadcount, workerthreadcount;
  18272. unsigned int i;
  18273. int itmp;
  18274. void (*exit_callback)(const struct mg_context *ctx) = 0;
  18275. const char **options =
  18276. ((init != NULL) ? (init->configuration_options) : (NULL));
  18277. struct mg_workerTLS tls;
  18278. if (error != NULL) {
  18279. error->code = MG_ERROR_DATA_CODE_OK;
  18280. error->code_sub = 0;
  18281. if (error->text_buffer_size > 0) {
  18282. *error->text = 0;
  18283. }
  18284. }
  18285. if (mg_init_library_called == 0) {
  18286. /* Legacy INIT, if mg_start is called without mg_init_library.
  18287. * Note: This will cause a memory leak when unloading the library.
  18288. */
  18289. legacy_init(options);
  18290. }
  18291. if (mg_init_library_called == 0) {
  18292. if (error != NULL) {
  18293. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  18294. mg_snprintf(NULL,
  18295. NULL, /* No truncation check for error buffers */
  18296. error->text,
  18297. error->text_buffer_size,
  18298. "%s",
  18299. "Library uninitialized");
  18300. }
  18301. return NULL;
  18302. }
  18303. /* Allocate context and initialize reasonable general case defaults. */
  18304. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  18305. if (ctx == NULL) {
  18306. if (error != NULL) {
  18307. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18308. error->code_sub = (unsigned)sizeof(*ctx);
  18309. mg_snprintf(NULL,
  18310. NULL, /* No truncation check for error buffers */
  18311. error->text,
  18312. error->text_buffer_size,
  18313. "%s",
  18314. "Out of memory");
  18315. }
  18316. return NULL;
  18317. }
  18318. /* Random number generator will initialize at the first call */
  18319. ctx->dd.auth_nonce_mask =
  18320. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  18321. /* Save started thread index to reuse in other external API calls
  18322. * For the sake of thread synchronization all non-civetweb threads
  18323. * can be considered as single external thread */
  18324. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  18325. tls.is_master = -1; /* Thread calling mg_start */
  18326. tls.thread_idx = ctx->starter_thread_idx;
  18327. #if defined(_WIN32)
  18328. tls.pthread_cond_helper_mutex = NULL;
  18329. #endif
  18330. pthread_setspecific(sTlsKey, &tls);
  18331. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  18332. #if !defined(ALTERNATIVE_QUEUE)
  18333. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  18334. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  18335. ctx->sq_blocked = 0;
  18336. #endif
  18337. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  18338. #if defined(USE_LUA)
  18339. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  18340. #endif
  18341. /** mg_stop() will close the user_shutdown_notification_socket, and that
  18342. * will cause poll() to return immediately in the master-thread, so that
  18343. * mg_stop() can also return immediately.
  18344. */
  18345. ok &= (0
  18346. == mg_socketpair(&ctx->user_shutdown_notification_socket,
  18347. &ctx->thread_shutdown_notification_socket));
  18348. if (!ok) {
  18349. unsigned error_id = (unsigned)ERRNO;
  18350. const char *err_msg =
  18351. "Cannot initialize thread synchronization objects";
  18352. /* Fatal error - abort start. However, this situation should never
  18353. * occur in practice. */
  18354. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18355. if (error != NULL) {
  18356. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18357. error->code_sub = error_id;
  18358. mg_snprintf(NULL,
  18359. NULL, /* No truncation check for error buffers */
  18360. error->text,
  18361. error->text_buffer_size,
  18362. "%s",
  18363. err_msg);
  18364. }
  18365. mg_free(ctx);
  18366. pthread_setspecific(sTlsKey, NULL);
  18367. return NULL;
  18368. }
  18369. if ((init != NULL) && (init->callbacks != NULL)) {
  18370. /* Set all callbacks except exit_context. */
  18371. ctx->callbacks = *init->callbacks;
  18372. exit_callback = init->callbacks->exit_context;
  18373. /* The exit callback is activated once the context is successfully
  18374. * created. It should not be called, if an incomplete context object
  18375. * is deleted during a failed initialization. */
  18376. ctx->callbacks.exit_context = 0;
  18377. }
  18378. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  18379. ctx->dd.handlers = NULL;
  18380. ctx->dd.next = NULL;
  18381. #if defined(USE_LUA)
  18382. lua_ctx_init(ctx);
  18383. #endif
  18384. /* Store options */
  18385. while (options && (name = *options++) != NULL) {
  18386. idx = get_option_index(name);
  18387. if (idx == -1) {
  18388. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18389. if (error != NULL) {
  18390. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18391. error->code_sub = (unsigned)-1;
  18392. mg_snprintf(NULL,
  18393. NULL, /* No truncation check for error buffers */
  18394. error->text,
  18395. error->text_buffer_size,
  18396. "Invalid configuration option: %s",
  18397. name);
  18398. }
  18399. free_context(ctx);
  18400. pthread_setspecific(sTlsKey, NULL);
  18401. return NULL;
  18402. } else if ((value = *options++) == NULL) {
  18403. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18404. if (error != NULL) {
  18405. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18406. error->code_sub = (unsigned)idx;
  18407. mg_snprintf(NULL,
  18408. NULL, /* No truncation check for error buffers */
  18409. error->text,
  18410. error->text_buffer_size,
  18411. "Invalid configuration option value: %s",
  18412. name);
  18413. }
  18414. free_context(ctx);
  18415. pthread_setspecific(sTlsKey, NULL);
  18416. return NULL;
  18417. }
  18418. if (ctx->dd.config[idx] != NULL) {
  18419. /* A duplicate configuration option is not an error - the last
  18420. * option value will be used. */
  18421. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18422. mg_free(ctx->dd.config[idx]);
  18423. }
  18424. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  18425. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18426. }
  18427. /* Set default value if needed */
  18428. for (i = 0; config_options[i].name != NULL; i++) {
  18429. default_value = config_options[i].default_value;
  18430. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  18431. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  18432. }
  18433. }
  18434. /* Request size option */
  18435. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  18436. if (itmp < 1024) {
  18437. mg_cry_ctx_internal(ctx,
  18438. "%s too small",
  18439. config_options[MAX_REQUEST_SIZE].name);
  18440. if (error != NULL) {
  18441. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18442. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  18443. mg_snprintf(NULL,
  18444. NULL, /* No truncation check for error buffers */
  18445. error->text,
  18446. error->text_buffer_size,
  18447. "Invalid configuration option value: %s",
  18448. config_options[MAX_REQUEST_SIZE].name);
  18449. }
  18450. free_context(ctx);
  18451. pthread_setspecific(sTlsKey, NULL);
  18452. return NULL;
  18453. }
  18454. ctx->max_request_size = (unsigned)itmp;
  18455. /* Queue length */
  18456. #if !defined(ALTERNATIVE_QUEUE)
  18457. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  18458. if (itmp < 1) {
  18459. mg_cry_ctx_internal(ctx,
  18460. "%s too small",
  18461. config_options[CONNECTION_QUEUE_SIZE].name);
  18462. if (error != NULL) {
  18463. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18464. error->code_sub = CONNECTION_QUEUE_SIZE;
  18465. mg_snprintf(NULL,
  18466. NULL, /* No truncation check for error buffers */
  18467. error->text,
  18468. error->text_buffer_size,
  18469. "Invalid configuration option value: %s",
  18470. config_options[CONNECTION_QUEUE_SIZE].name);
  18471. }
  18472. free_context(ctx);
  18473. pthread_setspecific(sTlsKey, NULL);
  18474. return NULL;
  18475. }
  18476. ctx->squeue =
  18477. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  18478. if (ctx->squeue == NULL) {
  18479. mg_cry_ctx_internal(ctx,
  18480. "Out of memory: Cannot allocate %s",
  18481. config_options[CONNECTION_QUEUE_SIZE].name);
  18482. if (error != NULL) {
  18483. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18484. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  18485. mg_snprintf(NULL,
  18486. NULL, /* No truncation check for error buffers */
  18487. error->text,
  18488. error->text_buffer_size,
  18489. "Out of memory: Cannot allocate %s",
  18490. config_options[CONNECTION_QUEUE_SIZE].name);
  18491. }
  18492. free_context(ctx);
  18493. pthread_setspecific(sTlsKey, NULL);
  18494. return NULL;
  18495. }
  18496. ctx->sq_size = itmp;
  18497. #endif
  18498. /* Worker thread count option */
  18499. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18500. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18501. if ((prespawnthreadcount < 0)
  18502. || (prespawnthreadcount > workerthreadcount)) {
  18503. prespawnthreadcount =
  18504. workerthreadcount; /* can't prespawn more than all of them! */
  18505. }
  18506. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18507. if (workerthreadcount <= 0) {
  18508. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18509. } else {
  18510. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18511. }
  18512. if (error != NULL) {
  18513. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18514. error->code_sub = NUM_THREADS;
  18515. mg_snprintf(NULL,
  18516. NULL, /* No truncation check for error buffers */
  18517. error->text,
  18518. error->text_buffer_size,
  18519. "Invalid configuration option value: %s",
  18520. config_options[NUM_THREADS].name);
  18521. }
  18522. free_context(ctx);
  18523. pthread_setspecific(sTlsKey, NULL);
  18524. return NULL;
  18525. }
  18526. /* Document root */
  18527. #if defined(NO_FILES)
  18528. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18529. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18530. if (error != NULL) {
  18531. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18532. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18533. mg_snprintf(NULL,
  18534. NULL, /* No truncation check for error buffers */
  18535. error->text,
  18536. error->text_buffer_size,
  18537. "Invalid configuration option value: %s",
  18538. config_options[DOCUMENT_ROOT].name);
  18539. }
  18540. free_context(ctx);
  18541. pthread_setspecific(sTlsKey, NULL);
  18542. return NULL;
  18543. }
  18544. #endif
  18545. get_system_name(&ctx->systemName);
  18546. #if defined(USE_LUA)
  18547. /* If a Lua background script has been configured, start it. */
  18548. ctx->lua_bg_log_available = 0;
  18549. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18550. char ebuf[256];
  18551. struct vec opt_vec;
  18552. struct vec eq_vec;
  18553. const char *sparams;
  18554. memset(ebuf, 0, sizeof(ebuf));
  18555. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18556. /* Create a Lua state, load all standard libraries and the mg table */
  18557. lua_State *state = mg_lua_context_script_prepare(
  18558. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18559. if (!state) {
  18560. mg_cry_ctx_internal(ctx,
  18561. "lua_background_script load error: %s",
  18562. ebuf);
  18563. if (error != NULL) {
  18564. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18565. mg_snprintf(NULL,
  18566. NULL, /* No truncation check for error buffers */
  18567. error->text,
  18568. error->text_buffer_size,
  18569. "Error in script %s: %s",
  18570. config_options[LUA_BACKGROUND_SCRIPT].name,
  18571. ebuf);
  18572. }
  18573. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18574. free_context(ctx);
  18575. pthread_setspecific(sTlsKey, NULL);
  18576. return NULL;
  18577. }
  18578. /* Add a table with parameters into mg.params */
  18579. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18580. if (sparams && sparams[0]) {
  18581. lua_getglobal(state, "mg");
  18582. lua_pushstring(state, "params");
  18583. lua_newtable(state);
  18584. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18585. != NULL) {
  18586. reg_llstring(
  18587. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18588. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18589. break;
  18590. }
  18591. lua_rawset(state, -3);
  18592. lua_pop(state, 1);
  18593. }
  18594. /* Call script */
  18595. state = mg_lua_context_script_run(state,
  18596. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18597. ctx,
  18598. ebuf,
  18599. sizeof(ebuf));
  18600. if (!state) {
  18601. mg_cry_ctx_internal(ctx,
  18602. "lua_background_script start error: %s",
  18603. ebuf);
  18604. if (error != NULL) {
  18605. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18606. mg_snprintf(NULL,
  18607. NULL, /* No truncation check for error buffers */
  18608. error->text,
  18609. error->text_buffer_size,
  18610. "Error in script %s: %s",
  18611. config_options[DOCUMENT_ROOT].name,
  18612. ebuf);
  18613. }
  18614. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18615. free_context(ctx);
  18616. pthread_setspecific(sTlsKey, NULL);
  18617. return NULL;
  18618. }
  18619. /* state remains valid */
  18620. ctx->lua_background_state = (void *)state;
  18621. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18622. } else {
  18623. ctx->lua_background_state = 0;
  18624. }
  18625. #endif
  18626. /* Step by step initialization of ctx - depending on build options */
  18627. #if !defined(NO_FILESYSTEMS)
  18628. if (!set_gpass_option(ctx, NULL)) {
  18629. const char *err_msg = "Invalid global password file";
  18630. /* Fatal error - abort start. */
  18631. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18632. if (error != NULL) {
  18633. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18634. mg_snprintf(NULL,
  18635. NULL, /* No truncation check for error buffers */
  18636. error->text,
  18637. error->text_buffer_size,
  18638. "%s",
  18639. err_msg);
  18640. }
  18641. free_context(ctx);
  18642. pthread_setspecific(sTlsKey, NULL);
  18643. return NULL;
  18644. }
  18645. #endif
  18646. #if defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  18647. if (!mg_sslctx_init(ctx, NULL)) {
  18648. const char *err_msg = "Error initializing SSL context";
  18649. /* Fatal error - abort start. */
  18650. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18651. if (error != NULL) {
  18652. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18653. mg_snprintf(NULL,
  18654. NULL, /* No truncation check for error buffers */
  18655. error->text,
  18656. error->text_buffer_size,
  18657. "%s",
  18658. err_msg);
  18659. }
  18660. free_context(ctx);
  18661. pthread_setspecific(sTlsKey, NULL);
  18662. return NULL;
  18663. }
  18664. #elif !defined(NO_SSL)
  18665. if (!init_ssl_ctx(ctx, NULL)) {
  18666. const char *err_msg = "Error initializing SSL context";
  18667. /* Fatal error - abort start. */
  18668. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18669. if (error != NULL) {
  18670. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18671. mg_snprintf(NULL,
  18672. NULL, /* No truncation check for error buffers */
  18673. error->text,
  18674. error->text_buffer_size,
  18675. "%s",
  18676. err_msg);
  18677. }
  18678. free_context(ctx);
  18679. pthread_setspecific(sTlsKey, NULL);
  18680. return NULL;
  18681. }
  18682. #endif
  18683. if (!set_ports_option(ctx)) {
  18684. const char *err_msg = "Failed to setup server ports";
  18685. /* Fatal error - abort start. */
  18686. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18687. if (error != NULL) {
  18688. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18689. mg_snprintf(NULL,
  18690. NULL, /* No truncation check for error buffers */
  18691. error->text,
  18692. error->text_buffer_size,
  18693. "%s",
  18694. err_msg);
  18695. }
  18696. free_context(ctx);
  18697. pthread_setspecific(sTlsKey, NULL);
  18698. return NULL;
  18699. }
  18700. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18701. if (!set_uid_option(ctx)) {
  18702. const char *err_msg = "Failed to run as configured user";
  18703. /* Fatal error - abort start. */
  18704. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18705. if (error != NULL) {
  18706. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18707. mg_snprintf(NULL,
  18708. NULL, /* No truncation check for error buffers */
  18709. error->text,
  18710. error->text_buffer_size,
  18711. "%s",
  18712. err_msg);
  18713. }
  18714. free_context(ctx);
  18715. pthread_setspecific(sTlsKey, NULL);
  18716. return NULL;
  18717. }
  18718. #endif
  18719. if (!set_acl_option(ctx)) {
  18720. const char *err_msg = "Failed to setup access control list";
  18721. /* Fatal error - abort start. */
  18722. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18723. if (error != NULL) {
  18724. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18725. mg_snprintf(NULL,
  18726. NULL, /* No truncation check for error buffers */
  18727. error->text,
  18728. error->text_buffer_size,
  18729. "%s",
  18730. err_msg);
  18731. }
  18732. free_context(ctx);
  18733. pthread_setspecific(sTlsKey, NULL);
  18734. return NULL;
  18735. }
  18736. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18737. ctx->worker_threadids =
  18738. (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18739. sizeof(pthread_t),
  18740. ctx);
  18741. if (ctx->worker_threadids == NULL) {
  18742. const char *err_msg = "Not enough memory for worker thread ID array";
  18743. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18744. if (error != NULL) {
  18745. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18746. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18747. * (unsigned)sizeof(pthread_t);
  18748. mg_snprintf(NULL,
  18749. NULL, /* No truncation check for error buffers */
  18750. error->text,
  18751. error->text_buffer_size,
  18752. "%s",
  18753. err_msg);
  18754. }
  18755. free_context(ctx);
  18756. pthread_setspecific(sTlsKey, NULL);
  18757. return NULL;
  18758. }
  18759. ctx->worker_connections =
  18760. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18761. sizeof(struct mg_connection),
  18762. ctx);
  18763. if (ctx->worker_connections == NULL) {
  18764. const char *err_msg =
  18765. "Not enough memory for worker thread connection array";
  18766. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18767. if (error != NULL) {
  18768. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18769. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18770. * (unsigned)sizeof(struct mg_connection);
  18771. mg_snprintf(NULL,
  18772. NULL, /* No truncation check for error buffers */
  18773. error->text,
  18774. error->text_buffer_size,
  18775. "%s",
  18776. err_msg);
  18777. }
  18778. free_context(ctx);
  18779. pthread_setspecific(sTlsKey, NULL);
  18780. return NULL;
  18781. }
  18782. #if defined(ALTERNATIVE_QUEUE)
  18783. ctx->client_wait_events =
  18784. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18785. sizeof(ctx->client_wait_events[0]),
  18786. ctx);
  18787. if (ctx->client_wait_events == NULL) {
  18788. const char *err_msg = "Not enough memory for worker event array";
  18789. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18790. mg_free(ctx->worker_threadids);
  18791. if (error != NULL) {
  18792. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18793. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18794. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18795. mg_snprintf(NULL,
  18796. NULL, /* No truncation check for error buffers */
  18797. error->text,
  18798. error->text_buffer_size,
  18799. "%s",
  18800. err_msg);
  18801. }
  18802. free_context(ctx);
  18803. pthread_setspecific(sTlsKey, NULL);
  18804. return NULL;
  18805. }
  18806. ctx->client_socks =
  18807. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18808. sizeof(ctx->client_socks[0]),
  18809. ctx);
  18810. if (ctx->client_socks == NULL) {
  18811. const char *err_msg = "Not enough memory for worker socket array";
  18812. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18813. mg_free(ctx->client_wait_events);
  18814. mg_free(ctx->worker_threadids);
  18815. if (error != NULL) {
  18816. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18817. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18818. * (unsigned)sizeof(ctx->client_socks[0]);
  18819. mg_snprintf(NULL,
  18820. NULL, /* No truncation check for error buffers */
  18821. error->text,
  18822. error->text_buffer_size,
  18823. "%s",
  18824. err_msg);
  18825. }
  18826. free_context(ctx);
  18827. pthread_setspecific(sTlsKey, NULL);
  18828. return NULL;
  18829. }
  18830. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18831. ctx->client_wait_events[i] = event_create();
  18832. if (ctx->client_wait_events[i] == 0) {
  18833. const char *err_msg = "Error creating worker event %i";
  18834. mg_cry_ctx_internal(ctx, err_msg, i);
  18835. while (i > 0) {
  18836. i--;
  18837. event_destroy(ctx->client_wait_events[i]);
  18838. }
  18839. mg_free(ctx->client_socks);
  18840. mg_free(ctx->client_wait_events);
  18841. mg_free(ctx->worker_threadids);
  18842. if (error != NULL) {
  18843. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18844. error->code_sub = (unsigned)ERRNO;
  18845. mg_snprintf(NULL,
  18846. NULL, /* No truncation check for error buffers */
  18847. error->text,
  18848. error->text_buffer_size,
  18849. err_msg,
  18850. i);
  18851. }
  18852. free_context(ctx);
  18853. pthread_setspecific(sTlsKey, NULL);
  18854. return NULL;
  18855. }
  18856. }
  18857. #endif
  18858. #if defined(USE_TIMERS)
  18859. if (timers_init(ctx) != 0) {
  18860. const char *err_msg = "Error creating timers";
  18861. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18862. if (error != NULL) {
  18863. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18864. error->code_sub = (unsigned)ERRNO;
  18865. mg_snprintf(NULL,
  18866. NULL, /* No truncation check for error buffers */
  18867. error->text,
  18868. error->text_buffer_size,
  18869. "%s",
  18870. err_msg);
  18871. }
  18872. free_context(ctx);
  18873. pthread_setspecific(sTlsKey, NULL);
  18874. return NULL;
  18875. }
  18876. #endif
  18877. /* Context has been created - init user libraries */
  18878. if (ctx->callbacks.init_context) {
  18879. ctx->callbacks.init_context(ctx);
  18880. }
  18881. /* From now, the context is successfully created.
  18882. * When it is destroyed, the exit callback should be called. */
  18883. ctx->callbacks.exit_context = exit_callback;
  18884. ctx->context_type = CONTEXT_SERVER; /* server context */
  18885. /* Start worker threads */
  18886. for (i = 0; (int)i < prespawnthreadcount; i++) {
  18887. /* worker_thread sets up the other fields */
  18888. if (mg_start_worker_thread(ctx, 0) != 0) {
  18889. long error_no = (long)ERRNO;
  18890. /* thread was not created */
  18891. if (ctx->spawned_worker_threads > 0) {
  18892. /* If the second, third, ... thread cannot be created, set a
  18893. * warning, but keep running. */
  18894. mg_cry_ctx_internal(ctx,
  18895. "Cannot start worker thread %i: error %ld",
  18896. ctx->spawned_worker_threads + 1,
  18897. error_no);
  18898. /* If the server initialization should stop here, all
  18899. * threads that have already been created must be stopped
  18900. * first, before any free_context(ctx) call.
  18901. */
  18902. } else {
  18903. /* If the first worker thread cannot be created, stop
  18904. * initialization and free the entire server context. */
  18905. mg_cry_ctx_internal(ctx,
  18906. "Cannot create threads: error %ld",
  18907. error_no);
  18908. if (error != NULL) {
  18909. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18910. error->code_sub = (unsigned)error_no;
  18911. mg_snprintf(
  18912. NULL,
  18913. NULL, /* No truncation check for error buffers */
  18914. error->text,
  18915. error->text_buffer_size,
  18916. "Cannot create first worker thread: error %ld",
  18917. error_no);
  18918. }
  18919. free_context(ctx);
  18920. pthread_setspecific(sTlsKey, NULL);
  18921. return NULL;
  18922. }
  18923. break;
  18924. }
  18925. }
  18926. /* Start master (listening) thread */
  18927. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18928. pthread_setspecific(sTlsKey, NULL);
  18929. return ctx;
  18930. }
  18931. CIVETWEB_API struct mg_context *
  18932. mg_start(const struct mg_callbacks *callbacks,
  18933. void *user_data,
  18934. const char **options)
  18935. {
  18936. struct mg_init_data init = {0};
  18937. init.callbacks = callbacks;
  18938. init.user_data = user_data;
  18939. init.configuration_options = options;
  18940. return mg_start2(&init, NULL);
  18941. }
  18942. /* Add an additional domain to an already running web server. */
  18943. CIVETWEB_API int
  18944. mg_start_domain2(struct mg_context *ctx,
  18945. const char **options,
  18946. struct mg_error_data *error)
  18947. {
  18948. const char *name;
  18949. const char *value;
  18950. const char *default_value;
  18951. struct mg_domain_context *new_dom;
  18952. struct mg_domain_context *dom;
  18953. int idx, i;
  18954. if (error != NULL) {
  18955. error->code = MG_ERROR_DATA_CODE_OK;
  18956. error->code_sub = 0;
  18957. if (error->text_buffer_size > 0) {
  18958. *error->text = 0;
  18959. }
  18960. }
  18961. if ((ctx == NULL) || (options == NULL)) {
  18962. if (error != NULL) {
  18963. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18964. mg_snprintf(NULL,
  18965. NULL, /* No truncation check for error buffers */
  18966. error->text,
  18967. error->text_buffer_size,
  18968. "%s",
  18969. "Invalid parameters");
  18970. }
  18971. return -1;
  18972. }
  18973. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18974. if (error != NULL) {
  18975. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18976. mg_snprintf(NULL,
  18977. NULL, /* No truncation check for error buffers */
  18978. error->text,
  18979. error->text_buffer_size,
  18980. "%s",
  18981. "Server already stopped");
  18982. }
  18983. return -7;
  18984. }
  18985. new_dom = (struct mg_domain_context *)
  18986. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18987. if (!new_dom) {
  18988. /* Out of memory */
  18989. if (error != NULL) {
  18990. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18991. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18992. mg_snprintf(NULL,
  18993. NULL, /* No truncation check for error buffers */
  18994. error->text,
  18995. error->text_buffer_size,
  18996. "%s",
  18997. "Out or memory");
  18998. }
  18999. return -6;
  19000. }
  19001. /* Store options - TODO: unite duplicate code */
  19002. while (options && (name = *options++) != NULL) {
  19003. idx = get_option_index(name);
  19004. if (idx == -1) {
  19005. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  19006. if (error != NULL) {
  19007. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19008. error->code_sub = (unsigned)-1;
  19009. mg_snprintf(NULL,
  19010. NULL, /* No truncation check for error buffers */
  19011. error->text,
  19012. error->text_buffer_size,
  19013. "Invalid option: %s",
  19014. name);
  19015. }
  19016. mg_free(new_dom);
  19017. return -2;
  19018. } else if ((value = *options++) == NULL) {
  19019. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  19020. if (error != NULL) {
  19021. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19022. error->code_sub = (unsigned)idx;
  19023. mg_snprintf(NULL,
  19024. NULL, /* No truncation check for error buffers */
  19025. error->text,
  19026. error->text_buffer_size,
  19027. "Invalid option value: %s",
  19028. name);
  19029. }
  19030. mg_free(new_dom);
  19031. return -2;
  19032. }
  19033. if (new_dom->config[idx] != NULL) {
  19034. /* Duplicate option: Later values overwrite earlier ones. */
  19035. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  19036. mg_free(new_dom->config[idx]);
  19037. }
  19038. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  19039. DEBUG_TRACE("[%s] -> [%s]", name, value);
  19040. }
  19041. /* Authentication domain is mandatory */
  19042. /* TODO: Maybe use a new option hostname? */
  19043. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  19044. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  19045. if (error != NULL) {
  19046. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  19047. error->code_sub = AUTHENTICATION_DOMAIN;
  19048. mg_snprintf(NULL,
  19049. NULL, /* No truncation check for error buffers */
  19050. error->text,
  19051. error->text_buffer_size,
  19052. "Mandatory option %s missing",
  19053. config_options[AUTHENTICATION_DOMAIN].name);
  19054. }
  19055. mg_free(new_dom);
  19056. return -4;
  19057. }
  19058. /* Set default value if needed. Take the config value from
  19059. * ctx as a default value. */
  19060. for (i = 0; config_options[i].name != NULL; i++) {
  19061. default_value = ctx->dd.config[i];
  19062. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  19063. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  19064. }
  19065. }
  19066. new_dom->handlers = NULL;
  19067. new_dom->next = NULL;
  19068. new_dom->nonce_count = 0;
  19069. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  19070. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  19071. new_dom->shared_lua_websockets = NULL;
  19072. #endif
  19073. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  19074. if (!init_ssl_ctx(ctx, new_dom)) {
  19075. /* Init SSL failed */
  19076. if (error != NULL) {
  19077. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  19078. mg_snprintf(NULL,
  19079. NULL, /* No truncation check for error buffers */
  19080. error->text,
  19081. error->text_buffer_size,
  19082. "%s",
  19083. "Initializing SSL context failed");
  19084. }
  19085. mg_free(new_dom);
  19086. return -3;
  19087. }
  19088. #endif
  19089. /* Add element to linked list. */
  19090. mg_lock_context(ctx);
  19091. idx = 0;
  19092. dom = &(ctx->dd);
  19093. for (;;) {
  19094. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  19095. dom->config[AUTHENTICATION_DOMAIN])) {
  19096. /* Domain collision */
  19097. mg_cry_ctx_internal(ctx,
  19098. "domain %s already in use",
  19099. new_dom->config[AUTHENTICATION_DOMAIN]);
  19100. if (error != NULL) {
  19101. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  19102. mg_snprintf(NULL,
  19103. NULL, /* No truncation check for error buffers */
  19104. error->text,
  19105. error->text_buffer_size,
  19106. "Domain %s specified by %s is already in use",
  19107. new_dom->config[AUTHENTICATION_DOMAIN],
  19108. config_options[AUTHENTICATION_DOMAIN].name);
  19109. }
  19110. mg_free(new_dom);
  19111. mg_unlock_context(ctx);
  19112. return -5;
  19113. }
  19114. /* Count number of domains */
  19115. idx++;
  19116. if (dom->next == NULL) {
  19117. dom->next = new_dom;
  19118. break;
  19119. }
  19120. dom = dom->next;
  19121. }
  19122. mg_unlock_context(ctx);
  19123. /* Return domain number */
  19124. return idx;
  19125. }
  19126. CIVETWEB_API int
  19127. mg_start_domain(struct mg_context *ctx, const char **options)
  19128. {
  19129. return mg_start_domain2(ctx, options, NULL);
  19130. }
  19131. /* Feature check API function */
  19132. CIVETWEB_API unsigned
  19133. mg_check_feature(unsigned feature)
  19134. {
  19135. static const unsigned feature_set = 0
  19136. /* Set bits for available features according to API documentation.
  19137. * This bit mask is created at compile time, according to the active
  19138. * preprocessor defines. It is a single const value at runtime. */
  19139. #if !defined(NO_FILES)
  19140. | MG_FEATURES_FILES
  19141. #endif
  19142. #if !defined(NO_SSL) || defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  19143. | MG_FEATURES_SSL
  19144. #endif
  19145. #if !defined(NO_CGI)
  19146. | MG_FEATURES_CGI
  19147. #endif
  19148. #if defined(USE_IPV6)
  19149. | MG_FEATURES_IPV6
  19150. #endif
  19151. #if defined(USE_WEBSOCKET)
  19152. | MG_FEATURES_WEBSOCKET
  19153. #endif
  19154. #if defined(USE_LUA)
  19155. | MG_FEATURES_LUA
  19156. #endif
  19157. #if defined(USE_DUKTAPE)
  19158. | MG_FEATURES_SSJS
  19159. #endif
  19160. #if !defined(NO_CACHING)
  19161. | MG_FEATURES_CACHE
  19162. #endif
  19163. #if defined(USE_SERVER_STATS)
  19164. | MG_FEATURES_STATS
  19165. #endif
  19166. #if defined(USE_ZLIB)
  19167. | MG_FEATURES_COMPRESSION
  19168. #endif
  19169. #if defined(USE_HTTP2)
  19170. | MG_FEATURES_HTTP2
  19171. #endif
  19172. #if defined(USE_X_DOM_SOCKET)
  19173. | MG_FEATURES_X_DOMAIN_SOCKET
  19174. #endif
  19175. /* Set some extra bits not defined in the API documentation.
  19176. * These bits may change without further notice. */
  19177. #if defined(MG_LEGACY_INTERFACE)
  19178. | 0x80000000u
  19179. #endif
  19180. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19181. | 0x40000000u
  19182. #endif
  19183. #if !defined(NO_RESPONSE_BUFFERING)
  19184. | 0x20000000u
  19185. #endif
  19186. #if defined(MEMORY_DEBUGGING)
  19187. | 0x10000000u
  19188. #endif
  19189. ;
  19190. return (feature & feature_set);
  19191. }
  19192. static size_t
  19193. mg_str_append(char **dst, char *end, const char *src)
  19194. {
  19195. size_t len = strlen(src);
  19196. if (*dst != end) {
  19197. /* Append src if enough space, or close dst. */
  19198. if ((size_t)(end - *dst) > len) {
  19199. strcpy(*dst, src);
  19200. *dst += len;
  19201. } else {
  19202. *dst = end;
  19203. }
  19204. }
  19205. return len;
  19206. }
  19207. /* Get system information. It can be printed or stored by the caller.
  19208. * Return the size of available information. */
  19209. CIVETWEB_API int
  19210. mg_get_system_info(char *buffer, int buflen)
  19211. {
  19212. char *end, *append_eoobj = NULL, block[256];
  19213. size_t system_info_length = 0;
  19214. #if defined(_WIN32)
  19215. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19216. #else
  19217. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19218. #endif
  19219. if ((buffer == NULL) || (buflen < 1)) {
  19220. buflen = 0;
  19221. end = buffer;
  19222. } else {
  19223. *buffer = 0;
  19224. end = buffer + buflen;
  19225. }
  19226. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19227. /* has enough space to append eoobj */
  19228. append_eoobj = buffer;
  19229. if (end) {
  19230. end -= sizeof(eoobj) - 1;
  19231. }
  19232. }
  19233. system_info_length += mg_str_append(&buffer, end, "{");
  19234. /* Server version */
  19235. {
  19236. const char *version = mg_version();
  19237. mg_snprintf(NULL,
  19238. NULL,
  19239. block,
  19240. sizeof(block),
  19241. "%s\"version\" : \"%s\"",
  19242. eol,
  19243. version);
  19244. system_info_length += mg_str_append(&buffer, end, block);
  19245. }
  19246. /* System info */
  19247. {
  19248. #if defined(_WIN32)
  19249. DWORD dwVersion = 0;
  19250. DWORD dwMajorVersion = 0;
  19251. DWORD dwMinorVersion = 0;
  19252. SYSTEM_INFO si;
  19253. GetSystemInfo(&si);
  19254. #if defined(_MSC_VER)
  19255. #pragma warning(push)
  19256. /* GetVersion was declared deprecated */
  19257. #pragma warning(disable : 4996)
  19258. #endif
  19259. dwVersion = GetVersion();
  19260. #if defined(_MSC_VER)
  19261. #pragma warning(pop)
  19262. #endif
  19263. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  19264. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  19265. mg_snprintf(NULL,
  19266. NULL,
  19267. block,
  19268. sizeof(block),
  19269. ",%s\"os\" : \"Windows %u.%u\"",
  19270. eol,
  19271. (unsigned)dwMajorVersion,
  19272. (unsigned)dwMinorVersion);
  19273. system_info_length += mg_str_append(&buffer, end, block);
  19274. mg_snprintf(NULL,
  19275. NULL,
  19276. block,
  19277. sizeof(block),
  19278. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  19279. eol,
  19280. (unsigned)si.wProcessorArchitecture,
  19281. (unsigned)si.dwNumberOfProcessors,
  19282. (unsigned)si.dwActiveProcessorMask);
  19283. system_info_length += mg_str_append(&buffer, end, block);
  19284. #elif defined(__rtems__)
  19285. mg_snprintf(NULL,
  19286. NULL,
  19287. block,
  19288. sizeof(block),
  19289. ",%s\"os\" : \"%s %s\"",
  19290. eol,
  19291. "RTEMS",
  19292. rtems_version());
  19293. system_info_length += mg_str_append(&buffer, end, block);
  19294. #elif defined(__ZEPHYR__)
  19295. mg_snprintf(NULL,
  19296. NULL,
  19297. block,
  19298. sizeof(block),
  19299. ",%s\"os\" : \"%s\"",
  19300. eol,
  19301. "Zephyr OS",
  19302. ZEPHYR_VERSION);
  19303. system_info_length += mg_str_append(&buffer, end, block);
  19304. #else
  19305. struct utsname name;
  19306. memset(&name, 0, sizeof(name));
  19307. uname(&name);
  19308. mg_snprintf(NULL,
  19309. NULL,
  19310. block,
  19311. sizeof(block),
  19312. ",%s\"os\" : \"%s %s (%s) - %s\"",
  19313. eol,
  19314. name.sysname,
  19315. name.version,
  19316. name.release,
  19317. name.machine);
  19318. system_info_length += mg_str_append(&buffer, end, block);
  19319. #endif
  19320. }
  19321. /* Features */
  19322. {
  19323. mg_snprintf(NULL,
  19324. NULL,
  19325. block,
  19326. sizeof(block),
  19327. ",%s\"features\" : %lu"
  19328. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  19329. eol,
  19330. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  19331. eol,
  19332. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  19333. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  19334. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  19335. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  19336. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  19337. : "",
  19338. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  19339. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  19340. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  19341. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  19342. system_info_length += mg_str_append(&buffer, end, block);
  19343. #if defined(USE_LUA)
  19344. mg_snprintf(NULL,
  19345. NULL,
  19346. block,
  19347. sizeof(block),
  19348. ",%s\"lua_version\" : \"%u (%s)\"",
  19349. eol,
  19350. (unsigned)LUA_VERSION_NUM,
  19351. LUA_RELEASE);
  19352. system_info_length += mg_str_append(&buffer, end, block);
  19353. #endif
  19354. #if defined(USE_DUKTAPE)
  19355. mg_snprintf(NULL,
  19356. NULL,
  19357. block,
  19358. sizeof(block),
  19359. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  19360. eol,
  19361. (unsigned)DUK_VERSION / 10000,
  19362. ((unsigned)DUK_VERSION / 100) % 100,
  19363. (unsigned)DUK_VERSION % 100);
  19364. system_info_length += mg_str_append(&buffer, end, block);
  19365. #endif
  19366. }
  19367. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  19368. {
  19369. #if defined(BUILD_DATE)
  19370. const char *bd = BUILD_DATE;
  19371. #else
  19372. #if defined(GCC_DIAGNOSTIC)
  19373. #if GCC_VERSION >= 40900
  19374. #pragma GCC diagnostic push
  19375. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  19376. * does not work in some versions. If "BUILD_DATE" is defined to some
  19377. * string, it is used instead of __DATE__. */
  19378. #pragma GCC diagnostic ignored "-Wdate-time"
  19379. #endif
  19380. #endif
  19381. const char *bd = __DATE__;
  19382. #if defined(GCC_DIAGNOSTIC)
  19383. #if GCC_VERSION >= 40900
  19384. #pragma GCC diagnostic pop
  19385. #endif
  19386. #endif
  19387. #endif
  19388. mg_snprintf(
  19389. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  19390. system_info_length += mg_str_append(&buffer, end, block);
  19391. }
  19392. /* Compiler information */
  19393. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  19394. {
  19395. #if defined(_MSC_VER)
  19396. mg_snprintf(NULL,
  19397. NULL,
  19398. block,
  19399. sizeof(block),
  19400. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  19401. eol,
  19402. (unsigned)_MSC_VER,
  19403. (unsigned)_MSC_FULL_VER);
  19404. system_info_length += mg_str_append(&buffer, end, block);
  19405. #elif defined(__MINGW64__)
  19406. mg_snprintf(NULL,
  19407. NULL,
  19408. block,
  19409. sizeof(block),
  19410. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  19411. eol,
  19412. (unsigned)__MINGW64_VERSION_MAJOR,
  19413. (unsigned)__MINGW64_VERSION_MINOR);
  19414. system_info_length += mg_str_append(&buffer, end, block);
  19415. mg_snprintf(NULL,
  19416. NULL,
  19417. block,
  19418. sizeof(block),
  19419. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19420. eol,
  19421. (unsigned)__MINGW32_MAJOR_VERSION,
  19422. (unsigned)__MINGW32_MINOR_VERSION);
  19423. system_info_length += mg_str_append(&buffer, end, block);
  19424. #elif defined(__MINGW32__)
  19425. mg_snprintf(NULL,
  19426. NULL,
  19427. block,
  19428. sizeof(block),
  19429. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19430. eol,
  19431. (unsigned)__MINGW32_MAJOR_VERSION,
  19432. (unsigned)__MINGW32_MINOR_VERSION);
  19433. system_info_length += mg_str_append(&buffer, end, block);
  19434. #elif defined(__clang__)
  19435. mg_snprintf(NULL,
  19436. NULL,
  19437. block,
  19438. sizeof(block),
  19439. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  19440. eol,
  19441. __clang_major__,
  19442. __clang_minor__,
  19443. __clang_patchlevel__,
  19444. __clang_version__);
  19445. system_info_length += mg_str_append(&buffer, end, block);
  19446. #elif defined(__GNUC__)
  19447. mg_snprintf(NULL,
  19448. NULL,
  19449. block,
  19450. sizeof(block),
  19451. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  19452. eol,
  19453. (unsigned)__GNUC__,
  19454. (unsigned)__GNUC_MINOR__,
  19455. (unsigned)__GNUC_PATCHLEVEL__);
  19456. system_info_length += mg_str_append(&buffer, end, block);
  19457. #elif defined(__INTEL_COMPILER)
  19458. mg_snprintf(NULL,
  19459. NULL,
  19460. block,
  19461. sizeof(block),
  19462. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  19463. eol,
  19464. (unsigned)__INTEL_COMPILER);
  19465. system_info_length += mg_str_append(&buffer, end, block);
  19466. #elif defined(__BORLANDC__)
  19467. mg_snprintf(NULL,
  19468. NULL,
  19469. block,
  19470. sizeof(block),
  19471. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  19472. eol,
  19473. (unsigned)__BORLANDC__);
  19474. system_info_length += mg_str_append(&buffer, end, block);
  19475. #elif defined(__SUNPRO_C)
  19476. mg_snprintf(NULL,
  19477. NULL,
  19478. block,
  19479. sizeof(block),
  19480. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  19481. eol,
  19482. (unsigned)__SUNPRO_C);
  19483. system_info_length += mg_str_append(&buffer, end, block);
  19484. #else
  19485. mg_snprintf(NULL,
  19486. NULL,
  19487. block,
  19488. sizeof(block),
  19489. ",%s\"compiler\" : \"other\"",
  19490. eol);
  19491. system_info_length += mg_str_append(&buffer, end, block);
  19492. #endif
  19493. }
  19494. /* Determine 32/64 bit data mode.
  19495. * see https://en.wikipedia.org/wiki/64-bit_computing */
  19496. {
  19497. mg_snprintf(NULL,
  19498. NULL,
  19499. block,
  19500. sizeof(block),
  19501. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  19502. "char:%u/%u, "
  19503. "ptr:%u, size:%u, time:%u\"",
  19504. eol,
  19505. (unsigned)sizeof(short),
  19506. (unsigned)sizeof(int),
  19507. (unsigned)sizeof(long),
  19508. (unsigned)sizeof(long long),
  19509. (unsigned)sizeof(float),
  19510. (unsigned)sizeof(double),
  19511. (unsigned)sizeof(long double),
  19512. (unsigned)sizeof(char),
  19513. (unsigned)sizeof(wchar_t),
  19514. (unsigned)sizeof(void *),
  19515. (unsigned)sizeof(size_t),
  19516. (unsigned)sizeof(time_t));
  19517. system_info_length += mg_str_append(&buffer, end, block);
  19518. }
  19519. /* Terminate string */
  19520. if (append_eoobj) {
  19521. strcat(append_eoobj, eoobj);
  19522. }
  19523. system_info_length += sizeof(eoobj) - 1;
  19524. return (int)system_info_length;
  19525. }
  19526. /* Get context information. It can be printed or stored by the caller.
  19527. * Return the size of available information. */
  19528. CIVETWEB_API int
  19529. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19530. {
  19531. #if defined(USE_SERVER_STATS)
  19532. char *end, *append_eoobj = NULL, block[256];
  19533. size_t context_info_length = 0;
  19534. #if defined(_WIN32)
  19535. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19536. #else
  19537. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19538. #endif
  19539. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19540. if ((buffer == NULL) || (buflen < 1)) {
  19541. buflen = 0;
  19542. end = buffer;
  19543. } else {
  19544. *buffer = 0;
  19545. end = buffer + buflen;
  19546. }
  19547. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19548. /* has enough space to append eoobj */
  19549. append_eoobj = buffer;
  19550. end -= sizeof(eoobj) - 1;
  19551. }
  19552. context_info_length += mg_str_append(&buffer, end, "{");
  19553. if (ms) { /* <-- should be always true */
  19554. /* Memory information */
  19555. int blockCount = (int)ms->blockCount;
  19556. int64_t totalMemUsed = ms->totalMemUsed;
  19557. int64_t maxMemUsed = ms->maxMemUsed;
  19558. if (totalMemUsed > maxMemUsed) {
  19559. maxMemUsed = totalMemUsed;
  19560. }
  19561. mg_snprintf(NULL,
  19562. NULL,
  19563. block,
  19564. sizeof(block),
  19565. "%s\"memory\" : {%s"
  19566. "\"blocks\" : %i,%s"
  19567. "\"used\" : %" INT64_FMT ",%s"
  19568. "\"maxUsed\" : %" INT64_FMT "%s"
  19569. "}",
  19570. eol,
  19571. eol,
  19572. blockCount,
  19573. eol,
  19574. totalMemUsed,
  19575. eol,
  19576. maxMemUsed,
  19577. eol);
  19578. context_info_length += mg_str_append(&buffer, end, block);
  19579. }
  19580. if (ctx) {
  19581. /* Declare all variables at begin of the block, to comply
  19582. * with old C standards. */
  19583. char start_time_str[64] = {0};
  19584. char now_str[64] = {0};
  19585. time_t start_time = ctx->start_time;
  19586. time_t now = time(NULL);
  19587. int64_t total_data_read, total_data_written;
  19588. int active_connections = (int)ctx->active_connections;
  19589. int max_active_connections = (int)ctx->max_active_connections;
  19590. int total_connections = (int)ctx->total_connections;
  19591. if (active_connections > max_active_connections) {
  19592. max_active_connections = active_connections;
  19593. }
  19594. if (active_connections > total_connections) {
  19595. total_connections = active_connections;
  19596. }
  19597. /* Connections information */
  19598. mg_snprintf(NULL,
  19599. NULL,
  19600. block,
  19601. sizeof(block),
  19602. ",%s\"connections\" : {%s"
  19603. "\"active\" : %i,%s"
  19604. "\"maxActive\" : %i,%s"
  19605. "\"total\" : %i%s"
  19606. "}",
  19607. eol,
  19608. eol,
  19609. active_connections,
  19610. eol,
  19611. max_active_connections,
  19612. eol,
  19613. total_connections,
  19614. eol);
  19615. context_info_length += mg_str_append(&buffer, end, block);
  19616. /* Queue information */
  19617. #if !defined(ALTERNATIVE_QUEUE)
  19618. mg_snprintf(NULL,
  19619. NULL,
  19620. block,
  19621. sizeof(block),
  19622. ",%s\"queue\" : {%s"
  19623. "\"length\" : %i,%s"
  19624. "\"filled\" : %i,%s"
  19625. "\"maxFilled\" : %i,%s"
  19626. "\"full\" : %s%s"
  19627. "}",
  19628. eol,
  19629. eol,
  19630. ctx->sq_size,
  19631. eol,
  19632. ctx->sq_head - ctx->sq_tail,
  19633. eol,
  19634. ctx->sq_max_fill,
  19635. eol,
  19636. (ctx->sq_blocked ? "true" : "false"),
  19637. eol);
  19638. context_info_length += mg_str_append(&buffer, end, block);
  19639. #endif
  19640. /* Requests information */
  19641. mg_snprintf(NULL,
  19642. NULL,
  19643. block,
  19644. sizeof(block),
  19645. ",%s\"requests\" : {%s"
  19646. "\"total\" : %lu%s"
  19647. "}",
  19648. eol,
  19649. eol,
  19650. (unsigned long)ctx->total_requests,
  19651. eol);
  19652. context_info_length += mg_str_append(&buffer, end, block);
  19653. /* Data information */
  19654. total_data_read =
  19655. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19656. total_data_written =
  19657. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19658. mg_snprintf(NULL,
  19659. NULL,
  19660. block,
  19661. sizeof(block),
  19662. ",%s\"data\" : {%s"
  19663. "\"read\" : %" INT64_FMT ",%s"
  19664. "\"written\" : %" INT64_FMT "%s"
  19665. "}",
  19666. eol,
  19667. eol,
  19668. total_data_read,
  19669. eol,
  19670. total_data_written,
  19671. eol);
  19672. context_info_length += mg_str_append(&buffer, end, block);
  19673. /* Execution time information */
  19674. gmt_time_string(start_time_str,
  19675. sizeof(start_time_str) - 1,
  19676. &start_time);
  19677. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19678. mg_snprintf(NULL,
  19679. NULL,
  19680. block,
  19681. sizeof(block),
  19682. ",%s\"time\" : {%s"
  19683. "\"uptime\" : %.0f,%s"
  19684. "\"start\" : \"%s\",%s"
  19685. "\"now\" : \"%s\"%s"
  19686. "}",
  19687. eol,
  19688. eol,
  19689. difftime(now, start_time),
  19690. eol,
  19691. start_time_str,
  19692. eol,
  19693. now_str,
  19694. eol);
  19695. context_info_length += mg_str_append(&buffer, end, block);
  19696. }
  19697. /* Terminate string */
  19698. if (append_eoobj) {
  19699. strcat(append_eoobj, eoobj);
  19700. }
  19701. context_info_length += sizeof(eoobj) - 1;
  19702. return (int)context_info_length;
  19703. #else
  19704. (void)ctx;
  19705. if ((buffer != NULL) && (buflen > 0)) {
  19706. *buffer = 0;
  19707. }
  19708. return 0;
  19709. #endif
  19710. }
  19711. CIVETWEB_API void
  19712. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19713. {
  19714. /* https://github.com/civetweb/civetweb/issues/727 */
  19715. if (conn != NULL) {
  19716. conn->must_close = 1;
  19717. }
  19718. }
  19719. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19720. /* Get connection information. It can be printed or stored by the caller.
  19721. * Return the size of available information. */
  19722. CIVETWEB_API int
  19723. mg_get_connection_info(const struct mg_context *ctx,
  19724. int idx,
  19725. char *buffer,
  19726. int buflen)
  19727. {
  19728. const struct mg_connection *conn;
  19729. const struct mg_request_info *ri;
  19730. char *end, *append_eoobj = NULL, block[256];
  19731. size_t connection_info_length = 0;
  19732. int state = 0;
  19733. const char *state_str = "unknown";
  19734. #if defined(_WIN32)
  19735. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19736. #else
  19737. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19738. #endif
  19739. if ((buffer == NULL) || (buflen < 1)) {
  19740. buflen = 0;
  19741. end = buffer;
  19742. } else {
  19743. *buffer = 0;
  19744. end = buffer + buflen;
  19745. }
  19746. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19747. /* has enough space to append eoobj */
  19748. append_eoobj = buffer;
  19749. end -= sizeof(eoobj) - 1;
  19750. }
  19751. if ((ctx == NULL) || (idx < 0)) {
  19752. /* Parameter error */
  19753. return 0;
  19754. }
  19755. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19756. /* Out of range */
  19757. return 0;
  19758. }
  19759. /* Take connection [idx]. This connection is not locked in
  19760. * any way, so some other thread might use it. */
  19761. conn = (ctx->worker_connections) + idx;
  19762. /* Initialize output string */
  19763. connection_info_length += mg_str_append(&buffer, end, "{");
  19764. /* Init variables */
  19765. ri = &(conn->request_info);
  19766. #if defined(USE_SERVER_STATS)
  19767. state = conn->conn_state;
  19768. /* State as string */
  19769. switch (state) {
  19770. case 0:
  19771. state_str = "undefined";
  19772. break;
  19773. case 1:
  19774. state_str = "not used";
  19775. break;
  19776. case 2:
  19777. state_str = "init";
  19778. break;
  19779. case 3:
  19780. state_str = "ready";
  19781. break;
  19782. case 4:
  19783. state_str = "processing";
  19784. break;
  19785. case 5:
  19786. state_str = "processed";
  19787. break;
  19788. case 6:
  19789. state_str = "to close";
  19790. break;
  19791. case 7:
  19792. state_str = "closing";
  19793. break;
  19794. case 8:
  19795. state_str = "closed";
  19796. break;
  19797. case 9:
  19798. state_str = "done";
  19799. break;
  19800. }
  19801. #endif
  19802. /* Connection info */
  19803. if ((state >= 3) && (state < 9)) {
  19804. mg_snprintf(NULL,
  19805. NULL,
  19806. block,
  19807. sizeof(block),
  19808. "%s\"connection\" : {%s"
  19809. "\"remote\" : {%s"
  19810. "\"protocol\" : \"%s\",%s"
  19811. "\"addr\" : \"%s\",%s"
  19812. "\"port\" : %u%s"
  19813. "},%s"
  19814. "\"handled_requests\" : %u%s"
  19815. "}",
  19816. eol,
  19817. eol,
  19818. eol,
  19819. get_proto_name(conn),
  19820. eol,
  19821. ri->remote_addr,
  19822. eol,
  19823. ri->remote_port,
  19824. eol,
  19825. eol,
  19826. conn->handled_requests,
  19827. eol);
  19828. connection_info_length += mg_str_append(&buffer, end, block);
  19829. }
  19830. /* Request info */
  19831. if ((state >= 4) && (state < 6)) {
  19832. mg_snprintf(NULL,
  19833. NULL,
  19834. block,
  19835. sizeof(block),
  19836. "%s%s\"request_info\" : {%s"
  19837. "\"method\" : \"%s\",%s"
  19838. "\"uri\" : \"%s\",%s"
  19839. "\"query\" : %s%s%s%s"
  19840. "}",
  19841. (connection_info_length > 1 ? "," : ""),
  19842. eol,
  19843. eol,
  19844. ri->request_method,
  19845. eol,
  19846. ri->request_uri,
  19847. eol,
  19848. ri->query_string ? "\"" : "",
  19849. ri->query_string ? ri->query_string : "null",
  19850. ri->query_string ? "\"" : "",
  19851. eol);
  19852. connection_info_length += mg_str_append(&buffer, end, block);
  19853. }
  19854. /* Execution time information */
  19855. if ((state >= 2) && (state < 9)) {
  19856. char start_time_str[64] = {0};
  19857. char close_time_str[64] = {0};
  19858. time_t start_time = conn->conn_birth_time;
  19859. time_t close_time = 0;
  19860. double time_diff;
  19861. gmt_time_string(start_time_str,
  19862. sizeof(start_time_str) - 1,
  19863. &start_time);
  19864. #if defined(USE_SERVER_STATS)
  19865. close_time = conn->conn_close_time;
  19866. #endif
  19867. if (close_time != 0) {
  19868. time_diff = difftime(close_time, start_time);
  19869. gmt_time_string(close_time_str,
  19870. sizeof(close_time_str) - 1,
  19871. &close_time);
  19872. } else {
  19873. time_t now = time(NULL);
  19874. time_diff = difftime(now, start_time);
  19875. close_time_str[0] = 0; /* or use "now" ? */
  19876. }
  19877. mg_snprintf(NULL,
  19878. NULL,
  19879. block,
  19880. sizeof(block),
  19881. "%s%s\"time\" : {%s"
  19882. "\"uptime\" : %.0f,%s"
  19883. "\"start\" : \"%s\",%s"
  19884. "\"closed\" : \"%s\"%s"
  19885. "}",
  19886. (connection_info_length > 1 ? "," : ""),
  19887. eol,
  19888. eol,
  19889. time_diff,
  19890. eol,
  19891. start_time_str,
  19892. eol,
  19893. close_time_str,
  19894. eol);
  19895. connection_info_length += mg_str_append(&buffer, end, block);
  19896. }
  19897. /* Remote user name */
  19898. if ((ri->remote_user) && (state < 9)) {
  19899. mg_snprintf(NULL,
  19900. NULL,
  19901. block,
  19902. sizeof(block),
  19903. "%s%s\"user\" : {%s"
  19904. "\"name\" : \"%s\",%s"
  19905. "}",
  19906. (connection_info_length > 1 ? "," : ""),
  19907. eol,
  19908. eol,
  19909. ri->remote_user,
  19910. eol);
  19911. connection_info_length += mg_str_append(&buffer, end, block);
  19912. }
  19913. /* Data block */
  19914. if (state >= 3) {
  19915. mg_snprintf(NULL,
  19916. NULL,
  19917. block,
  19918. sizeof(block),
  19919. "%s%s\"data\" : {%s"
  19920. "\"read\" : %" INT64_FMT ",%s"
  19921. "\"written\" : %" INT64_FMT "%s"
  19922. "}",
  19923. (connection_info_length > 1 ? "," : ""),
  19924. eol,
  19925. eol,
  19926. conn->consumed_content,
  19927. eol,
  19928. conn->num_bytes_sent,
  19929. eol);
  19930. connection_info_length += mg_str_append(&buffer, end, block);
  19931. }
  19932. /* State */
  19933. mg_snprintf(NULL,
  19934. NULL,
  19935. block,
  19936. sizeof(block),
  19937. "%s%s\"state\" : \"%s\"",
  19938. (connection_info_length > 1 ? "," : ""),
  19939. eol,
  19940. state_str);
  19941. connection_info_length += mg_str_append(&buffer, end, block);
  19942. /* Terminate string */
  19943. if (append_eoobj) {
  19944. strcat(append_eoobj, eoobj);
  19945. }
  19946. connection_info_length += sizeof(eoobj) - 1;
  19947. return (int)connection_info_length;
  19948. }
  19949. #if 0
  19950. /* Get handler information. Not fully implemented. Is it required? */
  19951. CIVETWEB_API int
  19952. mg_get_handler_info(struct mg_context *ctx,
  19953. char *buffer,
  19954. int buflen)
  19955. {
  19956. int handler_info_len = 0;
  19957. struct mg_handler_info *tmp_rh;
  19958. mg_lock_context(ctx);
  19959. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19960. if (buflen > handler_info_len + tmp_rh->uri_len) {
  19961. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19962. }
  19963. handler_info_len += tmp_rh->uri_len;
  19964. switch (tmp_rh->handler_type) {
  19965. case REQUEST_HANDLER:
  19966. (void)tmp_rh->handler;
  19967. break;
  19968. case WEBSOCKET_HANDLER:
  19969. (void)tmp_rh->connect_handler;
  19970. (void)tmp_rh->ready_handler;
  19971. (void)tmp_rh->data_handler;
  19972. (void)tmp_rh->close_handler;
  19973. break;
  19974. case AUTH_HANDLER:
  19975. (void)tmp_rh->auth_handler;
  19976. break;
  19977. }
  19978. (void)cbdata;
  19979. }
  19980. mg_unlock_context(ctx);
  19981. return handler_info_len;
  19982. }
  19983. #endif
  19984. #endif
  19985. /* Initialize this library. This function does not need to be thread safe.
  19986. */
  19987. CIVETWEB_API unsigned
  19988. mg_init_library(unsigned features)
  19989. {
  19990. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19991. unsigned features_inited = features_to_init;
  19992. if (mg_init_library_called <= 0) {
  19993. /* Not initialized yet */
  19994. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19995. return 0;
  19996. }
  19997. }
  19998. mg_global_lock();
  19999. if (mg_init_library_called <= 0) {
  20000. int i;
  20001. size_t len;
  20002. #if defined(_WIN32)
  20003. int file_mutex_init = 1;
  20004. int wsa = 1;
  20005. #else
  20006. int mutexattr_init = 1;
  20007. #endif
  20008. int failed = 1;
  20009. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  20010. if (key_create == 0) {
  20011. #if defined(_WIN32)
  20012. file_mutex_init =
  20013. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  20014. if (file_mutex_init == 0) {
  20015. /* Start WinSock */
  20016. WSADATA data;
  20017. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  20018. }
  20019. #else
  20020. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  20021. if (mutexattr_init == 0) {
  20022. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  20023. PTHREAD_MUTEX_RECURSIVE);
  20024. }
  20025. #endif
  20026. }
  20027. if (failed) {
  20028. #if defined(_WIN32)
  20029. if (wsa == 0) {
  20030. (void)WSACleanup();
  20031. }
  20032. if (file_mutex_init == 0) {
  20033. (void)pthread_mutex_destroy(&global_log_file_lock);
  20034. }
  20035. #else
  20036. if (mutexattr_init == 0) {
  20037. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20038. }
  20039. #endif
  20040. if (key_create == 0) {
  20041. (void)pthread_key_delete(sTlsKey);
  20042. }
  20043. mg_global_unlock();
  20044. (void)pthread_mutex_destroy(&global_lock_mutex);
  20045. return 0;
  20046. }
  20047. len = 1;
  20048. for (i = 0; http_methods[i].name != NULL; i++) {
  20049. size_t sl = strlen(http_methods[i].name);
  20050. len += sl;
  20051. if (i > 0) {
  20052. len += 2;
  20053. }
  20054. }
  20055. all_methods = (char *)mg_malloc(len);
  20056. if (!all_methods) {
  20057. /* Must never happen */
  20058. mg_global_unlock();
  20059. (void)pthread_mutex_destroy(&global_lock_mutex);
  20060. return 0;
  20061. }
  20062. all_methods[0] = 0;
  20063. for (i = 0; http_methods[i].name != NULL; i++) {
  20064. if (i > 0) {
  20065. strcat(all_methods, ", ");
  20066. strcat(all_methods, http_methods[i].name);
  20067. } else {
  20068. strcpy(all_methods, http_methods[i].name);
  20069. }
  20070. }
  20071. }
  20072. #if defined(USE_LUA)
  20073. lua_init_optional_libraries();
  20074. #endif
  20075. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  20076. || defined(OPENSSL_API_3_0)) \
  20077. && !defined(NO_SSL)
  20078. if (features_to_init & MG_FEATURES_SSL) {
  20079. if (!mg_openssl_initialized) {
  20080. char ebuf[128];
  20081. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  20082. mg_openssl_initialized = 1;
  20083. } else {
  20084. (void)ebuf;
  20085. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  20086. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  20087. }
  20088. } else {
  20089. /* ssl already initialized */
  20090. }
  20091. }
  20092. #endif
  20093. if (mg_init_library_called <= 0) {
  20094. mg_init_library_called = 1;
  20095. } else {
  20096. mg_init_library_called++;
  20097. }
  20098. mg_global_unlock();
  20099. return features_inited;
  20100. }
  20101. /* Un-initialize this library. */
  20102. CIVETWEB_API unsigned
  20103. mg_exit_library(void)
  20104. {
  20105. if (mg_init_library_called <= 0) {
  20106. return 0;
  20107. }
  20108. mg_global_lock();
  20109. mg_init_library_called--;
  20110. if (mg_init_library_called == 0) {
  20111. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  20112. if (mg_openssl_initialized) {
  20113. uninitialize_openssl();
  20114. mg_openssl_initialized = 0;
  20115. }
  20116. #endif
  20117. #if defined(_WIN32)
  20118. (void)WSACleanup();
  20119. (void)pthread_mutex_destroy(&global_log_file_lock);
  20120. #else
  20121. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20122. #endif
  20123. (void)pthread_key_delete(sTlsKey);
  20124. #if defined(USE_LUA)
  20125. lua_exit_optional_libraries();
  20126. #endif
  20127. mg_free(all_methods);
  20128. all_methods = NULL;
  20129. mg_global_unlock();
  20130. (void)pthread_mutex_destroy(&global_lock_mutex);
  20131. return 1;
  20132. }
  20133. mg_global_unlock();
  20134. return 1;
  20135. }
  20136. /* End of civetweb.c */