civetweb.c 619 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176
  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 stderr
  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. ports[cnt].is_bound = ctx->listening_sockets[i].sock != INVALID_SOCKET;
  2801. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2802. /* IPv4 */
  2803. ports[cnt].protocol = 1;
  2804. cnt++;
  2805. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2806. /* IPv6 */
  2807. ports[cnt].protocol = 3;
  2808. cnt++;
  2809. }
  2810. }
  2811. return cnt;
  2812. }
  2813. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2814. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2815. #endif
  2816. static void
  2817. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2818. {
  2819. buf[0] = '\0';
  2820. if (!usa) {
  2821. return;
  2822. }
  2823. if (usa->sa.sa_family == AF_INET) {
  2824. getnameinfo(&usa->sa,
  2825. sizeof(usa->sin),
  2826. buf,
  2827. (unsigned)len,
  2828. NULL,
  2829. 0,
  2830. NI_NUMERICHOST);
  2831. }
  2832. #if defined(USE_IPV6)
  2833. else if (usa->sa.sa_family == AF_INET6) {
  2834. getnameinfo(&usa->sa,
  2835. sizeof(usa->sin6),
  2836. buf,
  2837. (unsigned)len,
  2838. NULL,
  2839. 0,
  2840. NI_NUMERICHOST);
  2841. }
  2842. #endif
  2843. #if defined(USE_X_DOM_SOCKET)
  2844. else if (usa->sa.sa_family == AF_UNIX) {
  2845. /* TODO: Define a remote address for unix domain sockets.
  2846. * This code will always return "localhost", identical to http+tcp:
  2847. getnameinfo(&usa->sa,
  2848. sizeof(usa->sun),
  2849. buf,
  2850. (unsigned)len,
  2851. NULL,
  2852. 0,
  2853. NI_NUMERICHOST);
  2854. */
  2855. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2856. }
  2857. #endif
  2858. }
  2859. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2860. * included in all responses other than 100, 101, 5xx. */
  2861. static void
  2862. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2863. {
  2864. #if !defined(REENTRANT_TIME)
  2865. struct tm *tm;
  2866. tm = ((t != NULL) ? gmtime(t) : NULL);
  2867. if (tm != NULL) {
  2868. #else
  2869. struct tm _tm;
  2870. struct tm *tm = &_tm;
  2871. if (t != NULL) {
  2872. gmtime_r(t, tm);
  2873. #endif
  2874. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2875. } else {
  2876. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2877. }
  2878. }
  2879. /* difftime for struct timespec. Return value is in seconds. */
  2880. static double
  2881. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2882. {
  2883. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2884. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2885. }
  2886. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2887. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2888. const char *func,
  2889. unsigned line,
  2890. const char *fmt,
  2891. va_list ap);
  2892. #include "external_mg_cry_internal_impl.inl"
  2893. #elif !defined(NO_FILESYSTEMS)
  2894. /* Print error message to the opened error log stream. */
  2895. static void
  2896. mg_cry_internal_impl(const struct mg_connection *conn,
  2897. const char *func,
  2898. unsigned line,
  2899. const char *fmt,
  2900. va_list ap)
  2901. {
  2902. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2903. struct mg_file fi;
  2904. time_t timestamp;
  2905. /* Unused, in the RELEASE build */
  2906. (void)func;
  2907. (void)line;
  2908. #if defined(GCC_DIAGNOSTIC)
  2909. #pragma GCC diagnostic push
  2910. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2911. #endif
  2912. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2913. #if defined(GCC_DIAGNOSTIC)
  2914. #pragma GCC diagnostic pop
  2915. #endif
  2916. buf[sizeof(buf) - 1] = 0;
  2917. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2918. if (!conn) {
  2919. puts(buf);
  2920. return;
  2921. }
  2922. /* Do not lock when getting the callback value, here and below.
  2923. * I suppose this is fine, since function cannot disappear in the
  2924. * same way string option can. */
  2925. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2926. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2927. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2928. if (mg_fopen(conn,
  2929. conn->dom_ctx->config[ERROR_LOG_FILE],
  2930. MG_FOPEN_MODE_APPEND,
  2931. &fi)
  2932. == 0) {
  2933. fi.access.fp = NULL;
  2934. }
  2935. } else {
  2936. fi.access.fp = NULL;
  2937. }
  2938. if (fi.access.fp != NULL) {
  2939. flockfile(fi.access.fp);
  2940. timestamp = time(NULL);
  2941. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2942. fprintf(fi.access.fp,
  2943. "[%010lu] [error] [client %s] ",
  2944. (unsigned long)timestamp,
  2945. src_addr);
  2946. if (conn->request_info.request_method != NULL) {
  2947. fprintf(fi.access.fp,
  2948. "%s %s: ",
  2949. conn->request_info.request_method,
  2950. conn->request_info.request_uri
  2951. ? conn->request_info.request_uri
  2952. : "");
  2953. }
  2954. fprintf(fi.access.fp, "%s", buf);
  2955. fputc('\n', fi.access.fp);
  2956. fflush(fi.access.fp);
  2957. funlockfile(fi.access.fp);
  2958. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2959. * mg_cry here anyway ;-) */
  2960. }
  2961. }
  2962. }
  2963. #else
  2964. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2965. #endif /* Externally provided function */
  2966. /* Construct fake connection structure. Used for logging, if connection
  2967. * is not applicable at the moment of logging. */
  2968. static struct mg_connection *
  2969. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2970. {
  2971. static const struct mg_connection conn_zero = {0};
  2972. *fc = conn_zero;
  2973. fc->phys_ctx = ctx;
  2974. fc->dom_ctx = &(ctx->dd);
  2975. return fc;
  2976. }
  2977. static void
  2978. mg_cry_internal_wrap(const struct mg_connection *conn,
  2979. struct mg_context *ctx,
  2980. const char *func,
  2981. unsigned line,
  2982. const char *fmt,
  2983. ...)
  2984. {
  2985. va_list ap;
  2986. va_start(ap, fmt);
  2987. if (!conn && ctx) {
  2988. struct mg_connection fc;
  2989. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2990. } else {
  2991. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2992. }
  2993. va_end(ap);
  2994. }
  2995. CIVETWEB_API void
  2996. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2997. {
  2998. va_list ap;
  2999. va_start(ap, fmt);
  3000. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3001. va_end(ap);
  3002. }
  3003. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3004. CIVETWEB_API const char *
  3005. mg_version(void)
  3006. {
  3007. return CIVETWEB_VERSION;
  3008. }
  3009. CIVETWEB_API const struct mg_request_info *
  3010. mg_get_request_info(const struct mg_connection *conn)
  3011. {
  3012. if (!conn) {
  3013. return NULL;
  3014. }
  3015. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3016. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3017. char txt[16];
  3018. struct mg_workerTLS *tls =
  3019. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3020. sprintf(txt, "%03i", conn->response_info.status_code);
  3021. if (strlen(txt) == 3) {
  3022. memcpy(tls->txtbuf, txt, 4);
  3023. } else {
  3024. strcpy(tls->txtbuf, "ERR");
  3025. }
  3026. ((struct mg_connection *)conn)->request_info.local_uri =
  3027. tls->txtbuf; /* use thread safe buffer */
  3028. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3029. tls->txtbuf; /* use the same thread safe buffer */
  3030. ((struct mg_connection *)conn)->request_info.request_uri =
  3031. tls->txtbuf; /* use the same thread safe buffer */
  3032. ((struct mg_connection *)conn)->request_info.num_headers =
  3033. conn->response_info.num_headers;
  3034. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3035. conn->response_info.http_headers,
  3036. sizeof(conn->response_info.http_headers));
  3037. } else
  3038. #endif
  3039. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3040. return NULL;
  3041. }
  3042. return &conn->request_info;
  3043. }
  3044. CIVETWEB_API const struct mg_response_info *
  3045. mg_get_response_info(const struct mg_connection *conn)
  3046. {
  3047. if (!conn) {
  3048. return NULL;
  3049. }
  3050. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3051. return NULL;
  3052. }
  3053. return &conn->response_info;
  3054. }
  3055. static const char *
  3056. get_proto_name(const struct mg_connection *conn)
  3057. {
  3058. #if defined(__clang__)
  3059. #pragma clang diagnostic push
  3060. #pragma clang diagnostic ignored "-Wunreachable-code"
  3061. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3062. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3063. * unreachable, but splitting into four different #ifdef clauses here is
  3064. * more complicated.
  3065. */
  3066. #endif
  3067. const struct mg_request_info *ri = &conn->request_info;
  3068. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3069. ? (ri->is_ssl ? "wss" : "ws")
  3070. : (ri->is_ssl ? "https" : "http"));
  3071. return proto;
  3072. #if defined(__clang__)
  3073. #pragma clang diagnostic pop
  3074. #endif
  3075. }
  3076. static int
  3077. mg_construct_local_link(const struct mg_connection *conn,
  3078. char *buf,
  3079. size_t buflen,
  3080. const char *define_proto,
  3081. int define_port,
  3082. const char *define_uri)
  3083. {
  3084. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3085. return -1;
  3086. } else {
  3087. int i, j;
  3088. int truncated = 0;
  3089. const struct mg_request_info *ri = &conn->request_info;
  3090. const char *proto =
  3091. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3092. const char *uri =
  3093. (define_uri != NULL)
  3094. ? define_uri
  3095. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3096. int port = (define_port > 0) ? define_port : ri->server_port;
  3097. int default_port = 80;
  3098. char *uri_encoded;
  3099. size_t uri_encoded_len;
  3100. if (uri == NULL) {
  3101. return -1;
  3102. }
  3103. uri_encoded_len = strlen(uri) * 3 + 1;
  3104. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3105. if (uri_encoded == NULL) {
  3106. return -1;
  3107. }
  3108. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3109. /* Directory separator should be preserved. */
  3110. for (i = j = 0; uri_encoded[i]; j++) {
  3111. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3112. uri_encoded[j] = '/';
  3113. i += 3;
  3114. } else {
  3115. uri_encoded[j] = uri_encoded[i++];
  3116. }
  3117. }
  3118. uri_encoded[j] = '\0';
  3119. #if defined(USE_X_DOM_SOCKET)
  3120. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3121. /* TODO: Define and document a link for UNIX domain sockets. */
  3122. /* There seems to be no official standard for this.
  3123. * Common uses seem to be "httpunix://", "http.unix://" or
  3124. * "http+unix://" as a protocol definition string, followed by
  3125. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3126. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3127. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3128. * "" (completely skipping the server name part). In any case, the
  3129. * last part is the server local path. */
  3130. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3131. mg_snprintf(conn,
  3132. &truncated,
  3133. buf,
  3134. buflen,
  3135. "%s.unix://%s%s",
  3136. proto,
  3137. server_name,
  3138. ri->local_uri);
  3139. default_port = 0;
  3140. mg_free(uri_encoded);
  3141. return 0;
  3142. }
  3143. #endif
  3144. if (define_proto) {
  3145. /* If we got a protocol name, use the default port accordingly. */
  3146. if ((0 == strcmp(define_proto, "https"))
  3147. || (0 == strcmp(define_proto, "wss"))) {
  3148. default_port = 443;
  3149. }
  3150. } else if (ri->is_ssl) {
  3151. /* If we did not get a protocol name, use TLS as default if it is
  3152. * already used. */
  3153. default_port = 443;
  3154. }
  3155. {
  3156. #if defined(USE_IPV6)
  3157. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3158. #endif
  3159. int auth_domain_check_enabled =
  3160. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3161. && (!mg_strcasecmp(
  3162. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3163. const char *server_domain =
  3164. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3165. char portstr[16];
  3166. char server_ip[48];
  3167. if (port != default_port) {
  3168. sprintf(portstr, ":%u", (unsigned)port);
  3169. } else {
  3170. portstr[0] = 0;
  3171. }
  3172. if (!auth_domain_check_enabled || !server_domain) {
  3173. sockaddr_to_string(server_ip,
  3174. sizeof(server_ip),
  3175. &conn->client.lsa);
  3176. server_domain = server_ip;
  3177. }
  3178. mg_snprintf(conn,
  3179. &truncated,
  3180. buf,
  3181. buflen,
  3182. #if defined(USE_IPV6)
  3183. "%s://%s%s%s%s%s",
  3184. proto,
  3185. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3186. server_domain,
  3187. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3188. #else
  3189. "%s://%s%s%s",
  3190. proto,
  3191. server_domain,
  3192. #endif
  3193. portstr,
  3194. uri_encoded);
  3195. mg_free(uri_encoded);
  3196. if (truncated) {
  3197. return -1;
  3198. }
  3199. return 0;
  3200. }
  3201. }
  3202. }
  3203. CIVETWEB_API int
  3204. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3205. {
  3206. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3207. }
  3208. /* Skip the characters until one of the delimiters characters found.
  3209. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3210. * Advance pointer to buffer to the next word. Return found 0-terminated
  3211. * word.
  3212. * Delimiters can be quoted with quotechar. */
  3213. static char *
  3214. skip_quoted(char **buf,
  3215. const char *delimiters,
  3216. const char *whitespace,
  3217. char quotechar)
  3218. {
  3219. char *p, *begin_word, *end_word, *end_whitespace;
  3220. begin_word = *buf;
  3221. end_word = begin_word + strcspn(begin_word, delimiters);
  3222. /* Check for quotechar */
  3223. if (end_word > begin_word) {
  3224. p = end_word - 1;
  3225. while (*p == quotechar) {
  3226. /* While the delimiter is quoted, look for the next delimiter. */
  3227. /* This happens, e.g., in calls from parse_auth_header,
  3228. * if the user name contains a " character. */
  3229. /* If there is anything beyond end_word, copy it. */
  3230. if (*end_word != '\0') {
  3231. size_t end_off = strcspn(end_word + 1, delimiters);
  3232. memmove(p, end_word, end_off + 1);
  3233. p += end_off; /* p must correspond to end_word - 1 */
  3234. end_word += end_off + 1;
  3235. } else {
  3236. *p = '\0';
  3237. break;
  3238. }
  3239. }
  3240. for (p++; p < end_word; p++) {
  3241. *p = '\0';
  3242. }
  3243. }
  3244. if (*end_word == '\0') {
  3245. *buf = end_word;
  3246. } else {
  3247. #if defined(GCC_DIAGNOSTIC)
  3248. /* Disable spurious conversion warning for GCC */
  3249. #pragma GCC diagnostic push
  3250. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3251. #endif /* defined(GCC_DIAGNOSTIC) */
  3252. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3253. #if defined(GCC_DIAGNOSTIC)
  3254. #pragma GCC diagnostic pop
  3255. #endif /* defined(GCC_DIAGNOSTIC) */
  3256. for (p = end_word; p < end_whitespace; p++) {
  3257. *p = '\0';
  3258. }
  3259. *buf = end_whitespace;
  3260. }
  3261. return begin_word;
  3262. }
  3263. /* Return HTTP header value, or NULL if not found. */
  3264. static const char *
  3265. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3266. {
  3267. int i;
  3268. for (i = 0; i < num_hdr; i++) {
  3269. if (!mg_strcasecmp(name, hdr[i].name)) {
  3270. return hdr[i].value;
  3271. }
  3272. }
  3273. return NULL;
  3274. }
  3275. /* Retrieve requested HTTP header multiple values, and return the number of
  3276. * found occurrences */
  3277. static int
  3278. get_req_headers(const struct mg_request_info *ri,
  3279. const char *name,
  3280. const char **output,
  3281. int output_max_size)
  3282. {
  3283. int i;
  3284. int cnt = 0;
  3285. if (ri) {
  3286. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3287. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3288. output[cnt++] = ri->http_headers[i].value;
  3289. }
  3290. }
  3291. }
  3292. return cnt;
  3293. }
  3294. CIVETWEB_API const char *
  3295. mg_get_header(const struct mg_connection *conn, const char *name)
  3296. {
  3297. if (!conn) {
  3298. return NULL;
  3299. }
  3300. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3301. return get_header(conn->request_info.http_headers,
  3302. conn->request_info.num_headers,
  3303. name);
  3304. }
  3305. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3306. return get_header(conn->response_info.http_headers,
  3307. conn->response_info.num_headers,
  3308. name);
  3309. }
  3310. return NULL;
  3311. }
  3312. static const char *
  3313. get_http_version(const struct mg_connection *conn)
  3314. {
  3315. if (!conn) {
  3316. return NULL;
  3317. }
  3318. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3319. return conn->request_info.http_version;
  3320. }
  3321. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3322. return conn->response_info.http_version;
  3323. }
  3324. return NULL;
  3325. }
  3326. /* A helper function for traversing a comma separated list of values.
  3327. * It returns a list pointer shifted to the next value, or NULL if the end
  3328. * of the list found.
  3329. * Value is stored in val vector. If value has form "x=y", then eq_val
  3330. * vector is initialized to point to the "y" part, and val vector length
  3331. * is adjusted to point only to "x". */
  3332. static const char *
  3333. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3334. {
  3335. int end;
  3336. reparse:
  3337. if (val == NULL || list == NULL || *list == '\0') {
  3338. /* End of the list */
  3339. return NULL;
  3340. }
  3341. /* Skip over leading LWS */
  3342. while (*list == ' ' || *list == '\t')
  3343. list++;
  3344. val->ptr = list;
  3345. if ((list = strchr(val->ptr, ',')) != NULL) {
  3346. /* Comma found. Store length and shift the list ptr */
  3347. val->len = ((size_t)(list - val->ptr));
  3348. list++;
  3349. } else {
  3350. /* This value is the last one */
  3351. list = val->ptr + strlen(val->ptr);
  3352. val->len = ((size_t)(list - val->ptr));
  3353. }
  3354. /* Adjust length for trailing LWS */
  3355. end = (int)val->len - 1;
  3356. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3357. end--;
  3358. val->len = (size_t)(end) + (size_t)(1);
  3359. if (val->len == 0) {
  3360. /* Ignore any empty entries. */
  3361. goto reparse;
  3362. }
  3363. if (eq_val != NULL) {
  3364. /* Value has form "x=y", adjust pointers and lengths
  3365. * so that val points to "x", and eq_val points to "y". */
  3366. eq_val->len = 0;
  3367. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3368. if (eq_val->ptr != NULL) {
  3369. eq_val->ptr++; /* Skip over '=' character */
  3370. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3371. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3372. }
  3373. }
  3374. return list;
  3375. }
  3376. /* A helper function for checking if a comma separated list of values
  3377. * contains
  3378. * the given option (case insensitvely).
  3379. * 'header' can be NULL, in which case false is returned. */
  3380. static int
  3381. header_has_option(const char *header, const char *option)
  3382. {
  3383. struct vec opt_vec;
  3384. struct vec eq_vec;
  3385. DEBUG_ASSERT(option != NULL);
  3386. DEBUG_ASSERT(option[0] != '\0');
  3387. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3388. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3389. return 1;
  3390. }
  3391. return 0;
  3392. }
  3393. /* Sorting function implemented in a separate file */
  3394. #include "sort.inl"
  3395. /* Pattern matching has been reimplemented in a new file */
  3396. #include "match.inl"
  3397. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3398. * This function must tolerate situations when connection info is not
  3399. * set up, for example if request parsing failed. */
  3400. static int
  3401. should_keep_alive(const struct mg_connection *conn)
  3402. {
  3403. const char *http_version;
  3404. const char *header;
  3405. /* First satisfy needs of the server */
  3406. if ((conn == NULL) || conn->must_close) {
  3407. /* Close, if civetweb framework needs to close */
  3408. return 0;
  3409. }
  3410. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3411. /* Close, if keep alive is not enabled */
  3412. return 0;
  3413. }
  3414. /* Check explicit wish of the client */
  3415. header = mg_get_header(conn, "Connection");
  3416. if (header) {
  3417. /* If there is a connection header from the client, obey */
  3418. if (header_has_option(header, "keep-alive")) {
  3419. return 1;
  3420. }
  3421. return 0;
  3422. }
  3423. /* Use default of the standard */
  3424. http_version = get_http_version(conn);
  3425. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3426. /* HTTP 1.1 default is keep alive */
  3427. return 1;
  3428. }
  3429. /* HTTP 1.0 (and earlier) default is to close the connection */
  3430. return 0;
  3431. }
  3432. static int
  3433. should_decode_url(const struct mg_connection *conn)
  3434. {
  3435. if (!conn || !conn->dom_ctx) {
  3436. return 0;
  3437. }
  3438. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3439. }
  3440. static int
  3441. should_decode_query_string(const struct mg_connection *conn)
  3442. {
  3443. if (!conn || !conn->dom_ctx) {
  3444. return 0;
  3445. }
  3446. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3447. == 0);
  3448. }
  3449. static const char *
  3450. suggest_connection_header(const struct mg_connection *conn)
  3451. {
  3452. return should_keep_alive(conn) ? "keep-alive" : "close";
  3453. }
  3454. #include "response.inl"
  3455. static void
  3456. send_no_cache_header(struct mg_connection *conn)
  3457. {
  3458. /* Send all current and obsolete cache opt-out directives. */
  3459. mg_response_header_add(conn,
  3460. "Cache-Control",
  3461. "no-cache, no-store, "
  3462. "must-revalidate, private, max-age=0",
  3463. -1);
  3464. mg_response_header_add(conn, "Expires", "0", -1);
  3465. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3466. /* Obsolete, but still send it for HTTP/1.0 */
  3467. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3468. }
  3469. }
  3470. static void
  3471. send_static_cache_header(struct mg_connection *conn)
  3472. {
  3473. #if !defined(NO_CACHING)
  3474. int max_age;
  3475. char val[64];
  3476. const char *cache_control =
  3477. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3478. /* If there is a full cache-control option configured,0 use it */
  3479. if (cache_control != NULL) {
  3480. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3481. return;
  3482. }
  3483. /* Read the server config to check how long a file may be cached.
  3484. * The configuration is in seconds. */
  3485. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3486. if (max_age <= 0) {
  3487. /* 0 means "do not cache". All values <0 are reserved
  3488. * and may be used differently in the future. */
  3489. /* If a file should not be cached, do not only send
  3490. * max-age=0, but also pragmas and Expires headers. */
  3491. send_no_cache_header(conn);
  3492. return;
  3493. }
  3494. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3495. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3496. /* See also https://www.mnot.net/cache_docs/ */
  3497. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3498. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3499. * leap
  3500. * year to 31622400 seconds. For the moment, we just send whatever has
  3501. * been configured, still the behavior for >1 year should be considered
  3502. * as undefined. */
  3503. mg_snprintf(
  3504. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3505. mg_response_header_add(conn, "Cache-Control", val, -1);
  3506. #else /* NO_CACHING */
  3507. send_no_cache_header(conn);
  3508. #endif /* !NO_CACHING */
  3509. }
  3510. static void
  3511. send_additional_header(struct mg_connection *conn)
  3512. {
  3513. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3514. #if !defined(NO_SSL)
  3515. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3516. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3517. if (max_age >= 0) {
  3518. char val[64];
  3519. mg_snprintf(conn,
  3520. NULL,
  3521. val,
  3522. sizeof(val),
  3523. "max-age=%lu",
  3524. (unsigned long)max_age);
  3525. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3526. }
  3527. }
  3528. #endif
  3529. // Content-Security-Policy
  3530. if (header && header[0]) {
  3531. mg_response_header_add_lines(conn, header);
  3532. }
  3533. }
  3534. static void
  3535. send_cors_header(struct mg_connection *conn)
  3536. {
  3537. const char *origin_hdr = mg_get_header(conn, "Origin");
  3538. const char *cors_orig_cfg =
  3539. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3540. const char *cors_cred_cfg =
  3541. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  3542. const char *cors_hdr_cfg =
  3543. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  3544. const char *cors_exphdr_cfg =
  3545. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  3546. const char *cors_meth_cfg =
  3547. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  3548. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3549. /* Cross-origin resource sharing (CORS), see
  3550. * http://www.html5rocks.com/en/tutorials/cors/,
  3551. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3552. * CORS preflight is not supported for files. */
  3553. mg_response_header_add(conn,
  3554. "Access-Control-Allow-Origin",
  3555. cors_orig_cfg,
  3556. -1);
  3557. }
  3558. if (cors_cred_cfg && *cors_cred_cfg && origin_hdr && *origin_hdr) {
  3559. /* Cross-origin resource sharing (CORS), see
  3560. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  3561. */
  3562. mg_response_header_add(conn,
  3563. "Access-Control-Allow-Credentials",
  3564. cors_cred_cfg,
  3565. -1);
  3566. }
  3567. if (cors_hdr_cfg && *cors_hdr_cfg) {
  3568. mg_response_header_add(conn,
  3569. "Access-Control-Allow-Headers",
  3570. cors_hdr_cfg,
  3571. -1);
  3572. }
  3573. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  3574. mg_response_header_add(conn,
  3575. "Access-Control-Expose-Headers",
  3576. cors_exphdr_cfg,
  3577. -1);
  3578. }
  3579. if (cors_meth_cfg && *cors_meth_cfg) {
  3580. mg_response_header_add(conn,
  3581. "Access-Control-Allow-Methods",
  3582. cors_meth_cfg,
  3583. -1);
  3584. }
  3585. }
  3586. #if !defined(NO_FILESYSTEMS)
  3587. static void handle_file_based_request(struct mg_connection *conn,
  3588. const char *path,
  3589. struct mg_file *filep);
  3590. #endif /* NO_FILESYSTEMS */
  3591. CIVETWEB_API const char *
  3592. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3593. {
  3594. /* See IANA HTTP status code assignment:
  3595. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3596. */
  3597. switch (response_code) {
  3598. /* RFC2616 Section 10.1 - Informational 1xx */
  3599. case 100:
  3600. return "Continue"; /* RFC2616 Section 10.1.1 */
  3601. case 101:
  3602. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3603. case 102:
  3604. return "Processing"; /* RFC2518 Section 10.1 */
  3605. /* RFC2616 Section 10.2 - Successful 2xx */
  3606. case 200:
  3607. return "OK"; /* RFC2616 Section 10.2.1 */
  3608. case 201:
  3609. return "Created"; /* RFC2616 Section 10.2.2 */
  3610. case 202:
  3611. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3612. case 203:
  3613. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3614. case 204:
  3615. return "No Content"; /* RFC2616 Section 10.2.5 */
  3616. case 205:
  3617. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3618. case 206:
  3619. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3620. case 207:
  3621. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3622. */
  3623. case 208:
  3624. return "Already Reported"; /* RFC5842 Section 7.1 */
  3625. case 226:
  3626. return "IM used"; /* RFC3229 Section 10.4.1 */
  3627. /* RFC2616 Section 10.3 - Redirection 3xx */
  3628. case 300:
  3629. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3630. case 301:
  3631. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3632. case 302:
  3633. return "Found"; /* RFC2616 Section 10.3.3 */
  3634. case 303:
  3635. return "See Other"; /* RFC2616 Section 10.3.4 */
  3636. case 304:
  3637. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3638. case 305:
  3639. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3640. case 307:
  3641. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3642. case 308:
  3643. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3644. /* RFC2616 Section 10.4 - Client Error 4xx */
  3645. case 400:
  3646. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3647. case 401:
  3648. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3649. case 402:
  3650. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3651. case 403:
  3652. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3653. case 404:
  3654. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3655. case 405:
  3656. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3657. case 406:
  3658. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3659. case 407:
  3660. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3661. case 408:
  3662. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3663. case 409:
  3664. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3665. case 410:
  3666. return "Gone"; /* RFC2616 Section 10.4.11 */
  3667. case 411:
  3668. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3669. case 412:
  3670. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3671. case 413:
  3672. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3673. case 414:
  3674. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3675. case 415:
  3676. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3677. case 416:
  3678. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3679. */
  3680. case 417:
  3681. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3682. case 421:
  3683. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3684. case 422:
  3685. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3686. * Section 11.2 */
  3687. case 423:
  3688. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3689. case 424:
  3690. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3691. * Section 11.4 */
  3692. case 426:
  3693. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3694. case 428:
  3695. return "Precondition Required"; /* RFC 6585, Section 3 */
  3696. case 429:
  3697. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3698. case 431:
  3699. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3700. case 451:
  3701. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3702. * Section 3 */
  3703. /* RFC2616 Section 10.5 - Server Error 5xx */
  3704. case 500:
  3705. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3706. case 501:
  3707. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3708. case 502:
  3709. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3710. case 503:
  3711. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3712. case 504:
  3713. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3714. case 505:
  3715. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3716. case 506:
  3717. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3718. case 507:
  3719. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3720. * Section 11.5 */
  3721. case 508:
  3722. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3723. case 510:
  3724. return "Not Extended"; /* RFC 2774, Section 7 */
  3725. case 511:
  3726. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3727. /* Other status codes, not shown in the IANA HTTP status code
  3728. * assignment.
  3729. * E.g., "de facto" standards due to common use, ... */
  3730. case 418:
  3731. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3732. case 419:
  3733. return "Authentication Timeout"; /* common use */
  3734. case 420:
  3735. return "Enhance Your Calm"; /* common use */
  3736. case 440:
  3737. return "Login Timeout"; /* common use */
  3738. case 509:
  3739. return "Bandwidth Limit Exceeded"; /* common use */
  3740. default:
  3741. /* This error code is unknown. This should not happen. */
  3742. if (conn) {
  3743. mg_cry_internal(conn,
  3744. "Unknown HTTP response code: %u",
  3745. response_code);
  3746. }
  3747. /* Return at least a category according to RFC 2616 Section 10. */
  3748. if (response_code >= 100 && response_code < 200) {
  3749. /* Unknown informational status code */
  3750. return "Information";
  3751. }
  3752. if (response_code >= 200 && response_code < 300) {
  3753. /* Unknown success code */
  3754. return "Success";
  3755. }
  3756. if (response_code >= 300 && response_code < 400) {
  3757. /* Unknown redirection code */
  3758. return "Redirection";
  3759. }
  3760. if (response_code >= 400 && response_code < 500) {
  3761. /* Unknown request error code */
  3762. return "Client Error";
  3763. }
  3764. if (response_code >= 500 && response_code < 600) {
  3765. /* Unknown server error code */
  3766. return "Server Error";
  3767. }
  3768. /* Response code not even within reasonable range */
  3769. return "";
  3770. }
  3771. }
  3772. static int
  3773. mg_send_http_error_impl(struct mg_connection *conn,
  3774. int status,
  3775. const char *fmt,
  3776. va_list args)
  3777. {
  3778. char errmsg_buf[MG_BUF_LEN];
  3779. va_list ap;
  3780. int has_body;
  3781. #if !defined(NO_FILESYSTEMS)
  3782. char path_buf[UTF8_PATH_MAX];
  3783. int len, i, page_handler_found, scope, truncated;
  3784. const char *error_handler = NULL;
  3785. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3786. const char *error_page_file_ext, *tstr;
  3787. #endif /* NO_FILESYSTEMS */
  3788. int handled_by_callback = 0;
  3789. if ((conn == NULL) || (fmt == NULL)) {
  3790. return -2;
  3791. }
  3792. /* Set status (for log) */
  3793. conn->status_code = status;
  3794. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3795. has_body = ((status > 199) && (status != 204) && (status != 304));
  3796. /* Prepare message in buf, if required */
  3797. if (has_body
  3798. || (!conn->in_error_handler
  3799. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3800. /* Store error message in errmsg_buf */
  3801. va_copy(ap, args);
  3802. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3803. va_end(ap);
  3804. /* In a debug build, print all html errors */
  3805. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3806. }
  3807. /* If there is a http_error callback, call it.
  3808. * But don't do it recursively, if callback calls mg_send_http_error again.
  3809. */
  3810. if (!conn->in_error_handler
  3811. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3812. /* Mark in_error_handler to avoid recursion and call user callback. */
  3813. conn->in_error_handler = 1;
  3814. handled_by_callback =
  3815. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3816. == 0);
  3817. conn->in_error_handler = 0;
  3818. }
  3819. if (!handled_by_callback) {
  3820. /* Check for recursion */
  3821. if (conn->in_error_handler) {
  3822. DEBUG_TRACE(
  3823. "Recursion when handling error %u - fall back to default",
  3824. status);
  3825. #if !defined(NO_FILESYSTEMS)
  3826. } else {
  3827. /* Send user defined error pages, if defined */
  3828. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3829. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3830. page_handler_found = 0;
  3831. if (error_handler != NULL) {
  3832. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3833. switch (scope) {
  3834. case 1: /* Handler for specific error, e.g. 404 error */
  3835. mg_snprintf(conn,
  3836. &truncated,
  3837. path_buf,
  3838. sizeof(path_buf) - 32,
  3839. "%serror%03u.",
  3840. error_handler,
  3841. status);
  3842. break;
  3843. case 2: /* Handler for error group, e.g., 5xx error
  3844. * handler
  3845. * for all server errors (500-599) */
  3846. mg_snprintf(conn,
  3847. &truncated,
  3848. path_buf,
  3849. sizeof(path_buf) - 32,
  3850. "%serror%01uxx.",
  3851. error_handler,
  3852. status / 100);
  3853. break;
  3854. default: /* Handler for all errors */
  3855. mg_snprintf(conn,
  3856. &truncated,
  3857. path_buf,
  3858. sizeof(path_buf) - 32,
  3859. "%serror.",
  3860. error_handler);
  3861. break;
  3862. }
  3863. /* String truncation in buf may only occur if
  3864. * error_handler is too long. This string is
  3865. * from the config, not from a client. */
  3866. (void)truncated;
  3867. /* The following code is redundant, but it should avoid
  3868. * false positives in static source code analyzers and
  3869. * vulnerability scanners.
  3870. */
  3871. path_buf[sizeof(path_buf) - 32] = 0;
  3872. len = (int)strlen(path_buf);
  3873. if (len > (int)sizeof(path_buf) - 32) {
  3874. len = (int)sizeof(path_buf) - 32;
  3875. }
  3876. /* Start with the file extension from the configuration. */
  3877. tstr = strchr(error_page_file_ext, '.');
  3878. while (tstr) {
  3879. for (i = 1;
  3880. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3881. i++) {
  3882. /* buffer overrun is not possible here, since
  3883. * (i < 32) && (len < sizeof(path_buf) - 32)
  3884. * ==> (i + len) < sizeof(path_buf) */
  3885. path_buf[len + i - 1] = tstr[i];
  3886. }
  3887. /* buffer overrun is not possible here, since
  3888. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3889. * ==> (i + len) <= sizeof(path_buf) */
  3890. path_buf[len + i - 1] = 0;
  3891. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3892. DEBUG_TRACE("Check error page %s - found",
  3893. path_buf);
  3894. page_handler_found = 1;
  3895. break;
  3896. }
  3897. DEBUG_TRACE("Check error page %s - not found",
  3898. path_buf);
  3899. /* Continue with the next file extension from the
  3900. * configuration (if there is a next one). */
  3901. tstr = strchr(tstr + i, '.');
  3902. }
  3903. }
  3904. }
  3905. if (page_handler_found) {
  3906. conn->in_error_handler = 1;
  3907. handle_file_based_request(conn, path_buf, &error_page_file);
  3908. conn->in_error_handler = 0;
  3909. return 0;
  3910. }
  3911. #endif /* NO_FILESYSTEMS */
  3912. }
  3913. /* No custom error page. Send default error page. */
  3914. conn->must_close = 1;
  3915. mg_response_header_start(conn, status);
  3916. send_no_cache_header(conn);
  3917. send_additional_header(conn);
  3918. send_cors_header(conn);
  3919. if (has_body) {
  3920. mg_response_header_add(conn,
  3921. "Content-Type",
  3922. "text/plain; charset=utf-8",
  3923. -1);
  3924. }
  3925. mg_response_header_send(conn);
  3926. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3927. if (has_body) {
  3928. /* For other errors, send a generic error message. */
  3929. const char *status_text = mg_get_response_code_text(conn, status);
  3930. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3931. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3932. } else {
  3933. /* No body allowed. Close the connection. */
  3934. DEBUG_TRACE("Error %i", status);
  3935. }
  3936. }
  3937. return 0;
  3938. }
  3939. CIVETWEB_API int
  3940. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3941. {
  3942. va_list ap;
  3943. int ret;
  3944. va_start(ap, fmt);
  3945. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3946. va_end(ap);
  3947. return ret;
  3948. }
  3949. CIVETWEB_API int
  3950. mg_send_http_ok(struct mg_connection *conn,
  3951. const char *mime_type,
  3952. long long content_length)
  3953. {
  3954. if ((mime_type == NULL) || (*mime_type == 0)) {
  3955. /* No content type defined: default to text/html */
  3956. mime_type = "text/html";
  3957. }
  3958. mg_response_header_start(conn, 200);
  3959. send_no_cache_header(conn);
  3960. send_additional_header(conn);
  3961. send_cors_header(conn);
  3962. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3963. if (content_length < 0) {
  3964. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3965. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3966. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3967. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3968. }
  3969. } else {
  3970. char len[32];
  3971. int trunc = 0;
  3972. mg_snprintf(conn,
  3973. &trunc,
  3974. len,
  3975. sizeof(len),
  3976. "%" UINT64_FMT,
  3977. (uint64_t)content_length);
  3978. if (!trunc) {
  3979. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3980. * !trunc is always true */
  3981. mg_response_header_add(conn, "Content-Length", len, -1);
  3982. }
  3983. }
  3984. mg_response_header_send(conn);
  3985. return 0;
  3986. }
  3987. CIVETWEB_API int
  3988. mg_send_http_redirect(struct mg_connection *conn,
  3989. const char *target_url,
  3990. int redirect_code)
  3991. {
  3992. /* Send a 30x redirect response.
  3993. *
  3994. * Redirect types (status codes):
  3995. *
  3996. * Status | Perm/Temp | Method | Version
  3997. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3998. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3999. * 303 | temporary | always use GET | HTTP/1.1
  4000. * 307 | temporary | always keep method | HTTP/1.1
  4001. * 308 | permanent | always keep method | HTTP/1.1
  4002. */
  4003. #if defined(MG_SEND_REDIRECT_BODY)
  4004. char redirect_body[MG_BUF_LEN];
  4005. size_t content_len = 0;
  4006. char content_len_text[32];
  4007. #endif
  4008. /* In case redirect_code=0, use 307. */
  4009. if (redirect_code == 0) {
  4010. redirect_code = 307;
  4011. }
  4012. /* In case redirect_code is none of the above, return error. */
  4013. if ((redirect_code != 301) && (redirect_code != 302)
  4014. && (redirect_code != 303) && (redirect_code != 307)
  4015. && (redirect_code != 308)) {
  4016. /* Parameter error */
  4017. return -2;
  4018. }
  4019. /* If target_url is not defined, redirect to "/". */
  4020. if ((target_url == NULL) || (*target_url == 0)) {
  4021. target_url = "/";
  4022. }
  4023. #if defined(MG_SEND_REDIRECT_BODY)
  4024. /* TODO: condition name? */
  4025. /* Prepare a response body with a hyperlink.
  4026. *
  4027. * According to RFC2616 (and RFC1945 before):
  4028. * Unless the request method was HEAD, the entity of the
  4029. * response SHOULD contain a short hypertext note with a hyperlink to
  4030. * the new URI(s).
  4031. *
  4032. * However, this response body is not useful in M2M communication.
  4033. * Probably the original reason in the RFC was, clients not supporting
  4034. * a 30x HTTP redirect could still show the HTML page and let the user
  4035. * press the link. Since current browsers support 30x HTTP, the additional
  4036. * HTML body does not seem to make sense anymore.
  4037. *
  4038. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4039. * but it only notes:
  4040. * The server's response payload usually contains a short
  4041. * hypertext note with a hyperlink to the new URI(s).
  4042. *
  4043. * Deactivated by default. If you need the 30x body, set the define.
  4044. */
  4045. mg_snprintf(
  4046. conn,
  4047. NULL /* ignore truncation */,
  4048. redirect_body,
  4049. sizeof(redirect_body),
  4050. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4051. redirect_text,
  4052. target_url,
  4053. target_url);
  4054. content_len = strlen(reply);
  4055. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4056. #endif
  4057. /* Send all required headers */
  4058. mg_response_header_start(conn, redirect_code);
  4059. mg_response_header_add(conn, "Location", target_url, -1);
  4060. if ((redirect_code == 301) || (redirect_code == 308)) {
  4061. /* Permanent redirect */
  4062. send_static_cache_header(conn);
  4063. } else {
  4064. /* Temporary redirect */
  4065. send_no_cache_header(conn);
  4066. }
  4067. send_additional_header(conn);
  4068. send_cors_header(conn);
  4069. #if defined(MG_SEND_REDIRECT_BODY)
  4070. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4071. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4072. #else
  4073. mg_response_header_add(conn, "Content-Length", "0", 1);
  4074. #endif
  4075. mg_response_header_send(conn);
  4076. #if defined(MG_SEND_REDIRECT_BODY)
  4077. /* Send response body */
  4078. /* ... unless it is a HEAD request */
  4079. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4080. ret = mg_write(conn, redirect_body, content_len);
  4081. }
  4082. #endif
  4083. return 1;
  4084. }
  4085. #if defined(_WIN32)
  4086. /* Create substitutes for POSIX functions in Win32. */
  4087. #if defined(GCC_DIAGNOSTIC)
  4088. /* Show no warning in case system functions are not used. */
  4089. #pragma GCC diagnostic push
  4090. #pragma GCC diagnostic ignored "-Wunused-function"
  4091. #endif
  4092. static int
  4093. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4094. {
  4095. (void)unused;
  4096. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4097. InitializeCriticalSection(&mutex->sec);
  4098. return 0;
  4099. }
  4100. static int
  4101. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4102. {
  4103. DeleteCriticalSection(&mutex->sec);
  4104. return 0;
  4105. }
  4106. static int
  4107. pthread_mutex_lock(pthread_mutex_t *mutex)
  4108. {
  4109. EnterCriticalSection(&mutex->sec);
  4110. return 0;
  4111. }
  4112. static int
  4113. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4114. {
  4115. LeaveCriticalSection(&mutex->sec);
  4116. return 0;
  4117. }
  4118. FUNCTION_MAY_BE_UNUSED
  4119. static int
  4120. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4121. {
  4122. (void)unused;
  4123. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4124. cv->waiting_thread = NULL;
  4125. return 0;
  4126. }
  4127. FUNCTION_MAY_BE_UNUSED
  4128. static int
  4129. pthread_cond_timedwait(pthread_cond_t *cv,
  4130. pthread_mutex_t *mutex,
  4131. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4132. {
  4133. struct mg_workerTLS **ptls,
  4134. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4135. int ok;
  4136. uint64_t nsnow, nswaitabs;
  4137. int64_t nswaitrel;
  4138. DWORD mswaitrel;
  4139. pthread_mutex_lock(&cv->threadIdSec);
  4140. /* Add this thread to cv's waiting list */
  4141. ptls = &cv->waiting_thread;
  4142. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4143. ;
  4144. tls->next_waiting_thread = NULL;
  4145. *ptls = tls;
  4146. pthread_mutex_unlock(&cv->threadIdSec);
  4147. if (abstime) {
  4148. nsnow = mg_get_current_time_ns();
  4149. nswaitabs =
  4150. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4151. nswaitrel = nswaitabs - nsnow;
  4152. if (nswaitrel < 0) {
  4153. nswaitrel = 0;
  4154. }
  4155. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4156. } else {
  4157. mswaitrel = (DWORD)INFINITE;
  4158. }
  4159. pthread_mutex_unlock(mutex);
  4160. ok = (WAIT_OBJECT_0
  4161. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4162. if (!ok) {
  4163. ok = 1;
  4164. pthread_mutex_lock(&cv->threadIdSec);
  4165. ptls = &cv->waiting_thread;
  4166. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4167. if (*ptls == tls) {
  4168. *ptls = tls->next_waiting_thread;
  4169. ok = 0;
  4170. break;
  4171. }
  4172. }
  4173. pthread_mutex_unlock(&cv->threadIdSec);
  4174. if (ok) {
  4175. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4176. (DWORD)INFINITE);
  4177. }
  4178. }
  4179. /* This thread has been removed from cv's waiting list */
  4180. pthread_mutex_lock(mutex);
  4181. return ok ? 0 : -1;
  4182. }
  4183. FUNCTION_MAY_BE_UNUSED
  4184. static int
  4185. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4186. {
  4187. return pthread_cond_timedwait(cv, mutex, NULL);
  4188. }
  4189. FUNCTION_MAY_BE_UNUSED
  4190. static int
  4191. pthread_cond_signal(pthread_cond_t *cv)
  4192. {
  4193. HANDLE wkup = NULL;
  4194. BOOL ok = FALSE;
  4195. pthread_mutex_lock(&cv->threadIdSec);
  4196. if (cv->waiting_thread) {
  4197. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4198. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4199. ok = SetEvent(wkup);
  4200. DEBUG_ASSERT(ok);
  4201. }
  4202. pthread_mutex_unlock(&cv->threadIdSec);
  4203. return ok ? 0 : 1;
  4204. }
  4205. FUNCTION_MAY_BE_UNUSED
  4206. static int
  4207. pthread_cond_broadcast(pthread_cond_t *cv)
  4208. {
  4209. pthread_mutex_lock(&cv->threadIdSec);
  4210. while (cv->waiting_thread) {
  4211. pthread_cond_signal(cv);
  4212. }
  4213. pthread_mutex_unlock(&cv->threadIdSec);
  4214. return 0;
  4215. }
  4216. FUNCTION_MAY_BE_UNUSED
  4217. static int
  4218. pthread_cond_destroy(pthread_cond_t *cv)
  4219. {
  4220. pthread_mutex_lock(&cv->threadIdSec);
  4221. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4222. pthread_mutex_unlock(&cv->threadIdSec);
  4223. pthread_mutex_destroy(&cv->threadIdSec);
  4224. return 0;
  4225. }
  4226. #if defined(ALTERNATIVE_QUEUE)
  4227. FUNCTION_MAY_BE_UNUSED
  4228. static void *
  4229. event_create(void)
  4230. {
  4231. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4232. }
  4233. FUNCTION_MAY_BE_UNUSED
  4234. static int
  4235. event_wait(void *eventhdl)
  4236. {
  4237. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4238. return (res == WAIT_OBJECT_0);
  4239. }
  4240. FUNCTION_MAY_BE_UNUSED
  4241. static int
  4242. event_signal(void *eventhdl)
  4243. {
  4244. return (int)SetEvent((HANDLE)eventhdl);
  4245. }
  4246. FUNCTION_MAY_BE_UNUSED
  4247. static void
  4248. event_destroy(void *eventhdl)
  4249. {
  4250. CloseHandle((HANDLE)eventhdl);
  4251. }
  4252. #endif
  4253. #if defined(GCC_DIAGNOSTIC)
  4254. /* Enable unused function warning again */
  4255. #pragma GCC diagnostic pop
  4256. #endif
  4257. /* For Windows, change all slashes to backslashes in path names. */
  4258. static void
  4259. change_slashes_to_backslashes(char *path)
  4260. {
  4261. int i;
  4262. for (i = 0; path[i] != '\0'; i++) {
  4263. if (path[i] == '/') {
  4264. path[i] = '\\';
  4265. }
  4266. /* remove double backslash (check i > 0 to preserve UNC paths,
  4267. * like \\server\file.txt) */
  4268. if ((i > 0) && (path[i] == '\\')) {
  4269. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4270. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4271. }
  4272. }
  4273. }
  4274. }
  4275. static int
  4276. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4277. {
  4278. int diff;
  4279. do {
  4280. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4281. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4282. s1++;
  4283. s2++;
  4284. } while ((diff == 0) && (s1[-1] != L'\0'));
  4285. return diff;
  4286. }
  4287. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4288. * wbuf and wbuf_len is a target buffer and its length. */
  4289. static void
  4290. path_to_unicode(const struct mg_connection *conn,
  4291. const char *path,
  4292. wchar_t *wbuf,
  4293. size_t wbuf_len)
  4294. {
  4295. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4296. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4297. DWORD long_len, err;
  4298. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4299. mg_strlcpy(buf, path, sizeof(buf));
  4300. change_slashes_to_backslashes(buf);
  4301. /* Convert to Unicode and back. If doubly-converted string does not
  4302. * match the original, something is fishy, reject. */
  4303. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4304. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4305. WideCharToMultiByte(
  4306. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4307. if (strcmp(buf, buf2) != 0) {
  4308. wbuf[0] = L'\0';
  4309. }
  4310. /* Windows file systems are not case sensitive, but you can still use
  4311. * uppercase and lowercase letters (on all modern file systems).
  4312. * The server can check if the URI uses the same upper/lowercase
  4313. * letters an the file system, effectively making Windows servers
  4314. * case sensitive (like Linux servers are). It is still not possible
  4315. * to use two files with the same name in different cases on Windows
  4316. * (like /a and /A) - this would be possible in Linux.
  4317. * As a default, Windows is not case sensitive, but the case sensitive
  4318. * file name check can be activated by an additional configuration. */
  4319. if (conn) {
  4320. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4321. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4322. "yes")) {
  4323. /* Use case sensitive compare function */
  4324. fcompare = wcscmp;
  4325. }
  4326. }
  4327. (void)conn; /* conn is currently unused */
  4328. /* Only accept a full file path, not a Windows short (8.3) path. */
  4329. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4330. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4331. if (long_len == 0) {
  4332. err = GetLastError();
  4333. if (err == ERROR_FILE_NOT_FOUND) {
  4334. /* File does not exist. This is not always a problem here. */
  4335. return;
  4336. }
  4337. }
  4338. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4339. /* Short name is used. */
  4340. wbuf[0] = L'\0';
  4341. }
  4342. }
  4343. #if !defined(NO_FILESYSTEMS)
  4344. /* Get file information, return 1 if file exists, 0 if not */
  4345. static int
  4346. mg_stat(const struct mg_connection *conn,
  4347. const char *path,
  4348. struct mg_file_stat *filep)
  4349. {
  4350. wchar_t wbuf[UTF16_PATH_MAX];
  4351. WIN32_FILE_ATTRIBUTE_DATA info;
  4352. time_t creation_time;
  4353. size_t len;
  4354. if (!filep) {
  4355. return 0;
  4356. }
  4357. memset(filep, 0, sizeof(*filep));
  4358. if (mg_path_suspicious(conn, path)) {
  4359. return 0;
  4360. }
  4361. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4362. /* Windows happily opens files with some garbage at the end of file name.
  4363. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4364. * "a.cgi", despite one would expect an error back. */
  4365. len = strlen(path);
  4366. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4367. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4368. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4369. filep->last_modified =
  4370. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4371. info.ftLastWriteTime.dwHighDateTime);
  4372. /* On Windows, the file creation time can be higher than the
  4373. * modification time, e.g. when a file is copied.
  4374. * Since the Last-Modified timestamp is used for caching
  4375. * it should be based on the most recent timestamp. */
  4376. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4377. info.ftCreationTime.dwHighDateTime);
  4378. if (creation_time > filep->last_modified) {
  4379. filep->last_modified = creation_time;
  4380. }
  4381. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4382. return 1;
  4383. }
  4384. return 0;
  4385. }
  4386. #endif
  4387. static int
  4388. mg_remove(const struct mg_connection *conn, const char *path)
  4389. {
  4390. wchar_t wbuf[UTF16_PATH_MAX];
  4391. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4392. return DeleteFileW(wbuf) ? 0 : -1;
  4393. }
  4394. static int
  4395. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4396. {
  4397. wchar_t wbuf[UTF16_PATH_MAX];
  4398. (void)mode;
  4399. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4400. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4401. }
  4402. /* Create substitutes for POSIX functions in Win32. */
  4403. #if defined(GCC_DIAGNOSTIC)
  4404. /* Show no warning in case system functions are not used. */
  4405. #pragma GCC diagnostic push
  4406. #pragma GCC diagnostic ignored "-Wunused-function"
  4407. #endif
  4408. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4409. FUNCTION_MAY_BE_UNUSED
  4410. static DIR *
  4411. mg_opendir(const struct mg_connection *conn, const char *name)
  4412. {
  4413. DIR *dir = NULL;
  4414. wchar_t wpath[UTF16_PATH_MAX];
  4415. DWORD attrs;
  4416. if (name == NULL) {
  4417. SetLastError(ERROR_BAD_ARGUMENTS);
  4418. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4419. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4420. } else {
  4421. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4422. attrs = GetFileAttributesW(wpath);
  4423. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4424. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4425. (void)wcscat(wpath, L"\\*");
  4426. dir->handle = FindFirstFileW(wpath, &dir->info);
  4427. dir->result.d_name[0] = '\0';
  4428. } else {
  4429. mg_free(dir);
  4430. dir = NULL;
  4431. }
  4432. }
  4433. return dir;
  4434. }
  4435. FUNCTION_MAY_BE_UNUSED
  4436. static int
  4437. mg_closedir(DIR *dir)
  4438. {
  4439. int result = 0;
  4440. if (dir != NULL) {
  4441. if (dir->handle != INVALID_HANDLE_VALUE)
  4442. result = FindClose(dir->handle) ? 0 : -1;
  4443. mg_free(dir);
  4444. } else {
  4445. result = -1;
  4446. SetLastError(ERROR_BAD_ARGUMENTS);
  4447. }
  4448. return result;
  4449. }
  4450. FUNCTION_MAY_BE_UNUSED
  4451. static struct dirent *
  4452. mg_readdir(DIR *dir)
  4453. {
  4454. struct dirent *result = 0;
  4455. if (dir) {
  4456. if (dir->handle != INVALID_HANDLE_VALUE) {
  4457. result = &dir->result;
  4458. (void)WideCharToMultiByte(CP_UTF8,
  4459. 0,
  4460. dir->info.cFileName,
  4461. -1,
  4462. result->d_name,
  4463. sizeof(result->d_name),
  4464. NULL,
  4465. NULL);
  4466. if (!FindNextFileW(dir->handle, &dir->info)) {
  4467. (void)FindClose(dir->handle);
  4468. dir->handle = INVALID_HANDLE_VALUE;
  4469. }
  4470. } else {
  4471. SetLastError(ERROR_FILE_NOT_FOUND);
  4472. }
  4473. } else {
  4474. SetLastError(ERROR_BAD_ARGUMENTS);
  4475. }
  4476. return result;
  4477. }
  4478. #if !defined(HAVE_POLL)
  4479. #undef POLLIN
  4480. #undef POLLPRI
  4481. #undef POLLOUT
  4482. #undef POLLERR
  4483. #define POLLIN (1) /* Data ready - read will not block. */
  4484. #define POLLPRI (2) /* Priority data ready. */
  4485. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4486. #define POLLERR (8) /* Error event */
  4487. FUNCTION_MAY_BE_UNUSED
  4488. static int
  4489. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4490. {
  4491. struct timeval tv;
  4492. fd_set rset;
  4493. fd_set wset;
  4494. fd_set eset;
  4495. unsigned int i;
  4496. int result;
  4497. SOCKET maxfd = 0;
  4498. memset(&tv, 0, sizeof(tv));
  4499. tv.tv_sec = milliseconds / 1000;
  4500. tv.tv_usec = (milliseconds % 1000) * 1000;
  4501. FD_ZERO(&rset);
  4502. FD_ZERO(&wset);
  4503. FD_ZERO(&eset);
  4504. for (i = 0; i < n; i++) {
  4505. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4506. if (pfd[i].events & POLLIN) {
  4507. FD_SET(pfd[i].fd, &rset);
  4508. }
  4509. if (pfd[i].events & POLLOUT) {
  4510. FD_SET(pfd[i].fd, &wset);
  4511. }
  4512. /* Check for errors for any FD in the set */
  4513. FD_SET(pfd[i].fd, &eset);
  4514. }
  4515. pfd[i].revents = 0;
  4516. if (pfd[i].fd > maxfd) {
  4517. maxfd = pfd[i].fd;
  4518. }
  4519. }
  4520. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4521. for (i = 0; i < n; i++) {
  4522. if (FD_ISSET(pfd[i].fd, &rset)) {
  4523. pfd[i].revents |= POLLIN;
  4524. }
  4525. if (FD_ISSET(pfd[i].fd, &wset)) {
  4526. pfd[i].revents |= POLLOUT;
  4527. }
  4528. if (FD_ISSET(pfd[i].fd, &eset)) {
  4529. pfd[i].revents |= POLLERR;
  4530. }
  4531. }
  4532. }
  4533. /* We should subtract the time used in select from remaining
  4534. * "milliseconds", in particular if called from mg_poll with a
  4535. * timeout quantum.
  4536. * Unfortunately, the remaining time is not stored in "tv" in all
  4537. * implementations, so the result in "tv" must be considered undefined.
  4538. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4539. return result;
  4540. }
  4541. #endif /* HAVE_POLL */
  4542. #if defined(GCC_DIAGNOSTIC)
  4543. /* Enable unused function warning again */
  4544. #pragma GCC diagnostic pop
  4545. #endif
  4546. static void
  4547. set_close_on_exec(SOCKET sock,
  4548. const struct mg_connection *conn /* may be null */,
  4549. struct mg_context *ctx /* may be null */)
  4550. {
  4551. (void)conn; /* Unused. */
  4552. (void)ctx;
  4553. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4554. }
  4555. CIVETWEB_API int
  4556. mg_start_thread(mg_thread_func_t f, void *p)
  4557. {
  4558. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4559. /* Compile-time option to control stack size, e.g.
  4560. * -DUSE_STACK_SIZE=16384
  4561. */
  4562. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4563. == ((uintptr_t)(-1L)))
  4564. ? -1
  4565. : 0);
  4566. #else
  4567. return (
  4568. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4569. ? -1
  4570. : 0);
  4571. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4572. }
  4573. /* Start a thread storing the thread context. */
  4574. static int
  4575. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4576. void *p,
  4577. pthread_t *threadidptr)
  4578. {
  4579. uintptr_t uip;
  4580. HANDLE threadhandle;
  4581. int result = -1;
  4582. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4583. threadhandle = (HANDLE)uip;
  4584. if ((uip != 0) && (threadidptr != NULL)) {
  4585. *threadidptr = threadhandle;
  4586. result = 0;
  4587. }
  4588. return result;
  4589. }
  4590. /* Wait for a thread to finish. */
  4591. static int
  4592. mg_join_thread(pthread_t threadid)
  4593. {
  4594. int result;
  4595. DWORD dwevent;
  4596. result = -1;
  4597. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4598. if (dwevent == WAIT_FAILED) {
  4599. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4600. } else {
  4601. if (dwevent == WAIT_OBJECT_0) {
  4602. CloseHandle(threadid);
  4603. result = 0;
  4604. }
  4605. }
  4606. return result;
  4607. }
  4608. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4609. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4610. /* Create substitutes for POSIX functions in Win32. */
  4611. #if defined(GCC_DIAGNOSTIC)
  4612. /* Show no warning in case system functions are not used. */
  4613. #pragma GCC diagnostic push
  4614. #pragma GCC diagnostic ignored "-Wunused-function"
  4615. #endif
  4616. FUNCTION_MAY_BE_UNUSED
  4617. static HANDLE
  4618. dlopen(const char *dll_name, int flags)
  4619. {
  4620. wchar_t wbuf[UTF16_PATH_MAX];
  4621. (void)flags;
  4622. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4623. return LoadLibraryW(wbuf);
  4624. }
  4625. FUNCTION_MAY_BE_UNUSED
  4626. static int
  4627. dlclose(void *handle)
  4628. {
  4629. int result;
  4630. if (FreeLibrary((HMODULE)handle) != 0) {
  4631. result = 0;
  4632. } else {
  4633. result = -1;
  4634. }
  4635. return result;
  4636. }
  4637. #if defined(GCC_DIAGNOSTIC)
  4638. /* Enable unused function warning again */
  4639. #pragma GCC diagnostic pop
  4640. #endif
  4641. #endif
  4642. #if !defined(NO_CGI)
  4643. #define SIGKILL (0)
  4644. static int
  4645. kill(pid_t pid, int sig_num)
  4646. {
  4647. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4648. (void)CloseHandle((HANDLE)pid);
  4649. return 0;
  4650. }
  4651. #if !defined(WNOHANG)
  4652. #define WNOHANG (1)
  4653. #endif
  4654. static pid_t
  4655. waitpid(pid_t pid, int *status, int flags)
  4656. {
  4657. DWORD timeout = INFINITE;
  4658. DWORD waitres;
  4659. (void)status; /* Currently not used by any client here */
  4660. if ((flags | WNOHANG) == WNOHANG) {
  4661. timeout = 0;
  4662. }
  4663. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4664. if (waitres == WAIT_OBJECT_0) {
  4665. return pid;
  4666. }
  4667. if (waitres == WAIT_TIMEOUT) {
  4668. return 0;
  4669. }
  4670. return (pid_t)-1;
  4671. }
  4672. static void
  4673. trim_trailing_whitespaces(char *s)
  4674. {
  4675. char *e = s + strlen(s);
  4676. while ((e > s) && isspace((unsigned char)e[-1])) {
  4677. *(--e) = '\0';
  4678. }
  4679. }
  4680. static pid_t
  4681. spawn_process(struct mg_connection *conn,
  4682. const char *prog,
  4683. char *envblk,
  4684. char *envp[],
  4685. int fdin[2],
  4686. int fdout[2],
  4687. int fderr[2],
  4688. const char *dir,
  4689. int cgi_config_idx)
  4690. {
  4691. HANDLE me;
  4692. char *interp;
  4693. char *interp_arg = 0;
  4694. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4695. int truncated;
  4696. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4697. STARTUPINFOA si;
  4698. PROCESS_INFORMATION pi = {0};
  4699. (void)envp;
  4700. memset(&si, 0, sizeof(si));
  4701. si.cb = sizeof(si);
  4702. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4703. si.wShowWindow = SW_HIDE;
  4704. me = GetCurrentProcess();
  4705. DuplicateHandle(me,
  4706. (HANDLE)_get_osfhandle(fdin[0]),
  4707. me,
  4708. &si.hStdInput,
  4709. 0,
  4710. TRUE,
  4711. DUPLICATE_SAME_ACCESS);
  4712. DuplicateHandle(me,
  4713. (HANDLE)_get_osfhandle(fdout[1]),
  4714. me,
  4715. &si.hStdOutput,
  4716. 0,
  4717. TRUE,
  4718. DUPLICATE_SAME_ACCESS);
  4719. DuplicateHandle(me,
  4720. (HANDLE)_get_osfhandle(fderr[1]),
  4721. me,
  4722. &si.hStdError,
  4723. 0,
  4724. TRUE,
  4725. DUPLICATE_SAME_ACCESS);
  4726. /* Mark handles that should not be inherited. See
  4727. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4728. */
  4729. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4730. HANDLE_FLAG_INHERIT,
  4731. 0);
  4732. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4733. HANDLE_FLAG_INHERIT,
  4734. 0);
  4735. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4736. HANDLE_FLAG_INHERIT,
  4737. 0);
  4738. /* First check, if there is a CGI interpreter configured for all CGI
  4739. * scripts. */
  4740. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4741. if (interp != NULL) {
  4742. /* If there is a configured interpreter, check for additional arguments
  4743. */
  4744. interp_arg =
  4745. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4746. } else {
  4747. /* Otherwise, the interpreter must be stated in the first line of the
  4748. * CGI script file, after a #! (shebang) mark. */
  4749. buf[0] = buf[1] = '\0';
  4750. /* Get the full script path */
  4751. mg_snprintf(
  4752. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4753. if (truncated) {
  4754. pi.hProcess = (pid_t)-1;
  4755. goto spawn_cleanup;
  4756. }
  4757. /* Open the script file, to read the first line */
  4758. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4759. /* Read the first line of the script into the buffer */
  4760. mg_fgets(buf, sizeof(buf), &file);
  4761. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4762. buf[sizeof(buf) - 1] = '\0';
  4763. }
  4764. if ((buf[0] == '#') && (buf[1] == '!')) {
  4765. trim_trailing_whitespaces(buf + 2);
  4766. } else {
  4767. buf[2] = '\0';
  4768. }
  4769. interp = buf + 2;
  4770. }
  4771. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4772. if (interp[0] != '\0') {
  4773. /* This is an interpreted script file. We must call the interpreter. */
  4774. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4775. mg_snprintf(conn,
  4776. &truncated,
  4777. cmdline,
  4778. sizeof(cmdline),
  4779. "\"%s\" %s \"%s\\%s\"",
  4780. interp,
  4781. interp_arg,
  4782. full_dir,
  4783. prog);
  4784. } else {
  4785. mg_snprintf(conn,
  4786. &truncated,
  4787. cmdline,
  4788. sizeof(cmdline),
  4789. "\"%s\" \"%s\\%s\"",
  4790. interp,
  4791. full_dir,
  4792. prog);
  4793. }
  4794. } else {
  4795. /* This is (probably) a compiled program. We call it directly. */
  4796. mg_snprintf(conn,
  4797. &truncated,
  4798. cmdline,
  4799. sizeof(cmdline),
  4800. "\"%s\\%s\"",
  4801. full_dir,
  4802. prog);
  4803. }
  4804. if (truncated) {
  4805. pi.hProcess = (pid_t)-1;
  4806. goto spawn_cleanup;
  4807. }
  4808. DEBUG_TRACE("Running [%s]", cmdline);
  4809. if (CreateProcessA(NULL,
  4810. cmdline,
  4811. NULL,
  4812. NULL,
  4813. TRUE,
  4814. CREATE_NEW_PROCESS_GROUP,
  4815. envblk,
  4816. NULL,
  4817. &si,
  4818. &pi)
  4819. == 0) {
  4820. mg_cry_internal(
  4821. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4822. pi.hProcess = (pid_t)-1;
  4823. /* goto spawn_cleanup; */
  4824. }
  4825. spawn_cleanup:
  4826. (void)CloseHandle(si.hStdOutput);
  4827. (void)CloseHandle(si.hStdError);
  4828. (void)CloseHandle(si.hStdInput);
  4829. if (pi.hThread != NULL) {
  4830. (void)CloseHandle(pi.hThread);
  4831. }
  4832. return (pid_t)pi.hProcess;
  4833. }
  4834. #endif /* !NO_CGI */
  4835. static int
  4836. set_blocking_mode(SOCKET sock)
  4837. {
  4838. unsigned long non_blocking = 0;
  4839. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4840. }
  4841. static int
  4842. set_non_blocking_mode(SOCKET sock)
  4843. {
  4844. unsigned long non_blocking = 1;
  4845. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4846. }
  4847. #else
  4848. #if !defined(NO_FILESYSTEMS)
  4849. static int
  4850. mg_stat(const struct mg_connection *conn,
  4851. const char *path,
  4852. struct mg_file_stat *filep)
  4853. {
  4854. struct stat st;
  4855. if (!filep) {
  4856. return 0;
  4857. }
  4858. memset(filep, 0, sizeof(*filep));
  4859. if (mg_path_suspicious(conn, path)) {
  4860. return 0;
  4861. }
  4862. if (0 == stat(path, &st)) {
  4863. filep->size = (uint64_t)(st.st_size);
  4864. filep->last_modified = st.st_mtime;
  4865. filep->is_directory = S_ISDIR(st.st_mode);
  4866. return 1;
  4867. }
  4868. return 0;
  4869. }
  4870. #endif /* NO_FILESYSTEMS */
  4871. static void
  4872. set_close_on_exec(int fd,
  4873. const struct mg_connection *conn /* may be null */,
  4874. struct mg_context *ctx /* may be null */)
  4875. {
  4876. #if defined(__ZEPHYR__)
  4877. (void)fd;
  4878. (void)conn;
  4879. (void)ctx;
  4880. #else
  4881. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4882. if (conn || ctx) {
  4883. struct mg_connection fc;
  4884. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4885. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4886. __func__,
  4887. strerror(ERRNO));
  4888. }
  4889. }
  4890. #endif
  4891. }
  4892. CIVETWEB_API int
  4893. mg_start_thread(mg_thread_func_t func, void *param)
  4894. {
  4895. pthread_t thread_id;
  4896. pthread_attr_t attr;
  4897. int result;
  4898. (void)pthread_attr_init(&attr);
  4899. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4900. #if defined(__ZEPHYR__)
  4901. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4902. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4903. /* Compile-time option to control stack size,
  4904. * e.g. -DUSE_STACK_SIZE=16384 */
  4905. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4906. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4907. result = pthread_create(&thread_id, &attr, func, param);
  4908. pthread_attr_destroy(&attr);
  4909. return result;
  4910. }
  4911. /* Start a thread storing the thread context. */
  4912. static int
  4913. mg_start_thread_with_id(mg_thread_func_t func,
  4914. void *param,
  4915. pthread_t *threadidptr)
  4916. {
  4917. pthread_t thread_id;
  4918. pthread_attr_t attr;
  4919. int result;
  4920. (void)pthread_attr_init(&attr);
  4921. #if defined(__ZEPHYR__)
  4922. pthread_attr_setstack(&attr,
  4923. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4924. ZEPHYR_STACK_SIZE);
  4925. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4926. /* Compile-time option to control stack size,
  4927. * e.g. -DUSE_STACK_SIZE=16384 */
  4928. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4929. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4930. result = pthread_create(&thread_id, &attr, func, param);
  4931. pthread_attr_destroy(&attr);
  4932. if ((result == 0) && (threadidptr != NULL)) {
  4933. *threadidptr = thread_id;
  4934. }
  4935. return result;
  4936. }
  4937. /* Wait for a thread to finish. */
  4938. static int
  4939. mg_join_thread(pthread_t threadid)
  4940. {
  4941. int result;
  4942. result = pthread_join(threadid, NULL);
  4943. return result;
  4944. }
  4945. #if !defined(NO_CGI)
  4946. static pid_t
  4947. spawn_process(struct mg_connection *conn,
  4948. const char *prog,
  4949. char *envblk,
  4950. char *envp[],
  4951. int fdin[2],
  4952. int fdout[2],
  4953. int fderr[2],
  4954. const char *dir,
  4955. int cgi_config_idx)
  4956. {
  4957. pid_t pid;
  4958. const char *interp;
  4959. (void)envblk;
  4960. if ((pid = fork()) == -1) {
  4961. /* Parent */
  4962. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4963. } else if (pid != 0) {
  4964. /* Make sure children close parent-side descriptors.
  4965. * The caller will close the child-side immediately. */
  4966. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4967. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4968. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4969. } else {
  4970. /* Child */
  4971. if (chdir(dir) != 0) {
  4972. mg_cry_internal(
  4973. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4974. } else if (dup2(fdin[0], 0) == -1) {
  4975. mg_cry_internal(conn,
  4976. "%s: dup2(%d, 0): %s",
  4977. __func__,
  4978. fdin[0],
  4979. strerror(ERRNO));
  4980. } else if (dup2(fdout[1], 1) == -1) {
  4981. mg_cry_internal(conn,
  4982. "%s: dup2(%d, 1): %s",
  4983. __func__,
  4984. fdout[1],
  4985. strerror(ERRNO));
  4986. } else if (dup2(fderr[1], 2) == -1) {
  4987. mg_cry_internal(conn,
  4988. "%s: dup2(%d, 2): %s",
  4989. __func__,
  4990. fderr[1],
  4991. strerror(ERRNO));
  4992. } else {
  4993. struct sigaction sa;
  4994. /* Keep stderr and stdout in two different pipes.
  4995. * Stdout will be sent back to the client,
  4996. * stderr should go into a server error log. */
  4997. (void)close(fdin[0]);
  4998. (void)close(fdout[1]);
  4999. (void)close(fderr[1]);
  5000. /* Close write end fdin and read end fdout and fderr */
  5001. (void)close(fdin[1]);
  5002. (void)close(fdout[0]);
  5003. (void)close(fderr[0]);
  5004. /* After exec, all signal handlers are restored to their default
  5005. * values, with one exception of SIGCHLD. According to
  5006. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5007. * will leave unchanged after exec if it was set to be ignored.
  5008. * Restore it to default action. */
  5009. memset(&sa, 0, sizeof(sa));
  5010. sa.sa_handler = SIG_DFL;
  5011. sigaction(SIGCHLD, &sa, NULL);
  5012. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  5013. if (interp == NULL) {
  5014. /* no interpreter configured, call the program directly */
  5015. (void)execle(prog, prog, NULL, envp);
  5016. mg_cry_internal(conn,
  5017. "%s: execle(%s): %s",
  5018. __func__,
  5019. prog,
  5020. strerror(ERRNO));
  5021. } else {
  5022. /* call the configured interpreter */
  5023. const char *interp_args =
  5024. conn->dom_ctx
  5025. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5026. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5027. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5028. } else {
  5029. (void)execle(interp, interp, prog, NULL, envp);
  5030. }
  5031. mg_cry_internal(conn,
  5032. "%s: execle(%s %s): %s",
  5033. __func__,
  5034. interp,
  5035. prog,
  5036. strerror(ERRNO));
  5037. }
  5038. }
  5039. exit(EXIT_FAILURE);
  5040. }
  5041. return pid;
  5042. }
  5043. #endif /* !NO_CGI */
  5044. static int
  5045. set_non_blocking_mode(SOCKET sock)
  5046. {
  5047. int flags = fcntl(sock, F_GETFL, 0);
  5048. if (flags < 0) {
  5049. return -1;
  5050. }
  5051. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5052. return -1;
  5053. }
  5054. return 0;
  5055. }
  5056. static int
  5057. set_blocking_mode(SOCKET sock)
  5058. {
  5059. int flags = fcntl(sock, F_GETFL, 0);
  5060. if (flags < 0) {
  5061. return -1;
  5062. }
  5063. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5064. return -1;
  5065. }
  5066. return 0;
  5067. }
  5068. #endif /* _WIN32 / else */
  5069. /* End of initial operating system specific define block. */
  5070. /* Get a random number (independent of C rand function) */
  5071. static uint64_t
  5072. get_random(void)
  5073. {
  5074. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5075. static uint64_t lcg = 0; /* Linear congruential generator */
  5076. uint64_t now = mg_get_current_time_ns();
  5077. if (lfsr == 0) {
  5078. /* lfsr will be only 0 if has not been initialized,
  5079. * so this code is called only once. */
  5080. lfsr = mg_get_current_time_ns();
  5081. lcg = mg_get_current_time_ns();
  5082. } else {
  5083. /* Get the next step of both random number generators. */
  5084. lfsr = (lfsr >> 1)
  5085. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5086. << 63);
  5087. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5088. }
  5089. /* Combining two pseudo-random number generators and a high resolution
  5090. * part
  5091. * of the current server time will make it hard (impossible?) to guess
  5092. * the
  5093. * next number. */
  5094. return (lfsr ^ lcg ^ now);
  5095. }
  5096. static int
  5097. mg_poll(struct mg_pollfd *pfd,
  5098. unsigned int n,
  5099. int milliseconds,
  5100. const stop_flag_t *stop_flag)
  5101. {
  5102. /* Call poll, but only for a maximum time of a few seconds.
  5103. * This will allow to stop the server after some seconds, instead
  5104. * of having to wait for a long socket timeout. */
  5105. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5106. int check_pollerr = 0;
  5107. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5108. /* If we wait for only one file descriptor, wait on error as well */
  5109. pfd[0].events |= POLLERR;
  5110. check_pollerr = 1;
  5111. }
  5112. do {
  5113. int result;
  5114. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5115. /* Shut down signal */
  5116. return -2;
  5117. }
  5118. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5119. ms_now = milliseconds;
  5120. }
  5121. result = poll(pfd, n, ms_now);
  5122. if (result != 0) {
  5123. int err = ERRNO;
  5124. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5125. /* Poll returned either success (1) or error (-1).
  5126. * Forward both to the caller. */
  5127. if ((check_pollerr)
  5128. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5129. == POLLERR)) {
  5130. /* One and only file descriptor returned error */
  5131. return -1;
  5132. }
  5133. return result;
  5134. }
  5135. }
  5136. /* Poll returned timeout (0). */
  5137. if (milliseconds > 0) {
  5138. milliseconds -= ms_now;
  5139. }
  5140. } while (milliseconds > 0);
  5141. /* timeout: return 0 */
  5142. return 0;
  5143. }
  5144. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5145. * descriptor.
  5146. * Return value:
  5147. * >=0 .. number of bytes successfully written
  5148. * -1 .. timeout
  5149. * -2 .. error
  5150. */
  5151. static int
  5152. push_inner(struct mg_context *ctx,
  5153. FILE *fp,
  5154. SOCKET sock,
  5155. SSL *ssl,
  5156. const char *buf,
  5157. int len,
  5158. double timeout)
  5159. {
  5160. uint64_t start = 0, now = 0, timeout_ns = 0;
  5161. int n, err;
  5162. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5163. #if defined(_WIN32)
  5164. typedef int len_t;
  5165. #else
  5166. typedef size_t len_t;
  5167. #endif
  5168. if (timeout > 0) {
  5169. now = mg_get_current_time_ns();
  5170. start = now;
  5171. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5172. }
  5173. if (ctx == NULL) {
  5174. return -2;
  5175. }
  5176. #if defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  5177. if (ssl) {
  5178. return -2;
  5179. }
  5180. #endif
  5181. /* Try to read until it succeeds, fails, times out, or the server
  5182. * shuts down. */
  5183. for (;;) {
  5184. #if defined(USE_MBEDTLS)
  5185. if (ssl != NULL) {
  5186. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5187. if (n <= 0) {
  5188. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5189. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5190. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5191. n = 0;
  5192. } else {
  5193. fprintf(stderr, "SSL write failed, error %d\n", n);
  5194. return -2;
  5195. }
  5196. } else {
  5197. err = 0;
  5198. }
  5199. } else
  5200. #elif defined(USE_GNUTLS)
  5201. if (ssl != NULL) {
  5202. n = gtls_ssl_write(ssl, (const unsigned char *)buf, (size_t) len);
  5203. if (n < 0) {
  5204. fprintf(stderr, "SSL write failed (%d): %s", n, gnutls_strerror(n));
  5205. return -2;
  5206. } else {
  5207. err = 0;
  5208. }
  5209. } else
  5210. #elif !defined(NO_SSL)
  5211. if (ssl != NULL) {
  5212. ERR_clear_error();
  5213. n = SSL_write(ssl, buf, len);
  5214. if (n <= 0) {
  5215. err = SSL_get_error(ssl, n);
  5216. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5217. err = ERRNO;
  5218. } else if ((err == SSL_ERROR_WANT_READ)
  5219. || (err == SSL_ERROR_WANT_WRITE)) {
  5220. n = 0;
  5221. } else {
  5222. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5223. ERR_clear_error();
  5224. return -2;
  5225. }
  5226. ERR_clear_error();
  5227. } else {
  5228. err = 0;
  5229. }
  5230. } else
  5231. #endif
  5232. if (fp != NULL) {
  5233. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5234. if (ferror(fp)) {
  5235. n = -1;
  5236. err = ERRNO;
  5237. } else {
  5238. err = 0;
  5239. }
  5240. } else {
  5241. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5242. err = (n < 0) ? ERRNO : 0;
  5243. if (ERROR_TRY_AGAIN(err)) {
  5244. err = 0;
  5245. n = 0;
  5246. }
  5247. if (n < 0) {
  5248. /* shutdown of the socket at client side */
  5249. return -2;
  5250. }
  5251. }
  5252. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5253. return -2;
  5254. }
  5255. if ((n > 0) || ((n == 0) && (len == 0))) {
  5256. /* some data has been read, or no data was requested */
  5257. return n;
  5258. }
  5259. if (n < 0) {
  5260. /* socket error - check errno */
  5261. DEBUG_TRACE("send() failed, error %d", err);
  5262. /* TODO (mid): error handling depending on the error code.
  5263. * These codes are different between Windows and Linux.
  5264. * Currently there is no problem with failing send calls,
  5265. * if there is a reproducible situation, it should be
  5266. * investigated in detail.
  5267. */
  5268. return -2;
  5269. }
  5270. /* Only in case n=0 (timeout), repeat calling the write function */
  5271. /* If send failed, wait before retry */
  5272. if (fp != NULL) {
  5273. /* For files, just wait a fixed time.
  5274. * Maybe it helps, maybe not. */
  5275. mg_sleep(5);
  5276. } else {
  5277. /* For sockets, wait for the socket using poll */
  5278. struct mg_pollfd pfd[2];
  5279. int pollres;
  5280. unsigned int num_sock = 1;
  5281. pfd[0].fd = sock;
  5282. pfd[0].events = POLLOUT;
  5283. if (ctx->context_type == CONTEXT_SERVER) {
  5284. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  5285. pfd[num_sock].events = POLLIN;
  5286. num_sock++;
  5287. }
  5288. pollres = mg_poll(pfd, num_sock, (int)(ms_wait), &(ctx->stop_flag));
  5289. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5290. return -2;
  5291. }
  5292. if (pollres > 0) {
  5293. continue;
  5294. }
  5295. }
  5296. if (timeout > 0) {
  5297. now = mg_get_current_time_ns();
  5298. if ((now - start) > timeout_ns) {
  5299. /* Timeout */
  5300. break;
  5301. }
  5302. }
  5303. }
  5304. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5305. used */
  5306. return -1;
  5307. }
  5308. static int
  5309. push_all(struct mg_context *ctx,
  5310. FILE *fp,
  5311. SOCKET sock,
  5312. SSL *ssl,
  5313. const char *buf,
  5314. int len)
  5315. {
  5316. double timeout = -1.0;
  5317. int n, nwritten = 0;
  5318. if (ctx == NULL) {
  5319. return -1;
  5320. }
  5321. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5322. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5323. }
  5324. if (timeout <= 0.0) {
  5325. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5326. / 1000.0;
  5327. }
  5328. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5329. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5330. if (n < 0) {
  5331. if (nwritten == 0) {
  5332. nwritten = -1; /* Propagate the error */
  5333. }
  5334. break;
  5335. } else if (n == 0) {
  5336. break; /* No more data to write */
  5337. } else {
  5338. nwritten += n;
  5339. len -= n;
  5340. }
  5341. }
  5342. return nwritten;
  5343. }
  5344. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5345. * Return value:
  5346. * >=0 .. number of bytes successfully read
  5347. * -1 .. timeout
  5348. * -2 .. error
  5349. */
  5350. static int
  5351. pull_inner(FILE *fp,
  5352. struct mg_connection *conn,
  5353. char *buf,
  5354. int len,
  5355. double timeout)
  5356. {
  5357. int nread, err = 0;
  5358. #if defined(_WIN32)
  5359. typedef int len_t;
  5360. #else
  5361. typedef size_t len_t;
  5362. #endif
  5363. /* We need an additional wait loop around this, because in some cases
  5364. * with TLSwe may get data from the socket but not from SSL_read.
  5365. * In this case we need to repeat at least once.
  5366. */
  5367. if (fp != NULL) {
  5368. /* Use read() instead of fread(), because if we're reading from the
  5369. * CGI pipe, fread() may block until IO buffer is filled up. We
  5370. * cannot afford to block and must pass all read bytes immediately
  5371. * to the client. */
  5372. nread = (int)read(fileno(fp), buf, (size_t)len);
  5373. err = (nread < 0) ? ERRNO : 0;
  5374. if ((nread == 0) && (len > 0)) {
  5375. /* Should get data, but got EOL */
  5376. return -2;
  5377. }
  5378. #if defined(USE_MBEDTLS)
  5379. } else if (conn->ssl != NULL) {
  5380. struct mg_pollfd pfd[2];
  5381. int to_read;
  5382. int pollres;
  5383. unsigned int num_sock = 1;
  5384. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5385. if (to_read > 0) {
  5386. /* We already know there is no more data buffered in conn->buf
  5387. * but there is more available in the SSL layer. So don't poll
  5388. * conn->client.sock yet. */
  5389. pollres = 1;
  5390. if (to_read > len)
  5391. to_read = len;
  5392. } else {
  5393. pfd[0].fd = conn->client.sock;
  5394. pfd[0].events = POLLIN;
  5395. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5396. pfd[num_sock].fd =
  5397. conn->phys_ctx->thread_shutdown_notification_socket;
  5398. pfd[num_sock].events = POLLIN;
  5399. num_sock++;
  5400. }
  5401. to_read = len;
  5402. pollres = mg_poll(pfd,
  5403. num_sock,
  5404. (int)(timeout * 1000.0),
  5405. &(conn->phys_ctx->stop_flag));
  5406. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5407. return -2;
  5408. }
  5409. }
  5410. if (pollres > 0) {
  5411. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5412. if (nread <= 0) {
  5413. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5414. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5415. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5416. nread = 0;
  5417. } else {
  5418. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5419. return -2;
  5420. }
  5421. } else {
  5422. err = 0;
  5423. }
  5424. } else if (pollres < 0) {
  5425. /* Error */
  5426. return -2;
  5427. } else {
  5428. /* pollres = 0 means timeout */
  5429. nread = 0;
  5430. }
  5431. #elif defined(USE_GNUTLS)
  5432. } else if (conn->ssl != NULL) {
  5433. struct mg_pollfd pfd[2];
  5434. size_t to_read;
  5435. int pollres;
  5436. unsigned int num_sock = 1;
  5437. to_read = gnutls_record_check_pending(conn->ssl->sess);
  5438. if (to_read > 0) {
  5439. /* We already know there is no more data buffered in conn->buf
  5440. * but there is more available in the SSL layer. So don't poll
  5441. * conn->client.sock yet. */
  5442. pollres = 1;
  5443. if (to_read > (size_t)len)
  5444. to_read = (size_t)len;
  5445. } else {
  5446. pfd[0].fd = conn->client.sock;
  5447. pfd[0].events = POLLIN;
  5448. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5449. pfd[num_sock].fd =
  5450. conn->phys_ctx->thread_shutdown_notification_socket;
  5451. pfd[num_sock].events = POLLIN;
  5452. num_sock++;
  5453. }
  5454. to_read = (size_t)len;
  5455. pollres = mg_poll(pfd,
  5456. num_sock,
  5457. (int)(timeout * 1000.0),
  5458. &(conn->phys_ctx->stop_flag));
  5459. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5460. return -2;
  5461. }
  5462. }
  5463. if (pollres > 0) {
  5464. nread = gtls_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5465. if (nread < 0) {
  5466. fprintf(stderr, "SSL read failed (%d): %s", nread, gnutls_strerror(nread));
  5467. return -2;
  5468. } else {
  5469. err = 0;
  5470. }
  5471. } else if (pollres < 0) {
  5472. /* Error */
  5473. return -2;
  5474. } else {
  5475. /* pollres = 0 means timeout */
  5476. nread = 0;
  5477. }
  5478. #elif !defined(NO_SSL)
  5479. } else if (conn->ssl != NULL) {
  5480. int ssl_pending;
  5481. struct mg_pollfd pfd[2];
  5482. int pollres;
  5483. unsigned int num_sock = 1;
  5484. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5485. /* We already know there is no more data buffered in conn->buf
  5486. * but there is more available in the SSL layer. So don't poll
  5487. * conn->client.sock yet. */
  5488. if (ssl_pending > len) {
  5489. ssl_pending = len;
  5490. }
  5491. pollres = 1;
  5492. } else {
  5493. pfd[0].fd = conn->client.sock;
  5494. pfd[0].events = POLLIN;
  5495. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5496. pfd[num_sock].fd =
  5497. conn->phys_ctx->thread_shutdown_notification_socket;
  5498. pfd[num_sock].events = POLLIN;
  5499. num_sock++;
  5500. }
  5501. pollres = mg_poll(pfd,
  5502. num_sock,
  5503. (int)(timeout * 1000.0),
  5504. &(conn->phys_ctx->stop_flag));
  5505. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5506. return -2;
  5507. }
  5508. }
  5509. if (pollres > 0) {
  5510. ERR_clear_error();
  5511. nread =
  5512. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5513. if (nread <= 0) {
  5514. err = SSL_get_error(conn->ssl, nread);
  5515. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5516. err = ERRNO;
  5517. } else if ((err == SSL_ERROR_WANT_READ)
  5518. || (err == SSL_ERROR_WANT_WRITE)) {
  5519. nread = 0;
  5520. } else {
  5521. /* All errors should return -2 */
  5522. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5523. ERR_clear_error();
  5524. return -2;
  5525. }
  5526. ERR_clear_error();
  5527. } else {
  5528. err = 0;
  5529. }
  5530. } else if (pollres < 0) {
  5531. /* Error */
  5532. return -2;
  5533. } else {
  5534. /* pollres = 0 means timeout */
  5535. nread = 0;
  5536. }
  5537. #endif
  5538. } else {
  5539. struct mg_pollfd pfd[2];
  5540. int pollres;
  5541. unsigned int num_sock = 1;
  5542. pfd[0].fd = conn->client.sock;
  5543. pfd[0].events = POLLIN;
  5544. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5545. pfd[num_sock].fd =
  5546. conn->phys_ctx->thread_shutdown_notification_socket;
  5547. pfd[num_sock].events = POLLIN;
  5548. num_sock++;
  5549. }
  5550. pollres = mg_poll(pfd,
  5551. num_sock,
  5552. (int)(timeout * 1000.0),
  5553. &(conn->phys_ctx->stop_flag));
  5554. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5555. return -2;
  5556. }
  5557. if (pollres > 0) {
  5558. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5559. err = (nread < 0) ? ERRNO : 0;
  5560. if (nread <= 0) {
  5561. /* shutdown of the socket at client side */
  5562. return -2;
  5563. }
  5564. } else if (pollres < 0) {
  5565. /* error calling poll */
  5566. return -2;
  5567. } else {
  5568. /* pollres = 0 means timeout */
  5569. nread = 0;
  5570. }
  5571. }
  5572. if (conn != NULL && !STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5573. return -2;
  5574. }
  5575. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5576. /* some data has been read, or no data was requested */
  5577. return nread;
  5578. }
  5579. if (nread < 0) {
  5580. /* socket error - check errno */
  5581. #if defined(_WIN32)
  5582. if (err == WSAEWOULDBLOCK) {
  5583. /* TODO (low): check if this is still required */
  5584. /* standard case if called from close_socket_gracefully */
  5585. return -2;
  5586. } else if (err == WSAETIMEDOUT) {
  5587. /* TODO (low): check if this is still required */
  5588. /* timeout is handled by the while loop */
  5589. return 0;
  5590. } else if (err == WSAECONNABORTED) {
  5591. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5592. return -2;
  5593. } else {
  5594. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5595. return -2;
  5596. }
  5597. #else
  5598. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5599. * if the timeout is reached and if the socket was set to non-
  5600. * blocking in close_socket_gracefully, so we can not distinguish
  5601. * here. We have to wait for the timeout in both cases for now.
  5602. */
  5603. if (ERROR_TRY_AGAIN(err)) {
  5604. /* TODO (low): check if this is still required */
  5605. /* EAGAIN/EWOULDBLOCK:
  5606. * standard case if called from close_socket_gracefully
  5607. * => should return -1 */
  5608. /* or timeout occurred
  5609. * => the code must stay in the while loop */
  5610. /* EINTR can be generated on a socket with a timeout set even
  5611. * when SA_RESTART is effective for all relevant signals
  5612. * (see signal(7)).
  5613. * => stay in the while loop */
  5614. } else {
  5615. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5616. return -2;
  5617. }
  5618. #endif
  5619. }
  5620. /* Timeout occurred, but no data available. */
  5621. return -1;
  5622. }
  5623. static int
  5624. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5625. {
  5626. int n, nread = 0;
  5627. double timeout = -1.0;
  5628. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5629. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5630. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5631. }
  5632. if (timeout <= 0.0) {
  5633. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5634. / 1000.0;
  5635. }
  5636. start_time = mg_get_current_time_ns();
  5637. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5638. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5639. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5640. if (n == -2) {
  5641. if (nread == 0) {
  5642. nread = -1; /* Propagate the error */
  5643. }
  5644. break;
  5645. } else if (n == -1) {
  5646. /* timeout */
  5647. if (timeout >= 0.0) {
  5648. now = mg_get_current_time_ns();
  5649. if ((now - start_time) <= timeout_ns) {
  5650. continue;
  5651. }
  5652. }
  5653. break;
  5654. } else if (n == 0) {
  5655. break; /* No more data to read */
  5656. } else {
  5657. nread += n;
  5658. len -= n;
  5659. }
  5660. }
  5661. return nread;
  5662. }
  5663. static void
  5664. discard_unread_request_data(struct mg_connection *conn)
  5665. {
  5666. char buf[MG_BUF_LEN];
  5667. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5668. ;
  5669. }
  5670. static int
  5671. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5672. {
  5673. int64_t content_len, n, buffered_len, nread;
  5674. int64_t len64 =
  5675. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5676. * int, we may not read more
  5677. * bytes */
  5678. const char *body;
  5679. if (conn == NULL) {
  5680. return 0;
  5681. }
  5682. /* If Content-Length is not set for a response with body data,
  5683. * we do not know in advance how much data should be read. */
  5684. content_len = conn->content_len;
  5685. if (content_len < 0) {
  5686. /* The body data is completed when the connection is closed. */
  5687. content_len = INT64_MAX;
  5688. }
  5689. nread = 0;
  5690. if (conn->consumed_content < content_len) {
  5691. /* Adjust number of bytes to read. */
  5692. int64_t left_to_read = content_len - conn->consumed_content;
  5693. if (left_to_read < len64) {
  5694. /* Do not read more than the total content length of the
  5695. * request.
  5696. */
  5697. len64 = left_to_read;
  5698. }
  5699. /* Return buffered data */
  5700. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5701. - conn->consumed_content;
  5702. if (buffered_len > 0) {
  5703. if (len64 < buffered_len) {
  5704. buffered_len = len64;
  5705. }
  5706. body = conn->buf + conn->request_len + conn->consumed_content;
  5707. memcpy(buf, body, (size_t)buffered_len);
  5708. len64 -= buffered_len;
  5709. conn->consumed_content += buffered_len;
  5710. nread += buffered_len;
  5711. buf = (char *)buf + buffered_len;
  5712. }
  5713. /* We have returned all buffered data. Read new data from the remote
  5714. * socket.
  5715. */
  5716. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5717. conn->consumed_content += n;
  5718. nread += n;
  5719. } else {
  5720. nread = ((nread > 0) ? nread : n);
  5721. }
  5722. }
  5723. return (int)nread;
  5724. }
  5725. /* Forward declarations */
  5726. static void handle_request(struct mg_connection *);
  5727. static void log_access(const struct mg_connection *);
  5728. /* Handle request, update statistics and call access log */
  5729. static void
  5730. handle_request_stat_log(struct mg_connection *conn)
  5731. {
  5732. #if defined(USE_SERVER_STATS)
  5733. struct timespec tnow;
  5734. conn->conn_state = 4; /* processing */
  5735. #endif
  5736. handle_request(conn);
  5737. #if defined(USE_SERVER_STATS)
  5738. conn->conn_state = 5; /* processed */
  5739. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5740. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5741. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5742. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5743. conn->num_bytes_sent);
  5744. #endif
  5745. DEBUG_TRACE("%s", "handle_request done");
  5746. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5747. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5748. DEBUG_TRACE("%s", "end_request callback done");
  5749. }
  5750. log_access(conn);
  5751. }
  5752. #if defined(USE_HTTP2)
  5753. #if defined(NO_SSL)
  5754. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5755. #endif
  5756. #define USE_ALPN
  5757. #include "http2.inl"
  5758. /* Not supported with HTTP/2 */
  5759. #define HTTP1_only \
  5760. { \
  5761. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5762. http2_must_use_http1(conn); \
  5763. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5764. return; \
  5765. } \
  5766. }
  5767. #else
  5768. #define HTTP1_only
  5769. #endif
  5770. CIVETWEB_API int
  5771. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5772. {
  5773. if (len > INT_MAX) {
  5774. len = INT_MAX;
  5775. }
  5776. if (conn == NULL) {
  5777. return 0;
  5778. }
  5779. if (conn->is_chunked) {
  5780. size_t all_read = 0;
  5781. while (len > 0) {
  5782. if (conn->is_chunked >= 3) {
  5783. /* No more data left to read */
  5784. return 0;
  5785. }
  5786. if (conn->is_chunked != 1) {
  5787. /* Has error */
  5788. return -1;
  5789. }
  5790. if (conn->consumed_content != conn->content_len) {
  5791. /* copy from the current chunk */
  5792. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5793. if (read_ret < 1) {
  5794. /* read error */
  5795. conn->is_chunked = 2;
  5796. return -1;
  5797. }
  5798. all_read += (size_t)read_ret;
  5799. len -= (size_t)read_ret;
  5800. if (conn->consumed_content == conn->content_len) {
  5801. /* Add data bytes in the current chunk have been read,
  5802. * so we are expecting \r\n now. */
  5803. char x[2];
  5804. conn->content_len += 2;
  5805. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5806. || (x[1] != '\n')) {
  5807. /* Protocol violation */
  5808. conn->is_chunked = 2;
  5809. return -1;
  5810. }
  5811. }
  5812. } else {
  5813. /* fetch a new chunk */
  5814. size_t i;
  5815. char lenbuf[64];
  5816. char *end = NULL;
  5817. unsigned long chunkSize = 0;
  5818. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5819. conn->content_len++;
  5820. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5821. lenbuf[i] = 0;
  5822. }
  5823. if ((i > 0) && (lenbuf[i] == ';')) {
  5824. // chunk extension --> skip chars until next CR
  5825. //
  5826. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5827. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5828. //
  5829. // chunk = chunk-size [ chunk-extension ] CRLF
  5830. // chunk-data CRLF
  5831. // ...
  5832. // chunk-extension= *( ";" chunk-ext-name [ "="
  5833. // chunk-ext-val ] )
  5834. do
  5835. ++conn->content_len;
  5836. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5837. && lenbuf[i] != '\r');
  5838. }
  5839. if ((i > 0) && (lenbuf[i] == '\r')
  5840. && (lenbuf[i - 1] != '\r')) {
  5841. continue;
  5842. }
  5843. if ((i > 1) && (lenbuf[i] == '\n')
  5844. && (lenbuf[i - 1] == '\r')) {
  5845. lenbuf[i + 1] = 0;
  5846. chunkSize = strtoul(lenbuf, &end, 16);
  5847. if (chunkSize == 0) {
  5848. /* regular end of content */
  5849. conn->is_chunked = 3;
  5850. }
  5851. break;
  5852. }
  5853. if (!isxdigit((unsigned char)lenbuf[i])) {
  5854. /* illegal character for chunk length */
  5855. conn->is_chunked = 2;
  5856. return -1;
  5857. }
  5858. }
  5859. if ((end == NULL) || (*end != '\r')) {
  5860. /* chunksize not set correctly */
  5861. conn->is_chunked = 2;
  5862. return -1;
  5863. }
  5864. if (conn->is_chunked == 3) {
  5865. /* try discarding trailer for keep-alive */
  5866. // We found the last chunk (length 0) including the
  5867. // CRLF that terminates that chunk. Now follows a possibly
  5868. // empty trailer and a final CRLF.
  5869. //
  5870. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5871. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5872. //
  5873. // Chunked-Body = *chunk
  5874. // last-chunk
  5875. // trailer
  5876. // CRLF
  5877. // ...
  5878. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5879. // ...
  5880. // trailer = *(entity-header CRLF)
  5881. int crlf_count = 2; // one CRLF already determined
  5882. while (crlf_count < 4 && conn->is_chunked == 3) {
  5883. ++conn->content_len;
  5884. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5885. if ((crlf_count == 0 || crlf_count == 2)) {
  5886. if (lenbuf[0] == '\r')
  5887. ++crlf_count;
  5888. else
  5889. crlf_count = 0;
  5890. } else {
  5891. // previous character was a CR
  5892. // --> next character must be LF
  5893. if (lenbuf[0] == '\n')
  5894. ++crlf_count;
  5895. else
  5896. conn->is_chunked = 2;
  5897. }
  5898. } else
  5899. // premature end of trailer
  5900. conn->is_chunked = 2;
  5901. }
  5902. if (conn->is_chunked == 2)
  5903. return -1;
  5904. else
  5905. conn->is_chunked = 4;
  5906. break;
  5907. }
  5908. /* append a new chunk */
  5909. conn->content_len += (int64_t)chunkSize;
  5910. }
  5911. }
  5912. return (int)all_read;
  5913. }
  5914. return mg_read_inner(conn, buf, len);
  5915. }
  5916. CIVETWEB_API int
  5917. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5918. {
  5919. time_t now;
  5920. int n, total, allowed;
  5921. if (conn == NULL) {
  5922. return 0;
  5923. }
  5924. if (len > INT_MAX) {
  5925. return -1;
  5926. }
  5927. /* Mark connection as "data sent" */
  5928. conn->request_state = 10;
  5929. #if defined(USE_HTTP2)
  5930. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5931. http2_data_frame_head(conn, len, 0);
  5932. }
  5933. #endif
  5934. if (conn->throttle > 0) {
  5935. if ((now = time(NULL)) != conn->last_throttle_time) {
  5936. conn->last_throttle_time = now;
  5937. conn->last_throttle_bytes = 0;
  5938. }
  5939. allowed = conn->throttle - conn->last_throttle_bytes;
  5940. if (allowed > (int)len) {
  5941. allowed = (int)len;
  5942. }
  5943. total = push_all(conn->phys_ctx,
  5944. NULL,
  5945. conn->client.sock,
  5946. conn->ssl,
  5947. (const char *)buf,
  5948. allowed);
  5949. if (total == allowed) {
  5950. buf = (const char *)buf + total;
  5951. conn->last_throttle_bytes += total;
  5952. while ((total < (int)len)
  5953. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5954. allowed = (conn->throttle > ((int)len - total))
  5955. ? (int)len - total
  5956. : conn->throttle;
  5957. n = push_all(conn->phys_ctx,
  5958. NULL,
  5959. conn->client.sock,
  5960. conn->ssl,
  5961. (const char *)buf,
  5962. allowed);
  5963. if (n != allowed) {
  5964. break;
  5965. }
  5966. sleep(1);
  5967. conn->last_throttle_bytes = allowed;
  5968. conn->last_throttle_time = time(NULL);
  5969. buf = (const char *)buf + n;
  5970. total += n;
  5971. }
  5972. }
  5973. } else {
  5974. total = push_all(conn->phys_ctx,
  5975. NULL,
  5976. conn->client.sock,
  5977. conn->ssl,
  5978. (const char *)buf,
  5979. (int)len);
  5980. }
  5981. if (total > 0) {
  5982. conn->num_bytes_sent += total;
  5983. }
  5984. return total;
  5985. }
  5986. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5987. CIVETWEB_API int
  5988. mg_send_chunk(struct mg_connection *conn,
  5989. const char *chunk,
  5990. unsigned int chunk_len)
  5991. {
  5992. char lenbuf[16];
  5993. size_t lenbuf_len;
  5994. int ret;
  5995. int t;
  5996. /* First store the length information in a text buffer. */
  5997. sprintf(lenbuf, "%x\r\n", chunk_len);
  5998. lenbuf_len = strlen(lenbuf);
  5999. /* Then send length information, chunk and terminating \r\n. */
  6000. ret = mg_write(conn, lenbuf, lenbuf_len);
  6001. if (ret != (int)lenbuf_len) {
  6002. return -1;
  6003. }
  6004. t = ret;
  6005. ret = mg_write(conn, chunk, chunk_len);
  6006. if (ret != (int)chunk_len) {
  6007. return -1;
  6008. }
  6009. t += ret;
  6010. ret = mg_write(conn, "\r\n", 2);
  6011. if (ret != 2) {
  6012. return -1;
  6013. }
  6014. t += ret;
  6015. return t;
  6016. }
  6017. #if defined(GCC_DIAGNOSTIC)
  6018. /* This block forwards format strings to printf implementations,
  6019. * so we need to disable the format-nonliteral warning. */
  6020. #pragma GCC diagnostic push
  6021. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6022. #endif
  6023. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6024. static int
  6025. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6026. {
  6027. va_list ap_copy;
  6028. size_t size = MG_BUF_LEN / 4;
  6029. int len = -1;
  6030. *buf = NULL;
  6031. while (len < 0) {
  6032. if (*buf) {
  6033. mg_free(*buf);
  6034. }
  6035. size *= 4;
  6036. *buf = (char *)mg_malloc(size);
  6037. if (!*buf) {
  6038. break;
  6039. }
  6040. va_copy(ap_copy, ap);
  6041. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6042. va_end(ap_copy);
  6043. (*buf)[size - 1] = 0;
  6044. }
  6045. return len;
  6046. }
  6047. /* Print message to buffer. If buffer is large enough to hold the message,
  6048. * return buffer. If buffer is to small, allocate large enough buffer on
  6049. * heap,
  6050. * and return allocated buffer. */
  6051. static int
  6052. alloc_vprintf(char **out_buf,
  6053. char *prealloc_buf,
  6054. size_t prealloc_size,
  6055. const char *fmt,
  6056. va_list ap)
  6057. {
  6058. va_list ap_copy;
  6059. int len;
  6060. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6061. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6062. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6063. * Therefore, we make two passes: on first pass, get required message
  6064. * length.
  6065. * On second pass, actually print the message. */
  6066. va_copy(ap_copy, ap);
  6067. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6068. va_end(ap_copy);
  6069. if (len < 0) {
  6070. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6071. * Switch to alternative code path that uses incremental
  6072. * allocations.
  6073. */
  6074. va_copy(ap_copy, ap);
  6075. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6076. va_end(ap_copy);
  6077. } else if ((size_t)(len) >= prealloc_size) {
  6078. /* The pre-allocated buffer not large enough. */
  6079. /* Allocate a new buffer. */
  6080. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6081. if (!*out_buf) {
  6082. /* Allocation failed. Return -1 as "out of memory" error. */
  6083. return -1;
  6084. }
  6085. /* Buffer allocation successful. Store the string there. */
  6086. va_copy(ap_copy, ap);
  6087. IGNORE_UNUSED_RESULT(
  6088. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6089. va_end(ap_copy);
  6090. } else {
  6091. /* The pre-allocated buffer is large enough.
  6092. * Use it to store the string and return the address. */
  6093. va_copy(ap_copy, ap);
  6094. IGNORE_UNUSED_RESULT(
  6095. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6096. va_end(ap_copy);
  6097. *out_buf = prealloc_buf;
  6098. }
  6099. return len;
  6100. }
  6101. static int
  6102. alloc_printf(char **out_buf, const char *fmt, ...)
  6103. {
  6104. va_list ap;
  6105. int result;
  6106. va_start(ap, fmt);
  6107. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6108. va_end(ap);
  6109. return result;
  6110. }
  6111. #if defined(GCC_DIAGNOSTIC)
  6112. /* Enable format-nonliteral warning again. */
  6113. #pragma GCC diagnostic pop
  6114. #endif
  6115. static int
  6116. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6117. {
  6118. char mem[MG_BUF_LEN];
  6119. char *buf = NULL;
  6120. int len;
  6121. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6122. len = mg_write(conn, buf, (size_t)len);
  6123. }
  6124. if (buf != mem) {
  6125. mg_free(buf);
  6126. }
  6127. return len;
  6128. }
  6129. CIVETWEB_API int
  6130. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6131. {
  6132. va_list ap;
  6133. int result;
  6134. va_start(ap, fmt);
  6135. result = mg_vprintf(conn, fmt, ap);
  6136. va_end(ap);
  6137. return result;
  6138. }
  6139. CIVETWEB_API int
  6140. mg_url_decode(const char *src,
  6141. int src_len,
  6142. char *dst,
  6143. int dst_len,
  6144. int is_form_url_encoded)
  6145. {
  6146. int i, j, a, b;
  6147. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6148. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6149. if ((i < src_len - 2) && (src[i] == '%')
  6150. && isxdigit((unsigned char)src[i + 1])
  6151. && isxdigit((unsigned char)src[i + 2])) {
  6152. a = tolower((unsigned char)src[i + 1]);
  6153. b = tolower((unsigned char)src[i + 2]);
  6154. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6155. i += 2;
  6156. } else if (is_form_url_encoded && (src[i] == '+')) {
  6157. dst[j] = ' ';
  6158. } else {
  6159. dst[j] = src[i];
  6160. }
  6161. }
  6162. dst[j] = '\0'; /* Null-terminate the destination */
  6163. return (i >= src_len) ? j : -1;
  6164. }
  6165. /* form url decoding of an entire string */
  6166. static void
  6167. url_decode_in_place(char *buf)
  6168. {
  6169. int len = (int)strlen(buf);
  6170. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6171. }
  6172. CIVETWEB_API int
  6173. mg_get_var(const char *data,
  6174. size_t data_len,
  6175. const char *name,
  6176. char *dst,
  6177. size_t dst_len)
  6178. {
  6179. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6180. }
  6181. CIVETWEB_API int
  6182. mg_get_var2(const char *data,
  6183. size_t data_len,
  6184. const char *name,
  6185. char *dst,
  6186. size_t dst_len,
  6187. size_t occurrence)
  6188. {
  6189. const char *p, *e, *s;
  6190. size_t name_len;
  6191. int len;
  6192. if ((dst == NULL) || (dst_len == 0)) {
  6193. len = -2;
  6194. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6195. len = -1;
  6196. dst[0] = '\0';
  6197. } else {
  6198. name_len = strlen(name);
  6199. e = data + data_len;
  6200. len = -1;
  6201. dst[0] = '\0';
  6202. /* data is "var1=val1&var2=val2...". Find variable first */
  6203. for (p = data; p + name_len < e; p++) {
  6204. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6205. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6206. /* Point p to variable value */
  6207. p += name_len + 1;
  6208. /* Point s to the end of the value */
  6209. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6210. if (s == NULL) {
  6211. s = e;
  6212. }
  6213. DEBUG_ASSERT(s >= p);
  6214. if (s < p) {
  6215. return -3;
  6216. }
  6217. /* Decode variable into destination buffer */
  6218. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6219. /* Redirect error code from -1 to -2 (destination buffer too
  6220. * small). */
  6221. if (len == -1) {
  6222. len = -2;
  6223. }
  6224. break;
  6225. }
  6226. }
  6227. }
  6228. return len;
  6229. }
  6230. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6231. CIVETWEB_API int
  6232. mg_split_form_urlencoded(char *data,
  6233. struct mg_header *form_fields,
  6234. unsigned num_form_fields)
  6235. {
  6236. char *b;
  6237. int i;
  6238. int num = 0;
  6239. if (data == NULL) {
  6240. /* parameter error */
  6241. return -1;
  6242. }
  6243. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6244. /* determine the number of expected fields */
  6245. if (data[0] == 0) {
  6246. return 0;
  6247. }
  6248. /* count number of & to return the number of key-value-pairs */
  6249. num = 1;
  6250. while (*data) {
  6251. if (*data == '&') {
  6252. num++;
  6253. }
  6254. data++;
  6255. }
  6256. return num;
  6257. }
  6258. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6259. /* parameter error */
  6260. return -1;
  6261. }
  6262. for (i = 0; i < (int)num_form_fields; i++) {
  6263. /* extract key-value pairs from input data */
  6264. while ((*data == ' ') || (*data == '\t')) {
  6265. /* skip initial spaces */
  6266. data++;
  6267. }
  6268. if (*data == 0) {
  6269. /* end of string reached */
  6270. break;
  6271. }
  6272. form_fields[num].name = data;
  6273. /* find & or = */
  6274. b = data;
  6275. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6276. b++;
  6277. }
  6278. if (*b == 0) {
  6279. /* last key without value */
  6280. form_fields[num].value = NULL;
  6281. } else if (*b == '&') {
  6282. /* mid key without value */
  6283. form_fields[num].value = NULL;
  6284. } else {
  6285. /* terminate string */
  6286. *b = 0;
  6287. /* value starts after '=' */
  6288. data = b + 1;
  6289. form_fields[num].value = data;
  6290. }
  6291. /* new field is stored */
  6292. num++;
  6293. /* find a next key */
  6294. b = strchr(data, '&');
  6295. if (b == 0) {
  6296. /* no more data */
  6297. break;
  6298. } else {
  6299. /* terminate value of last field at '&' */
  6300. *b = 0;
  6301. /* next key-value-pairs starts after '&' */
  6302. data = b + 1;
  6303. }
  6304. }
  6305. /* Decode all values */
  6306. for (i = 0; i < num; i++) {
  6307. if (form_fields[i].name) {
  6308. url_decode_in_place((char *)form_fields[i].name);
  6309. }
  6310. if (form_fields[i].value) {
  6311. url_decode_in_place((char *)form_fields[i].value);
  6312. }
  6313. }
  6314. /* return number of fields found */
  6315. return num;
  6316. }
  6317. /* HCP24: some changes to compare whole var_name */
  6318. CIVETWEB_API int
  6319. mg_get_cookie(const char *cookie_header,
  6320. const char *var_name,
  6321. char *dst,
  6322. size_t dst_size)
  6323. {
  6324. const char *s, *p, *end;
  6325. int name_len, len = -1;
  6326. if ((dst == NULL) || (dst_size == 0)) {
  6327. return -2;
  6328. }
  6329. dst[0] = '\0';
  6330. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6331. return -1;
  6332. }
  6333. name_len = (int)strlen(var_name);
  6334. end = s + strlen(s);
  6335. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6336. if (s[name_len] == '=') {
  6337. /* HCP24: now check is it a substring or a full cookie name */
  6338. if ((s == cookie_header) || (s[-1] == ' ')) {
  6339. s += name_len + 1;
  6340. if ((p = strchr(s, ' ')) == NULL) {
  6341. p = end;
  6342. }
  6343. if (p[-1] == ';') {
  6344. p--;
  6345. }
  6346. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6347. s++;
  6348. p--;
  6349. }
  6350. if ((size_t)(p - s) < dst_size) {
  6351. len = (int)(p - s);
  6352. mg_strlcpy(dst, s, (size_t)len + 1);
  6353. } else {
  6354. len = -3;
  6355. }
  6356. break;
  6357. }
  6358. }
  6359. }
  6360. return len;
  6361. }
  6362. CIVETWEB_API int
  6363. mg_base64_encode(const unsigned char *src,
  6364. size_t src_len,
  6365. char *dst,
  6366. size_t *dst_len)
  6367. {
  6368. static const char *b64 =
  6369. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6370. size_t i, j;
  6371. int a, b, c;
  6372. if (dst_len != NULL) {
  6373. /* Expected length including 0 termination: */
  6374. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6375. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6376. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6377. if (*dst_len < expected_len) {
  6378. if (*dst_len > 0) {
  6379. dst[0] = '\0';
  6380. }
  6381. *dst_len = expected_len;
  6382. return 0;
  6383. }
  6384. }
  6385. for (i = j = 0; i < src_len; i += 3) {
  6386. a = src[i];
  6387. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6388. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6389. dst[j++] = b64[a >> 2];
  6390. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6391. if (i + 1 < src_len) {
  6392. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6393. }
  6394. if (i + 2 < src_len) {
  6395. dst[j++] = b64[c & 63];
  6396. }
  6397. }
  6398. while (j % 4 != 0) {
  6399. dst[j++] = '=';
  6400. }
  6401. dst[j++] = '\0';
  6402. if (dst_len != NULL) {
  6403. *dst_len = (size_t)j;
  6404. }
  6405. /* Return -1 for "OK" */
  6406. return -1;
  6407. }
  6408. static unsigned char
  6409. b64reverse(char letter)
  6410. {
  6411. if ((letter >= 'A') && (letter <= 'Z')) {
  6412. return (unsigned char)(letter - 'A');
  6413. }
  6414. if ((letter >= 'a') && (letter <= 'z')) {
  6415. return (unsigned char)(letter - 'a' + 26);
  6416. }
  6417. if ((letter >= '0') && (letter <= '9')) {
  6418. return (unsigned char)(letter - '0' + 52);
  6419. }
  6420. if (letter == '+') {
  6421. return 62;
  6422. }
  6423. if (letter == '/') {
  6424. return 63;
  6425. }
  6426. if (letter == '=') {
  6427. return 255; /* normal end */
  6428. }
  6429. return 254; /* error */
  6430. }
  6431. CIVETWEB_API int
  6432. mg_base64_decode(const char *src,
  6433. size_t src_len,
  6434. unsigned char *dst,
  6435. size_t *dst_len)
  6436. {
  6437. size_t i;
  6438. unsigned char a, b, c, d;
  6439. size_t dst_len_limit = (size_t)-1;
  6440. size_t dst_len_used = 0;
  6441. if (dst_len != NULL) {
  6442. dst_len_limit = *dst_len;
  6443. *dst_len = 0;
  6444. }
  6445. for (i = 0; i < src_len; i += 4) {
  6446. /* Read 4 characters from BASE64 string */
  6447. a = b64reverse(src[i]);
  6448. if (a >= 254) {
  6449. return (int)i;
  6450. }
  6451. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6452. if (b >= 254) {
  6453. return (int)i + 1;
  6454. }
  6455. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6456. if (c == 254) {
  6457. return (int)i + 2;
  6458. }
  6459. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6460. if (d == 254) {
  6461. return (int)i + 3;
  6462. }
  6463. /* Add first (of 3) decoded character */
  6464. if (dst_len_used < dst_len_limit) {
  6465. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6466. + (unsigned char)(b >> 4));
  6467. }
  6468. dst_len_used++;
  6469. if (c != 255) {
  6470. if (dst_len_used < dst_len_limit) {
  6471. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6472. + (unsigned char)(c >> 2));
  6473. }
  6474. dst_len_used++;
  6475. if (d != 255) {
  6476. if (dst_len_used < dst_len_limit) {
  6477. dst[dst_len_used] =
  6478. (unsigned char)((unsigned char)(c << 6) + d);
  6479. }
  6480. dst_len_used++;
  6481. }
  6482. }
  6483. }
  6484. /* Add terminating zero */
  6485. if (dst_len_used < dst_len_limit) {
  6486. dst[dst_len_used] = '\0';
  6487. }
  6488. dst_len_used++;
  6489. if (dst_len != NULL) {
  6490. *dst_len = dst_len_used;
  6491. }
  6492. if (dst_len_used > dst_len_limit) {
  6493. /* Out of memory */
  6494. return 0;
  6495. }
  6496. /* Return -1 for "OK" */
  6497. return -1;
  6498. }
  6499. static int
  6500. is_put_or_delete_method(const struct mg_connection *conn)
  6501. {
  6502. if (conn) {
  6503. const char *s = conn->request_info.request_method;
  6504. if (s != NULL) {
  6505. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6506. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6507. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6508. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6509. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6510. || !strcmp(s, "COPY"));
  6511. }
  6512. }
  6513. return 0;
  6514. }
  6515. static int
  6516. is_civetweb_webdav_method(const struct mg_connection *conn)
  6517. {
  6518. /* Note: Here we only have to identify the WebDav methods that need special
  6519. * handling in the CivetWeb code - not all methods used in WebDav. In
  6520. * particular, methods used on directories (when using Windows Explorer as
  6521. * WebDav client).
  6522. */
  6523. if (conn) {
  6524. const char *s = conn->request_info.request_method;
  6525. if (s != NULL) {
  6526. /* These are the civetweb builtin DAV methods */
  6527. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6528. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6529. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6530. }
  6531. }
  6532. return 0;
  6533. }
  6534. #if !defined(NO_FILES)
  6535. static int
  6536. extention_matches_script(
  6537. struct mg_connection *conn, /* in: request (must be valid) */
  6538. const char *filename /* in: filename (must be valid) */
  6539. )
  6540. {
  6541. #if !defined(NO_CGI)
  6542. int cgi_config_idx, inc, max;
  6543. #endif
  6544. #if defined(USE_LUA)
  6545. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6546. filename)
  6547. > 0) {
  6548. return 1;
  6549. }
  6550. #endif
  6551. #if defined(USE_DUKTAPE)
  6552. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6553. filename)
  6554. > 0) {
  6555. return 1;
  6556. }
  6557. #endif
  6558. #if !defined(NO_CGI)
  6559. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6560. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6561. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6562. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6563. && (match_prefix_strlen(
  6564. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6565. filename)
  6566. > 0)) {
  6567. return 1;
  6568. }
  6569. }
  6570. #endif
  6571. /* filename and conn could be unused, if all preocessor conditions
  6572. * are false (no script language supported). */
  6573. (void)filename;
  6574. (void)conn;
  6575. return 0;
  6576. }
  6577. static int
  6578. extention_matches_template_text(
  6579. struct mg_connection *conn, /* in: request (must be valid) */
  6580. const char *filename /* in: filename (must be valid) */
  6581. )
  6582. {
  6583. #if defined(USE_LUA)
  6584. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6585. filename)
  6586. > 0) {
  6587. return 1;
  6588. }
  6589. #endif
  6590. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6591. > 0) {
  6592. return 1;
  6593. }
  6594. return 0;
  6595. }
  6596. /* For given directory path, substitute it to valid index file.
  6597. * Return 1 if index file has been found, 0 if not found.
  6598. * If the file is found, it's stats is returned in stp. */
  6599. static int
  6600. substitute_index_file_aux(struct mg_connection *conn,
  6601. char *path,
  6602. size_t path_len,
  6603. struct mg_file_stat *filestat)
  6604. {
  6605. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6606. struct vec filename_vec;
  6607. size_t n = strlen(path);
  6608. int found = 0;
  6609. /* The 'path' given to us points to the directory. Remove all trailing
  6610. * directory separator characters from the end of the path, and
  6611. * then append single directory separator character. */
  6612. while ((n > 0) && (path[n - 1] == '/')) {
  6613. n--;
  6614. }
  6615. path[n] = '/';
  6616. /* Traverse index files list. For each entry, append it to the given
  6617. * path and see if the file exists. If it exists, break the loop */
  6618. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6619. /* Ignore too long entries that may overflow path buffer */
  6620. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6621. continue;
  6622. }
  6623. /* Prepare full path to the index file */
  6624. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6625. /* Does it exist? */
  6626. if (mg_stat(conn, path, filestat)) {
  6627. /* Yes it does, break the loop */
  6628. found = 1;
  6629. break;
  6630. }
  6631. }
  6632. /* If no index file exists, restore directory path */
  6633. if (!found) {
  6634. path[n] = '\0';
  6635. }
  6636. return found;
  6637. }
  6638. /* Same as above, except if the first try fails and a fallback-root is
  6639. * configured, we'll try there also */
  6640. static int
  6641. substitute_index_file(struct mg_connection *conn,
  6642. char *path,
  6643. size_t path_len,
  6644. struct mg_file_stat *filestat)
  6645. {
  6646. int ret = substitute_index_file_aux(conn, path, path_len, filestat);
  6647. if (ret == 0) {
  6648. const char *root_prefix = conn->dom_ctx->config[DOCUMENT_ROOT];
  6649. const char *fallback_root_prefix =
  6650. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT];
  6651. if ((root_prefix) && (fallback_root_prefix)) {
  6652. const size_t root_prefix_len = strlen(root_prefix);
  6653. if ((strncmp(path, root_prefix, root_prefix_len) == 0)) {
  6654. char scratch_path[UTF8_PATH_MAX]; /* separate storage, to avoid
  6655. side effects if we fail */
  6656. size_t sub_path_len;
  6657. const size_t fallback_root_prefix_len =
  6658. strlen(fallback_root_prefix);
  6659. const char *sub_path = path + root_prefix_len;
  6660. while (*sub_path == '/') {
  6661. sub_path++;
  6662. }
  6663. sub_path_len = strlen(sub_path);
  6664. if (((fallback_root_prefix_len + 1 + sub_path_len + 1)
  6665. < sizeof(scratch_path))) {
  6666. /* The concatenations below are all safe because we
  6667. * pre-verified string lengths above */
  6668. char *nul;
  6669. strcpy(scratch_path, fallback_root_prefix);
  6670. nul = strchr(scratch_path, '\0');
  6671. if ((nul > scratch_path) && (*(nul - 1) != '/')) {
  6672. *nul++ = '/';
  6673. *nul = '\0';
  6674. }
  6675. strcat(scratch_path, sub_path);
  6676. if (substitute_index_file_aux(conn,
  6677. scratch_path,
  6678. sizeof(scratch_path),
  6679. filestat)) {
  6680. mg_strlcpy(path, scratch_path, path_len);
  6681. return 1;
  6682. }
  6683. }
  6684. }
  6685. }
  6686. }
  6687. return ret;
  6688. }
  6689. #endif
  6690. static void
  6691. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6692. char *filename, /* out: filename */
  6693. size_t filename_buf_len, /* in: size of filename buffer */
  6694. struct mg_file_stat *filestat, /* out: file status structure */
  6695. int *is_found, /* out: file found (directly) */
  6696. int *is_script_resource, /* out: handled by a script? */
  6697. int *is_websocket_request, /* out: websocket connection? */
  6698. int *is_put_or_delete_request, /* out: put/delete a file? */
  6699. int *is_webdav_request, /* out: webdav request? */
  6700. int *is_template_text /* out: SSI file or LSP file? */
  6701. )
  6702. {
  6703. char const *accept_encoding;
  6704. #if !defined(NO_FILES)
  6705. const char *uri = conn->request_info.local_uri;
  6706. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT],
  6707. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT],
  6708. NULL};
  6709. int fileExists = 0;
  6710. const char *rewrite;
  6711. struct vec a, b;
  6712. ptrdiff_t match_len;
  6713. char gz_path[UTF8_PATH_MAX];
  6714. int truncated;
  6715. int i;
  6716. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6717. char *tmp_str;
  6718. size_t tmp_str_len, sep_pos;
  6719. int allow_substitute_script_subresources;
  6720. #endif
  6721. #else
  6722. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6723. #endif
  6724. /* Step 1: Set all initially unknown outputs to zero */
  6725. memset(filestat, 0, sizeof(*filestat));
  6726. *filename = 0;
  6727. *is_found = 0;
  6728. *is_script_resource = 0;
  6729. *is_template_text = 0;
  6730. /* Step 2: Classify the request method */
  6731. /* Step 2a: Check if the request attempts to modify the file system */
  6732. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6733. /* Step 2b: Check if the request uses WebDav method that requires special
  6734. * handling */
  6735. *is_webdav_request = is_civetweb_webdav_method(conn);
  6736. /* Step 3: Check if it is a websocket request, and modify the document
  6737. * root if required */
  6738. #if defined(USE_WEBSOCKET)
  6739. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6740. #if !defined(NO_FILES)
  6741. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6742. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6743. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6744. }
  6745. #endif /* !NO_FILES */
  6746. #else /* USE_WEBSOCKET */
  6747. *is_websocket_request = 0;
  6748. #endif /* USE_WEBSOCKET */
  6749. /* Step 4: Check if gzip encoded response is allowed */
  6750. conn->accept_gzip = 0;
  6751. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6752. if (strstr(accept_encoding, "gzip") != NULL) {
  6753. conn->accept_gzip = 1;
  6754. }
  6755. }
  6756. #if !defined(NO_FILES)
  6757. /* Step 5: If there is no root directory, don't look for files. */
  6758. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6759. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6760. * config is not required. */
  6761. if (roots[0] == NULL) {
  6762. /* all file related outputs have already been set to 0, just return
  6763. */
  6764. return;
  6765. }
  6766. for (i = 0; roots[i] != NULL; i++) {
  6767. /* Step 6: Determine the local file path from the root path and the
  6768. * request uri. */
  6769. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6770. * part of the path one byte on the right. */
  6771. truncated = 0;
  6772. mg_snprintf(conn,
  6773. &truncated,
  6774. filename,
  6775. filename_buf_len - 1,
  6776. "%s%s",
  6777. roots[i],
  6778. uri);
  6779. if (truncated) {
  6780. goto interpret_cleanup;
  6781. }
  6782. /* Step 7: URI rewriting */
  6783. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6784. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6785. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6786. mg_snprintf(conn,
  6787. &truncated,
  6788. filename,
  6789. filename_buf_len - 1,
  6790. "%.*s%s",
  6791. (int)b.len,
  6792. b.ptr,
  6793. uri + match_len);
  6794. break;
  6795. }
  6796. }
  6797. if (truncated) {
  6798. goto interpret_cleanup;
  6799. }
  6800. /* Step 8: Check if the file exists at the server */
  6801. /* Local file path and name, corresponding to requested URI
  6802. * is now stored in "filename" variable. */
  6803. if (mg_stat(conn, filename, filestat)) {
  6804. fileExists = 1;
  6805. break;
  6806. }
  6807. }
  6808. if (fileExists) {
  6809. int uri_len = (int)strlen(uri);
  6810. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6811. /* 8.1: File exists. */
  6812. *is_found = 1;
  6813. /* 8.2: Check if it is a script type. */
  6814. if (extention_matches_script(conn, filename)) {
  6815. /* The request addresses a CGI resource, Lua script or
  6816. * server-side javascript.
  6817. * The URI corresponds to the script itself (like
  6818. * /path/script.cgi), and there is no additional resource
  6819. * path (like /path/script.cgi/something).
  6820. * Requests that modify (replace or delete) a resource, like
  6821. * PUT and DELETE requests, should replace/delete the script
  6822. * file.
  6823. * Requests that read or write from/to a resource, like GET and
  6824. * POST requests, should call the script and return the
  6825. * generated response. */
  6826. *is_script_resource = (!*is_put_or_delete_request);
  6827. }
  6828. /* 8.3: Check for SSI and LSP files */
  6829. if (extention_matches_template_text(conn, filename)) {
  6830. /* Same as above, but for *.lsp and *.shtml files. */
  6831. /* A "template text" is a file delivered directly to the client,
  6832. * but with some text tags replaced by dynamic content.
  6833. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6834. * (LP, LSP) file. */
  6835. *is_template_text = (!*is_put_or_delete_request);
  6836. }
  6837. /* 8.4: If the request target is a directory, there could be
  6838. * a substitute file (index.html, index.cgi, ...). */
  6839. /* But do not substitute a directory for a WebDav request */
  6840. if (filestat->is_directory && is_uri_end_slash
  6841. && (!*is_webdav_request)) {
  6842. /* Use a local copy here, since substitute_index_file will
  6843. * change the content of the file status */
  6844. struct mg_file_stat tmp_filestat;
  6845. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6846. if (substitute_index_file(
  6847. conn, filename, filename_buf_len, &tmp_filestat)) {
  6848. /* Substitute file found. Copy stat to the output, then
  6849. * check if the file is a script file */
  6850. *filestat = tmp_filestat;
  6851. if (extention_matches_script(conn, filename)) {
  6852. /* Substitute file is a script file */
  6853. *is_script_resource = 1;
  6854. } else if (extention_matches_template_text(conn, filename)) {
  6855. /* Substitute file is a LSP or SSI file */
  6856. *is_template_text = 1;
  6857. } else {
  6858. /* Substitute file is a regular file */
  6859. *is_script_resource = 0;
  6860. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6861. }
  6862. }
  6863. /* If there is no substitute file, the server could return
  6864. * a directory listing in a later step */
  6865. }
  6866. return;
  6867. }
  6868. /* Step 9: Check for zipped files: */
  6869. /* If we can't find the actual file, look for the file
  6870. * with the same name but a .gz extension. If we find it,
  6871. * use that and set the gzipped flag in the file struct
  6872. * to indicate that the response need to have the content-
  6873. * encoding: gzip header.
  6874. * We can only do this if the browser declares support. */
  6875. if (conn->accept_gzip) {
  6876. mg_snprintf(
  6877. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6878. if (truncated) {
  6879. goto interpret_cleanup;
  6880. }
  6881. if (mg_stat(conn, gz_path, filestat)) {
  6882. if (filestat) {
  6883. filestat->is_gzipped = 1;
  6884. *is_found = 1;
  6885. }
  6886. /* Currently gz files can not be scripts. */
  6887. return;
  6888. }
  6889. }
  6890. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6891. /* Step 10: Script resources may handle sub-resources */
  6892. /* Support PATH_INFO for CGI scripts. */
  6893. tmp_str_len = strlen(filename);
  6894. tmp_str =
  6895. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6896. if (!tmp_str) {
  6897. /* Out of memory */
  6898. goto interpret_cleanup;
  6899. }
  6900. memcpy(tmp_str, filename, tmp_str_len + 1);
  6901. /* Check config, if index scripts may have sub-resources */
  6902. allow_substitute_script_subresources =
  6903. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6904. "yes");
  6905. if (*is_webdav_request) {
  6906. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6907. * PROPFIND for their subresources? */
  6908. /* allow_substitute_script_subresources = 0; */
  6909. }
  6910. sep_pos = tmp_str_len;
  6911. while (sep_pos > 0) {
  6912. sep_pos--;
  6913. if (tmp_str[sep_pos] == '/') {
  6914. int is_script = 0, does_exist = 0;
  6915. tmp_str[sep_pos] = 0;
  6916. if (tmp_str[0]) {
  6917. is_script = extention_matches_script(conn, tmp_str);
  6918. does_exist = mg_stat(conn, tmp_str, filestat);
  6919. }
  6920. if (does_exist && is_script) {
  6921. filename[sep_pos] = 0;
  6922. memmove(filename + sep_pos + 2,
  6923. filename + sep_pos + 1,
  6924. strlen(filename + sep_pos + 1) + 1);
  6925. conn->path_info = filename + sep_pos + 1;
  6926. filename[sep_pos + 1] = '/';
  6927. *is_script_resource = 1;
  6928. *is_found = 1;
  6929. break;
  6930. }
  6931. if (allow_substitute_script_subresources) {
  6932. if (substitute_index_file(
  6933. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6934. /* some intermediate directory has an index file */
  6935. if (extention_matches_script(conn, tmp_str)) {
  6936. size_t script_name_len = strlen(tmp_str);
  6937. /* subres_name read before this memory locatio will be
  6938. overwritten */
  6939. char *subres_name = filename + sep_pos;
  6940. size_t subres_name_len = strlen(subres_name);
  6941. DEBUG_TRACE("Substitute script %s serving path %s",
  6942. tmp_str,
  6943. filename);
  6944. /* this index file is a script */
  6945. if ((script_name_len + subres_name_len + 2)
  6946. >= filename_buf_len) {
  6947. mg_free(tmp_str);
  6948. goto interpret_cleanup;
  6949. }
  6950. conn->path_info =
  6951. filename + script_name_len + 1; /* new target */
  6952. memmove(conn->path_info, subres_name, subres_name_len);
  6953. conn->path_info[subres_name_len] = 0;
  6954. memcpy(filename, tmp_str, script_name_len + 1);
  6955. *is_script_resource = 1;
  6956. *is_found = 1;
  6957. break;
  6958. } else {
  6959. DEBUG_TRACE("Substitute file %s serving path %s",
  6960. tmp_str,
  6961. filename);
  6962. /* non-script files will not have sub-resources */
  6963. filename[sep_pos] = 0;
  6964. conn->path_info = 0;
  6965. *is_script_resource = 0;
  6966. *is_found = 0;
  6967. break;
  6968. }
  6969. }
  6970. }
  6971. tmp_str[sep_pos] = '/';
  6972. }
  6973. }
  6974. mg_free(tmp_str);
  6975. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6976. #endif /* !defined(NO_FILES) */
  6977. return;
  6978. #if !defined(NO_FILES)
  6979. /* Reset all outputs */
  6980. interpret_cleanup:
  6981. memset(filestat, 0, sizeof(*filestat));
  6982. *filename = 0;
  6983. *is_found = 0;
  6984. *is_script_resource = 0;
  6985. *is_websocket_request = 0;
  6986. *is_put_or_delete_request = 0;
  6987. #endif /* !defined(NO_FILES) */
  6988. }
  6989. /* Check whether full request is buffered. Return:
  6990. * -1 if request or response is malformed
  6991. * 0 if request or response is not yet fully buffered
  6992. * >0 actual request length, including last \r\n\r\n */
  6993. static int
  6994. get_http_header_len(const char *buf, int buflen)
  6995. {
  6996. int i;
  6997. for (i = 0; i < buflen; i++) {
  6998. /* Do an unsigned comparison in some conditions below */
  6999. const unsigned char c = (unsigned char)buf[i];
  7000. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7001. && !isprint(c)) {
  7002. /* abort scan as soon as one malformed character is found */
  7003. return -1;
  7004. }
  7005. if (i < buflen - 1) {
  7006. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7007. /* Two newline, no carriage return - not standard compliant,
  7008. * but it should be accepted */
  7009. return i + 2;
  7010. }
  7011. }
  7012. if (i < buflen - 3) {
  7013. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7014. && (buf[i + 3] == '\n')) {
  7015. /* Two \r\n - standard compliant */
  7016. return i + 4;
  7017. }
  7018. }
  7019. }
  7020. return 0;
  7021. }
  7022. #if !defined(NO_CACHING)
  7023. /* Convert month to the month number. Return -1 on error, or month number */
  7024. static int
  7025. get_month_index(const char *s)
  7026. {
  7027. size_t i;
  7028. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7029. if (!strcmp(s, month_names[i])) {
  7030. return (int)i;
  7031. }
  7032. }
  7033. return -1;
  7034. }
  7035. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7036. static time_t
  7037. parse_date_string(const char *datetime)
  7038. {
  7039. char month_str[32] = {0};
  7040. int second, minute, hour, day, month, year;
  7041. time_t result = (time_t)0;
  7042. struct tm tm;
  7043. if ((sscanf(datetime,
  7044. "%d/%3s/%d %d:%d:%d",
  7045. &day,
  7046. month_str,
  7047. &year,
  7048. &hour,
  7049. &minute,
  7050. &second)
  7051. == 6)
  7052. || (sscanf(datetime,
  7053. "%d %3s %d %d:%d:%d",
  7054. &day,
  7055. month_str,
  7056. &year,
  7057. &hour,
  7058. &minute,
  7059. &second)
  7060. == 6)
  7061. || (sscanf(datetime,
  7062. "%*3s, %d %3s %d %d:%d:%d",
  7063. &day,
  7064. month_str,
  7065. &year,
  7066. &hour,
  7067. &minute,
  7068. &second)
  7069. == 6)
  7070. || (sscanf(datetime,
  7071. "%d-%3s-%d %d:%d:%d",
  7072. &day,
  7073. month_str,
  7074. &year,
  7075. &hour,
  7076. &minute,
  7077. &second)
  7078. == 6)) {
  7079. month = get_month_index(month_str);
  7080. if ((month >= 0) && (year >= 1970)) {
  7081. memset(&tm, 0, sizeof(tm));
  7082. tm.tm_year = year - 1900;
  7083. tm.tm_mon = month;
  7084. tm.tm_mday = day;
  7085. tm.tm_hour = hour;
  7086. tm.tm_min = minute;
  7087. tm.tm_sec = second;
  7088. result = timegm(&tm);
  7089. }
  7090. }
  7091. return result;
  7092. }
  7093. #endif /* !NO_CACHING */
  7094. /* Pre-process URIs according to RFC + protect against directory disclosure
  7095. * attacks by removing '..', excessive '/' and '\' characters */
  7096. static void
  7097. remove_dot_segments(char *inout)
  7098. {
  7099. /* Windows backend protection
  7100. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7101. * in URI by slash */
  7102. char *out_end = inout;
  7103. char *in = inout;
  7104. if (!in) {
  7105. /* Param error. */
  7106. return;
  7107. }
  7108. while (*in) {
  7109. if (*in == '\\') {
  7110. *in = '/';
  7111. }
  7112. in++;
  7113. }
  7114. /* Algorithm "remove_dot_segments" from
  7115. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7116. /* Step 1:
  7117. * The input buffer is initialized.
  7118. * The output buffer is initialized to the empty string.
  7119. */
  7120. in = inout;
  7121. /* Step 2:
  7122. * While the input buffer is not empty, loop as follows:
  7123. */
  7124. /* Less than out_end of the inout buffer is used as output, so keep
  7125. * condition: out_end <= in */
  7126. while (*in) {
  7127. /* Step 2a:
  7128. * If the input buffer begins with a prefix of "../" or "./",
  7129. * then remove that prefix from the input buffer;
  7130. */
  7131. if (!strncmp(in, "../", 3)) {
  7132. in += 3;
  7133. } else if (!strncmp(in, "./", 2)) {
  7134. in += 2;
  7135. }
  7136. /* otherwise */
  7137. /* Step 2b:
  7138. * if the input buffer begins with a prefix of "/./" or "/.",
  7139. * where "." is a complete path segment, then replace that
  7140. * prefix with "/" in the input buffer;
  7141. */
  7142. else if (!strncmp(in, "/./", 3)) {
  7143. in += 2;
  7144. } else if (!strcmp(in, "/.")) {
  7145. in[1] = 0;
  7146. }
  7147. /* otherwise */
  7148. /* Step 2c:
  7149. * if the input buffer begins with a prefix of "/../" or "/..",
  7150. * where ".." is a complete path segment, then replace that
  7151. * prefix with "/" in the input buffer and remove the last
  7152. * segment and its preceding "/" (if any) from the output
  7153. * buffer;
  7154. */
  7155. else if (!strncmp(in, "/../", 4)) {
  7156. in += 3;
  7157. if (inout != out_end) {
  7158. /* remove last segment */
  7159. do {
  7160. out_end--;
  7161. } while ((inout != out_end) && (*out_end != '/'));
  7162. }
  7163. } else if (!strcmp(in, "/..")) {
  7164. in[1] = 0;
  7165. if (inout != out_end) {
  7166. /* remove last segment */
  7167. do {
  7168. out_end--;
  7169. } while ((inout != out_end) && (*out_end != '/'));
  7170. }
  7171. }
  7172. /* otherwise */
  7173. /* Step 2d:
  7174. * if the input buffer consists only of "." or "..", then remove
  7175. * that from the input buffer;
  7176. */
  7177. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7178. *in = 0;
  7179. }
  7180. /* otherwise */
  7181. /* Step 2e:
  7182. * move the first path segment in the input buffer to the end of
  7183. * the output buffer, including the initial "/" character (if
  7184. * any) and any subsequent characters up to, but not including,
  7185. * the next "/" character or the end of the input buffer.
  7186. */
  7187. else {
  7188. do {
  7189. *out_end = *in;
  7190. out_end++;
  7191. in++;
  7192. } while ((*in != 0) && (*in != '/'));
  7193. }
  7194. }
  7195. /* Step 3:
  7196. * Finally, the output buffer is returned as the result of
  7197. * remove_dot_segments.
  7198. */
  7199. /* Terminate output */
  7200. *out_end = 0;
  7201. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7202. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7203. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7204. * or "//" anymore.
  7205. */
  7206. out_end = in = inout;
  7207. while (*in) {
  7208. if (*in == '.') {
  7209. /* remove . at the end or preceding of / */
  7210. char *in_ahead = in;
  7211. do {
  7212. in_ahead++;
  7213. } while (*in_ahead == '.');
  7214. if (*in_ahead == '/') {
  7215. in = in_ahead;
  7216. if ((out_end != inout) && (out_end[-1] == '/')) {
  7217. /* remove generated // */
  7218. out_end--;
  7219. }
  7220. } else if (*in_ahead == 0) {
  7221. in = in_ahead;
  7222. } else {
  7223. do {
  7224. *out_end++ = '.';
  7225. in++;
  7226. } while (in != in_ahead);
  7227. }
  7228. } else if (*in == '/') {
  7229. /* replace // by / */
  7230. *out_end++ = '/';
  7231. do {
  7232. in++;
  7233. } while (*in == '/');
  7234. } else {
  7235. *out_end++ = *in;
  7236. in++;
  7237. }
  7238. }
  7239. *out_end = 0;
  7240. }
  7241. static const struct {
  7242. const char *extension;
  7243. size_t ext_len;
  7244. const char *mime_type;
  7245. } builtin_mime_types[] = {
  7246. /* IANA registered MIME types
  7247. * (http://www.iana.org/assignments/media-types)
  7248. * application types */
  7249. {".bin", 4, "application/octet-stream"},
  7250. {".deb", 4, "application/octet-stream"},
  7251. {".dmg", 4, "application/octet-stream"},
  7252. {".dll", 4, "application/octet-stream"},
  7253. {".doc", 4, "application/msword"},
  7254. {".eps", 4, "application/postscript"},
  7255. {".exe", 4, "application/octet-stream"},
  7256. {".iso", 4, "application/octet-stream"},
  7257. {".js", 3, "application/javascript"},
  7258. {".json", 5, "application/json"},
  7259. {".mjs", 4, "application/javascript"},
  7260. {".msi", 4, "application/octet-stream"},
  7261. {".pdf", 4, "application/pdf"},
  7262. {".ps", 3, "application/postscript"},
  7263. {".rtf", 4, "application/rtf"},
  7264. {".wasm", 5, "application/wasm"},
  7265. {".xhtml", 6, "application/xhtml+xml"},
  7266. {".xsl", 4, "application/xml"},
  7267. {".xslt", 5, "application/xml"},
  7268. /* fonts */
  7269. {".ttf", 4, "application/font-sfnt"},
  7270. {".cff", 4, "application/font-sfnt"},
  7271. {".otf", 4, "application/font-sfnt"},
  7272. {".aat", 4, "application/font-sfnt"},
  7273. {".sil", 4, "application/font-sfnt"},
  7274. {".pfr", 4, "application/font-tdpfr"},
  7275. {".woff", 5, "application/font-woff"},
  7276. {".woff2", 6, "application/font-woff2"},
  7277. /* audio */
  7278. {".mp3", 4, "audio/mpeg"},
  7279. {".oga", 4, "audio/ogg"},
  7280. {".ogg", 4, "audio/ogg"},
  7281. /* image */
  7282. {".gif", 4, "image/gif"},
  7283. {".ief", 4, "image/ief"},
  7284. {".jpeg", 5, "image/jpeg"},
  7285. {".jpg", 4, "image/jpeg"},
  7286. {".jpm", 4, "image/jpm"},
  7287. {".jpx", 4, "image/jpx"},
  7288. {".png", 4, "image/png"},
  7289. {".svg", 4, "image/svg+xml"},
  7290. {".tif", 4, "image/tiff"},
  7291. {".tiff", 5, "image/tiff"},
  7292. /* model */
  7293. {".wrl", 4, "model/vrml"},
  7294. /* text */
  7295. {".css", 4, "text/css"},
  7296. {".csv", 4, "text/csv"},
  7297. {".htm", 4, "text/html"},
  7298. {".html", 5, "text/html"},
  7299. {".sgm", 4, "text/sgml"},
  7300. {".shtm", 5, "text/html"},
  7301. {".shtml", 6, "text/html"},
  7302. {".txt", 4, "text/plain"},
  7303. {".xml", 4, "text/xml"},
  7304. /* video */
  7305. {".mov", 4, "video/quicktime"},
  7306. {".mp4", 4, "video/mp4"},
  7307. {".mpeg", 5, "video/mpeg"},
  7308. {".mpg", 4, "video/mpeg"},
  7309. {".ogv", 4, "video/ogg"},
  7310. {".qt", 3, "video/quicktime"},
  7311. /* not registered types
  7312. * (http://reference.sitepoint.com/html/mime-types-full,
  7313. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7314. {".arj", 4, "application/x-arj-compressed"},
  7315. {".gz", 3, "application/x-gunzip"},
  7316. {".rar", 4, "application/x-arj-compressed"},
  7317. {".swf", 4, "application/x-shockwave-flash"},
  7318. {".tar", 4, "application/x-tar"},
  7319. {".tgz", 4, "application/x-tar-gz"},
  7320. {".torrent", 8, "application/x-bittorrent"},
  7321. {".ppt", 4, "application/x-mspowerpoint"},
  7322. {".xls", 4, "application/x-msexcel"},
  7323. {".zip", 4, "application/x-zip-compressed"},
  7324. {".aac",
  7325. 4,
  7326. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7327. {".flac", 5, "audio/flac"},
  7328. {".aif", 4, "audio/x-aif"},
  7329. {".m3u", 4, "audio/x-mpegurl"},
  7330. {".mid", 4, "audio/x-midi"},
  7331. {".ra", 3, "audio/x-pn-realaudio"},
  7332. {".ram", 4, "audio/x-pn-realaudio"},
  7333. {".wav", 4, "audio/x-wav"},
  7334. {".bmp", 4, "image/bmp"},
  7335. {".ico", 4, "image/x-icon"},
  7336. {".pct", 4, "image/x-pct"},
  7337. {".pict", 5, "image/pict"},
  7338. {".rgb", 4, "image/x-rgb"},
  7339. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7340. {".asf", 4, "video/x-ms-asf"},
  7341. {".avi", 4, "video/x-msvideo"},
  7342. {".m4v", 4, "video/x-m4v"},
  7343. {NULL, 0, NULL}};
  7344. CIVETWEB_API const char *
  7345. mg_get_builtin_mime_type(const char *path)
  7346. {
  7347. const char *ext;
  7348. size_t i, path_len;
  7349. path_len = strlen(path);
  7350. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7351. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7352. if ((path_len > builtin_mime_types[i].ext_len)
  7353. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7354. return builtin_mime_types[i].mime_type;
  7355. }
  7356. }
  7357. return "text/plain";
  7358. }
  7359. /* Look at the "path" extension and figure what mime type it has.
  7360. * Store mime type in the vector. */
  7361. static void
  7362. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7363. {
  7364. struct vec ext_vec, mime_vec;
  7365. const char *list, *ext;
  7366. size_t path_len;
  7367. path_len = strlen(path);
  7368. if ((conn == NULL) || (vec == NULL)) {
  7369. if (vec != NULL) {
  7370. memset(vec, '\0', sizeof(struct vec));
  7371. }
  7372. return;
  7373. }
  7374. /* Scan user-defined mime types first, in case user wants to
  7375. * override default mime types. */
  7376. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7377. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7378. /* ext now points to the path suffix */
  7379. ext = path + path_len - ext_vec.len;
  7380. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7381. *vec = mime_vec;
  7382. return;
  7383. }
  7384. }
  7385. vec->ptr = mg_get_builtin_mime_type(path);
  7386. vec->len = strlen(vec->ptr);
  7387. }
  7388. /* Stringify binary data. Output buffer must be twice as big as input,
  7389. * because each byte takes 2 bytes in string representation */
  7390. static void
  7391. bin2str(char *to, const unsigned char *p, size_t len)
  7392. {
  7393. static const char *hex = "0123456789abcdef";
  7394. for (; len--; p++) {
  7395. *to++ = hex[p[0] >> 4];
  7396. *to++ = hex[p[0] & 0x0f];
  7397. }
  7398. *to = '\0';
  7399. }
  7400. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7401. */
  7402. CIVETWEB_API char *
  7403. mg_md5(char buf[33], ...)
  7404. {
  7405. md5_byte_t hash[16];
  7406. const char *p;
  7407. va_list ap;
  7408. md5_state_t ctx;
  7409. md5_init(&ctx);
  7410. va_start(ap, buf);
  7411. while ((p = va_arg(ap, const char *)) != NULL) {
  7412. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7413. }
  7414. va_end(ap);
  7415. md5_finish(&ctx, hash);
  7416. bin2str(buf, hash, sizeof(hash));
  7417. return buf;
  7418. }
  7419. /* Check the user's password, return 1 if OK */
  7420. static int
  7421. check_password_digest(const char *method,
  7422. const char *ha1,
  7423. const char *uri,
  7424. const char *nonce,
  7425. const char *nc,
  7426. const char *cnonce,
  7427. const char *qop,
  7428. const char *response)
  7429. {
  7430. char ha2[32 + 1], expected_response[32 + 1];
  7431. /* Some of the parameters may be NULL */
  7432. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7433. || (qop == NULL) || (response == NULL)) {
  7434. return 0;
  7435. }
  7436. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7437. if (strlen(response) != 32) {
  7438. return 0;
  7439. }
  7440. mg_md5(ha2, method, ":", uri, NULL);
  7441. mg_md5(expected_response,
  7442. ha1,
  7443. ":",
  7444. nonce,
  7445. ":",
  7446. nc,
  7447. ":",
  7448. cnonce,
  7449. ":",
  7450. qop,
  7451. ":",
  7452. ha2,
  7453. NULL);
  7454. return mg_strcasecmp(response, expected_response) == 0;
  7455. }
  7456. #if !defined(NO_FILESYSTEMS)
  7457. /* Use the global passwords file, if specified by auth_gpass option,
  7458. * or search for .htpasswd in the requested directory. */
  7459. static void
  7460. open_auth_file(struct mg_connection *conn,
  7461. const char *path,
  7462. struct mg_file *filep)
  7463. {
  7464. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7465. char name[UTF8_PATH_MAX];
  7466. const char *p, *e,
  7467. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7468. int truncated;
  7469. if (gpass != NULL) {
  7470. /* Use global passwords file */
  7471. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7472. #if defined(DEBUG)
  7473. /* Use mg_cry_internal here, since gpass has been
  7474. * configured. */
  7475. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7476. #endif
  7477. }
  7478. /* Important: using local struct mg_file to test path for
  7479. * is_directory flag. If filep is used, mg_stat() makes it
  7480. * appear as if auth file was opened.
  7481. * TODO(mid): Check if this is still required after rewriting
  7482. * mg_stat */
  7483. } else if (mg_stat(conn, path, &filep->stat)
  7484. && filep->stat.is_directory) {
  7485. mg_snprintf(conn,
  7486. &truncated,
  7487. name,
  7488. sizeof(name),
  7489. "%s/%s",
  7490. path,
  7491. PASSWORDS_FILE_NAME);
  7492. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7493. #if defined(DEBUG)
  7494. /* Don't use mg_cry_internal here, but only a trace, since
  7495. * this is a typical case. It will occur for every directory
  7496. * without a password file. */
  7497. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7498. #endif
  7499. }
  7500. } else {
  7501. /* Try to find .htpasswd in requested directory. */
  7502. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7503. if (e[0] == '/') {
  7504. break;
  7505. }
  7506. }
  7507. mg_snprintf(conn,
  7508. &truncated,
  7509. name,
  7510. sizeof(name),
  7511. "%.*s/%s",
  7512. (int)(e - p),
  7513. p,
  7514. PASSWORDS_FILE_NAME);
  7515. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7516. #if defined(DEBUG)
  7517. /* Don't use mg_cry_internal here, but only a trace, since
  7518. * this is a typical case. It will occur for every directory
  7519. * without a password file. */
  7520. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7521. #endif
  7522. }
  7523. }
  7524. }
  7525. }
  7526. #endif /* NO_FILESYSTEMS */
  7527. /* Parsed Authorization header */
  7528. struct auth_header {
  7529. char *user;
  7530. int type; /* 1 = basic, 2 = digest */
  7531. char *plain_password; /* Basic only */
  7532. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7533. };
  7534. /* Return 1 on success. Always initializes the auth_header structure. */
  7535. static int
  7536. parse_auth_header(struct mg_connection *conn,
  7537. char *buf,
  7538. size_t buf_size,
  7539. struct auth_header *auth_header)
  7540. {
  7541. char *name, *value, *s;
  7542. const char *ah;
  7543. uint64_t nonce;
  7544. if (!auth_header || !conn) {
  7545. return 0;
  7546. }
  7547. (void)memset(auth_header, 0, sizeof(*auth_header));
  7548. ah = mg_get_header(conn, "Authorization");
  7549. if (ah == NULL) {
  7550. /* No Authorization header at all */
  7551. return 0;
  7552. }
  7553. if (0 == mg_strncasecmp(ah, "Basic ", 6)) {
  7554. /* Basic Auth (we never asked for this, but some client may send it) */
  7555. char *split;
  7556. const char *userpw_b64 = ah + 6;
  7557. size_t userpw_b64_len = strlen(userpw_b64);
  7558. size_t buf_len_r = buf_size;
  7559. if (mg_base64_decode(
  7560. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7561. != -1) {
  7562. return 0; /* decode error */
  7563. }
  7564. split = strchr(buf, ':');
  7565. if (!split) {
  7566. return 0; /* Format error */
  7567. }
  7568. /* Separate string at ':' */
  7569. *split = 0;
  7570. /* User name is before ':', Password is after ':' */
  7571. auth_header->user = buf;
  7572. auth_header->type = 1;
  7573. auth_header->plain_password = split + 1;
  7574. return 1;
  7575. } else if (0 == mg_strncasecmp(ah, "Digest ", 7)) {
  7576. /* Digest Auth ... implemented below */
  7577. auth_header->type = 2;
  7578. } else {
  7579. /* Unknown or invalid Auth method */
  7580. return 0;
  7581. }
  7582. /* Make modifiable copy of the auth header */
  7583. (void)mg_strlcpy(buf, ah + 7, buf_size);
  7584. s = buf;
  7585. /* Parse authorization header */
  7586. for (;;) {
  7587. /* Gobble initial spaces */
  7588. while (isspace((unsigned char)*s)) {
  7589. s++;
  7590. }
  7591. name = skip_quoted(&s, "=", " ", 0);
  7592. /* Value is either quote-delimited, or ends at first comma or space.
  7593. */
  7594. if (s[0] == '\"') {
  7595. s++;
  7596. value = skip_quoted(&s, "\"", " ", '\\');
  7597. if (s[0] == ',') {
  7598. s++;
  7599. }
  7600. } else {
  7601. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7602. * uses spaces */
  7603. }
  7604. if (*name == '\0') {
  7605. break;
  7606. }
  7607. if (!strcmp(name, "username")) {
  7608. auth_header->user = value;
  7609. } else if (!strcmp(name, "cnonce")) {
  7610. auth_header->cnonce = value;
  7611. } else if (!strcmp(name, "response")) {
  7612. auth_header->response = value;
  7613. } else if (!strcmp(name, "uri")) {
  7614. auth_header->uri = value;
  7615. } else if (!strcmp(name, "qop")) {
  7616. auth_header->qop = value;
  7617. } else if (!strcmp(name, "nc")) {
  7618. auth_header->nc = value;
  7619. } else if (!strcmp(name, "nonce")) {
  7620. auth_header->nonce = value;
  7621. }
  7622. }
  7623. #if !defined(NO_NONCE_CHECK)
  7624. /* Read the nonce from the response. */
  7625. if (auth_header->nonce == NULL) {
  7626. return 0;
  7627. }
  7628. s = NULL;
  7629. nonce = strtoull(auth_header->nonce, &s, 10);
  7630. if ((s == NULL) || (*s != 0)) {
  7631. return 0;
  7632. }
  7633. /* Convert the nonce from the client to a number. */
  7634. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7635. /* The converted number corresponds to the time the nounce has been
  7636. * created. This should not be earlier than the server start. */
  7637. /* Server side nonce check is valuable in all situations but one:
  7638. * if the server restarts frequently, but the client should not see
  7639. * that, so the server should accept nonces from previous starts. */
  7640. /* However, the reasonable default is to not accept a nonce from a
  7641. * previous start, so if anyone changed the access rights between
  7642. * two restarts, a new login is required. */
  7643. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7644. /* nonce is from a previous start of the server and no longer valid
  7645. * (replay attack?) */
  7646. return 0;
  7647. }
  7648. /* Check if the nonce is too high, so it has not (yet) been used by the
  7649. * server. */
  7650. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7651. + conn->dom_ctx->nonce_count)) {
  7652. return 0;
  7653. }
  7654. #else
  7655. (void)nonce;
  7656. #endif
  7657. return (auth_header->user != NULL);
  7658. }
  7659. static const char *
  7660. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7661. {
  7662. if (!filep) {
  7663. return NULL;
  7664. }
  7665. if (filep->access.fp != NULL) {
  7666. return fgets(buf, (int)size, filep->access.fp);
  7667. } else {
  7668. return NULL;
  7669. }
  7670. }
  7671. /* Define the initial recursion depth for procesesing htpasswd files that
  7672. * include other htpasswd
  7673. * (or even the same) files. It is not difficult to provide a file or files
  7674. * s.t. they force civetweb
  7675. * to infinitely recurse and then crash.
  7676. */
  7677. #define INITIAL_DEPTH 9
  7678. #if INITIAL_DEPTH <= 0
  7679. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7680. #endif
  7681. #if !defined(NO_FILESYSTEMS)
  7682. struct read_auth_file_struct {
  7683. struct mg_connection *conn;
  7684. struct auth_header auth_header;
  7685. const char *domain;
  7686. char buf[256 + 256 + 40];
  7687. const char *f_user;
  7688. const char *f_domain;
  7689. const char *f_ha1;
  7690. };
  7691. static int
  7692. read_auth_file(struct mg_file *filep,
  7693. struct read_auth_file_struct *workdata,
  7694. int depth)
  7695. {
  7696. int is_authorized = 0;
  7697. struct mg_file fp;
  7698. size_t l;
  7699. if (!filep || !workdata || (0 == depth)) {
  7700. return 0;
  7701. }
  7702. /* Loop over passwords file */
  7703. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7704. l = strlen(workdata->buf);
  7705. while (l > 0) {
  7706. if (isspace((unsigned char)workdata->buf[l - 1])
  7707. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7708. l--;
  7709. workdata->buf[l] = 0;
  7710. } else
  7711. break;
  7712. }
  7713. if (l < 1) {
  7714. continue;
  7715. }
  7716. workdata->f_user = workdata->buf;
  7717. if (workdata->f_user[0] == ':') {
  7718. /* user names may not contain a ':' and may not be empty,
  7719. * so lines starting with ':' may be used for a special purpose
  7720. */
  7721. if (workdata->f_user[1] == '#') {
  7722. /* :# is a comment */
  7723. continue;
  7724. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7725. if (mg_fopen(workdata->conn,
  7726. workdata->f_user + 9,
  7727. MG_FOPEN_MODE_READ,
  7728. &fp)) {
  7729. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7730. (void)mg_fclose(
  7731. &fp.access); /* ignore error on read only file */
  7732. /* No need to continue processing files once we have a
  7733. * match, since nothing will reset it back
  7734. * to 0.
  7735. */
  7736. if (is_authorized) {
  7737. return is_authorized;
  7738. }
  7739. } else {
  7740. mg_cry_internal(workdata->conn,
  7741. "%s: cannot open authorization file: %s",
  7742. __func__,
  7743. workdata->buf);
  7744. }
  7745. continue;
  7746. }
  7747. /* everything is invalid for the moment (might change in the
  7748. * future) */
  7749. mg_cry_internal(workdata->conn,
  7750. "%s: syntax error in authorization file: %s",
  7751. __func__,
  7752. workdata->buf);
  7753. continue;
  7754. }
  7755. workdata->f_domain = strchr(workdata->f_user, ':');
  7756. if (workdata->f_domain == NULL) {
  7757. mg_cry_internal(workdata->conn,
  7758. "%s: syntax error in authorization file: %s",
  7759. __func__,
  7760. workdata->buf);
  7761. continue;
  7762. }
  7763. *(char *)(workdata->f_domain) = 0;
  7764. (workdata->f_domain)++;
  7765. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7766. if (workdata->f_ha1 == NULL) {
  7767. mg_cry_internal(workdata->conn,
  7768. "%s: syntax error in authorization file: %s",
  7769. __func__,
  7770. workdata->buf);
  7771. continue;
  7772. }
  7773. *(char *)(workdata->f_ha1) = 0;
  7774. (workdata->f_ha1)++;
  7775. if (!strcmp(workdata->auth_header.user, workdata->f_user)
  7776. && !strcmp(workdata->domain, workdata->f_domain)) {
  7777. switch (workdata->auth_header.type) {
  7778. case 1: /* Basic */
  7779. {
  7780. char md5[33];
  7781. mg_md5(md5,
  7782. workdata->f_user,
  7783. ":",
  7784. workdata->domain,
  7785. ":",
  7786. workdata->auth_header.plain_password,
  7787. NULL);
  7788. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7789. }
  7790. case 2: /* Digest */
  7791. return check_password_digest(
  7792. workdata->conn->request_info.request_method,
  7793. workdata->f_ha1,
  7794. workdata->auth_header.uri,
  7795. workdata->auth_header.nonce,
  7796. workdata->auth_header.nc,
  7797. workdata->auth_header.cnonce,
  7798. workdata->auth_header.qop,
  7799. workdata->auth_header.response);
  7800. default: /* None/Other/Unknown */
  7801. return 0;
  7802. }
  7803. }
  7804. }
  7805. return is_authorized;
  7806. }
  7807. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7808. static int
  7809. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7810. {
  7811. struct read_auth_file_struct workdata;
  7812. char buf[MG_BUF_LEN];
  7813. if (!conn || !conn->dom_ctx) {
  7814. return 0;
  7815. }
  7816. memset(&workdata, 0, sizeof(workdata));
  7817. workdata.conn = conn;
  7818. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.auth_header)) {
  7819. return 0;
  7820. }
  7821. /* CGI needs it as REMOTE_USER */
  7822. conn->request_info.remote_user =
  7823. mg_strdup_ctx(workdata.auth_header.user, conn->phys_ctx);
  7824. if (realm) {
  7825. workdata.domain = realm;
  7826. } else {
  7827. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7828. }
  7829. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7830. }
  7831. /* Public function to check http digest authentication header */
  7832. CIVETWEB_API int
  7833. mg_check_digest_access_authentication(struct mg_connection *conn,
  7834. const char *realm,
  7835. const char *filename)
  7836. {
  7837. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7838. int auth;
  7839. if (!conn || !filename) {
  7840. return -1;
  7841. }
  7842. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7843. return -2;
  7844. }
  7845. auth = authorize(conn, &file, realm);
  7846. mg_fclose(&file.access);
  7847. return auth;
  7848. }
  7849. #endif /* NO_FILESYSTEMS */
  7850. /* Return 1 if request is authorised, 0 otherwise. */
  7851. static int
  7852. check_authorization(struct mg_connection *conn, const char *path)
  7853. {
  7854. #if !defined(NO_FILESYSTEMS)
  7855. char fname[UTF8_PATH_MAX];
  7856. struct vec uri_vec, filename_vec;
  7857. const char *list;
  7858. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7859. int authorized = 1, truncated;
  7860. if (!conn || !conn->dom_ctx) {
  7861. return 0;
  7862. }
  7863. list = conn->dom_ctx->config[PROTECT_URI];
  7864. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7865. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7866. mg_snprintf(conn,
  7867. &truncated,
  7868. fname,
  7869. sizeof(fname),
  7870. "%.*s",
  7871. (int)filename_vec.len,
  7872. filename_vec.ptr);
  7873. if (truncated
  7874. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7875. mg_cry_internal(conn,
  7876. "%s: cannot open %s: %s",
  7877. __func__,
  7878. fname,
  7879. strerror(errno));
  7880. }
  7881. break;
  7882. }
  7883. }
  7884. if (!is_file_opened(&file.access)) {
  7885. open_auth_file(conn, path, &file);
  7886. }
  7887. if (is_file_opened(&file.access)) {
  7888. authorized = authorize(conn, &file, NULL);
  7889. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7890. }
  7891. return authorized;
  7892. #else
  7893. (void)conn;
  7894. (void)path;
  7895. return 1;
  7896. #endif /* NO_FILESYSTEMS */
  7897. }
  7898. /* Internal function. Assumes conn is valid */
  7899. static void
  7900. send_authorization_request(struct mg_connection *conn, const char *realm)
  7901. {
  7902. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7903. int trunc = 0;
  7904. char buf[128];
  7905. if (!realm) {
  7906. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7907. }
  7908. mg_lock_context(conn->phys_ctx);
  7909. nonce += conn->dom_ctx->nonce_count;
  7910. ++conn->dom_ctx->nonce_count;
  7911. mg_unlock_context(conn->phys_ctx);
  7912. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7913. conn->must_close = 1;
  7914. /* Create 401 response */
  7915. mg_response_header_start(conn, 401);
  7916. send_no_cache_header(conn);
  7917. send_additional_header(conn);
  7918. mg_response_header_add(conn, "Content-Length", "0", -1);
  7919. /* Content for "WWW-Authenticate" header */
  7920. mg_snprintf(conn,
  7921. &trunc,
  7922. buf,
  7923. sizeof(buf),
  7924. "Digest qop=\"auth\", realm=\"%s\", "
  7925. "nonce=\"%" UINT64_FMT "\"",
  7926. realm,
  7927. nonce);
  7928. if (!trunc) {
  7929. /* !trunc should always be true */
  7930. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7931. }
  7932. /* Send all headers */
  7933. mg_response_header_send(conn);
  7934. }
  7935. /* Interface function. Parameters are provided by the user, so do
  7936. * at least some basic checks.
  7937. */
  7938. CIVETWEB_API int
  7939. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7940. const char *realm)
  7941. {
  7942. if (conn && conn->dom_ctx) {
  7943. send_authorization_request(conn, realm);
  7944. return 0;
  7945. }
  7946. return -1;
  7947. }
  7948. #if !defined(NO_FILES)
  7949. static int
  7950. is_authorized_for_put(struct mg_connection *conn)
  7951. {
  7952. int ret = 0;
  7953. if (conn) {
  7954. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7955. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7956. if (passfile != NULL
  7957. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7958. ret = authorize(conn, &file, NULL);
  7959. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7960. }
  7961. }
  7962. DEBUG_TRACE("file write authorization: %i", ret);
  7963. return ret;
  7964. }
  7965. #endif
  7966. CIVETWEB_API int
  7967. mg_modify_passwords_file_ha1(const char *fname,
  7968. const char *domain,
  7969. const char *user,
  7970. const char *ha1)
  7971. {
  7972. int found = 0, i, result = 1;
  7973. char line[512], u[256], d[256], h[256];
  7974. struct stat st = {0};
  7975. FILE *fp = NULL;
  7976. char *temp_file = NULL;
  7977. int temp_file_offs = 0;
  7978. /* Regard empty password as no password - remove user record. */
  7979. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7980. ha1 = NULL;
  7981. }
  7982. /* Other arguments must not be empty */
  7983. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7984. return 0;
  7985. }
  7986. /* Using the given file format, user name and domain must not contain
  7987. * the ':' character */
  7988. if (strchr(user, ':') != NULL) {
  7989. return 0;
  7990. }
  7991. if (strchr(domain, ':') != NULL) {
  7992. return 0;
  7993. }
  7994. /* Do not allow control characters like newline in user name and domain.
  7995. * Do not allow excessively long names either. */
  7996. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7997. if (iscntrl((unsigned char)user[i])) {
  7998. return 0;
  7999. }
  8000. }
  8001. if (user[i]) {
  8002. return 0; /* user name too long */
  8003. }
  8004. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  8005. if (iscntrl((unsigned char)domain[i])) {
  8006. return 0;
  8007. }
  8008. }
  8009. if (domain[i]) {
  8010. return 0; /* domain name too long */
  8011. }
  8012. /* The maximum length of the path to the password file is limited */
  8013. if (strlen(fname) >= UTF8_PATH_MAX) {
  8014. return 0;
  8015. }
  8016. /* Check if the file exists, and get file size */
  8017. if (0 == stat(fname, &st)) {
  8018. int temp_buf_len;
  8019. if (st.st_size > 10485760) {
  8020. /* Some funster provided a >10 MB text file */
  8021. return 0;
  8022. }
  8023. /* Add enough space for one more line */
  8024. temp_buf_len = (int)st.st_size + 1024;
  8025. /* Allocate memory (instead of using a temporary file) */
  8026. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  8027. if (!temp_file) {
  8028. /* Out of memory */
  8029. return 0;
  8030. }
  8031. /* File exists. Read it into a memory buffer. */
  8032. fp = fopen(fname, "r");
  8033. if (fp == NULL) {
  8034. /* Cannot read file. No permission? */
  8035. mg_free(temp_file);
  8036. return 0;
  8037. }
  8038. /* Read content and store in memory */
  8039. while ((fgets(line, sizeof(line), fp) != NULL)
  8040. && ((temp_file_offs + 600) < temp_buf_len)) {
  8041. /* file format is "user:domain:hash\n" */
  8042. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  8043. continue;
  8044. }
  8045. u[255] = 0;
  8046. d[255] = 0;
  8047. h[255] = 0;
  8048. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8049. /* Found the user: change the password hash or drop the user
  8050. */
  8051. if ((ha1 != NULL) && (!found)) {
  8052. i = sprintf(temp_file + temp_file_offs,
  8053. "%s:%s:%s\n",
  8054. user,
  8055. domain,
  8056. ha1);
  8057. if (i < 1) {
  8058. fclose(fp);
  8059. mg_free(temp_file);
  8060. return 0;
  8061. }
  8062. temp_file_offs += i;
  8063. }
  8064. found = 1;
  8065. } else {
  8066. /* Copy existing user, including password hash */
  8067. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  8068. if (i < 1) {
  8069. fclose(fp);
  8070. mg_free(temp_file);
  8071. return 0;
  8072. }
  8073. temp_file_offs += i;
  8074. }
  8075. }
  8076. fclose(fp);
  8077. }
  8078. /* Create new file */
  8079. fp = fopen(fname, "w");
  8080. if (!fp) {
  8081. mg_free(temp_file);
  8082. return 0;
  8083. }
  8084. #if !defined(_WIN32)
  8085. /* On Linux & co., restrict file read/write permissions to the owner */
  8086. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  8087. result = 0;
  8088. }
  8089. #endif
  8090. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  8091. /* Store buffered content of old file */
  8092. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  8093. != (size_t)temp_file_offs) {
  8094. result = 0;
  8095. }
  8096. }
  8097. /* If new user, just add it */
  8098. if ((ha1 != NULL) && (!found)) {
  8099. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  8100. result = 0;
  8101. }
  8102. }
  8103. /* All data written */
  8104. if (fclose(fp) != 0) {
  8105. result = 0;
  8106. }
  8107. mg_free(temp_file);
  8108. return result;
  8109. }
  8110. CIVETWEB_API int
  8111. mg_modify_passwords_file(const char *fname,
  8112. const char *domain,
  8113. const char *user,
  8114. const char *pass)
  8115. {
  8116. char ha1buf[33];
  8117. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8118. return 0;
  8119. }
  8120. if ((pass == NULL) || (pass[0] == 0)) {
  8121. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  8122. }
  8123. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  8124. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  8125. }
  8126. static int
  8127. is_valid_port(unsigned long port)
  8128. {
  8129. return (port <= 0xffff);
  8130. }
  8131. static int
  8132. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8133. {
  8134. struct addrinfo hints, *res, *ressave;
  8135. int func_ret = 0;
  8136. int gai_ret;
  8137. memset(&hints, 0, sizeof(struct addrinfo));
  8138. hints.ai_family = af;
  8139. if (!resolve_src) {
  8140. hints.ai_flags = AI_NUMERICHOST;
  8141. }
  8142. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8143. if (gai_ret != 0) {
  8144. /* gai_strerror could be used to convert gai_ret to a string */
  8145. /* POSIX return values: see
  8146. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8147. */
  8148. /* Windows return values: see
  8149. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8150. */
  8151. return 0;
  8152. }
  8153. ressave = res;
  8154. while (res) {
  8155. if ((dstlen >= (size_t)res->ai_addrlen)
  8156. && (res->ai_addr->sa_family == af)) {
  8157. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8158. func_ret = 1;
  8159. }
  8160. res = res->ai_next;
  8161. }
  8162. freeaddrinfo(ressave);
  8163. return func_ret;
  8164. }
  8165. static int
  8166. connect_socket(
  8167. struct mg_context *ctx /* may be NULL */,
  8168. const char *host,
  8169. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  8170. int use_ssl, /* 0 or 1 */
  8171. struct mg_error_data *error,
  8172. SOCKET *sock /* output: socket, must not be NULL */,
  8173. union usa *sa /* output: socket address, must not be NULL */
  8174. )
  8175. {
  8176. int ip_ver = 0;
  8177. int conn_ret = -1;
  8178. int sockerr = 0;
  8179. *sock = INVALID_SOCKET;
  8180. memset(sa, 0, sizeof(*sa));
  8181. if (host == NULL) {
  8182. if (error != NULL) {
  8183. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8184. mg_snprintf(NULL,
  8185. NULL, /* No truncation check for ebuf */
  8186. error->text,
  8187. error->text_buffer_size,
  8188. "%s",
  8189. "NULL host");
  8190. }
  8191. return 0;
  8192. }
  8193. #if defined(USE_X_DOM_SOCKET)
  8194. if (port == -99) {
  8195. /* Unix domain socket */
  8196. size_t hostlen = strlen(host);
  8197. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8198. if (error != NULL) {
  8199. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8200. mg_snprintf(NULL,
  8201. NULL, /* No truncation check for ebuf */
  8202. error->text,
  8203. error->text_buffer_size,
  8204. "%s",
  8205. "host length exceeds limit");
  8206. }
  8207. return 0;
  8208. }
  8209. } else
  8210. #endif
  8211. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8212. if (error != NULL) {
  8213. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8214. mg_snprintf(NULL,
  8215. NULL, /* No truncation check for ebuf */
  8216. error->text,
  8217. error->text_buffer_size,
  8218. "%s",
  8219. "invalid port");
  8220. }
  8221. return 0;
  8222. }
  8223. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) && !defined(NO_SSL_DL)
  8224. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8225. if (use_ssl && (TLS_client_method == NULL)) {
  8226. if (error != NULL) {
  8227. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8228. mg_snprintf(NULL,
  8229. NULL, /* No truncation check for ebuf */
  8230. error->text,
  8231. error->text_buffer_size,
  8232. "%s",
  8233. "SSL is not initialized");
  8234. }
  8235. return 0;
  8236. }
  8237. #else
  8238. if (use_ssl && (SSLv23_client_method == NULL)) {
  8239. if (error != 0) {
  8240. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8241. mg_snprintf(NULL,
  8242. NULL, /* No truncation check for ebuf */
  8243. error->text,
  8244. error->text_buffer_size,
  8245. "%s",
  8246. "SSL is not initialized");
  8247. }
  8248. return 0;
  8249. }
  8250. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8251. #else
  8252. (void)use_ssl;
  8253. #endif /* NO SSL */
  8254. #if defined(USE_X_DOM_SOCKET)
  8255. if (port == -99) {
  8256. size_t hostlen = strlen(host);
  8257. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8258. ip_ver = -99;
  8259. sa->sun.sun_family = AF_UNIX;
  8260. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8261. memcpy(sa->sun.sun_path, host, hostlen);
  8262. } else
  8263. #endif
  8264. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8265. sa->sin.sin_port = htons((uint16_t)port);
  8266. ip_ver = 4;
  8267. #if defined(USE_IPV6)
  8268. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8269. sa->sin6.sin6_port = htons((uint16_t)port);
  8270. ip_ver = 6;
  8271. } else if (host[0] == '[') {
  8272. /* While getaddrinfo on Windows will work with [::1],
  8273. * getaddrinfo on Linux only works with ::1 (without []). */
  8274. size_t l = strlen(host + 1);
  8275. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8276. if (h) {
  8277. h[l - 1] = 0;
  8278. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8279. sa->sin6.sin6_port = htons((uint16_t)port);
  8280. ip_ver = 6;
  8281. }
  8282. mg_free(h);
  8283. }
  8284. #endif
  8285. }
  8286. if (ip_ver == 0) {
  8287. if (error != NULL) {
  8288. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8289. mg_snprintf(NULL,
  8290. NULL, /* No truncation check for ebuf */
  8291. error->text,
  8292. error->text_buffer_size,
  8293. "%s",
  8294. "host not found");
  8295. }
  8296. return 0;
  8297. }
  8298. if (ip_ver == 4) {
  8299. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8300. }
  8301. #if defined(USE_IPV6)
  8302. else if (ip_ver == 6) {
  8303. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8304. }
  8305. #endif
  8306. #if defined(USE_X_DOM_SOCKET)
  8307. else if (ip_ver == -99) {
  8308. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8309. }
  8310. #endif
  8311. if (*sock == INVALID_SOCKET) {
  8312. if (error != NULL) {
  8313. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8314. error->code_sub = (unsigned)ERRNO;
  8315. mg_snprintf(NULL,
  8316. NULL, /* No truncation check for ebuf */
  8317. error->text,
  8318. error->text_buffer_size,
  8319. "socket(): %s",
  8320. strerror(ERRNO));
  8321. }
  8322. return 0;
  8323. }
  8324. if (0 != set_non_blocking_mode(*sock)) {
  8325. if (error != NULL) {
  8326. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8327. error->code_sub = (unsigned)ERRNO;
  8328. mg_snprintf(NULL,
  8329. NULL, /* No truncation check for ebuf */
  8330. error->text,
  8331. error->text_buffer_size,
  8332. "Cannot set socket to non-blocking: %s",
  8333. strerror(ERRNO));
  8334. }
  8335. closesocket(*sock);
  8336. *sock = INVALID_SOCKET;
  8337. return 0;
  8338. }
  8339. set_close_on_exec(*sock, NULL, ctx);
  8340. if (ip_ver == 4) {
  8341. /* connected with IPv4 */
  8342. conn_ret = connect(*sock,
  8343. (struct sockaddr *)((void *)&sa->sin),
  8344. sizeof(sa->sin));
  8345. }
  8346. #if defined(USE_IPV6)
  8347. else if (ip_ver == 6) {
  8348. /* connected with IPv6 */
  8349. conn_ret = connect(*sock,
  8350. (struct sockaddr *)((void *)&sa->sin6),
  8351. sizeof(sa->sin6));
  8352. }
  8353. #endif
  8354. #if defined(USE_X_DOM_SOCKET)
  8355. else if (ip_ver == -99) {
  8356. /* connected to domain socket */
  8357. conn_ret = connect(*sock,
  8358. (struct sockaddr *)((void *)&sa->sun),
  8359. sizeof(sa->sun));
  8360. }
  8361. #endif
  8362. if (conn_ret != 0) {
  8363. sockerr = ERRNO;
  8364. }
  8365. #if defined(_WIN32)
  8366. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8367. #else
  8368. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8369. #endif
  8370. /* Data for getsockopt */
  8371. void *psockerr = &sockerr;
  8372. int ret;
  8373. #if defined(_WIN32)
  8374. int len = (int)sizeof(sockerr);
  8375. #else
  8376. socklen_t len = (socklen_t)sizeof(sockerr);
  8377. #endif
  8378. /* Data for poll */
  8379. struct mg_pollfd pfd[2];
  8380. int pollres;
  8381. int ms_wait = 10000; /* 10 second timeout */
  8382. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8383. unsigned int num_sock = 1; /* use one or two sockets */
  8384. /* For a non-blocking socket, the connect sequence is:
  8385. * 1) call connect (will not block)
  8386. * 2) wait until the socket is ready for writing (select or poll)
  8387. * 3) check connection state with getsockopt
  8388. */
  8389. pfd[0].fd = *sock;
  8390. pfd[0].events = POLLOUT;
  8391. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  8392. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  8393. pfd[num_sock].events = POLLIN;
  8394. num_sock++;
  8395. }
  8396. pollres =
  8397. mg_poll(pfd, num_sock, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8398. if (pollres != 1) {
  8399. /* Not connected */
  8400. if (error != NULL) {
  8401. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8402. mg_snprintf(NULL,
  8403. NULL, /* No truncation check for ebuf */
  8404. error->text,
  8405. error->text_buffer_size,
  8406. "connect(%s:%d): timeout",
  8407. host,
  8408. port);
  8409. }
  8410. closesocket(*sock);
  8411. *sock = INVALID_SOCKET;
  8412. return 0;
  8413. }
  8414. #if defined(_WIN32)
  8415. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8416. #else
  8417. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8418. #endif
  8419. if ((ret == 0) && (sockerr == 0)) {
  8420. conn_ret = 0;
  8421. }
  8422. }
  8423. if (conn_ret != 0) {
  8424. /* Not connected */
  8425. if (error != NULL) {
  8426. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8427. error->code_sub = (unsigned)ERRNO;
  8428. mg_snprintf(NULL,
  8429. NULL, /* No truncation check for ebuf */
  8430. error->text,
  8431. error->text_buffer_size,
  8432. "connect(%s:%d): error %s",
  8433. host,
  8434. port,
  8435. strerror(sockerr));
  8436. }
  8437. closesocket(*sock);
  8438. *sock = INVALID_SOCKET;
  8439. return 0;
  8440. }
  8441. return 1;
  8442. }
  8443. CIVETWEB_API int
  8444. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8445. {
  8446. static const char *dont_escape = "._-$,;~()";
  8447. static const char *hex = "0123456789abcdef";
  8448. char *pos = dst;
  8449. const char *end = dst + dst_len - 1;
  8450. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8451. if (isalnum((unsigned char)*src)
  8452. || (strchr(dont_escape, *src) != NULL)) {
  8453. *pos = *src;
  8454. } else if (pos + 2 < end) {
  8455. pos[0] = '%';
  8456. pos[1] = hex[(unsigned char)*src >> 4];
  8457. pos[2] = hex[(unsigned char)*src & 0xf];
  8458. pos += 2;
  8459. } else {
  8460. break;
  8461. }
  8462. }
  8463. *pos = '\0';
  8464. return (*src == '\0') ? (int)(pos - dst) : -1;
  8465. }
  8466. /* Return 0 on success, non-zero if an error occurs. */
  8467. static int
  8468. print_dir_entry(struct mg_connection *conn, struct de *de)
  8469. {
  8470. size_t namesize, escsize, i;
  8471. char *href, *esc, *p;
  8472. char size[64], mod[64];
  8473. #if defined(REENTRANT_TIME)
  8474. struct tm _tm;
  8475. struct tm *tm = &_tm;
  8476. #else
  8477. struct tm *tm;
  8478. #endif
  8479. /* Estimate worst case size for encoding and escaping */
  8480. namesize = strlen(de->file_name) + 1;
  8481. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8482. href = (char *)mg_malloc(namesize * 3 + escsize);
  8483. if (href == NULL) {
  8484. return -1;
  8485. }
  8486. mg_url_encode(de->file_name, href, namesize * 3);
  8487. esc = NULL;
  8488. if (escsize > 0) {
  8489. /* HTML escaping needed */
  8490. esc = href + namesize * 3;
  8491. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8492. mg_strlcpy(p, de->file_name + i, 2);
  8493. if (*p == '&') {
  8494. strcpy(p, "&amp;");
  8495. } else if (*p == '<') {
  8496. strcpy(p, "&lt;");
  8497. } else if (*p == '>') {
  8498. strcpy(p, "&gt;");
  8499. }
  8500. }
  8501. }
  8502. if (de->file.is_directory) {
  8503. mg_snprintf(conn,
  8504. NULL, /* Buffer is big enough */
  8505. size,
  8506. sizeof(size),
  8507. "%s",
  8508. "[DIRECTORY]");
  8509. } else {
  8510. /* We use (signed) cast below because MSVC 6 compiler cannot
  8511. * convert unsigned __int64 to double. Sigh. */
  8512. if (de->file.size < 1024) {
  8513. mg_snprintf(conn,
  8514. NULL, /* Buffer is big enough */
  8515. size,
  8516. sizeof(size),
  8517. "%d",
  8518. (int)de->file.size);
  8519. } else if (de->file.size < 0x100000) {
  8520. mg_snprintf(conn,
  8521. NULL, /* Buffer is big enough */
  8522. size,
  8523. sizeof(size),
  8524. "%.1fk",
  8525. (double)de->file.size / 1024.0);
  8526. } else if (de->file.size < 0x40000000) {
  8527. mg_snprintf(conn,
  8528. NULL, /* Buffer is big enough */
  8529. size,
  8530. sizeof(size),
  8531. "%.1fM",
  8532. (double)de->file.size / 1048576);
  8533. } else {
  8534. mg_snprintf(conn,
  8535. NULL, /* Buffer is big enough */
  8536. size,
  8537. sizeof(size),
  8538. "%.1fG",
  8539. (double)de->file.size / 1073741824);
  8540. }
  8541. }
  8542. /* Note: mg_snprintf will not cause a buffer overflow above.
  8543. * So, string truncation checks are not required here. */
  8544. #if defined(REENTRANT_TIME)
  8545. localtime_r(&de->file.last_modified, tm);
  8546. #else
  8547. tm = localtime(&de->file.last_modified);
  8548. #endif
  8549. if (tm != NULL) {
  8550. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8551. } else {
  8552. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8553. }
  8554. mg_printf(conn,
  8555. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8556. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8557. href,
  8558. de->file.is_directory ? "/" : "",
  8559. esc ? esc : de->file_name,
  8560. de->file.is_directory ? "/" : "",
  8561. mod,
  8562. size);
  8563. mg_free(href);
  8564. return 0;
  8565. }
  8566. /* This function is called from send_directory() and used for
  8567. * sorting directory entries by size, name, or modification time. */
  8568. static int
  8569. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8570. {
  8571. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8572. if (p1 && p2) {
  8573. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8574. int cmp_result = 0;
  8575. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8576. query_string = "n";
  8577. }
  8578. /* Sort Directories vs Files */
  8579. if (a->file.is_directory && !b->file.is_directory) {
  8580. return -1; /* Always put directories on top */
  8581. } else if (!a->file.is_directory && b->file.is_directory) {
  8582. return 1; /* Always put directories on top */
  8583. }
  8584. /* Sort by size or date */
  8585. if (*query_string == 's') {
  8586. cmp_result = (a->file.size == b->file.size)
  8587. ? 0
  8588. : ((a->file.size > b->file.size) ? 1 : -1);
  8589. } else if (*query_string == 'd') {
  8590. cmp_result =
  8591. (a->file.last_modified == b->file.last_modified)
  8592. ? 0
  8593. : ((a->file.last_modified > b->file.last_modified) ? 1
  8594. : -1);
  8595. }
  8596. /* Sort by name:
  8597. * if (*query_string == 'n') ...
  8598. * but also sort files of same size/date by name as secondary criterion.
  8599. */
  8600. if (cmp_result == 0) {
  8601. cmp_result = strcmp(a->file_name, b->file_name);
  8602. }
  8603. /* For descending order, invert result */
  8604. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8605. }
  8606. return 0;
  8607. }
  8608. static int
  8609. must_hide_file(struct mg_connection *conn, const char *path)
  8610. {
  8611. if (conn && conn->dom_ctx) {
  8612. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8613. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8614. return (match_prefix_strlen(pw_pattern, path) > 0)
  8615. || (match_prefix_strlen(pattern, path) > 0);
  8616. }
  8617. return 0;
  8618. }
  8619. #if !defined(NO_FILESYSTEMS)
  8620. static int
  8621. scan_directory(struct mg_connection *conn,
  8622. const char *dir,
  8623. void *data,
  8624. int (*cb)(struct de *, void *))
  8625. {
  8626. char path[UTF8_PATH_MAX];
  8627. struct dirent *dp;
  8628. DIR *dirp;
  8629. struct de de;
  8630. int truncated;
  8631. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8632. return 0;
  8633. } else {
  8634. while ((dp = mg_readdir(dirp)) != NULL) {
  8635. /* Do not show current dir and hidden files */
  8636. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8637. || must_hide_file(conn, dp->d_name)) {
  8638. continue;
  8639. }
  8640. mg_snprintf(
  8641. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8642. /* If we don't memset stat structure to zero, mtime will have
  8643. * garbage and strftime() will segfault later on in
  8644. * print_dir_entry(). memset is required only if mg_stat()
  8645. * fails. For more details, see
  8646. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8647. memset(&de.file, 0, sizeof(de.file));
  8648. if (truncated) {
  8649. /* If the path is not complete, skip processing. */
  8650. continue;
  8651. }
  8652. if (!mg_stat(conn, path, &de.file)) {
  8653. mg_cry_internal(conn,
  8654. "%s: mg_stat(%s) failed: %s",
  8655. __func__,
  8656. path,
  8657. strerror(ERRNO));
  8658. }
  8659. de.file_name = dp->d_name;
  8660. if (cb(&de, data)) {
  8661. /* stopped */
  8662. break;
  8663. }
  8664. }
  8665. (void)mg_closedir(dirp);
  8666. }
  8667. return 1;
  8668. }
  8669. #endif /* NO_FILESYSTEMS */
  8670. #if !defined(NO_FILES)
  8671. static int
  8672. remove_directory(struct mg_connection *conn, const char *dir)
  8673. {
  8674. char path[UTF8_PATH_MAX];
  8675. struct dirent *dp;
  8676. DIR *dirp;
  8677. struct de de;
  8678. int truncated;
  8679. int ok = 1;
  8680. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8681. return 0;
  8682. } else {
  8683. while ((dp = mg_readdir(dirp)) != NULL) {
  8684. /* Do not show current dir (but show hidden files as they will
  8685. * also be removed) */
  8686. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8687. continue;
  8688. }
  8689. mg_snprintf(
  8690. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8691. /* If we don't memset stat structure to zero, mtime will have
  8692. * garbage and strftime() will segfault later on in
  8693. * print_dir_entry(). memset is required only if mg_stat()
  8694. * fails. For more details, see
  8695. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8696. memset(&de.file, 0, sizeof(de.file));
  8697. if (truncated) {
  8698. /* Do not delete anything shorter */
  8699. ok = 0;
  8700. continue;
  8701. }
  8702. if (!mg_stat(conn, path, &de.file)) {
  8703. mg_cry_internal(conn,
  8704. "%s: mg_stat(%s) failed: %s",
  8705. __func__,
  8706. path,
  8707. strerror(ERRNO));
  8708. ok = 0;
  8709. }
  8710. if (de.file.is_directory) {
  8711. if (remove_directory(conn, path) == 0) {
  8712. ok = 0;
  8713. }
  8714. } else {
  8715. /* This will fail file is the file is in memory */
  8716. if (mg_remove(conn, path) == 0) {
  8717. ok = 0;
  8718. }
  8719. }
  8720. }
  8721. (void)mg_closedir(dirp);
  8722. IGNORE_UNUSED_RESULT(rmdir(dir));
  8723. }
  8724. return ok;
  8725. }
  8726. #endif
  8727. struct dir_scan_data {
  8728. struct de *entries;
  8729. size_t num_entries;
  8730. size_t arr_size;
  8731. };
  8732. #if !defined(NO_FILESYSTEMS)
  8733. static int
  8734. dir_scan_callback(struct de *de, void *data)
  8735. {
  8736. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8737. struct de *entries = dsd->entries;
  8738. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8739. /* Here "entries" is a temporary pointer and can be replaced,
  8740. * "dsd->entries" is the original pointer */
  8741. entries =
  8742. (struct de *)mg_realloc(entries,
  8743. dsd->arr_size * 2 * sizeof(entries[0]));
  8744. if (entries == NULL) {
  8745. /* stop scan */
  8746. return 1;
  8747. }
  8748. dsd->entries = entries;
  8749. dsd->arr_size *= 2;
  8750. }
  8751. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8752. if (entries[dsd->num_entries].file_name == NULL) {
  8753. /* stop scan */
  8754. return 1;
  8755. }
  8756. entries[dsd->num_entries].file = de->file;
  8757. dsd->num_entries++;
  8758. return 0;
  8759. }
  8760. static void
  8761. handle_directory_request(struct mg_connection *conn, const char *dir)
  8762. {
  8763. size_t i;
  8764. int sort_direction;
  8765. struct dir_scan_data data = {NULL, 0, 128};
  8766. char date[64], *esc, *p;
  8767. const char *title;
  8768. time_t curtime = time(NULL);
  8769. if (!conn) {
  8770. return;
  8771. }
  8772. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8773. mg_send_http_error(conn,
  8774. 500,
  8775. "Error: Cannot open directory\nopendir(%s): %s",
  8776. dir,
  8777. strerror(ERRNO));
  8778. return;
  8779. }
  8780. gmt_time_string(date, sizeof(date), &curtime);
  8781. esc = NULL;
  8782. title = conn->request_info.local_uri;
  8783. if (title[strcspn(title, "&<>")]) {
  8784. /* HTML escaping needed */
  8785. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8786. if (esc) {
  8787. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8788. mg_strlcpy(p, title + i, 2);
  8789. if (*p == '&') {
  8790. strcpy(p, "&amp;");
  8791. } else if (*p == '<') {
  8792. strcpy(p, "&lt;");
  8793. } else if (*p == '>') {
  8794. strcpy(p, "&gt;");
  8795. }
  8796. }
  8797. } else {
  8798. title = "";
  8799. }
  8800. }
  8801. sort_direction = ((conn->request_info.query_string != NULL)
  8802. && (conn->request_info.query_string[0] != '\0')
  8803. && (conn->request_info.query_string[1] == 'd'))
  8804. ? 'a'
  8805. : 'd';
  8806. conn->must_close = 1;
  8807. /* Create 200 OK response */
  8808. mg_response_header_start(conn, 200);
  8809. send_static_cache_header(conn);
  8810. send_additional_header(conn);
  8811. mg_response_header_add(conn,
  8812. "Content-Type",
  8813. "text/html; charset=utf-8",
  8814. -1);
  8815. /* Send all headers */
  8816. mg_response_header_send(conn);
  8817. /* Body */
  8818. mg_printf(conn,
  8819. "<!DOCTYPE html>"
  8820. "<html><head><title>Index of %s</title>"
  8821. "<style>th {text-align: left;}</style></head>"
  8822. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8823. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8824. "<th><a href=\"?d%c\">Modified</a></th>"
  8825. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8826. "<tr><td colspan=\"3\"><hr></td></tr>",
  8827. esc ? esc : title,
  8828. esc ? esc : title,
  8829. sort_direction,
  8830. sort_direction,
  8831. sort_direction);
  8832. mg_free(esc);
  8833. /* Print first entry - link to a parent directory */
  8834. mg_printf(conn,
  8835. "<tr><td><a href=\"%s\">%s</a></td>"
  8836. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8837. "..",
  8838. "Parent directory",
  8839. "-",
  8840. "-");
  8841. /* Sort and print directory entries */
  8842. if (data.entries != NULL) {
  8843. mg_sort(data.entries,
  8844. data.num_entries,
  8845. sizeof(data.entries[0]),
  8846. compare_dir_entries,
  8847. (void *)conn->request_info.query_string);
  8848. for (i = 0; i < data.num_entries; i++) {
  8849. print_dir_entry(conn, &data.entries[i]);
  8850. mg_free(data.entries[i].file_name);
  8851. }
  8852. mg_free(data.entries);
  8853. }
  8854. mg_printf(conn, "%s", "</table></pre></body></html>");
  8855. conn->status_code = 200;
  8856. }
  8857. #endif /* NO_FILESYSTEMS */
  8858. /* Send len bytes from the opened file to the client. */
  8859. static void
  8860. send_file_data(struct mg_connection *conn,
  8861. struct mg_file *filep,
  8862. int64_t offset,
  8863. int64_t len,
  8864. int no_buffering)
  8865. {
  8866. char buf[MG_BUF_LEN];
  8867. int to_read, num_read, num_written;
  8868. int64_t size;
  8869. if (!filep || !conn) {
  8870. return;
  8871. }
  8872. /* Sanity check the offset */
  8873. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8874. : (int64_t)(filep->stat.size);
  8875. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8876. if (len > 0 && filep->access.fp != NULL) {
  8877. /* file stored on disk */
  8878. #if defined(__linux__)
  8879. /* sendfile is only available for Linux */
  8880. if ((conn->ssl == 0) && (conn->throttle == 0)
  8881. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8882. "yes"))) {
  8883. off_t sf_offs = (off_t)offset;
  8884. ssize_t sf_sent;
  8885. int sf_file = fileno(filep->access.fp);
  8886. int loop_cnt = 0;
  8887. do {
  8888. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8889. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8890. size_t sf_tosend =
  8891. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8892. sf_sent =
  8893. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8894. if (sf_sent > 0) {
  8895. len -= sf_sent;
  8896. offset += sf_sent;
  8897. } else if (loop_cnt == 0) {
  8898. /* This file can not be sent using sendfile.
  8899. * This might be the case for pseudo-files in the
  8900. * /sys/ and /proc/ file system.
  8901. * Use the regular user mode copy code instead. */
  8902. break;
  8903. } else if (sf_sent == 0) {
  8904. /* No error, but 0 bytes sent. May be EOF? */
  8905. return;
  8906. }
  8907. loop_cnt++;
  8908. } while ((len > 0) && (sf_sent >= 0));
  8909. if (sf_sent > 0) {
  8910. return; /* OK */
  8911. }
  8912. /* sf_sent<0 means error, thus fall back to the classic way */
  8913. /* This is always the case, if sf_file is not a "normal" file,
  8914. * e.g., for sending data from the output of a CGI process. */
  8915. offset = (int64_t)sf_offs;
  8916. }
  8917. #endif
  8918. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8919. mg_cry_internal(conn,
  8920. "%s: fseeko() failed: %s",
  8921. __func__,
  8922. strerror(ERRNO));
  8923. mg_send_http_error(
  8924. conn,
  8925. 500,
  8926. "%s",
  8927. "Error: Unable to access file at requested position.");
  8928. } else {
  8929. while (len > 0) {
  8930. /* Calculate how much to read from the file into the buffer. */
  8931. /* If no_buffering is set, we should not wait until the
  8932. * CGI->Server buffer is filled, but send everything
  8933. * immediately. In theory buffering could be turned off using
  8934. * setbuf(filep->access.fp, NULL);
  8935. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8936. * but in practice this does not work. A "Linux only" solution
  8937. * may be to use select(). The only portable way is to read byte
  8938. * by byte, but this is quite inefficient from a performance
  8939. * point of view. */
  8940. to_read = no_buffering ? 1 : sizeof(buf);
  8941. if ((int64_t)to_read > len) {
  8942. to_read = (int)len;
  8943. }
  8944. /* Read from file, exit the loop on error */
  8945. if ((num_read = pull_inner(filep->access.fp,
  8946. NULL,
  8947. buf,
  8948. to_read,
  8949. /* unused */ 0.0))
  8950. <= 0) {
  8951. break;
  8952. }
  8953. /* Send read bytes to the client, exit the loop on error */
  8954. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8955. != num_read) {
  8956. break;
  8957. }
  8958. /* Both read and were successful, adjust counters */
  8959. len -= num_written;
  8960. }
  8961. }
  8962. }
  8963. }
  8964. static int
  8965. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8966. {
  8967. return sscanf(header,
  8968. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8969. a,
  8970. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8971. // to an integer value, but function will not report
  8972. // conversion errors; consider using 'strtol' instead
  8973. }
  8974. static void
  8975. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8976. {
  8977. if ((filestat != NULL) && (buf != NULL)) {
  8978. mg_snprintf(NULL,
  8979. NULL, /* All calls to construct_etag use 64 byte buffer */
  8980. buf,
  8981. buf_len,
  8982. "\"%lx.%" INT64_FMT "\"",
  8983. (unsigned long)filestat->last_modified,
  8984. filestat->size);
  8985. }
  8986. }
  8987. static void
  8988. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8989. {
  8990. if (filep != NULL && filep->fp != NULL) {
  8991. #if defined(_WIN32)
  8992. (void)conn; /* Unused. */
  8993. #else
  8994. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8995. mg_cry_internal(conn,
  8996. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8997. __func__,
  8998. strerror(ERRNO));
  8999. }
  9000. #endif
  9001. }
  9002. }
  9003. #if defined(USE_ZLIB)
  9004. #include "mod_zlib.inl"
  9005. #endif
  9006. #if !defined(NO_FILESYSTEMS)
  9007. static void
  9008. handle_static_file_request(struct mg_connection *conn,
  9009. const char *path,
  9010. struct mg_file *filep,
  9011. const char *mime_type,
  9012. const char *additional_headers)
  9013. {
  9014. char lm[64], etag[64];
  9015. char range[128]; /* large enough, so there will be no overflow */
  9016. const char *range_hdr;
  9017. int64_t cl, r1, r2;
  9018. struct vec mime_vec;
  9019. int n, truncated;
  9020. char gz_path[UTF8_PATH_MAX];
  9021. const char *encoding = 0;
  9022. int is_head_request;
  9023. #if defined(USE_ZLIB)
  9024. /* Compression is allowed, unless there is a reason not to use
  9025. * compression. If the file is already compressed, too small or a
  9026. * "range" request was made, on the fly compression is not possible. */
  9027. int allow_on_the_fly_compression = 1;
  9028. #endif
  9029. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  9030. return;
  9031. }
  9032. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  9033. if (mime_type == NULL) {
  9034. get_mime_type(conn, path, &mime_vec);
  9035. } else {
  9036. mime_vec.ptr = mime_type;
  9037. mime_vec.len = strlen(mime_type);
  9038. }
  9039. if (filep->stat.size > INT64_MAX) {
  9040. mg_send_http_error(conn,
  9041. 500,
  9042. "Error: File size is too large to send\n%" INT64_FMT,
  9043. filep->stat.size);
  9044. return;
  9045. }
  9046. cl = (int64_t)filep->stat.size;
  9047. conn->status_code = 200;
  9048. range[0] = '\0';
  9049. #if defined(USE_ZLIB)
  9050. /* if this file is in fact a pre-gzipped file, rewrite its filename
  9051. * it's important to rewrite the filename after resolving
  9052. * the mime type from it, to preserve the actual file's type */
  9053. if (!conn->accept_gzip) {
  9054. allow_on_the_fly_compression = 0;
  9055. }
  9056. #endif
  9057. /* Check if there is a range header */
  9058. range_hdr = mg_get_header(conn, "Range");
  9059. /* For gzipped files, add *.gz */
  9060. if (filep->stat.is_gzipped) {
  9061. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9062. if (truncated) {
  9063. mg_send_http_error(conn,
  9064. 500,
  9065. "Error: Path of zipped file too long (%s)",
  9066. path);
  9067. return;
  9068. }
  9069. path = gz_path;
  9070. encoding = "gzip";
  9071. #if defined(USE_ZLIB)
  9072. /* File is already compressed. No "on the fly" compression. */
  9073. allow_on_the_fly_compression = 0;
  9074. #endif
  9075. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  9076. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  9077. struct mg_file_stat file_stat;
  9078. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9079. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  9080. && !file_stat.is_directory) {
  9081. file_stat.is_gzipped = 1;
  9082. filep->stat = file_stat;
  9083. cl = (int64_t)filep->stat.size;
  9084. path = gz_path;
  9085. encoding = "gzip";
  9086. #if defined(USE_ZLIB)
  9087. /* File is already compressed. No "on the fly" compression. */
  9088. allow_on_the_fly_compression = 0;
  9089. #endif
  9090. }
  9091. }
  9092. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9093. mg_send_http_error(conn,
  9094. 500,
  9095. "Error: Cannot open file\nfopen(%s): %s",
  9096. path,
  9097. strerror(ERRNO));
  9098. return;
  9099. }
  9100. fclose_on_exec(&filep->access, conn);
  9101. /* If "Range" request was made: parse header, send only selected part
  9102. * of the file. */
  9103. r1 = r2 = 0;
  9104. if ((range_hdr != NULL)
  9105. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  9106. && (r2 >= 0)) {
  9107. /* actually, range requests don't play well with a pre-gzipped
  9108. * file (since the range is specified in the uncompressed space) */
  9109. if (filep->stat.is_gzipped) {
  9110. mg_send_http_error(
  9111. conn,
  9112. 416, /* 416 = Range Not Satisfiable */
  9113. "%s",
  9114. "Error: Range requests in gzipped files are not supported");
  9115. (void)mg_fclose(
  9116. &filep->access); /* ignore error on read only file */
  9117. return;
  9118. }
  9119. conn->status_code = 206;
  9120. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  9121. mg_snprintf(conn,
  9122. NULL, /* range buffer is big enough */
  9123. range,
  9124. sizeof(range),
  9125. "bytes "
  9126. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  9127. r1,
  9128. r1 + cl - 1,
  9129. filep->stat.size);
  9130. #if defined(USE_ZLIB)
  9131. /* Do not compress ranges. */
  9132. allow_on_the_fly_compression = 0;
  9133. #endif
  9134. }
  9135. /* Do not compress small files. Small files do not benefit from file
  9136. * compression, but there is still some overhead. */
  9137. #if defined(USE_ZLIB)
  9138. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  9139. /* File is below the size limit. */
  9140. allow_on_the_fly_compression = 0;
  9141. }
  9142. #endif
  9143. /* Prepare Etag, and Last-Modified headers. */
  9144. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9145. construct_etag(etag, sizeof(etag), &filep->stat);
  9146. /* Create 2xx (200, 206) response */
  9147. mg_response_header_start(conn, conn->status_code);
  9148. send_static_cache_header(conn);
  9149. send_additional_header(conn);
  9150. send_cors_header(conn);
  9151. mg_response_header_add(conn,
  9152. "Content-Type",
  9153. mime_vec.ptr,
  9154. (int)mime_vec.len);
  9155. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9156. mg_response_header_add(conn, "Etag", etag, -1);
  9157. #if defined(USE_ZLIB)
  9158. /* On the fly compression allowed */
  9159. if (allow_on_the_fly_compression) {
  9160. /* For on the fly compression, we don't know the content size in
  9161. * advance, so we have to use chunked encoding */
  9162. encoding = "gzip";
  9163. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9164. /* HTTP/2 is always using "chunks" (frames) */
  9165. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9166. }
  9167. } else
  9168. #endif
  9169. {
  9170. /* Without on-the-fly compression, we know the content-length
  9171. * and we can use ranges (with on-the-fly compression we cannot).
  9172. * So we send these response headers only in this case. */
  9173. char len[32];
  9174. int trunc = 0;
  9175. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9176. if (!trunc) {
  9177. mg_response_header_add(conn, "Content-Length", len, -1);
  9178. }
  9179. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9180. }
  9181. if (encoding) {
  9182. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9183. }
  9184. if (range[0] != 0) {
  9185. mg_response_header_add(conn, "Content-Range", range, -1);
  9186. }
  9187. /* The code above does not add any header starting with X- to make
  9188. * sure no one of the additional_headers is included twice */
  9189. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9190. mg_response_header_add_lines(conn, additional_headers);
  9191. }
  9192. /* Send all headers */
  9193. mg_response_header_send(conn);
  9194. if (!is_head_request) {
  9195. #if defined(USE_ZLIB)
  9196. if (allow_on_the_fly_compression) {
  9197. /* Compress and send */
  9198. send_compressed_data(conn, filep);
  9199. } else
  9200. #endif
  9201. {
  9202. /* Send file directly */
  9203. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9204. }
  9205. }
  9206. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9207. }
  9208. CIVETWEB_API int
  9209. mg_send_file_body(struct mg_connection *conn, const char *path)
  9210. {
  9211. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9212. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9213. return -1;
  9214. }
  9215. fclose_on_exec(&file.access, conn);
  9216. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9217. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9218. return 0; /* >= 0 for OK */
  9219. }
  9220. #endif /* NO_FILESYSTEMS */
  9221. #if !defined(NO_CACHING)
  9222. /* Return True if we should reply 304 Not Modified. */
  9223. static int
  9224. is_not_modified(const struct mg_connection *conn,
  9225. const struct mg_file_stat *filestat)
  9226. {
  9227. char etag[64];
  9228. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9229. const char *inm = mg_get_header(conn, "If-None-Match");
  9230. construct_etag(etag, sizeof(etag), filestat);
  9231. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9232. || ((ims != NULL)
  9233. && (filestat->last_modified <= parse_date_string(ims)));
  9234. }
  9235. static void
  9236. handle_not_modified_static_file_request(struct mg_connection *conn,
  9237. struct mg_file *filep)
  9238. {
  9239. char lm[64], etag[64];
  9240. if ((conn == NULL) || (filep == NULL)) {
  9241. return;
  9242. }
  9243. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9244. construct_etag(etag, sizeof(etag), &filep->stat);
  9245. /* Create 304 "not modified" response */
  9246. mg_response_header_start(conn, 304);
  9247. send_static_cache_header(conn);
  9248. send_additional_header(conn);
  9249. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9250. mg_response_header_add(conn, "Etag", etag, -1);
  9251. /* Send all headers */
  9252. mg_response_header_send(conn);
  9253. }
  9254. #endif
  9255. #if !defined(NO_FILESYSTEMS)
  9256. CIVETWEB_API void
  9257. mg_send_file(struct mg_connection *conn, const char *path)
  9258. {
  9259. mg_send_mime_file2(conn, path, NULL, NULL);
  9260. }
  9261. CIVETWEB_API void
  9262. mg_send_mime_file(struct mg_connection *conn,
  9263. const char *path,
  9264. const char *mime_type)
  9265. {
  9266. mg_send_mime_file2(conn, path, mime_type, NULL);
  9267. }
  9268. CIVETWEB_API void
  9269. mg_send_mime_file2(struct mg_connection *conn,
  9270. const char *path,
  9271. const char *mime_type,
  9272. const char *additional_headers)
  9273. {
  9274. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9275. if (!conn) {
  9276. /* No conn */
  9277. return;
  9278. }
  9279. if (mg_stat(conn, path, &file.stat)) {
  9280. #if !defined(NO_CACHING)
  9281. if (is_not_modified(conn, &file.stat)) {
  9282. /* Send 304 "Not Modified" - this must not send any body data */
  9283. handle_not_modified_static_file_request(conn, &file);
  9284. } else
  9285. #endif /* NO_CACHING */
  9286. if (file.stat.is_directory) {
  9287. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9288. "yes")) {
  9289. handle_directory_request(conn, path);
  9290. } else {
  9291. mg_send_http_error(conn,
  9292. 403,
  9293. "%s",
  9294. "Error: Directory listing denied");
  9295. }
  9296. } else {
  9297. handle_static_file_request(
  9298. conn, path, &file, mime_type, additional_headers);
  9299. }
  9300. } else {
  9301. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9302. }
  9303. }
  9304. /* For a given PUT path, create all intermediate subdirectories.
  9305. * Return 0 if the path itself is a directory.
  9306. * Return 1 if the path leads to a file.
  9307. * Return -1 for if the path is too long.
  9308. * Return -2 if path can not be created.
  9309. */
  9310. static int
  9311. put_dir(struct mg_connection *conn, const char *path)
  9312. {
  9313. char buf[UTF8_PATH_MAX];
  9314. const char *s, *p;
  9315. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9316. size_t len;
  9317. int res = 1;
  9318. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9319. len = (size_t)(p - path);
  9320. if (len >= sizeof(buf)) {
  9321. /* path too long */
  9322. res = -1;
  9323. break;
  9324. }
  9325. memcpy(buf, path, len);
  9326. buf[len] = '\0';
  9327. /* Try to create intermediate directory */
  9328. DEBUG_TRACE("mkdir(%s)", buf);
  9329. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9330. /* path does not exist and can not be created */
  9331. res = -2;
  9332. break;
  9333. }
  9334. /* Is path itself a directory? */
  9335. if (p[1] == '\0') {
  9336. res = 0;
  9337. }
  9338. }
  9339. return res;
  9340. }
  9341. static void
  9342. remove_bad_file(const struct mg_connection *conn, const char *path)
  9343. {
  9344. int r = mg_remove(conn, path);
  9345. if (r != 0) {
  9346. mg_cry_internal(conn,
  9347. "%s: Cannot remove invalid file %s",
  9348. __func__,
  9349. path);
  9350. }
  9351. }
  9352. CIVETWEB_API long long
  9353. mg_store_body(struct mg_connection *conn, const char *path)
  9354. {
  9355. char buf[MG_BUF_LEN];
  9356. long long len = 0;
  9357. int ret, n;
  9358. struct mg_file fi;
  9359. if (conn->consumed_content != 0) {
  9360. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9361. return -11;
  9362. }
  9363. ret = put_dir(conn, path);
  9364. if (ret < 0) {
  9365. /* -1 for path too long,
  9366. * -2 for path can not be created. */
  9367. return ret;
  9368. }
  9369. if (ret != 1) {
  9370. /* Return 0 means, path itself is a directory. */
  9371. return 0;
  9372. }
  9373. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9374. return -12;
  9375. }
  9376. ret = mg_read(conn, buf, sizeof(buf));
  9377. while (ret > 0) {
  9378. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9379. if (n != ret) {
  9380. (void)mg_fclose(
  9381. &fi.access); /* File is bad and will be removed anyway. */
  9382. remove_bad_file(conn, path);
  9383. return -13;
  9384. }
  9385. len += ret;
  9386. ret = mg_read(conn, buf, sizeof(buf));
  9387. }
  9388. /* File is open for writing. If fclose fails, there was probably an
  9389. * error flushing the buffer to disk, so the file on disk might be
  9390. * broken. Delete it and return an error to the caller. */
  9391. if (mg_fclose(&fi.access) != 0) {
  9392. remove_bad_file(conn, path);
  9393. return -14;
  9394. }
  9395. return len;
  9396. }
  9397. #endif /* NO_FILESYSTEMS */
  9398. /* Parse a buffer:
  9399. * Forward the string pointer till the end of a word, then
  9400. * terminate it and forward till the begin of the next word.
  9401. */
  9402. static int
  9403. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9404. {
  9405. /* Forward until a space is found - use isgraph here */
  9406. /* Extended ASCII characters are also treated as word characters. */
  9407. /* See http://www.cplusplus.com/reference/cctype/ */
  9408. while ((unsigned char)**ppw > 127 || isgraph((unsigned char)**ppw)) {
  9409. (*ppw)++;
  9410. }
  9411. /* Check end of word */
  9412. if (eol) {
  9413. /* must be a end of line */
  9414. if ((**ppw != '\r') && (**ppw != '\n')) {
  9415. return -1;
  9416. }
  9417. } else {
  9418. /* must be a end of a word, but not a line */
  9419. if (**ppw != ' ') {
  9420. return -1;
  9421. }
  9422. }
  9423. /* Terminate and forward to the next word */
  9424. do {
  9425. **ppw = 0;
  9426. (*ppw)++;
  9427. } while (isspace((unsigned char)**ppw));
  9428. /* Check after term */
  9429. if (!eol) {
  9430. /* if it's not the end of line, there must be a next word */
  9431. if (!isgraph((unsigned char)**ppw)) {
  9432. return -1;
  9433. }
  9434. }
  9435. /* ok */
  9436. return 1;
  9437. }
  9438. /* Parse HTTP headers from the given buffer, advance buf pointer
  9439. * to the point where parsing stopped.
  9440. * All parameters must be valid pointers (not NULL).
  9441. * Return <0 on error. */
  9442. static int
  9443. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9444. {
  9445. int i;
  9446. int num_headers = 0;
  9447. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9448. char *dp = *buf;
  9449. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9450. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9451. dp++;
  9452. }
  9453. if (dp == *buf) {
  9454. /* End of headers reached. */
  9455. break;
  9456. }
  9457. /* Drop all spaces after header name before : */
  9458. while (*dp == ' ') {
  9459. *dp = 0;
  9460. dp++;
  9461. }
  9462. if (*dp != ':') {
  9463. /* This is not a valid field. */
  9464. return -1;
  9465. }
  9466. /* End of header key (*dp == ':') */
  9467. /* Truncate here and set the key name */
  9468. *dp = 0;
  9469. hdr[i].name = *buf;
  9470. /* Skip all spaces */
  9471. do {
  9472. dp++;
  9473. } while ((*dp == ' ') || (*dp == '\t'));
  9474. /* The rest of the line is the value */
  9475. hdr[i].value = dp;
  9476. /* Find end of line */
  9477. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9478. dp++;
  9479. };
  9480. /* eliminate \r */
  9481. if (*dp == '\r') {
  9482. *dp = 0;
  9483. dp++;
  9484. if (*dp != '\n') {
  9485. /* This is not a valid line. */
  9486. return -1;
  9487. }
  9488. }
  9489. /* here *dp is either 0 or '\n' */
  9490. /* in any case, we have found a complete header */
  9491. num_headers = i + 1;
  9492. if (*dp) {
  9493. *dp = 0;
  9494. dp++;
  9495. *buf = dp;
  9496. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9497. /* We've had CRLF twice in a row
  9498. * This is the end of the headers */
  9499. break;
  9500. }
  9501. /* continue within the loop, find the next header */
  9502. } else {
  9503. *buf = dp;
  9504. break;
  9505. }
  9506. }
  9507. return num_headers;
  9508. }
  9509. struct mg_http_method_info {
  9510. const char *name;
  9511. int request_has_body;
  9512. int response_has_body;
  9513. int is_safe;
  9514. int is_idempotent;
  9515. int is_cacheable;
  9516. };
  9517. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9518. static const struct mg_http_method_info http_methods[] = {
  9519. /* HTTP (RFC 2616) */
  9520. {"GET", 0, 1, 1, 1, 1},
  9521. {"POST", 1, 1, 0, 0, 0},
  9522. {"PUT", 1, 0, 0, 1, 0},
  9523. {"DELETE", 0, 0, 0, 1, 0},
  9524. {"HEAD", 0, 0, 1, 1, 1},
  9525. {"OPTIONS", 0, 0, 1, 1, 0},
  9526. {"CONNECT", 1, 1, 0, 0, 0},
  9527. /* TRACE method (RFC 2616) is not supported for security reasons */
  9528. /* PATCH method (RFC 5789) */
  9529. {"PATCH", 1, 0, 0, 0, 0},
  9530. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9531. /* WEBDAV (RFC 2518) */
  9532. {"PROPFIND", 0, 1, 1, 1, 0},
  9533. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9534. * Some PROPFIND results MAY be cached, with care,
  9535. * as there is no cache validation mechanism for
  9536. * most properties. This method is both safe and
  9537. * idempotent (see Section 9.1 of [RFC2616]). */
  9538. {"MKCOL", 0, 0, 0, 1, 0},
  9539. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9540. * When MKCOL is invoked without a request body,
  9541. * the newly created collection SHOULD have no
  9542. * members. A MKCOL request message may contain
  9543. * a message body. The precise behavior of a MKCOL
  9544. * request when the body is present is undefined,
  9545. * ... ==> We do not support MKCOL with body data.
  9546. * This method is idempotent, but not safe (see
  9547. * Section 9.1 of [RFC2616]). Responses to this
  9548. * method MUST NOT be cached. */
  9549. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9550. {"LOCK", 1, 1, 0, 0, 0},
  9551. {"UNLOCK", 1, 0, 0, 0, 0},
  9552. {"PROPPATCH", 1, 1, 0, 0, 0},
  9553. {"COPY", 1, 0, 0, 0, 0},
  9554. {"MOVE", 1, 1, 0, 0, 0},
  9555. /* Unsupported WEBDAV Methods: */
  9556. /* + 11 methods from RFC 3253 */
  9557. /* ORDERPATCH (RFC 3648) */
  9558. /* ACL (RFC 3744) */
  9559. /* SEARCH (RFC 5323) */
  9560. /* + MicroSoft extensions
  9561. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9562. /* REPORT method (RFC 3253) */
  9563. {"REPORT", 1, 1, 1, 1, 1},
  9564. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9565. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9566. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9567. * to be useful for REST in case a "GET request with body" is
  9568. * required. */
  9569. {NULL, 0, 0, 0, 0, 0}
  9570. /* end of list */
  9571. };
  9572. /* All method names */
  9573. static char *all_methods = NULL; /* Built by mg_init_library */
  9574. static const struct mg_http_method_info *
  9575. get_http_method_info(const char *method)
  9576. {
  9577. /* Check if the method is known to the server. The list of all known
  9578. * HTTP methods can be found here at
  9579. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9580. */
  9581. const struct mg_http_method_info *m = http_methods;
  9582. while (m->name) {
  9583. if (!strcmp(m->name, method)) {
  9584. return m;
  9585. }
  9586. m++;
  9587. }
  9588. return NULL;
  9589. }
  9590. static int
  9591. is_valid_http_method(const char *method)
  9592. {
  9593. return (get_http_method_info(method) != NULL);
  9594. }
  9595. /* Parse HTTP request, fill in mg_request_info structure.
  9596. * This function modifies the buffer by NUL-terminating
  9597. * HTTP request components, header names and header values.
  9598. * Parameters:
  9599. * buf (in/out): pointer to the HTTP header to parse and split
  9600. * len (in): length of HTTP header buffer
  9601. * re (out): parsed header as mg_request_info
  9602. * buf and ri must be valid pointers (not NULL), len>0.
  9603. * Returns <0 on error. */
  9604. static int
  9605. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9606. {
  9607. int request_length;
  9608. int init_skip = 0;
  9609. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9610. * remote_port */
  9611. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9612. NULL;
  9613. ri->num_headers = 0;
  9614. /* RFC says that all initial whitespaces should be ignored */
  9615. /* This included all leading \r and \n (isspace) */
  9616. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9617. while ((len > 0) && isspace((unsigned char)*buf)) {
  9618. buf++;
  9619. len--;
  9620. init_skip++;
  9621. }
  9622. if (len == 0) {
  9623. /* Incomplete request */
  9624. return 0;
  9625. }
  9626. /* Control characters are not allowed, including zero */
  9627. if (iscntrl((unsigned char)*buf)) {
  9628. return -1;
  9629. }
  9630. /* Find end of HTTP header */
  9631. request_length = get_http_header_len(buf, len);
  9632. if (request_length <= 0) {
  9633. return request_length;
  9634. }
  9635. buf[request_length - 1] = '\0';
  9636. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9637. return -1;
  9638. }
  9639. /* The first word has to be the HTTP method */
  9640. ri->request_method = buf;
  9641. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9642. return -1;
  9643. }
  9644. /* The second word is the URI */
  9645. ri->request_uri = buf;
  9646. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9647. return -1;
  9648. }
  9649. /* Next would be the HTTP version */
  9650. ri->http_version = buf;
  9651. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9652. return -1;
  9653. }
  9654. /* Check for a valid HTTP version key */
  9655. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9656. /* Invalid request */
  9657. return -1;
  9658. }
  9659. ri->http_version += 5;
  9660. /* Check for a valid http method */
  9661. if (!is_valid_http_method(ri->request_method)) {
  9662. return -1;
  9663. }
  9664. /* Parse all HTTP headers */
  9665. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9666. if (ri->num_headers < 0) {
  9667. /* Error while parsing headers */
  9668. return -1;
  9669. }
  9670. return request_length + init_skip;
  9671. }
  9672. static int
  9673. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9674. {
  9675. int response_length;
  9676. int init_skip = 0;
  9677. char *tmp, *tmp2;
  9678. long l;
  9679. /* Initialize elements. */
  9680. ri->http_version = ri->status_text = NULL;
  9681. ri->num_headers = ri->status_code = 0;
  9682. /* RFC says that all initial whitespaces should be ignored */
  9683. /* This included all leading \r and \n (isspace) */
  9684. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9685. while ((len > 0) && isspace((unsigned char)*buf)) {
  9686. buf++;
  9687. len--;
  9688. init_skip++;
  9689. }
  9690. if (len == 0) {
  9691. /* Incomplete request */
  9692. return 0;
  9693. }
  9694. /* Control characters are not allowed, including zero */
  9695. if (iscntrl((unsigned char)*buf)) {
  9696. return -1;
  9697. }
  9698. /* Find end of HTTP header */
  9699. response_length = get_http_header_len(buf, len);
  9700. if (response_length <= 0) {
  9701. return response_length;
  9702. }
  9703. buf[response_length - 1] = '\0';
  9704. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9705. return -1;
  9706. }
  9707. /* The first word is the HTTP version */
  9708. /* Check for a valid HTTP version key */
  9709. if (strncmp(buf, "HTTP/", 5) != 0) {
  9710. /* Invalid request */
  9711. return -1;
  9712. }
  9713. buf += 5;
  9714. if (!isgraph((unsigned char)buf[0])) {
  9715. /* Invalid request */
  9716. return -1;
  9717. }
  9718. ri->http_version = buf;
  9719. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9720. return -1;
  9721. }
  9722. /* The second word is the status as a number */
  9723. tmp = buf;
  9724. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9725. return -1;
  9726. }
  9727. l = strtol(tmp, &tmp2, 10);
  9728. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9729. /* Everything else but a 3 digit code is invalid */
  9730. return -1;
  9731. }
  9732. ri->status_code = (int)l;
  9733. /* The rest of the line is the status text */
  9734. ri->status_text = buf;
  9735. /* Find end of status text */
  9736. /* isgraph or isspace = isprint */
  9737. while (isprint((unsigned char)*buf)) {
  9738. buf++;
  9739. }
  9740. if ((*buf != '\r') && (*buf != '\n')) {
  9741. return -1;
  9742. }
  9743. /* Terminate string and forward buf to next line */
  9744. do {
  9745. *buf = 0;
  9746. buf++;
  9747. } while (isspace((unsigned char)*buf));
  9748. /* Parse all HTTP headers */
  9749. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9750. if (ri->num_headers < 0) {
  9751. /* Error while parsing headers */
  9752. return -1;
  9753. }
  9754. return response_length + init_skip;
  9755. }
  9756. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9757. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9758. * buffer (which marks the end of HTTP request). Buffer buf may already
  9759. * have some data. The length of the data is stored in nread.
  9760. * Upon every read operation, increase nread by the number of bytes read. */
  9761. static int
  9762. read_message(FILE *fp,
  9763. struct mg_connection *conn,
  9764. char *buf,
  9765. int bufsiz,
  9766. int *nread)
  9767. {
  9768. int request_len, n = 0;
  9769. struct timespec last_action_time;
  9770. double request_timeout;
  9771. if (!conn) {
  9772. return 0;
  9773. }
  9774. memset(&last_action_time, 0, sizeof(last_action_time));
  9775. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9776. /* value of request_timeout is in seconds, config in milliseconds */
  9777. request_timeout =
  9778. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9779. } else {
  9780. request_timeout =
  9781. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9782. / 1000.0;
  9783. }
  9784. if (conn->handled_requests > 0) {
  9785. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9786. request_timeout =
  9787. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9788. / 1000.0;
  9789. }
  9790. }
  9791. request_len = get_http_header_len(buf, *nread);
  9792. while (request_len == 0) {
  9793. /* Full request not yet received */
  9794. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9795. /* Server is to be stopped. */
  9796. return -1;
  9797. }
  9798. if (*nread >= bufsiz) {
  9799. /* Request too long */
  9800. return -2;
  9801. }
  9802. n = pull_inner(
  9803. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9804. if (n == -2) {
  9805. /* Receive error */
  9806. return -1;
  9807. }
  9808. /* update clock after every read request */
  9809. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9810. if (n > 0) {
  9811. *nread += n;
  9812. request_len = get_http_header_len(buf, *nread);
  9813. }
  9814. if ((n <= 0) && (request_timeout >= 0)) {
  9815. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9816. > request_timeout) {
  9817. /* Timeout */
  9818. return -3;
  9819. }
  9820. }
  9821. }
  9822. return request_len;
  9823. }
  9824. #if !defined(NO_CGI) || !defined(NO_FILES)
  9825. static int
  9826. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9827. {
  9828. const char *expect;
  9829. char buf[MG_BUF_LEN];
  9830. int success = 0;
  9831. if (!conn) {
  9832. return 0;
  9833. }
  9834. expect = mg_get_header(conn, "Expect");
  9835. DEBUG_ASSERT(fp != NULL);
  9836. if (!fp) {
  9837. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9838. return 0;
  9839. }
  9840. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9841. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9842. */
  9843. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9844. } else {
  9845. if (expect != NULL) {
  9846. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9847. conn->status_code = 100;
  9848. } else {
  9849. conn->status_code = 200;
  9850. }
  9851. DEBUG_ASSERT(conn->consumed_content == 0);
  9852. if (conn->consumed_content != 0) {
  9853. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9854. return 0;
  9855. }
  9856. for (;;) {
  9857. int nread = mg_read(conn, buf, sizeof(buf));
  9858. if (nread <= 0) {
  9859. success = (nread == 0);
  9860. break;
  9861. }
  9862. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9863. break;
  9864. }
  9865. }
  9866. /* Each error code path in this function must send an error */
  9867. if (!success) {
  9868. /* NOTE: Maybe some data has already been sent. */
  9869. /* TODO (low): If some data has been sent, a correct error
  9870. * reply can no longer be sent, so just close the connection */
  9871. mg_send_http_error(conn, 500, "%s", "");
  9872. }
  9873. }
  9874. return success;
  9875. }
  9876. #endif
  9877. #if defined(USE_TIMERS)
  9878. #define TIMER_API static
  9879. #include "timer.inl"
  9880. #endif /* USE_TIMERS */
  9881. #if !defined(NO_CGI)
  9882. /* This structure helps to create an environment for the spawned CGI
  9883. * program.
  9884. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9885. * last element must be NULL.
  9886. * However, on Windows there is a requirement that all these
  9887. * VARIABLE=VALUE\0
  9888. * strings must reside in a contiguous buffer. The end of the buffer is
  9889. * marked by two '\0' characters.
  9890. * We satisfy both worlds: we create an envp array (which is vars), all
  9891. * entries are actually pointers inside buf. */
  9892. struct cgi_environment {
  9893. struct mg_connection *conn;
  9894. /* Data block */
  9895. char *buf; /* Environment buffer */
  9896. size_t buflen; /* Space available in buf */
  9897. size_t bufused; /* Space taken in buf */
  9898. /* Index block */
  9899. char **var; /* char **envp */
  9900. size_t varlen; /* Number of variables available in var */
  9901. size_t varused; /* Number of variables stored in var */
  9902. };
  9903. static void addenv(struct cgi_environment *env,
  9904. PRINTF_FORMAT_STRING(const char *fmt),
  9905. ...) PRINTF_ARGS(2, 3);
  9906. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9907. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9908. static void
  9909. addenv(struct cgi_environment *env, const char *fmt, ...)
  9910. {
  9911. size_t i, n, space;
  9912. int truncated = 0;
  9913. char *added;
  9914. va_list ap;
  9915. if ((env->varlen - env->varused) < 2) {
  9916. mg_cry_internal(env->conn,
  9917. "%s: Cannot register CGI variable [%s]",
  9918. __func__,
  9919. fmt);
  9920. return;
  9921. }
  9922. /* Calculate how much space is left in the buffer */
  9923. space = (env->buflen - env->bufused);
  9924. do {
  9925. /* Space for "\0\0" is always needed. */
  9926. if (space <= 2) {
  9927. /* Allocate new buffer */
  9928. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9929. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9930. if (!added) {
  9931. /* Out of memory */
  9932. mg_cry_internal(
  9933. env->conn,
  9934. "%s: Cannot allocate memory for CGI variable [%s]",
  9935. __func__,
  9936. fmt);
  9937. return;
  9938. }
  9939. /* Retarget pointers */
  9940. env->buf = added;
  9941. env->buflen = n;
  9942. for (i = 0, n = 0; i < env->varused; i++) {
  9943. env->var[i] = added + n;
  9944. n += strlen(added + n) + 1;
  9945. }
  9946. space = (env->buflen - env->bufused);
  9947. }
  9948. /* Make a pointer to the free space int the buffer */
  9949. added = env->buf + env->bufused;
  9950. /* Copy VARIABLE=VALUE\0 string into the free space */
  9951. va_start(ap, fmt);
  9952. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9953. va_end(ap);
  9954. /* Do not add truncated strings to the environment */
  9955. if (truncated) {
  9956. /* Reallocate the buffer */
  9957. space = 0;
  9958. }
  9959. } while (truncated);
  9960. /* Calculate number of bytes added to the environment */
  9961. n = strlen(added) + 1;
  9962. env->bufused += n;
  9963. /* Append a pointer to the added string into the envp array */
  9964. env->var[env->varused] = added;
  9965. env->varused++;
  9966. }
  9967. /* Return 0 on success, non-zero if an error occurs. */
  9968. static int
  9969. prepare_cgi_environment(struct mg_connection *conn,
  9970. const char *prog,
  9971. struct cgi_environment *env,
  9972. int cgi_config_idx)
  9973. {
  9974. const char *s;
  9975. struct vec var_vec;
  9976. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9977. int i, truncated, uri_len;
  9978. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9979. return -1;
  9980. }
  9981. env->conn = conn;
  9982. env->buflen = CGI_ENVIRONMENT_SIZE;
  9983. env->bufused = 0;
  9984. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9985. if (env->buf == NULL) {
  9986. mg_cry_internal(conn,
  9987. "%s: Not enough memory for environmental buffer",
  9988. __func__);
  9989. return -1;
  9990. }
  9991. env->varlen = MAX_CGI_ENVIR_VARS;
  9992. env->varused = 0;
  9993. env->var =
  9994. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9995. if (env->var == NULL) {
  9996. mg_cry_internal(conn,
  9997. "%s: Not enough memory for environmental variables",
  9998. __func__);
  9999. mg_free(env->buf);
  10000. return -1;
  10001. }
  10002. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  10003. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10004. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10005. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  10006. addenv(env,
  10007. "FALLBACK_DOCUMENT_ROOT=%s",
  10008. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  10009. }
  10010. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  10011. /* Prepare the environment block */
  10012. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  10013. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  10014. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  10015. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  10016. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10017. addenv(env, "REMOTE_ADDR=%s", src_addr);
  10018. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  10019. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  10020. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  10021. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  10022. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  10023. /* SCRIPT_NAME */
  10024. uri_len = (int)strlen(conn->request_info.local_uri);
  10025. if (conn->path_info == NULL) {
  10026. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  10027. /* URI: /path_to_script/script.cgi */
  10028. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  10029. } else {
  10030. /* URI: /path_to_script/ ... using index.cgi */
  10031. const char *index_file = strrchr(prog, '/');
  10032. if (index_file) {
  10033. addenv(env,
  10034. "SCRIPT_NAME=%s%s",
  10035. conn->request_info.local_uri,
  10036. index_file + 1);
  10037. }
  10038. }
  10039. } else {
  10040. /* URI: /path_to_script/script.cgi/path_info */
  10041. addenv(env,
  10042. "SCRIPT_NAME=%.*s",
  10043. uri_len - (int)strlen(conn->path_info),
  10044. conn->request_info.local_uri);
  10045. }
  10046. addenv(env, "SCRIPT_FILENAME=%s", prog);
  10047. if (conn->path_info == NULL) {
  10048. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10049. } else {
  10050. addenv(env,
  10051. "PATH_TRANSLATED=%s%s",
  10052. conn->dom_ctx->config[DOCUMENT_ROOT],
  10053. conn->path_info);
  10054. }
  10055. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  10056. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  10057. addenv(env, "CONTENT_TYPE=%s", s);
  10058. }
  10059. if (conn->request_info.query_string != NULL) {
  10060. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  10061. }
  10062. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  10063. addenv(env, "CONTENT_LENGTH=%s", s);
  10064. }
  10065. if ((s = getenv("PATH")) != NULL) {
  10066. addenv(env, "PATH=%s", s);
  10067. }
  10068. if (conn->path_info != NULL) {
  10069. addenv(env, "PATH_INFO=%s", conn->path_info);
  10070. }
  10071. if (conn->status_code > 0) {
  10072. /* CGI error handler should show the status code */
  10073. addenv(env, "STATUS=%d", conn->status_code);
  10074. }
  10075. #if defined(_WIN32)
  10076. if ((s = getenv("COMSPEC")) != NULL) {
  10077. addenv(env, "COMSPEC=%s", s);
  10078. }
  10079. if ((s = getenv("SYSTEMROOT")) != NULL) {
  10080. addenv(env, "SYSTEMROOT=%s", s);
  10081. }
  10082. if ((s = getenv("SystemDrive")) != NULL) {
  10083. addenv(env, "SystemDrive=%s", s);
  10084. }
  10085. if ((s = getenv("ProgramFiles")) != NULL) {
  10086. addenv(env, "ProgramFiles=%s", s);
  10087. }
  10088. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  10089. addenv(env, "ProgramFiles(x86)=%s", s);
  10090. }
  10091. #else
  10092. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  10093. addenv(env, "LD_LIBRARY_PATH=%s", s);
  10094. }
  10095. #endif /* _WIN32 */
  10096. if ((s = getenv("PERLLIB")) != NULL) {
  10097. addenv(env, "PERLLIB=%s", s);
  10098. }
  10099. if (conn->request_info.remote_user != NULL) {
  10100. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  10101. addenv(env, "%s", "AUTH_TYPE=Digest");
  10102. }
  10103. /* Add all headers as HTTP_* variables */
  10104. for (i = 0; i < conn->request_info.num_headers; i++) {
  10105. (void)mg_snprintf(conn,
  10106. &truncated,
  10107. http_var_name,
  10108. sizeof(http_var_name),
  10109. "HTTP_%s",
  10110. conn->request_info.http_headers[i].name);
  10111. if (truncated) {
  10112. mg_cry_internal(conn,
  10113. "%s: HTTP header variable too long [%s]",
  10114. __func__,
  10115. conn->request_info.http_headers[i].name);
  10116. continue;
  10117. }
  10118. /* Convert variable name into uppercase, and change - to _ */
  10119. for (p = http_var_name; *p != '\0'; p++) {
  10120. if (*p == '-') {
  10121. *p = '_';
  10122. }
  10123. *p = (char)toupper((unsigned char)*p);
  10124. }
  10125. addenv(env,
  10126. "%s=%s",
  10127. http_var_name,
  10128. conn->request_info.http_headers[i].value);
  10129. }
  10130. /* Add user-specified variables */
  10131. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  10132. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  10133. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  10134. }
  10135. env->var[env->varused] = NULL;
  10136. env->buf[env->bufused] = '\0';
  10137. return 0;
  10138. }
  10139. /* Data for CGI process control: PID and number of references */
  10140. struct process_control_data {
  10141. pid_t pid;
  10142. ptrdiff_t references;
  10143. };
  10144. static int
  10145. abort_cgi_process(void *data)
  10146. {
  10147. /* Waitpid checks for child status and won't work for a pid that does
  10148. * not identify a child of the current process. Thus, if the pid is
  10149. * reused, we will not affect a different process. */
  10150. struct process_control_data *proc = (struct process_control_data *)data;
  10151. int status = 0;
  10152. ptrdiff_t refs;
  10153. pid_t ret_pid;
  10154. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  10155. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  10156. /* Stop child process */
  10157. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  10158. kill(proc->pid, SIGABRT);
  10159. /* Wait until process is terminated (don't leave zombies) */
  10160. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  10161. ;
  10162. } else {
  10163. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10164. }
  10165. /* Dec reference counter */
  10166. refs = mg_atomic_dec(&proc->references);
  10167. if (refs == 0) {
  10168. /* no more references - free data */
  10169. mg_free(data);
  10170. }
  10171. return 0;
  10172. }
  10173. /* Local (static) function assumes all arguments are valid. */
  10174. static void
  10175. handle_cgi_request(struct mg_connection *conn,
  10176. const char *prog,
  10177. int cgi_config_idx)
  10178. {
  10179. char *buf;
  10180. size_t buflen;
  10181. int headers_len, data_len, i, truncated;
  10182. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10183. const char *status, *status_text;
  10184. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10185. struct mg_request_info ri;
  10186. struct cgi_environment blk;
  10187. FILE *in = NULL, *out = NULL, *err = NULL;
  10188. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10189. pid_t pid = (pid_t)-1;
  10190. struct process_control_data *proc = NULL;
  10191. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  10192. int no_buffering = 0;
  10193. #if defined(USE_TIMERS)
  10194. double cgi_timeout;
  10195. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  10196. /* Get timeout in seconds */
  10197. cgi_timeout =
  10198. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  10199. } else {
  10200. cgi_timeout =
  10201. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10202. }
  10203. #endif
  10204. if (cfg_buffering != NULL) {
  10205. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10206. no_buffering = 1;
  10207. }
  10208. }
  10209. buf = NULL;
  10210. buflen = conn->phys_ctx->max_request_size;
  10211. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10212. if (i != 0) {
  10213. blk.buf = NULL;
  10214. blk.var = NULL;
  10215. goto done;
  10216. }
  10217. /* CGI must be executed in its own directory. 'dir' must point to the
  10218. * directory containing executable program, 'p' must point to the
  10219. * executable program name relative to 'dir'. */
  10220. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10221. if (truncated) {
  10222. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10223. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10224. goto done;
  10225. }
  10226. if ((p = strrchr(dir, '/')) != NULL) {
  10227. *p++ = '\0';
  10228. } else {
  10229. dir[0] = '.';
  10230. dir[1] = '\0';
  10231. p = (char *)prog;
  10232. }
  10233. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10234. status = strerror(ERRNO);
  10235. mg_cry_internal(
  10236. conn,
  10237. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10238. prog,
  10239. status);
  10240. mg_send_http_error(conn,
  10241. 500,
  10242. "Error: Cannot create CGI pipe: %s",
  10243. status);
  10244. goto done;
  10245. }
  10246. proc = (struct process_control_data *)
  10247. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10248. if (proc == NULL) {
  10249. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10250. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10251. goto done;
  10252. }
  10253. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10254. pid = spawn_process(
  10255. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10256. if (pid == (pid_t)-1) {
  10257. status = strerror(ERRNO);
  10258. mg_cry_internal(
  10259. conn,
  10260. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10261. prog,
  10262. status);
  10263. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10264. mg_free(proc);
  10265. proc = NULL;
  10266. goto done;
  10267. }
  10268. /* Store data in shared process_control_data */
  10269. proc->pid = pid;
  10270. proc->references = 1;
  10271. #if defined(USE_TIMERS)
  10272. if (cgi_timeout > 0.0) {
  10273. proc->references = 2;
  10274. // Start a timer for CGI
  10275. timer_add(conn->phys_ctx,
  10276. cgi_timeout /* in seconds */,
  10277. 0.0,
  10278. 1,
  10279. abort_cgi_process,
  10280. (void *)proc,
  10281. NULL);
  10282. }
  10283. #endif
  10284. /* Parent closes only one side of the pipes.
  10285. * If we don't mark them as closed, close() attempt before
  10286. * return from this function throws an exception on Windows.
  10287. * Windows does not like when closed descriptor is closed again. */
  10288. (void)close(fdin[0]);
  10289. (void)close(fdout[1]);
  10290. (void)close(fderr[1]);
  10291. fdin[0] = fdout[1] = fderr[1] = -1;
  10292. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10293. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10294. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10295. status = strerror(ERRNO);
  10296. mg_cry_internal(conn,
  10297. "Error: CGI program \"%s\": Can not open fd: %s",
  10298. prog,
  10299. status);
  10300. mg_send_http_error(conn,
  10301. 500,
  10302. "Error: CGI can not open fd\nfdopen: %s",
  10303. status);
  10304. goto done;
  10305. }
  10306. setbuf(in, NULL);
  10307. setbuf(out, NULL);
  10308. setbuf(err, NULL);
  10309. fout.access.fp = out;
  10310. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10311. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10312. conn->content_len);
  10313. /* This is a POST/PUT request, or another request with body data. */
  10314. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10315. /* Error sending the body data */
  10316. mg_cry_internal(
  10317. conn,
  10318. "Error: CGI program \"%s\": Forward body data failed",
  10319. prog);
  10320. goto done;
  10321. }
  10322. }
  10323. /* Close so child gets an EOF. */
  10324. fclose(in);
  10325. in = NULL;
  10326. fdin[1] = -1;
  10327. /* Now read CGI reply into a buffer. We need to set correct
  10328. * status code, thus we need to see all HTTP headers first.
  10329. * Do not send anything back to client, until we buffer in all
  10330. * HTTP headers. */
  10331. data_len = 0;
  10332. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10333. if (buf == NULL) {
  10334. mg_send_http_error(conn,
  10335. 500,
  10336. "Error: Not enough memory for CGI buffer (%u bytes)",
  10337. (unsigned int)buflen);
  10338. mg_cry_internal(
  10339. conn,
  10340. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10341. "bytes)",
  10342. prog,
  10343. (unsigned int)buflen);
  10344. goto done;
  10345. }
  10346. DEBUG_TRACE("CGI: %s", "wait for response");
  10347. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10348. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10349. if (headers_len <= 0) {
  10350. /* Could not parse the CGI response. Check if some error message on
  10351. * stderr. */
  10352. i = pull_all(err, conn, buf, (int)buflen);
  10353. if (i > 0) {
  10354. /* CGI program explicitly sent an error */
  10355. /* Write the error message to the internal log */
  10356. mg_cry_internal(conn,
  10357. "Error: CGI program \"%s\" sent error "
  10358. "message: [%.*s]",
  10359. prog,
  10360. i,
  10361. buf);
  10362. /* Don't send the error message back to the client */
  10363. mg_send_http_error(conn,
  10364. 500,
  10365. "Error: CGI program \"%s\" failed.",
  10366. prog);
  10367. } else {
  10368. /* CGI program did not explicitly send an error, but a broken
  10369. * respon header */
  10370. mg_cry_internal(conn,
  10371. "Error: CGI program sent malformed or too big "
  10372. "(>%u bytes) HTTP headers: [%.*s]",
  10373. (unsigned)buflen,
  10374. data_len,
  10375. buf);
  10376. mg_send_http_error(conn,
  10377. 500,
  10378. "Error: CGI program sent malformed or too big "
  10379. "(>%u bytes) HTTP headers: [%.*s]",
  10380. (unsigned)buflen,
  10381. data_len,
  10382. buf);
  10383. }
  10384. /* in both cases, abort processing CGI */
  10385. goto done;
  10386. }
  10387. pbuf = buf;
  10388. buf[headers_len - 1] = '\0';
  10389. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10390. /* Make up and send the status line */
  10391. status_text = "OK";
  10392. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10393. != NULL) {
  10394. conn->status_code = atoi(status);
  10395. status_text = status;
  10396. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10397. status_text++;
  10398. }
  10399. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10400. != NULL) {
  10401. conn->status_code = 307;
  10402. } else {
  10403. conn->status_code = 200;
  10404. }
  10405. if (!should_keep_alive(conn)) {
  10406. conn->must_close = 1;
  10407. }
  10408. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10409. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10410. /* Send headers */
  10411. for (i = 0; i < ri.num_headers; i++) {
  10412. DEBUG_TRACE("CGI header: %s: %s",
  10413. ri.http_headers[i].name,
  10414. ri.http_headers[i].value);
  10415. mg_printf(conn,
  10416. "%s: %s\r\n",
  10417. ri.http_headers[i].name,
  10418. ri.http_headers[i].value);
  10419. }
  10420. mg_write(conn, "\r\n", 2);
  10421. /* Send chunk of data that may have been read after the headers */
  10422. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10423. /* Read the rest of CGI output and send to the client */
  10424. DEBUG_TRACE("CGI: %s", "forward all data");
  10425. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10426. DEBUG_TRACE("CGI: %s", "all data sent");
  10427. done:
  10428. mg_free(blk.var);
  10429. mg_free(blk.buf);
  10430. if (pid != (pid_t)-1) {
  10431. abort_cgi_process((void *)proc);
  10432. }
  10433. if (fdin[0] != -1) {
  10434. close(fdin[0]);
  10435. }
  10436. if (fdout[1] != -1) {
  10437. close(fdout[1]);
  10438. }
  10439. if (fderr[1] != -1) {
  10440. close(fderr[1]);
  10441. }
  10442. if (in != NULL) {
  10443. fclose(in);
  10444. } else if (fdin[1] != -1) {
  10445. close(fdin[1]);
  10446. }
  10447. if (out != NULL) {
  10448. fclose(out);
  10449. } else if (fdout[0] != -1) {
  10450. close(fdout[0]);
  10451. }
  10452. if (err != NULL) {
  10453. fclose(err);
  10454. } else if (fderr[0] != -1) {
  10455. close(fderr[0]);
  10456. }
  10457. mg_free(buf);
  10458. }
  10459. #endif /* !NO_CGI */
  10460. #if !defined(NO_FILES)
  10461. static void
  10462. dav_mkcol(struct mg_connection *conn, const char *path)
  10463. {
  10464. int rc, body_len;
  10465. struct de de;
  10466. if (conn == NULL) {
  10467. return;
  10468. }
  10469. /* TODO (mid): Check the mg_send_http_error situations in this function
  10470. */
  10471. memset(&de.file, 0, sizeof(de.file));
  10472. if (!mg_stat(conn, path, &de.file)) {
  10473. mg_cry_internal(conn,
  10474. "%s: mg_stat(%s) failed: %s",
  10475. __func__,
  10476. path,
  10477. strerror(ERRNO));
  10478. }
  10479. if (de.file.last_modified) {
  10480. /* TODO (mid): This check does not seem to make any sense ! */
  10481. /* TODO (mid): Add a webdav unit test first, before changing
  10482. * anything here. */
  10483. mg_send_http_error(
  10484. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10485. return;
  10486. }
  10487. body_len = conn->data_len - conn->request_len;
  10488. if (body_len > 0) {
  10489. mg_send_http_error(
  10490. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10491. return;
  10492. }
  10493. rc = mg_mkdir(conn, path, 0755);
  10494. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10495. if (rc == 0) {
  10496. /* Create 201 "Created" response */
  10497. mg_response_header_start(conn, 201);
  10498. send_static_cache_header(conn);
  10499. send_additional_header(conn);
  10500. mg_response_header_add(conn, "Content-Length", "0", -1);
  10501. /* Send all headers - there is no body */
  10502. mg_response_header_send(conn);
  10503. } else {
  10504. int http_status = 500;
  10505. switch (errno) {
  10506. case EEXIST:
  10507. http_status = 405;
  10508. break;
  10509. case EACCES:
  10510. http_status = 403;
  10511. break;
  10512. case ENOENT:
  10513. http_status = 409;
  10514. break;
  10515. }
  10516. mg_send_http_error(conn,
  10517. http_status,
  10518. "Error processing %s: %s",
  10519. path,
  10520. strerror(ERRNO));
  10521. }
  10522. }
  10523. /* Forward decrlaration */
  10524. static int get_uri_type(const char *uri);
  10525. static const char *
  10526. get_rel_url_at_current_server(const char *uri,
  10527. const struct mg_connection *conn);
  10528. static void
  10529. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10530. {
  10531. const char *overwrite_hdr;
  10532. const char *destination_hdr;
  10533. const char *root;
  10534. int rc, dest_uri_type;
  10535. int http_status = 400;
  10536. int do_overwrite = 0;
  10537. int destination_ok = 0;
  10538. char dest_path[UTF8_PATH_MAX];
  10539. struct mg_file_stat ignored;
  10540. if (conn == NULL) {
  10541. return;
  10542. }
  10543. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10544. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10545. destination_hdr = mg_get_header(conn, "Destination");
  10546. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10547. do_overwrite = 1;
  10548. }
  10549. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10550. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10551. return;
  10552. }
  10553. if (root != NULL) {
  10554. char *local_dest = NULL;
  10555. dest_uri_type = get_uri_type(destination_hdr);
  10556. if (dest_uri_type == 2) {
  10557. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10558. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10559. const char *h =
  10560. get_rel_url_at_current_server(destination_hdr, conn);
  10561. if (h) {
  10562. size_t len = strlen(h);
  10563. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10564. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10565. }
  10566. }
  10567. if (local_dest != NULL) {
  10568. remove_dot_segments(local_dest);
  10569. if (local_dest[0] == '/') {
  10570. int trunc_check = 0;
  10571. mg_snprintf(conn,
  10572. &trunc_check,
  10573. dest_path,
  10574. sizeof(dest_path),
  10575. "%s/%s",
  10576. root,
  10577. local_dest);
  10578. if (trunc_check == 0) {
  10579. destination_ok = 1;
  10580. }
  10581. }
  10582. mg_free(local_dest);
  10583. }
  10584. }
  10585. if (!destination_ok) {
  10586. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10587. return;
  10588. }
  10589. /* Check now if this file exists */
  10590. if (mg_stat(conn, dest_path, &ignored)) {
  10591. /* File exists */
  10592. if (do_overwrite) {
  10593. /* Overwrite allowed: delete the file first */
  10594. if (0 != remove(dest_path)) {
  10595. /* No overwrite: return error */
  10596. mg_send_http_error(conn,
  10597. 403,
  10598. "Cannot overwrite file: %s",
  10599. dest_path);
  10600. return;
  10601. }
  10602. } else {
  10603. /* No overwrite: return error */
  10604. mg_send_http_error(conn,
  10605. 412,
  10606. "Destination already exists: %s",
  10607. dest_path);
  10608. return;
  10609. }
  10610. }
  10611. /* Copy / Move / Rename operation. */
  10612. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10613. #if defined(_WIN32)
  10614. {
  10615. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10616. wchar_t wSource[UTF16_PATH_MAX];
  10617. wchar_t wDest[UTF16_PATH_MAX];
  10618. BOOL ok;
  10619. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10620. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10621. if (do_copy) {
  10622. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10623. } else {
  10624. ok = MoveFileExW(wSource,
  10625. wDest,
  10626. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10627. }
  10628. if (ok) {
  10629. rc = 0;
  10630. } else {
  10631. DWORD lastErr = GetLastError();
  10632. if (lastErr == ERROR_ALREADY_EXISTS) {
  10633. mg_send_http_error(conn,
  10634. 412,
  10635. "Destination already exists: %s",
  10636. dest_path);
  10637. return;
  10638. }
  10639. rc = -1;
  10640. http_status = 400;
  10641. }
  10642. }
  10643. #else
  10644. {
  10645. /* Linux uses already UTF-8, we don't need to convert file names. */
  10646. if (do_copy) {
  10647. /* TODO: COPY for Linux. */
  10648. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10649. return;
  10650. }
  10651. rc = rename(path, dest_path);
  10652. if (rc) {
  10653. switch (errno) {
  10654. case EEXIST:
  10655. http_status = 412;
  10656. break;
  10657. case EACCES:
  10658. http_status = 403;
  10659. break;
  10660. case ENOENT:
  10661. http_status = 409;
  10662. break;
  10663. }
  10664. }
  10665. }
  10666. #endif
  10667. if (rc == 0) {
  10668. /* Create 204 "No Content" response */
  10669. mg_response_header_start(conn, 204);
  10670. mg_response_header_add(conn, "Content-Length", "0", -1);
  10671. /* Send all headers - there is no body */
  10672. mg_response_header_send(conn);
  10673. } else {
  10674. mg_send_http_error(conn, http_status, "Operation failed");
  10675. }
  10676. }
  10677. static void
  10678. put_file(struct mg_connection *conn, const char *path)
  10679. {
  10680. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10681. const char *range;
  10682. int64_t r1, r2;
  10683. int rc;
  10684. if (conn == NULL) {
  10685. return;
  10686. }
  10687. DEBUG_TRACE("store %s", path);
  10688. if (mg_stat(conn, path, &file.stat)) {
  10689. /* File already exists */
  10690. conn->status_code = 200;
  10691. if (file.stat.is_directory) {
  10692. /* This is an already existing directory,
  10693. * so there is nothing to do for the server. */
  10694. rc = 0;
  10695. } else {
  10696. /* File exists and is not a directory. */
  10697. /* Can it be replaced? */
  10698. /* Check if the server may write this file */
  10699. if (access(path, W_OK) == 0) {
  10700. /* Access granted */
  10701. rc = 1;
  10702. } else {
  10703. mg_send_http_error(
  10704. conn,
  10705. 403,
  10706. "Error: Put not possible\nReplacing %s is not allowed",
  10707. path);
  10708. return;
  10709. }
  10710. }
  10711. } else {
  10712. /* File should be created */
  10713. conn->status_code = 201;
  10714. rc = put_dir(conn, path);
  10715. }
  10716. if (rc == 0) {
  10717. /* put_dir returns 0 if path is a directory */
  10718. /* Create response */
  10719. mg_response_header_start(conn, conn->status_code);
  10720. send_no_cache_header(conn);
  10721. send_additional_header(conn);
  10722. mg_response_header_add(conn, "Content-Length", "0", -1);
  10723. /* Send all headers - there is no body */
  10724. mg_response_header_send(conn);
  10725. /* Request to create a directory has been fulfilled successfully.
  10726. * No need to put a file. */
  10727. return;
  10728. }
  10729. if (rc == -1) {
  10730. /* put_dir returns -1 if the path is too long */
  10731. mg_send_http_error(conn,
  10732. 414,
  10733. "Error: Path too long\nput_dir(%s): %s",
  10734. path,
  10735. strerror(ERRNO));
  10736. return;
  10737. }
  10738. if (rc == -2) {
  10739. /* put_dir returns -2 if the directory can not be created */
  10740. mg_send_http_error(conn,
  10741. 500,
  10742. "Error: Can not create directory\nput_dir(%s): %s",
  10743. path,
  10744. strerror(ERRNO));
  10745. return;
  10746. }
  10747. /* A file should be created or overwritten. */
  10748. /* Currently CivetWeb does not need read+write access. */
  10749. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10750. || file.access.fp == NULL) {
  10751. (void)mg_fclose(&file.access);
  10752. mg_send_http_error(conn,
  10753. 500,
  10754. "Error: Can not create file\nfopen(%s): %s",
  10755. path,
  10756. strerror(ERRNO));
  10757. return;
  10758. }
  10759. fclose_on_exec(&file.access, conn);
  10760. range = mg_get_header(conn, "Content-Range");
  10761. r1 = r2 = 0;
  10762. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10763. conn->status_code = 206; /* Partial content */
  10764. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10765. mg_send_http_error(conn,
  10766. 500,
  10767. "Error: Internal error processing file %s",
  10768. path);
  10769. return;
  10770. }
  10771. }
  10772. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10773. /* forward_body_data failed.
  10774. * The error code has already been sent to the client,
  10775. * and conn->status_code is already set. */
  10776. (void)mg_fclose(&file.access);
  10777. return;
  10778. }
  10779. if (mg_fclose(&file.access) != 0) {
  10780. /* fclose failed. This might have different reasons, but a likely
  10781. * one is "no space on disk", http 507. */
  10782. conn->status_code = 507;
  10783. }
  10784. /* Create response (status_code has been set before) */
  10785. mg_response_header_start(conn, conn->status_code);
  10786. send_no_cache_header(conn);
  10787. send_additional_header(conn);
  10788. mg_response_header_add(conn, "Content-Length", "0", -1);
  10789. /* Send all headers - there is no body */
  10790. mg_response_header_send(conn);
  10791. }
  10792. static void
  10793. delete_file(struct mg_connection *conn, const char *path)
  10794. {
  10795. struct de de;
  10796. memset(&de.file, 0, sizeof(de.file));
  10797. if (!mg_stat(conn, path, &de.file)) {
  10798. /* mg_stat returns 0 if the file does not exist */
  10799. mg_send_http_error(conn,
  10800. 404,
  10801. "Error: Cannot delete file\nFile %s not found",
  10802. path);
  10803. return;
  10804. }
  10805. DEBUG_TRACE("delete %s", path);
  10806. if (de.file.is_directory) {
  10807. if (remove_directory(conn, path)) {
  10808. /* Delete is successful: Return 204 without content. */
  10809. mg_send_http_error(conn, 204, "%s", "");
  10810. } else {
  10811. /* Delete is not successful: Return 500 (Server error). */
  10812. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10813. }
  10814. return;
  10815. }
  10816. /* This is an existing file (not a directory).
  10817. * Check if write permission is granted. */
  10818. if (access(path, W_OK) != 0) {
  10819. /* File is read only */
  10820. mg_send_http_error(
  10821. conn,
  10822. 403,
  10823. "Error: Delete not possible\nDeleting %s is not allowed",
  10824. path);
  10825. return;
  10826. }
  10827. /* Try to delete it. */
  10828. if (mg_remove(conn, path) == 0) {
  10829. /* Delete was successful: Return 204 without content. */
  10830. mg_response_header_start(conn, 204);
  10831. send_no_cache_header(conn);
  10832. send_additional_header(conn);
  10833. mg_response_header_add(conn, "Content-Length", "0", -1);
  10834. mg_response_header_send(conn);
  10835. } else {
  10836. /* Delete not successful (file locked). */
  10837. mg_send_http_error(conn,
  10838. 423,
  10839. "Error: Cannot delete file\nremove(%s): %s",
  10840. path,
  10841. strerror(ERRNO));
  10842. }
  10843. }
  10844. #endif /* !NO_FILES */
  10845. #if !defined(NO_FILESYSTEMS)
  10846. static void
  10847. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10848. static void
  10849. do_ssi_include(struct mg_connection *conn,
  10850. const char *ssi,
  10851. char *tag,
  10852. int include_level)
  10853. {
  10854. char file_name[MG_BUF_LEN], path[512], *p;
  10855. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10856. size_t len;
  10857. int truncated = 0;
  10858. if (conn == NULL) {
  10859. return;
  10860. }
  10861. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10862. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10863. * always < MG_BUF_LEN. */
  10864. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10865. /* File name is relative to the webserver root */
  10866. file_name[511] = 0;
  10867. (void)mg_snprintf(conn,
  10868. &truncated,
  10869. path,
  10870. sizeof(path),
  10871. "%s/%s",
  10872. conn->dom_ctx->config[DOCUMENT_ROOT],
  10873. file_name);
  10874. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10875. /* File name is relative to the webserver working directory
  10876. * or it is absolute system path */
  10877. file_name[511] = 0;
  10878. (void)
  10879. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10880. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10881. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10882. /* File name is relative to the current document */
  10883. file_name[511] = 0;
  10884. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10885. if (!truncated) {
  10886. if ((p = strrchr(path, '/')) != NULL) {
  10887. p[1] = '\0';
  10888. }
  10889. len = strlen(path);
  10890. (void)mg_snprintf(conn,
  10891. &truncated,
  10892. path + len,
  10893. sizeof(path) - len,
  10894. "%s",
  10895. file_name);
  10896. }
  10897. } else {
  10898. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10899. return;
  10900. }
  10901. if (truncated) {
  10902. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10903. return;
  10904. }
  10905. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10906. mg_cry_internal(conn,
  10907. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10908. tag,
  10909. path,
  10910. strerror(ERRNO));
  10911. } else {
  10912. fclose_on_exec(&file.access, conn);
  10913. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10914. > 0) {
  10915. send_ssi_file(conn, path, &file, include_level + 1);
  10916. } else {
  10917. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10918. }
  10919. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10920. }
  10921. }
  10922. #if !defined(NO_POPEN)
  10923. static void
  10924. do_ssi_exec(struct mg_connection *conn, char *tag)
  10925. {
  10926. char cmd[1024] = "";
  10927. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10928. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10929. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10930. } else {
  10931. cmd[1023] = 0;
  10932. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10933. mg_cry_internal(conn,
  10934. "Cannot SSI #exec: [%s]: %s",
  10935. cmd,
  10936. strerror(ERRNO));
  10937. } else {
  10938. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10939. pclose(file.access.fp);
  10940. }
  10941. }
  10942. }
  10943. #endif /* !NO_POPEN */
  10944. static int
  10945. mg_fgetc(struct mg_file *filep)
  10946. {
  10947. if (filep == NULL) {
  10948. return EOF;
  10949. }
  10950. if (filep->access.fp != NULL) {
  10951. return fgetc(filep->access.fp);
  10952. } else {
  10953. return EOF;
  10954. }
  10955. }
  10956. static void
  10957. send_ssi_file(struct mg_connection *conn,
  10958. const char *path,
  10959. struct mg_file *filep,
  10960. int include_level)
  10961. {
  10962. char buf[MG_BUF_LEN];
  10963. int ch, len, in_tag, in_ssi_tag;
  10964. if (include_level > 10) {
  10965. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10966. return;
  10967. }
  10968. in_tag = in_ssi_tag = len = 0;
  10969. /* Read file, byte by byte, and look for SSI include tags */
  10970. while ((ch = mg_fgetc(filep)) != EOF) {
  10971. if (in_tag) {
  10972. /* We are in a tag, either SSI tag or html tag */
  10973. if (ch == '>') {
  10974. /* Tag is closing */
  10975. buf[len++] = '>';
  10976. if (in_ssi_tag) {
  10977. /* Handle SSI tag */
  10978. buf[len] = 0;
  10979. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10980. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10981. #if !defined(NO_POPEN)
  10982. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10983. do_ssi_exec(conn, buf + 9);
  10984. #endif /* !NO_POPEN */
  10985. } else {
  10986. mg_cry_internal(conn,
  10987. "%s: unknown SSI "
  10988. "command: \"%s\"",
  10989. path,
  10990. buf);
  10991. }
  10992. len = 0;
  10993. in_ssi_tag = in_tag = 0;
  10994. } else {
  10995. /* Not an SSI tag */
  10996. /* Flush buffer */
  10997. (void)mg_write(conn, buf, (size_t)len);
  10998. len = 0;
  10999. in_tag = 0;
  11000. }
  11001. } else {
  11002. /* Tag is still open */
  11003. buf[len++] = (char)(ch & 0xff);
  11004. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  11005. /* All SSI tags start with <!--# */
  11006. in_ssi_tag = 1;
  11007. }
  11008. if ((len + 2) > (int)sizeof(buf)) {
  11009. /* Tag to long for buffer */
  11010. mg_cry_internal(conn, "%s: tag is too large", path);
  11011. return;
  11012. }
  11013. }
  11014. } else {
  11015. /* We are not in a tag yet. */
  11016. if (ch == '<') {
  11017. /* Tag is opening */
  11018. in_tag = 1;
  11019. if (len > 0) {
  11020. /* Flush current buffer.
  11021. * Buffer is filled with "len" bytes. */
  11022. (void)mg_write(conn, buf, (size_t)len);
  11023. }
  11024. /* Store the < */
  11025. len = 1;
  11026. buf[0] = '<';
  11027. } else {
  11028. /* No Tag */
  11029. /* Add data to buffer */
  11030. buf[len++] = (char)(ch & 0xff);
  11031. /* Flush if buffer is full */
  11032. if (len == (int)sizeof(buf)) {
  11033. mg_write(conn, buf, (size_t)len);
  11034. len = 0;
  11035. }
  11036. }
  11037. }
  11038. }
  11039. /* Send the rest of buffered data */
  11040. if (len > 0) {
  11041. mg_write(conn, buf, (size_t)len);
  11042. }
  11043. }
  11044. static void
  11045. handle_ssi_file_request(struct mg_connection *conn,
  11046. const char *path,
  11047. struct mg_file *filep)
  11048. {
  11049. char date[64];
  11050. time_t curtime = time(NULL);
  11051. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  11052. return;
  11053. }
  11054. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  11055. /* File exists (precondition for calling this function),
  11056. * but can not be opened by the server. */
  11057. mg_send_http_error(conn,
  11058. 500,
  11059. "Error: Cannot read file\nfopen(%s): %s",
  11060. path,
  11061. strerror(ERRNO));
  11062. } else {
  11063. /* Set "must_close" for HTTP/1.x, since we do not know the
  11064. * content length */
  11065. conn->must_close = 1;
  11066. gmt_time_string(date, sizeof(date), &curtime);
  11067. fclose_on_exec(&filep->access, conn);
  11068. /* 200 OK response */
  11069. mg_response_header_start(conn, 200);
  11070. send_no_cache_header(conn);
  11071. send_additional_header(conn);
  11072. send_cors_header(conn);
  11073. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11074. mg_response_header_send(conn);
  11075. /* Header sent, now send body */
  11076. send_ssi_file(conn, path, filep, 0);
  11077. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  11078. }
  11079. }
  11080. #endif /* NO_FILESYSTEMS */
  11081. #if !defined(NO_FILES)
  11082. static void
  11083. send_options(struct mg_connection *conn)
  11084. {
  11085. if (!conn || !all_methods) {
  11086. return;
  11087. }
  11088. /* We do not set a "Cache-Control" header here, but leave the default.
  11089. * Since browsers do not send an OPTIONS request, we can not test the
  11090. * effect anyway. */
  11091. mg_response_header_start(conn, 200);
  11092. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11093. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  11094. /* Use the same as before */
  11095. mg_response_header_add(conn, "Allow", all_methods, -1);
  11096. mg_response_header_add(conn, "DAV", "1", -1);
  11097. } else {
  11098. /* TODO: Check this later for HTTP/2 */
  11099. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  11100. }
  11101. send_additional_header(conn);
  11102. mg_response_header_send(conn);
  11103. }
  11104. /* Writes PROPFIND properties for a collection element */
  11105. static int
  11106. print_props(struct mg_connection *conn,
  11107. const char *uri,
  11108. const char *name,
  11109. struct mg_file_stat *filep)
  11110. {
  11111. size_t i;
  11112. char mtime[64];
  11113. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11114. char *link_concat;
  11115. size_t link_concat_len;
  11116. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  11117. return 0;
  11118. }
  11119. link_concat_len = strlen(uri) + strlen(name) + 1;
  11120. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  11121. if (!link_concat) {
  11122. return 0;
  11123. }
  11124. strcpy(link_concat, uri);
  11125. strcat(link_concat, name);
  11126. /* Get full link used in request */
  11127. mg_construct_local_link(
  11128. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  11129. /*
  11130. OutputDebugStringA("print_props:\n uri: ");
  11131. OutputDebugStringA(uri);
  11132. OutputDebugStringA("\n name: ");
  11133. OutputDebugStringA(name);
  11134. OutputDebugStringA("\n link: ");
  11135. OutputDebugStringA(link_buf);
  11136. OutputDebugStringA("\n");
  11137. */
  11138. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  11139. mg_printf(conn,
  11140. "<d:response>"
  11141. "<d:href>%s</d:href>"
  11142. "<d:propstat>"
  11143. "<d:prop>"
  11144. "<d:resourcetype>%s</d:resourcetype>"
  11145. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  11146. "<d:getlastmodified>%s</d:getlastmodified>"
  11147. "<d:lockdiscovery>",
  11148. link_buf,
  11149. filep->is_directory ? "<d:collection/>" : "",
  11150. filep->size,
  11151. mtime);
  11152. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11153. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11154. if (!strcmp(dav_lock[i].path, link_buf)) {
  11155. mg_printf(conn,
  11156. "<d:activelock>"
  11157. "<d:locktype><d:write/></d:locktype>"
  11158. "<d:lockscope><d:exclusive/></d:lockscope>"
  11159. "<d:depth>0</d:depth>"
  11160. "<d:owner>%s</d:owner>"
  11161. "<d:timeout>Second-%u</d:timeout>"
  11162. "<d:locktoken>"
  11163. "<d:href>%s</d:href>"
  11164. "</d:locktoken>"
  11165. "</d:activelock>\n",
  11166. dav_lock[i].user,
  11167. (unsigned)LOCK_DURATION_S,
  11168. dav_lock[i].token);
  11169. }
  11170. }
  11171. mg_printf(conn,
  11172. "</d:lockdiscovery>"
  11173. "</d:prop>"
  11174. "<d:status>HTTP/1.1 200 OK</d:status>"
  11175. "</d:propstat>"
  11176. "</d:response>\n");
  11177. mg_free(link_concat);
  11178. return 1;
  11179. }
  11180. static int
  11181. print_dav_dir_entry(struct de *de, void *data)
  11182. {
  11183. struct mg_connection *conn = (struct mg_connection *)data;
  11184. if (!de || !conn
  11185. || !print_props(
  11186. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  11187. /* stop scan */
  11188. return 1;
  11189. }
  11190. return 0;
  11191. }
  11192. static void
  11193. handle_propfind(struct mg_connection *conn,
  11194. const char *path,
  11195. struct mg_file_stat *filep)
  11196. {
  11197. const char *depth = mg_get_header(conn, "Depth");
  11198. if (!conn || !path || !filep || !conn->dom_ctx) {
  11199. return;
  11200. }
  11201. /* return 207 "Multi-Status" */
  11202. conn->must_close = 1;
  11203. mg_response_header_start(conn, 207);
  11204. send_static_cache_header(conn);
  11205. send_additional_header(conn);
  11206. mg_response_header_add(conn,
  11207. "Content-Type",
  11208. "application/xml; charset=utf-8",
  11209. -1);
  11210. mg_response_header_send(conn);
  11211. /* Content */
  11212. mg_printf(conn,
  11213. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11214. "<d:multistatus xmlns:d='DAV:'>\n");
  11215. /* Print properties for the requested resource itself */
  11216. print_props(conn, conn->request_info.local_uri, "", filep);
  11217. /* If it is a directory, print directory entries too if Depth is not 0
  11218. */
  11219. if (filep->is_directory
  11220. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11221. "yes")
  11222. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11223. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11224. }
  11225. mg_printf(conn, "%s\n", "</d:multistatus>");
  11226. }
  11227. static void
  11228. dav_lock_file(struct mg_connection *conn, const char *path)
  11229. {
  11230. /* internal function - therefore conn is assumed to be valid */
  11231. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11232. uint64_t new_locktime;
  11233. int lock_index = -1;
  11234. int i;
  11235. uint64_t LOCK_DURATION_NS =
  11236. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11237. struct twebdav_lock *dav_lock = NULL;
  11238. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11239. || !conn->phys_ctx) {
  11240. return;
  11241. }
  11242. dav_lock = conn->phys_ctx->webdav_lock;
  11243. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11244. /* const char *refresh = mg_get_header(conn, "If"); */
  11245. /* Link refresh should have an "If" header:
  11246. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11247. * But it seems Windows Explorer does not send them.
  11248. */
  11249. mg_lock_context(conn->phys_ctx);
  11250. new_locktime = mg_get_current_time_ns();
  11251. /* Find a slot for a lock */
  11252. while (lock_index < 0) {
  11253. /* find existing lock */
  11254. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11255. if (!strcmp(dav_lock[i].path, link_buf)) {
  11256. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11257. /* locked by the same user */
  11258. dav_lock[i].locktime = new_locktime;
  11259. lock_index = i;
  11260. break;
  11261. } else {
  11262. /* already locked by someone else */
  11263. if (new_locktime
  11264. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11265. /* Lock expired */
  11266. dav_lock[i].path[0] = 0;
  11267. } else {
  11268. /* Lock still valid */
  11269. mg_unlock_context(conn->phys_ctx);
  11270. mg_send_http_error(conn, 423, "%s", "Already locked");
  11271. return;
  11272. }
  11273. }
  11274. }
  11275. }
  11276. /* create new lock token */
  11277. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11278. if (dav_lock[i].path[0] == 0) {
  11279. char s[32];
  11280. dav_lock[i].locktime = mg_get_current_time_ns();
  11281. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11282. mg_md5(dav_lock[i].token,
  11283. link_buf,
  11284. "\x01",
  11285. s,
  11286. "\x01",
  11287. conn->request_info.remote_user,
  11288. NULL);
  11289. mg_strlcpy(dav_lock[i].path,
  11290. link_buf,
  11291. sizeof(dav_lock[i].path));
  11292. mg_strlcpy(dav_lock[i].user,
  11293. conn->request_info.remote_user,
  11294. sizeof(dav_lock[i].user));
  11295. lock_index = i;
  11296. break;
  11297. }
  11298. }
  11299. if (lock_index < 0) {
  11300. /* too many locks. Find oldest lock */
  11301. uint64_t oldest_locktime = dav_lock[0].locktime;
  11302. lock_index = 0;
  11303. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11304. if (dav_lock[i].locktime < oldest_locktime) {
  11305. oldest_locktime = dav_lock[i].locktime;
  11306. lock_index = i;
  11307. }
  11308. }
  11309. /* invalidate oldest lock */
  11310. dav_lock[lock_index].path[0] = 0;
  11311. }
  11312. }
  11313. mg_unlock_context(conn->phys_ctx);
  11314. /* return 200 "OK" */
  11315. conn->must_close = 1;
  11316. mg_response_header_start(conn, 200);
  11317. send_static_cache_header(conn);
  11318. send_additional_header(conn);
  11319. mg_response_header_add(conn,
  11320. "Content-Type",
  11321. "application/xml; charset=utf-8",
  11322. -1);
  11323. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11324. mg_response_header_send(conn);
  11325. /* Content */
  11326. mg_printf(conn,
  11327. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11328. "<d:prop xmlns:d=\"DAV:\">\n"
  11329. " <d:lockdiscovery>\n"
  11330. " <d:activelock>\n"
  11331. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11332. " <d:locktype><d:write/></d:locktype>\n"
  11333. " <d:owner>\n"
  11334. " <d:href>%s</d:href>\n"
  11335. " </d:owner>\n"
  11336. " <d:timeout>Second-%u</d:timeout>\n"
  11337. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11338. " <d:lockroot>\n"
  11339. " <d:href>%s</d:href>\n"
  11340. " </d:lockroot>\n"
  11341. " </d:activelock>\n"
  11342. " </d:lockdiscovery>\n"
  11343. " </d:prop>\n",
  11344. dav_lock[lock_index].user,
  11345. (LOCK_DURATION_S),
  11346. dav_lock[lock_index].token,
  11347. dav_lock[lock_index].path);
  11348. }
  11349. static void
  11350. dav_unlock_file(struct mg_connection *conn, const char *path)
  11351. {
  11352. /* internal function - therefore conn is assumed to be valid */
  11353. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11354. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11355. int lock_index;
  11356. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11357. return;
  11358. }
  11359. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11360. mg_lock_context(conn->phys_ctx);
  11361. /* find existing lock */
  11362. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11363. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11364. /* Success: return 204 "No Content" */
  11365. mg_unlock_context(conn->phys_ctx);
  11366. conn->must_close = 1;
  11367. mg_response_header_start(conn, 204);
  11368. mg_response_header_send(conn);
  11369. return;
  11370. }
  11371. }
  11372. mg_unlock_context(conn->phys_ctx);
  11373. /* Error: Cannot unlock a resource that is not locked */
  11374. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11375. }
  11376. static void
  11377. dav_proppatch(struct mg_connection *conn, const char *path)
  11378. {
  11379. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11380. if (!conn || !path || !conn->dom_ctx) {
  11381. return;
  11382. }
  11383. /* return 207 "Multi-Status" */
  11384. conn->must_close = 1;
  11385. mg_response_header_start(conn, 207);
  11386. send_static_cache_header(conn);
  11387. send_additional_header(conn);
  11388. mg_response_header_add(conn,
  11389. "Content-Type",
  11390. "application/xml; charset=utf-8",
  11391. -1);
  11392. mg_response_header_send(conn);
  11393. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11394. /* Content */
  11395. mg_printf(conn,
  11396. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11397. "<d:multistatus xmlns:d='DAV:'>\n"
  11398. "<d:response>\n<d:href>%s</d:href>\n",
  11399. link_buf);
  11400. mg_printf(conn,
  11401. "<d:propstat><d:status>HTTP/1.1 403 "
  11402. "Forbidden</d:status></d:propstat>\n");
  11403. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11404. }
  11405. #endif
  11406. CIVETWEB_API void
  11407. mg_lock_connection(struct mg_connection *conn)
  11408. {
  11409. if (conn) {
  11410. (void)pthread_mutex_lock(&conn->mutex);
  11411. }
  11412. }
  11413. CIVETWEB_API void
  11414. mg_unlock_connection(struct mg_connection *conn)
  11415. {
  11416. if (conn) {
  11417. (void)pthread_mutex_unlock(&conn->mutex);
  11418. }
  11419. }
  11420. CIVETWEB_API void
  11421. mg_lock_context(struct mg_context *ctx)
  11422. {
  11423. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11424. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11425. }
  11426. }
  11427. CIVETWEB_API void
  11428. mg_unlock_context(struct mg_context *ctx)
  11429. {
  11430. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11431. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11432. }
  11433. }
  11434. #if defined(USE_LUA)
  11435. #include "mod_lua.inl"
  11436. #endif /* USE_LUA */
  11437. #if defined(USE_DUKTAPE)
  11438. #include "mod_duktape.inl"
  11439. #endif /* USE_DUKTAPE */
  11440. #if defined(USE_WEBSOCKET)
  11441. #if !defined(NO_SSL_DL)
  11442. #if !defined(OPENSSL_API_3_0)
  11443. #define SHA_API static
  11444. #include "sha1.inl"
  11445. #endif
  11446. #endif
  11447. static int
  11448. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11449. {
  11450. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11451. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11452. size_t dst_len = sizeof(b64_sha);
  11453. #if !defined(OPENSSL_API_3_0)
  11454. SHA_CTX sha_ctx;
  11455. #endif
  11456. int truncated;
  11457. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11458. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11459. if (truncated) {
  11460. conn->must_close = 1;
  11461. return 0;
  11462. }
  11463. DEBUG_TRACE("%s", "Send websocket handshake");
  11464. #if defined(OPENSSL_API_3_0)
  11465. EVP_Digest((unsigned char *)buf,
  11466. (uint32_t)strlen(buf),
  11467. (unsigned char *)sha,
  11468. NULL,
  11469. EVP_get_digestbyname("sha1"),
  11470. NULL);
  11471. #else
  11472. SHA1_Init(&sha_ctx);
  11473. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11474. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11475. #endif
  11476. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11477. mg_printf(conn,
  11478. "HTTP/1.1 101 Switching Protocols\r\n"
  11479. "Upgrade: websocket\r\n"
  11480. "Connection: Upgrade\r\n"
  11481. "Sec-WebSocket-Accept: %s\r\n",
  11482. b64_sha);
  11483. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11484. // Send negotiated compression extension parameters
  11485. websocket_deflate_response(conn);
  11486. #endif
  11487. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11488. mg_printf(conn,
  11489. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11490. conn->request_info.acceptedWebSocketSubprotocol);
  11491. } else {
  11492. mg_printf(conn, "%s", "\r\n");
  11493. }
  11494. return 1;
  11495. }
  11496. #if !defined(MG_MAX_UNANSWERED_PING)
  11497. /* Configuration of the maximum number of websocket PINGs that might
  11498. * stay unanswered before the connection is considered broken.
  11499. * Note: The name of this define may still change (until it is
  11500. * defined as a compile parameter in a documentation).
  11501. */
  11502. #define MG_MAX_UNANSWERED_PING (5)
  11503. #endif
  11504. static void
  11505. read_websocket(struct mg_connection *conn,
  11506. mg_websocket_data_handler ws_data_handler,
  11507. void *callback_data)
  11508. {
  11509. /* Pointer to the beginning of the portion of the incoming websocket
  11510. * message queue.
  11511. * The original websocket upgrade request is never removed, so the queue
  11512. * begins after it. */
  11513. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11514. int n, error, exit_by_callback;
  11515. int ret;
  11516. /* body_len is the length of the entire queue in bytes
  11517. * len is the length of the current message
  11518. * data_len is the length of the current message's data payload
  11519. * header_len is the length of the current message's header */
  11520. size_t i, len, mask_len = 0, header_len, body_len;
  11521. uint64_t data_len = 0;
  11522. /* "The masking key is a 32-bit value chosen at random by the client."
  11523. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11524. */
  11525. unsigned char mask[4];
  11526. /* data points to the place where the message is stored when passed to
  11527. * the websocket_data callback. This is either mem on the stack, or a
  11528. * dynamically allocated buffer if it is too large. */
  11529. unsigned char mem[4096];
  11530. unsigned char mop; /* mask flag and opcode */
  11531. /* Variables used for connection monitoring */
  11532. double timeout = -1.0;
  11533. int enable_ping_pong = 0;
  11534. int ping_count = 0;
  11535. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11536. enable_ping_pong =
  11537. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11538. "yes");
  11539. }
  11540. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11541. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11542. }
  11543. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11544. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11545. }
  11546. if (timeout <= 0.0) {
  11547. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11548. }
  11549. /* Enter data processing loop */
  11550. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11551. conn->request_info.remote_addr,
  11552. conn->request_info.remote_port);
  11553. conn->in_websocket_handling = 1;
  11554. mg_set_thread_name("wsock");
  11555. /* Loop continuously, reading messages from the socket, invoking the
  11556. * callback, and waiting repeatedly until an error occurs. */
  11557. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11558. && (!conn->must_close)) {
  11559. header_len = 0;
  11560. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11561. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11562. len = buf[1] & 127;
  11563. mask_len = (buf[1] & 128) ? 4 : 0;
  11564. if ((len < 126) && (body_len >= mask_len)) {
  11565. /* inline 7-bit length field */
  11566. data_len = len;
  11567. header_len = 2 + mask_len;
  11568. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11569. /* 16-bit length field */
  11570. header_len = 4 + mask_len;
  11571. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11572. } else if (body_len >= (10 + mask_len)) {
  11573. /* 64-bit length field */
  11574. uint32_t l1, l2;
  11575. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11576. memcpy(&l2, &buf[6], 4);
  11577. header_len = 10 + mask_len;
  11578. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11579. if (data_len > (uint64_t)0x7FFF0000ul) {
  11580. /* no can do */
  11581. mg_cry_internal(
  11582. conn,
  11583. "%s",
  11584. "websocket out of memory; closing connection");
  11585. break;
  11586. }
  11587. }
  11588. }
  11589. if ((header_len > 0) && (body_len >= header_len)) {
  11590. /* Allocate space to hold websocket payload */
  11591. unsigned char *data = mem;
  11592. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11593. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11594. conn->phys_ctx);
  11595. if (data == NULL) {
  11596. /* Allocation failed, exit the loop and then close the
  11597. * connection */
  11598. mg_cry_internal(
  11599. conn,
  11600. "%s",
  11601. "websocket out of memory; closing connection");
  11602. break;
  11603. }
  11604. }
  11605. /* Copy the mask before we shift the queue and destroy it */
  11606. if (mask_len > 0) {
  11607. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11608. } else {
  11609. memset(mask, 0, sizeof(mask));
  11610. }
  11611. /* Read frame payload from the first message in the queue into
  11612. * data and advance the queue by moving the memory in place. */
  11613. DEBUG_ASSERT(body_len >= header_len);
  11614. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11615. mop = buf[0]; /* current mask and opcode */
  11616. /* Overflow case */
  11617. len = body_len - header_len;
  11618. memcpy(data, buf + header_len, len);
  11619. error = 0;
  11620. while ((uint64_t)len < data_len) {
  11621. n = pull_inner(NULL,
  11622. conn,
  11623. (char *)(data + len),
  11624. (int)(data_len - len),
  11625. timeout);
  11626. if (n <= -2) {
  11627. error = 1;
  11628. break;
  11629. } else if (n > 0) {
  11630. len += (size_t)n;
  11631. } else {
  11632. /* Timeout: should retry */
  11633. /* TODO: retry condition */
  11634. }
  11635. }
  11636. if (error) {
  11637. mg_cry_internal(
  11638. conn,
  11639. "%s",
  11640. "Websocket pull failed; closing connection");
  11641. if (data != mem) {
  11642. mg_free(data);
  11643. }
  11644. break;
  11645. }
  11646. conn->data_len = conn->request_len;
  11647. } else {
  11648. mop = buf[0]; /* current mask and opcode, overwritten by
  11649. * memmove() */
  11650. /* Length of the message being read at the front of the
  11651. * queue. Cast to 31 bit is OK, since we limited
  11652. * data_len before. */
  11653. len = (size_t)data_len + header_len;
  11654. /* Copy the data payload into the data pointer for the
  11655. * callback. Cast to 31 bit is OK, since we
  11656. * limited data_len */
  11657. memcpy(data, buf + header_len, (size_t)data_len);
  11658. /* Move the queue forward len bytes */
  11659. memmove(buf, buf + len, body_len - len);
  11660. /* Mark the queue as advanced */
  11661. conn->data_len -= (int)len;
  11662. }
  11663. /* Apply mask if necessary */
  11664. if (mask_len > 0) {
  11665. for (i = 0; i < (size_t)data_len; i++) {
  11666. data[i] ^= mask[i & 3];
  11667. }
  11668. }
  11669. exit_by_callback = 0;
  11670. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11671. /* filter PONG messages */
  11672. DEBUG_TRACE("PONG from %s:%u",
  11673. conn->request_info.remote_addr,
  11674. conn->request_info.remote_port);
  11675. /* No unanwered PINGs left */
  11676. ping_count = 0;
  11677. } else if (enable_ping_pong
  11678. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11679. /* reply PING messages */
  11680. DEBUG_TRACE("Reply PING from %s:%u",
  11681. conn->request_info.remote_addr,
  11682. conn->request_info.remote_port);
  11683. ret = mg_websocket_write(conn,
  11684. MG_WEBSOCKET_OPCODE_PONG,
  11685. (char *)data,
  11686. (size_t)data_len);
  11687. if (ret <= 0) {
  11688. /* Error: send failed */
  11689. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11690. break;
  11691. }
  11692. } else {
  11693. /* Exit the loop if callback signals to exit (server side),
  11694. * or "connection close" opcode received (client side). */
  11695. if (ws_data_handler != NULL) {
  11696. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11697. if (mop & 0x40) {
  11698. /* Inflate the data received if bit RSV1 is set. */
  11699. if (!conn->websocket_deflate_initialized) {
  11700. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11701. exit_by_callback = 1;
  11702. }
  11703. if (!exit_by_callback) {
  11704. size_t inflate_buf_size_old = 0;
  11705. size_t inflate_buf_size =
  11706. data_len
  11707. * 4; // Initial guess of the inflated message
  11708. // size. We double the memory when needed.
  11709. Bytef *inflated = NULL;
  11710. Bytef *new_mem = NULL;
  11711. conn->websocket_inflate_state.avail_in =
  11712. (uInt)(data_len + 4);
  11713. conn->websocket_inflate_state.next_in = data;
  11714. // Add trailing 0x00 0x00 0xff 0xff bytes
  11715. data[data_len] = '\x00';
  11716. data[data_len + 1] = '\x00';
  11717. data[data_len + 2] = '\xff';
  11718. data[data_len + 3] = '\xff';
  11719. do {
  11720. if (inflate_buf_size_old == 0) {
  11721. new_mem =
  11722. (Bytef *)mg_calloc(inflate_buf_size,
  11723. sizeof(Bytef));
  11724. } else {
  11725. inflate_buf_size *= 2;
  11726. new_mem =
  11727. (Bytef *)mg_realloc(inflated,
  11728. inflate_buf_size);
  11729. }
  11730. if (new_mem == NULL) {
  11731. mg_cry_internal(
  11732. conn,
  11733. "Out of memory: Cannot allocate "
  11734. "inflate buffer of %lu bytes",
  11735. (unsigned long)inflate_buf_size);
  11736. exit_by_callback = 1;
  11737. break;
  11738. }
  11739. inflated = new_mem;
  11740. conn->websocket_inflate_state.avail_out =
  11741. (uInt)(inflate_buf_size
  11742. - inflate_buf_size_old);
  11743. conn->websocket_inflate_state.next_out =
  11744. inflated + inflate_buf_size_old;
  11745. ret = inflate(&conn->websocket_inflate_state,
  11746. Z_SYNC_FLUSH);
  11747. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11748. || ret == Z_MEM_ERROR) {
  11749. mg_cry_internal(
  11750. conn,
  11751. "ZLIB inflate error: %i %s",
  11752. ret,
  11753. (conn->websocket_inflate_state.msg
  11754. ? conn->websocket_inflate_state.msg
  11755. : "<no error message>"));
  11756. exit_by_callback = 1;
  11757. break;
  11758. }
  11759. inflate_buf_size_old = inflate_buf_size;
  11760. } while (conn->websocket_inflate_state.avail_out
  11761. == 0);
  11762. inflate_buf_size -=
  11763. conn->websocket_inflate_state.avail_out;
  11764. if (!ws_data_handler(conn,
  11765. mop,
  11766. (char *)inflated,
  11767. inflate_buf_size,
  11768. callback_data)) {
  11769. exit_by_callback = 1;
  11770. }
  11771. mg_free(inflated);
  11772. }
  11773. } else
  11774. #endif
  11775. if (!ws_data_handler(conn,
  11776. mop,
  11777. (char *)data,
  11778. (size_t)data_len,
  11779. callback_data)) {
  11780. exit_by_callback = 1;
  11781. }
  11782. }
  11783. }
  11784. /* It a buffer has been allocated, free it again */
  11785. if (data != mem) {
  11786. mg_free(data);
  11787. }
  11788. if (exit_by_callback) {
  11789. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11790. conn->request_info.remote_addr,
  11791. conn->request_info.remote_port);
  11792. break;
  11793. }
  11794. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11795. /* Opcode == 8, connection close */
  11796. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11797. conn->request_info.remote_addr,
  11798. conn->request_info.remote_port);
  11799. break;
  11800. }
  11801. /* Not breaking the loop, process next websocket frame. */
  11802. } else {
  11803. /* Read from the socket into the next available location in the
  11804. * message queue. */
  11805. n = pull_inner(NULL,
  11806. conn,
  11807. conn->buf + conn->data_len,
  11808. conn->buf_size - conn->data_len,
  11809. timeout);
  11810. if (n <= -2) {
  11811. /* Error, no bytes read */
  11812. DEBUG_TRACE("PULL from %s:%u failed",
  11813. conn->request_info.remote_addr,
  11814. conn->request_info.remote_port);
  11815. break;
  11816. }
  11817. if (n > 0) {
  11818. conn->data_len += n;
  11819. /* Reset open PING count */
  11820. ping_count = 0;
  11821. } else {
  11822. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11823. && (!conn->must_close)) {
  11824. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11825. /* Stop sending PING */
  11826. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11827. "- closing connection",
  11828. ping_count,
  11829. conn->request_info.remote_addr,
  11830. conn->request_info.remote_port);
  11831. break;
  11832. }
  11833. if (enable_ping_pong) {
  11834. /* Send Websocket PING message */
  11835. DEBUG_TRACE("PING to %s:%u",
  11836. conn->request_info.remote_addr,
  11837. conn->request_info.remote_port);
  11838. ret = mg_websocket_write(conn,
  11839. MG_WEBSOCKET_OPCODE_PING,
  11840. NULL,
  11841. 0);
  11842. if (ret <= 0) {
  11843. /* Error: send failed */
  11844. DEBUG_TRACE("Send PING failed (%i)", ret);
  11845. break;
  11846. }
  11847. ping_count++;
  11848. }
  11849. }
  11850. /* Timeout: should retry */
  11851. /* TODO: get timeout def */
  11852. }
  11853. }
  11854. }
  11855. /* Leave data processing loop */
  11856. mg_set_thread_name("worker");
  11857. conn->in_websocket_handling = 0;
  11858. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11859. conn->request_info.remote_addr,
  11860. conn->request_info.remote_port);
  11861. }
  11862. static int
  11863. mg_websocket_write_exec(struct mg_connection *conn,
  11864. int opcode,
  11865. const char *data,
  11866. size_t dataLen,
  11867. uint32_t masking_key)
  11868. {
  11869. unsigned char header[14];
  11870. size_t headerLen;
  11871. int retval;
  11872. #if defined(GCC_DIAGNOSTIC)
  11873. /* Disable spurious conversion warning for GCC */
  11874. #pragma GCC diagnostic push
  11875. #pragma GCC diagnostic ignored "-Wconversion"
  11876. #endif
  11877. /* Note that POSIX/Winsock's send() is threadsafe
  11878. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11879. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11880. * push(), although that is only a problem if the packet is large or
  11881. * outgoing buffer is full). */
  11882. /* TODO: Check if this lock should be moved to user land.
  11883. * Currently the server sets this lock for websockets, but
  11884. * not for any other connection. It must be set for every
  11885. * conn read/written by more than one thread, no matter if
  11886. * it is a websocket or regular connection. */
  11887. (void)mg_lock_connection(conn);
  11888. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11889. size_t deflated_size = 0;
  11890. Bytef *deflated = 0;
  11891. // Deflate websocket messages over 100kb
  11892. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11893. if (use_deflate) {
  11894. if (!conn->websocket_deflate_initialized) {
  11895. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11896. return 0;
  11897. }
  11898. // Deflating the message
  11899. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11900. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11901. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11902. deflated_size = (size_t)compressBound((uLong)dataLen);
  11903. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11904. if (deflated == NULL) {
  11905. mg_cry_internal(
  11906. conn,
  11907. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11908. (unsigned long)deflated_size);
  11909. mg_unlock_connection(conn);
  11910. return -1;
  11911. }
  11912. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11913. conn->websocket_deflate_state.next_out = deflated;
  11914. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11915. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11916. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11917. } else
  11918. #endif
  11919. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11920. #if defined(GCC_DIAGNOSTIC)
  11921. #pragma GCC diagnostic pop
  11922. #endif
  11923. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11924. if (dataLen < 126) {
  11925. /* inline 7-bit length field */
  11926. header[1] = (unsigned char)dataLen;
  11927. headerLen = 2;
  11928. } else if (dataLen <= 0xFFFF) {
  11929. /* 16-bit length field */
  11930. uint16_t len = htons((uint16_t)dataLen);
  11931. header[1] = 126;
  11932. memcpy(header + 2, &len, 2);
  11933. headerLen = 4;
  11934. } else {
  11935. /* 64-bit length field */
  11936. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11937. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11938. header[1] = 127;
  11939. memcpy(header + 2, &len1, 4);
  11940. memcpy(header + 6, &len2, 4);
  11941. headerLen = 10;
  11942. }
  11943. if (masking_key) {
  11944. /* add mask */
  11945. header[1] |= 0x80;
  11946. memcpy(header + headerLen, &masking_key, 4);
  11947. headerLen += 4;
  11948. }
  11949. retval = mg_write(conn, header, headerLen);
  11950. if (retval != (int)headerLen) {
  11951. /* Did not send complete header */
  11952. retval = -1;
  11953. } else {
  11954. if (dataLen > 0) {
  11955. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11956. if (use_deflate) {
  11957. retval = mg_write(conn, deflated, dataLen);
  11958. mg_free(deflated);
  11959. } else
  11960. #endif
  11961. retval = mg_write(conn, data, dataLen);
  11962. }
  11963. /* if dataLen == 0, the header length (2) is returned */
  11964. }
  11965. /* TODO: Remove this unlock as well, when lock is removed. */
  11966. mg_unlock_connection(conn);
  11967. return retval;
  11968. }
  11969. CIVETWEB_API int
  11970. mg_websocket_write(struct mg_connection *conn,
  11971. int opcode,
  11972. const char *data,
  11973. size_t dataLen)
  11974. {
  11975. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11976. }
  11977. static void
  11978. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11979. {
  11980. size_t i = 0;
  11981. i = 0;
  11982. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11983. /* Convert in 32 bit words, if data is 4 byte aligned */
  11984. while (i < (in_len - 3)) {
  11985. *(uint32_t *)(void *)(out + i) =
  11986. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11987. i += 4;
  11988. }
  11989. }
  11990. if (i != in_len) {
  11991. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11992. while (i < in_len) {
  11993. *(uint8_t *)(void *)(out + i) =
  11994. *(uint8_t *)(void *)(in + i)
  11995. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11996. i++;
  11997. }
  11998. }
  11999. }
  12000. CIVETWEB_API int
  12001. mg_websocket_client_write(struct mg_connection *conn,
  12002. int opcode,
  12003. const char *data,
  12004. size_t dataLen)
  12005. {
  12006. int retval = -1;
  12007. char *masked_data =
  12008. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  12009. uint32_t masking_key = 0;
  12010. if (masked_data == NULL) {
  12011. /* Return -1 in an error case */
  12012. mg_cry_internal(conn,
  12013. "%s",
  12014. "Cannot allocate buffer for masked websocket response: "
  12015. "Out of memory");
  12016. return -1;
  12017. }
  12018. do {
  12019. /* Get a masking key - but not 0 */
  12020. masking_key = (uint32_t)get_random();
  12021. } while (masking_key == 0);
  12022. mask_data(data, dataLen, masking_key, masked_data);
  12023. retval = mg_websocket_write_exec(
  12024. conn, opcode, masked_data, dataLen, masking_key);
  12025. mg_free(masked_data);
  12026. return retval;
  12027. }
  12028. static void
  12029. handle_websocket_request(struct mg_connection *conn,
  12030. const char *path,
  12031. int is_callback_resource,
  12032. struct mg_websocket_subprotocols *subprotocols,
  12033. mg_websocket_connect_handler ws_connect_handler,
  12034. mg_websocket_ready_handler ws_ready_handler,
  12035. mg_websocket_data_handler ws_data_handler,
  12036. mg_websocket_close_handler ws_close_handler,
  12037. void *cbData)
  12038. {
  12039. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  12040. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  12041. ptrdiff_t lua_websock = 0;
  12042. #if !defined(USE_LUA)
  12043. (void)path;
  12044. #endif
  12045. /* Step 1: Check websocket protocol version. */
  12046. /* Step 1.1: Check Sec-WebSocket-Key. */
  12047. if (!websock_key) {
  12048. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  12049. * requires a Sec-WebSocket-Key header.
  12050. */
  12051. /* It could be the hixie draft version
  12052. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  12053. */
  12054. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  12055. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  12056. char key3[8];
  12057. if ((key1 != NULL) && (key2 != NULL)) {
  12058. /* This version uses 8 byte body data in a GET request */
  12059. conn->content_len = 8;
  12060. if (8 == mg_read(conn, key3, 8)) {
  12061. /* This is the hixie version */
  12062. mg_send_http_error(conn,
  12063. 426,
  12064. "%s",
  12065. "Protocol upgrade to RFC 6455 required");
  12066. return;
  12067. }
  12068. }
  12069. /* This is an unknown version */
  12070. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  12071. return;
  12072. }
  12073. /* Step 1.2: Check websocket protocol version. */
  12074. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  12075. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  12076. /* Reject wrong versions */
  12077. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  12078. return;
  12079. }
  12080. /* Step 1.3: Could check for "Host", but we do not really need this
  12081. * value for anything, so just ignore it. */
  12082. /* Step 2: If a callback is responsible, call it. */
  12083. if (is_callback_resource) {
  12084. /* Step 2.1 check and select subprotocol */
  12085. const char *protocols[64]; // max 64 headers
  12086. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  12087. "Sec-WebSocket-Protocol",
  12088. protocols,
  12089. 64);
  12090. if ((nbSubprotocolHeader > 0) && subprotocols) {
  12091. int headerNo, idx;
  12092. size_t len;
  12093. const char *sep, *curSubProtocol,
  12094. *acceptedWebSocketSubprotocol = NULL;
  12095. /* look for matching subprotocol */
  12096. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  12097. /* There might be multiple headers ... */
  12098. const char *protocol = protocols[headerNo];
  12099. curSubProtocol = protocol;
  12100. /* ... and in every header there might be a , separated list */
  12101. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  12102. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  12103. curSubProtocol++;
  12104. sep = strchr(curSubProtocol, ',');
  12105. if (sep) {
  12106. len = (size_t)(sep - curSubProtocol);
  12107. } else {
  12108. len = strlen(curSubProtocol);
  12109. }
  12110. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  12111. // COMPARE: curSubProtocol ==
  12112. // subprotocols->subprotocols[idx]
  12113. if ((strlen(subprotocols->subprotocols[idx]) == len)
  12114. && (strncmp(curSubProtocol,
  12115. subprotocols->subprotocols[idx],
  12116. len)
  12117. == 0)) {
  12118. acceptedWebSocketSubprotocol =
  12119. subprotocols->subprotocols[idx];
  12120. break;
  12121. }
  12122. }
  12123. curSubProtocol += len;
  12124. }
  12125. }
  12126. conn->request_info.acceptedWebSocketSubprotocol =
  12127. acceptedWebSocketSubprotocol;
  12128. }
  12129. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12130. websocket_deflate_negotiate(conn);
  12131. #endif
  12132. if ((ws_connect_handler != NULL)
  12133. && (ws_connect_handler(conn, cbData) != 0)) {
  12134. /* C callback has returned non-zero, do not proceed with
  12135. * handshake.
  12136. */
  12137. /* Note that C callbacks are no longer called when Lua is
  12138. * responsible, so C can no longer filter callbacks for Lua. */
  12139. return;
  12140. }
  12141. }
  12142. #if defined(USE_LUA)
  12143. /* Step 3: No callback. Check if Lua is responsible. */
  12144. else {
  12145. /* Step 3.1: Check if Lua is responsible. */
  12146. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  12147. lua_websock = match_prefix_strlen(
  12148. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  12149. }
  12150. if (lua_websock > 0) {
  12151. /* Step 3.2: Lua is responsible: call it. */
  12152. conn->lua_websocket_state = lua_websocket_new(path, conn);
  12153. if (!conn->lua_websocket_state) {
  12154. /* Lua rejected the new client */
  12155. return;
  12156. }
  12157. }
  12158. }
  12159. #endif
  12160. /* Step 4: Check if there is a responsible websocket handler. */
  12161. if (!is_callback_resource && !lua_websock) {
  12162. /* There is no callback, and Lua is not responsible either. */
  12163. /* Reply with a 404 Not Found. We are still at a standard
  12164. * HTTP request here, before the websocket handshake, so
  12165. * we can still send standard HTTP error replies. */
  12166. mg_send_http_error(conn, 404, "%s", "Not found");
  12167. return;
  12168. }
  12169. /* Step 5: The websocket connection has been accepted */
  12170. if (!send_websocket_handshake(conn, websock_key)) {
  12171. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  12172. return;
  12173. }
  12174. /* Step 6: Call the ready handler */
  12175. if (is_callback_resource) {
  12176. if (ws_ready_handler != NULL) {
  12177. ws_ready_handler(conn, cbData);
  12178. }
  12179. #if defined(USE_LUA)
  12180. } else if (lua_websock) {
  12181. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  12182. /* the ready handler returned false */
  12183. return;
  12184. }
  12185. #endif
  12186. }
  12187. /* Step 7: Enter the read loop */
  12188. if (is_callback_resource) {
  12189. read_websocket(conn, ws_data_handler, cbData);
  12190. #if defined(USE_LUA)
  12191. } else if (lua_websock) {
  12192. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  12193. #endif
  12194. }
  12195. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12196. /* Step 8: Close the deflate & inflate buffers */
  12197. if (conn->websocket_deflate_initialized) {
  12198. deflateEnd(&conn->websocket_deflate_state);
  12199. inflateEnd(&conn->websocket_inflate_state);
  12200. }
  12201. #endif
  12202. /* Step 9: Call the close handler */
  12203. if (ws_close_handler) {
  12204. ws_close_handler(conn, cbData);
  12205. }
  12206. }
  12207. #endif /* !USE_WEBSOCKET */
  12208. /* Is upgrade request:
  12209. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12210. * 1 = upgrade to websocket
  12211. * 2 = upgrade to HTTP/2
  12212. * -1 = upgrade to unknown protocol
  12213. */
  12214. static int
  12215. should_switch_to_protocol(const struct mg_connection *conn)
  12216. {
  12217. const char *connection_headers[8];
  12218. const char *upgrade_to;
  12219. int connection_header_count, i, should_upgrade;
  12220. /* A websocket protocol has the following HTTP headers:
  12221. *
  12222. * Connection: Upgrade
  12223. * Upgrade: Websocket
  12224. *
  12225. * It seems some clients use multiple headers:
  12226. * see https://github.com/civetweb/civetweb/issues/1083
  12227. */
  12228. connection_header_count = get_req_headers(&conn->request_info,
  12229. "Connection",
  12230. connection_headers,
  12231. 8);
  12232. should_upgrade = 0;
  12233. for (i = 0; i < connection_header_count; i++) {
  12234. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12235. should_upgrade = 1;
  12236. }
  12237. }
  12238. if (!should_upgrade) {
  12239. return PROTOCOL_TYPE_HTTP1;
  12240. }
  12241. upgrade_to = mg_get_header(conn, "Upgrade");
  12242. if (upgrade_to == NULL) {
  12243. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12244. return -1;
  12245. }
  12246. /* Upgrade to ... */
  12247. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12248. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12249. * "Sec-WebSocket-Version" are also required.
  12250. * Don't check them here, since even an unsupported websocket protocol
  12251. * request still IS a websocket request (in contrast to a standard HTTP
  12252. * request). It will fail later in handle_websocket_request.
  12253. */
  12254. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12255. }
  12256. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12257. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12258. }
  12259. /* Upgrade to another protocol */
  12260. return -1;
  12261. }
  12262. static int
  12263. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12264. {
  12265. int n;
  12266. unsigned int a, b, c, d, slash;
  12267. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12268. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12269. // integer value, but function will not report conversion
  12270. // errors; consider using 'strtol' instead
  12271. slash = 32;
  12272. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12273. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12274. // an integer value, but function will not report conversion
  12275. // errors; consider using 'strtol' instead
  12276. n = 0;
  12277. }
  12278. }
  12279. if ((n > 0) && ((size_t)n == vec->len)) {
  12280. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12281. /* IPv4 format */
  12282. if (sa->sa.sa_family == AF_INET) {
  12283. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12284. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12285. | ((uint32_t)c << 8) | (uint32_t)d;
  12286. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12287. return (ip & mask) == net;
  12288. }
  12289. return 0;
  12290. }
  12291. }
  12292. #if defined(USE_IPV6)
  12293. else {
  12294. char ad[50];
  12295. const char *p;
  12296. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12297. slash = 128;
  12298. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12299. n = 0;
  12300. }
  12301. }
  12302. if ((n <= 0) && no_strict) {
  12303. /* no square brackets? */
  12304. p = strchr(vec->ptr, '/');
  12305. if (p && (p < (vec->ptr + vec->len))) {
  12306. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12307. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12308. n += (int)(p - vec->ptr);
  12309. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12310. } else {
  12311. n = 0;
  12312. }
  12313. } else if (vec->len < sizeof(ad)) {
  12314. n = (int)vec->len;
  12315. slash = 128;
  12316. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12317. }
  12318. }
  12319. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12320. p = ad;
  12321. c = 0;
  12322. /* zone indexes are unsupported, at least two colons are needed */
  12323. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12324. if (*(p++) == ':') {
  12325. c++;
  12326. }
  12327. }
  12328. if ((*p == '\0') && (c >= 2)) {
  12329. struct sockaddr_in6 sin6;
  12330. unsigned int i;
  12331. /* for strict validation, an actual IPv6 argument is needed */
  12332. if (sa->sa.sa_family != AF_INET6) {
  12333. return 0;
  12334. }
  12335. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12336. /* IPv6 format */
  12337. for (i = 0; i < 16; i++) {
  12338. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12339. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12340. uint8_t mask = 0;
  12341. if (8 * i + 8 < slash) {
  12342. mask = 0xFFu;
  12343. } else if (8 * i < slash) {
  12344. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12345. }
  12346. if ((ip & mask) != net) {
  12347. return 0;
  12348. }
  12349. }
  12350. return 1;
  12351. }
  12352. }
  12353. }
  12354. }
  12355. #else
  12356. (void)no_strict;
  12357. #endif
  12358. /* malformed */
  12359. return -1;
  12360. }
  12361. static int
  12362. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12363. {
  12364. int throttle = 0;
  12365. struct vec vec, val;
  12366. char mult;
  12367. double v;
  12368. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12369. mult = ',';
  12370. if ((val.ptr == NULL)
  12371. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12372. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12373. // to an integer value, but function will not report
  12374. // conversion errors; consider using 'strtol' instead
  12375. || (v < 0)
  12376. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12377. && (mult != ','))) {
  12378. continue;
  12379. }
  12380. v *= (lowercase(&mult) == 'k')
  12381. ? 1024
  12382. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12383. if (vec.len == 1 && vec.ptr[0] == '*') {
  12384. throttle = (int)v;
  12385. } else {
  12386. int matched = parse_match_net(&vec, rsa, 0);
  12387. if (matched >= 0) {
  12388. /* a valid IP subnet */
  12389. if (matched) {
  12390. throttle = (int)v;
  12391. }
  12392. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12393. throttle = (int)v;
  12394. }
  12395. }
  12396. }
  12397. return throttle;
  12398. }
  12399. /* The mg_upload function is superseded by mg_handle_form_request. */
  12400. #include "handle_form.inl"
  12401. static int
  12402. get_first_ssl_listener_index(const struct mg_context *ctx)
  12403. {
  12404. unsigned int i;
  12405. int idx = -1;
  12406. if (ctx) {
  12407. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12408. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12409. }
  12410. }
  12411. return idx;
  12412. }
  12413. /* Return host (without port) */
  12414. static void
  12415. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12416. {
  12417. const char *host_header =
  12418. get_header(ri->http_headers, ri->num_headers, "Host");
  12419. host->ptr = NULL;
  12420. host->len = 0;
  12421. if (host_header != NULL) {
  12422. const char *pos;
  12423. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12424. * is found. */
  12425. if (*host_header == '[') {
  12426. pos = strchr(host_header, ']');
  12427. if (!pos) {
  12428. /* Malformed hostname starts with '[', but no ']' found */
  12429. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12430. return;
  12431. }
  12432. /* terminate after ']' */
  12433. host->ptr = host_header;
  12434. host->len = (size_t)(pos + 1 - host_header);
  12435. } else {
  12436. /* Otherwise, a ':' separates hostname and port number */
  12437. pos = strchr(host_header, ':');
  12438. if (pos != NULL) {
  12439. host->len = (size_t)(pos - host_header);
  12440. } else {
  12441. host->len = strlen(host_header);
  12442. }
  12443. host->ptr = host_header;
  12444. }
  12445. }
  12446. }
  12447. static int
  12448. switch_domain_context(struct mg_connection *conn)
  12449. {
  12450. struct vec host;
  12451. get_host_from_request_info(&host, &conn->request_info);
  12452. if (host.ptr) {
  12453. if (conn->ssl) {
  12454. /* This is a HTTPS connection, maybe we have a hostname
  12455. * from SNI (set in ssl_servername_callback). */
  12456. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12457. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12458. /* We are not using the default domain */
  12459. if ((strlen(sslhost) != host.len)
  12460. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12461. /* Mismatch between SNI domain and HTTP domain */
  12462. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12463. sslhost,
  12464. (int)host.len,
  12465. host.ptr);
  12466. return 0;
  12467. }
  12468. }
  12469. } else {
  12470. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12471. while (dom) {
  12472. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12473. size_t domNameLen = strlen(domName);
  12474. if ((domNameLen == host.len)
  12475. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12476. /* Found matching domain */
  12477. DEBUG_TRACE("HTTP domain %s found",
  12478. dom->config[AUTHENTICATION_DOMAIN]);
  12479. /* TODO: Check if this is a HTTP or HTTPS domain */
  12480. conn->dom_ctx = dom;
  12481. break;
  12482. }
  12483. mg_lock_context(conn->phys_ctx);
  12484. dom = dom->next;
  12485. mg_unlock_context(conn->phys_ctx);
  12486. }
  12487. }
  12488. DEBUG_TRACE("HTTP%s Host: %.*s",
  12489. conn->ssl ? "S" : "",
  12490. (int)host.len,
  12491. host.ptr);
  12492. } else {
  12493. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12494. return 1;
  12495. }
  12496. return 1;
  12497. }
  12498. static void
  12499. redirect_to_https_port(struct mg_connection *conn, int port)
  12500. {
  12501. char target_url[MG_BUF_LEN];
  12502. int truncated = 0;
  12503. const char *expect_proto =
  12504. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12505. /* Use "308 Permanent Redirect" */
  12506. int redirect_code = 308;
  12507. /* In any case, close the current connection */
  12508. conn->must_close = 1;
  12509. /* Send host, port, uri and (if it exists) ?query_string */
  12510. if (mg_construct_local_link(
  12511. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12512. < 0) {
  12513. truncated = 1;
  12514. } else if (conn->request_info.query_string != NULL) {
  12515. size_t slen1 = strlen(target_url);
  12516. size_t slen2 = strlen(conn->request_info.query_string);
  12517. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12518. target_url[slen1] = '?';
  12519. memcpy(target_url + slen1 + 1,
  12520. conn->request_info.query_string,
  12521. slen2);
  12522. target_url[slen1 + slen2 + 1] = 0;
  12523. } else {
  12524. truncated = 1;
  12525. }
  12526. }
  12527. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12528. * is used as buffer size) */
  12529. if (truncated) {
  12530. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12531. return;
  12532. }
  12533. /* Use redirect helper function */
  12534. mg_send_http_redirect(conn, target_url, redirect_code);
  12535. }
  12536. static void
  12537. mg_set_handler_type(struct mg_context *phys_ctx,
  12538. struct mg_domain_context *dom_ctx,
  12539. const char *uri,
  12540. int handler_type,
  12541. int is_delete_request,
  12542. mg_request_handler handler,
  12543. struct mg_websocket_subprotocols *subprotocols,
  12544. mg_websocket_connect_handler connect_handler,
  12545. mg_websocket_ready_handler ready_handler,
  12546. mg_websocket_data_handler data_handler,
  12547. mg_websocket_close_handler close_handler,
  12548. mg_authorization_handler auth_handler,
  12549. void *cbdata)
  12550. {
  12551. struct mg_handler_info *tmp_rh, **lastref;
  12552. size_t urilen = strlen(uri);
  12553. if (handler_type == WEBSOCKET_HANDLER) {
  12554. DEBUG_ASSERT(handler == NULL);
  12555. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12556. || ready_handler != NULL || data_handler != NULL
  12557. || close_handler != NULL);
  12558. DEBUG_ASSERT(auth_handler == NULL);
  12559. if (handler != NULL) {
  12560. return;
  12561. }
  12562. if (!is_delete_request && (connect_handler == NULL)
  12563. && (ready_handler == NULL) && (data_handler == NULL)
  12564. && (close_handler == NULL)) {
  12565. return;
  12566. }
  12567. if (auth_handler != NULL) {
  12568. return;
  12569. }
  12570. } else if (handler_type == REQUEST_HANDLER) {
  12571. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12572. && data_handler == NULL && close_handler == NULL);
  12573. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12574. DEBUG_ASSERT(auth_handler == NULL);
  12575. if ((connect_handler != NULL) || (ready_handler != NULL)
  12576. || (data_handler != NULL) || (close_handler != NULL)) {
  12577. return;
  12578. }
  12579. if (!is_delete_request && (handler == NULL)) {
  12580. return;
  12581. }
  12582. if (auth_handler != NULL) {
  12583. return;
  12584. }
  12585. } else if (handler_type == AUTH_HANDLER) {
  12586. DEBUG_ASSERT(handler == NULL);
  12587. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12588. && data_handler == NULL && close_handler == NULL);
  12589. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12590. if (handler != NULL) {
  12591. return;
  12592. }
  12593. if ((connect_handler != NULL) || (ready_handler != NULL)
  12594. || (data_handler != NULL) || (close_handler != NULL)) {
  12595. return;
  12596. }
  12597. if (!is_delete_request && (auth_handler == NULL)) {
  12598. return;
  12599. }
  12600. } else {
  12601. /* Unknown handler type. */
  12602. return;
  12603. }
  12604. if (!phys_ctx || !dom_ctx) {
  12605. /* no context available */
  12606. return;
  12607. }
  12608. mg_lock_context(phys_ctx);
  12609. /* first try to find an existing handler */
  12610. do {
  12611. lastref = &(dom_ctx->handlers);
  12612. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12613. tmp_rh = tmp_rh->next) {
  12614. if (tmp_rh->handler_type == handler_type
  12615. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12616. if (!is_delete_request) {
  12617. /* update existing handler */
  12618. if (handler_type == REQUEST_HANDLER) {
  12619. /* Wait for end of use before updating */
  12620. if (tmp_rh->refcount) {
  12621. mg_unlock_context(phys_ctx);
  12622. mg_sleep(1);
  12623. mg_lock_context(phys_ctx);
  12624. /* tmp_rh might have been freed, search again. */
  12625. break;
  12626. }
  12627. /* Ok, the handler is no more use -> Update it */
  12628. tmp_rh->handler = handler;
  12629. } else if (handler_type == WEBSOCKET_HANDLER) {
  12630. tmp_rh->subprotocols = subprotocols;
  12631. tmp_rh->connect_handler = connect_handler;
  12632. tmp_rh->ready_handler = ready_handler;
  12633. tmp_rh->data_handler = data_handler;
  12634. tmp_rh->close_handler = close_handler;
  12635. } else { /* AUTH_HANDLER */
  12636. tmp_rh->auth_handler = auth_handler;
  12637. }
  12638. tmp_rh->cbdata = cbdata;
  12639. } else {
  12640. /* remove existing handler */
  12641. if (handler_type == REQUEST_HANDLER) {
  12642. /* Wait for end of use before removing */
  12643. if (tmp_rh->refcount) {
  12644. tmp_rh->removing = 1;
  12645. mg_unlock_context(phys_ctx);
  12646. mg_sleep(1);
  12647. mg_lock_context(phys_ctx);
  12648. /* tmp_rh might have been freed, search again. */
  12649. break;
  12650. }
  12651. /* Ok, the handler is no more used */
  12652. }
  12653. *lastref = tmp_rh->next;
  12654. mg_free(tmp_rh->uri);
  12655. mg_free(tmp_rh);
  12656. }
  12657. mg_unlock_context(phys_ctx);
  12658. return;
  12659. }
  12660. lastref = &(tmp_rh->next);
  12661. }
  12662. } while (tmp_rh != NULL);
  12663. if (is_delete_request) {
  12664. /* no handler to set, this was a remove request to a non-existing
  12665. * handler */
  12666. mg_unlock_context(phys_ctx);
  12667. return;
  12668. }
  12669. tmp_rh =
  12670. (struct mg_handler_info *)mg_calloc_ctx(1,
  12671. sizeof(struct mg_handler_info),
  12672. phys_ctx);
  12673. if (tmp_rh == NULL) {
  12674. mg_unlock_context(phys_ctx);
  12675. mg_cry_ctx_internal(phys_ctx,
  12676. "%s",
  12677. "Cannot create new request handler struct, OOM");
  12678. return;
  12679. }
  12680. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12681. if (!tmp_rh->uri) {
  12682. mg_unlock_context(phys_ctx);
  12683. mg_free(tmp_rh);
  12684. mg_cry_ctx_internal(phys_ctx,
  12685. "%s",
  12686. "Cannot create new request handler struct, OOM");
  12687. return;
  12688. }
  12689. tmp_rh->uri_len = urilen;
  12690. if (handler_type == REQUEST_HANDLER) {
  12691. tmp_rh->refcount = 0;
  12692. tmp_rh->removing = 0;
  12693. tmp_rh->handler = handler;
  12694. } else if (handler_type == WEBSOCKET_HANDLER) {
  12695. tmp_rh->subprotocols = subprotocols;
  12696. tmp_rh->connect_handler = connect_handler;
  12697. tmp_rh->ready_handler = ready_handler;
  12698. tmp_rh->data_handler = data_handler;
  12699. tmp_rh->close_handler = close_handler;
  12700. } else { /* AUTH_HANDLER */
  12701. tmp_rh->auth_handler = auth_handler;
  12702. }
  12703. tmp_rh->cbdata = cbdata;
  12704. tmp_rh->handler_type = handler_type;
  12705. tmp_rh->next = NULL;
  12706. *lastref = tmp_rh;
  12707. mg_unlock_context(phys_ctx);
  12708. }
  12709. CIVETWEB_API void
  12710. mg_set_request_handler(struct mg_context *ctx,
  12711. const char *uri,
  12712. mg_request_handler handler,
  12713. void *cbdata)
  12714. {
  12715. mg_set_handler_type(ctx,
  12716. &(ctx->dd),
  12717. uri,
  12718. REQUEST_HANDLER,
  12719. handler == NULL,
  12720. handler,
  12721. NULL,
  12722. NULL,
  12723. NULL,
  12724. NULL,
  12725. NULL,
  12726. NULL,
  12727. cbdata);
  12728. }
  12729. CIVETWEB_API void
  12730. mg_set_websocket_handler(struct mg_context *ctx,
  12731. const char *uri,
  12732. mg_websocket_connect_handler connect_handler,
  12733. mg_websocket_ready_handler ready_handler,
  12734. mg_websocket_data_handler data_handler,
  12735. mg_websocket_close_handler close_handler,
  12736. void *cbdata)
  12737. {
  12738. mg_set_websocket_handler_with_subprotocols(ctx,
  12739. uri,
  12740. NULL,
  12741. connect_handler,
  12742. ready_handler,
  12743. data_handler,
  12744. close_handler,
  12745. cbdata);
  12746. }
  12747. CIVETWEB_API void
  12748. mg_set_websocket_handler_with_subprotocols(
  12749. struct mg_context *ctx,
  12750. const char *uri,
  12751. struct mg_websocket_subprotocols *subprotocols,
  12752. mg_websocket_connect_handler connect_handler,
  12753. mg_websocket_ready_handler ready_handler,
  12754. mg_websocket_data_handler data_handler,
  12755. mg_websocket_close_handler close_handler,
  12756. void *cbdata)
  12757. {
  12758. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12759. && (data_handler == NULL)
  12760. && (close_handler == NULL);
  12761. mg_set_handler_type(ctx,
  12762. &(ctx->dd),
  12763. uri,
  12764. WEBSOCKET_HANDLER,
  12765. is_delete_request,
  12766. NULL,
  12767. subprotocols,
  12768. connect_handler,
  12769. ready_handler,
  12770. data_handler,
  12771. close_handler,
  12772. NULL,
  12773. cbdata);
  12774. }
  12775. CIVETWEB_API void
  12776. mg_set_auth_handler(struct mg_context *ctx,
  12777. const char *uri,
  12778. mg_authorization_handler handler,
  12779. void *cbdata)
  12780. {
  12781. mg_set_handler_type(ctx,
  12782. &(ctx->dd),
  12783. uri,
  12784. AUTH_HANDLER,
  12785. handler == NULL,
  12786. NULL,
  12787. NULL,
  12788. NULL,
  12789. NULL,
  12790. NULL,
  12791. NULL,
  12792. handler,
  12793. cbdata);
  12794. }
  12795. static int
  12796. get_request_handler(struct mg_connection *conn,
  12797. int handler_type,
  12798. mg_request_handler *handler,
  12799. struct mg_websocket_subprotocols **subprotocols,
  12800. mg_websocket_connect_handler *connect_handler,
  12801. mg_websocket_ready_handler *ready_handler,
  12802. mg_websocket_data_handler *data_handler,
  12803. mg_websocket_close_handler *close_handler,
  12804. mg_authorization_handler *auth_handler,
  12805. void **cbdata,
  12806. struct mg_handler_info **handler_info)
  12807. {
  12808. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12809. if (request_info) {
  12810. const char *uri = request_info->local_uri;
  12811. size_t urilen = strlen(uri);
  12812. struct mg_handler_info *tmp_rh;
  12813. int step, matched;
  12814. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12815. return 0;
  12816. }
  12817. mg_lock_context(conn->phys_ctx);
  12818. for (step = 0; step < 3; step++) {
  12819. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12820. tmp_rh = tmp_rh->next) {
  12821. if (tmp_rh->handler_type != handler_type) {
  12822. continue;
  12823. }
  12824. if (step == 0) {
  12825. /* first try for an exact match */
  12826. matched = (tmp_rh->uri_len == urilen)
  12827. && (strcmp(tmp_rh->uri, uri) == 0);
  12828. } else if (step == 1) {
  12829. /* next try for a partial match, we will accept
  12830. uri/something */
  12831. matched =
  12832. (tmp_rh->uri_len < urilen)
  12833. && (uri[tmp_rh->uri_len] == '/')
  12834. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12835. } else {
  12836. /* finally try for pattern match */
  12837. matched =
  12838. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12839. }
  12840. if (matched) {
  12841. if (handler_type == WEBSOCKET_HANDLER) {
  12842. *subprotocols = tmp_rh->subprotocols;
  12843. *connect_handler = tmp_rh->connect_handler;
  12844. *ready_handler = tmp_rh->ready_handler;
  12845. *data_handler = tmp_rh->data_handler;
  12846. *close_handler = tmp_rh->close_handler;
  12847. } else if (handler_type == REQUEST_HANDLER) {
  12848. if (tmp_rh->removing) {
  12849. /* Treat as none found */
  12850. step = 2;
  12851. break;
  12852. }
  12853. *handler = tmp_rh->handler;
  12854. /* Acquire handler and give it back */
  12855. tmp_rh->refcount++;
  12856. *handler_info = tmp_rh;
  12857. } else { /* AUTH_HANDLER */
  12858. *auth_handler = tmp_rh->auth_handler;
  12859. }
  12860. *cbdata = tmp_rh->cbdata;
  12861. mg_unlock_context(conn->phys_ctx);
  12862. return 1;
  12863. }
  12864. }
  12865. }
  12866. mg_unlock_context(conn->phys_ctx);
  12867. }
  12868. return 0; /* none found */
  12869. }
  12870. /* Check if the script file is in a path, allowed for script files.
  12871. * This can be used if uploading files is possible not only for the server
  12872. * admin, and the upload mechanism does not check the file extension.
  12873. */
  12874. static int
  12875. is_in_script_path(const struct mg_connection *conn, const char *path)
  12876. {
  12877. /* TODO (Feature): Add config value for allowed script path.
  12878. * Default: All allowed. */
  12879. (void)conn;
  12880. (void)path;
  12881. return 1;
  12882. }
  12883. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12884. static int
  12885. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12886. int bits,
  12887. char *data,
  12888. size_t len,
  12889. void *cbdata)
  12890. {
  12891. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12892. if (pcallbacks->websocket_data) {
  12893. return pcallbacks->websocket_data(conn, bits, data, len);
  12894. }
  12895. /* No handler set - assume "OK" */
  12896. return 1;
  12897. }
  12898. static void
  12899. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12900. void *cbdata)
  12901. {
  12902. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12903. if (pcallbacks->connection_close) {
  12904. pcallbacks->connection_close(conn);
  12905. }
  12906. }
  12907. #endif
  12908. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12909. */
  12910. static void
  12911. release_handler_ref(struct mg_connection *conn,
  12912. struct mg_handler_info *handler_info)
  12913. {
  12914. if (handler_info != NULL) {
  12915. /* Use context lock for ref counter */
  12916. mg_lock_context(conn->phys_ctx);
  12917. handler_info->refcount--;
  12918. mg_unlock_context(conn->phys_ctx);
  12919. }
  12920. }
  12921. /* This is the heart of the Civetweb's logic.
  12922. * This function is called when the request is read, parsed and validated,
  12923. * and Civetweb must decide what action to take: serve a file, or
  12924. * a directory, or call embedded function, etcetera. */
  12925. static void
  12926. handle_request(struct mg_connection *conn)
  12927. {
  12928. struct mg_request_info *ri = &conn->request_info;
  12929. char path[UTF8_PATH_MAX];
  12930. int uri_len, ssl_index;
  12931. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12932. is_put_or_delete_request = 0, is_callback_resource = 0,
  12933. is_template_text_file = 0, is_webdav_request = 0;
  12934. int i;
  12935. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12936. mg_request_handler callback_handler = NULL;
  12937. struct mg_handler_info *handler_info = NULL;
  12938. struct mg_websocket_subprotocols *subprotocols;
  12939. mg_websocket_connect_handler ws_connect_handler = NULL;
  12940. mg_websocket_ready_handler ws_ready_handler = NULL;
  12941. mg_websocket_data_handler ws_data_handler = NULL;
  12942. mg_websocket_close_handler ws_close_handler = NULL;
  12943. void *callback_data = NULL;
  12944. mg_authorization_handler auth_handler = NULL;
  12945. void *auth_callback_data = NULL;
  12946. int handler_type;
  12947. time_t curtime = time(NULL);
  12948. char date[64];
  12949. char *tmp;
  12950. path[0] = 0;
  12951. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12952. conn->request_state = 0;
  12953. /* 1. get the request url */
  12954. /* 1.1. split into url and query string */
  12955. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12956. != NULL) {
  12957. *((char *)conn->request_info.query_string++) = '\0';
  12958. }
  12959. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12960. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12961. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12962. if (ssl_index >= 0) {
  12963. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12964. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12965. redirect_to_https_port(conn, port);
  12966. } else {
  12967. /* A http to https forward port has been specified,
  12968. * but no https port to forward to. */
  12969. mg_send_http_error(conn,
  12970. 503,
  12971. "%s",
  12972. "Error: SSL forward not configured properly");
  12973. mg_cry_internal(conn,
  12974. "%s",
  12975. "Can not redirect to SSL, no SSL port available");
  12976. }
  12977. return;
  12978. }
  12979. uri_len = (int)strlen(ri->local_uri);
  12980. /* 1.3. decode url (if config says so) */
  12981. if (should_decode_url(conn)) {
  12982. url_decode_in_place((char *)ri->local_uri);
  12983. }
  12984. /* URL decode the query-string only if explicitly set in the configuration
  12985. */
  12986. if (conn->request_info.query_string) {
  12987. if (should_decode_query_string(conn)) {
  12988. url_decode_in_place((char *)conn->request_info.query_string);
  12989. }
  12990. }
  12991. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12992. * possible. The fact that we cleaned the URI is stored in that the
  12993. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12994. * ri->local_uri_raw still points to memory allocated in
  12995. * worker_thread_run(). ri->local_uri is private to the request so we
  12996. * don't have to use preallocated memory here. */
  12997. tmp = mg_strdup(ri->local_uri_raw);
  12998. if (!tmp) {
  12999. /* Out of memory. We cannot do anything reasonable here. */
  13000. return;
  13001. }
  13002. remove_dot_segments(tmp);
  13003. ri->local_uri = tmp;
  13004. /* step 1. completed, the url is known now */
  13005. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  13006. /* 2. if this ip has limited speed, set it for this connection */
  13007. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  13008. &conn->client.rsa,
  13009. ri->local_uri);
  13010. /* 3. call a "handle everything" callback, if registered */
  13011. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  13012. /* Note that since V1.7 the "begin_request" function is called
  13013. * before an authorization check. If an authorization check is
  13014. * required, use a request_handler instead. */
  13015. i = conn->phys_ctx->callbacks.begin_request(conn);
  13016. if (i > 0) {
  13017. /* callback already processed the request. Store the
  13018. return value as a status code for the access log. */
  13019. conn->status_code = i;
  13020. if (!conn->must_close) {
  13021. discard_unread_request_data(conn);
  13022. }
  13023. DEBUG_TRACE("%s", "begin_request handled request");
  13024. return;
  13025. } else if (i == 0) {
  13026. /* civetweb should process the request */
  13027. } else {
  13028. /* unspecified - may change with the next version */
  13029. DEBUG_TRACE("%s", "done (undocumented behavior)");
  13030. return;
  13031. }
  13032. }
  13033. /* request not yet handled by a handler or redirect, so the request
  13034. * is processed here */
  13035. /* 4. Check for CORS preflight requests and handle them (if configured).
  13036. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  13037. */
  13038. if (!strcmp(ri->request_method, "OPTIONS")) {
  13039. /* Send a response to CORS preflights only if
  13040. * access_control_allow_methods is not NULL and not an empty string.
  13041. * In this case, scripts can still handle CORS. */
  13042. const char *cors_meth_cfg =
  13043. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  13044. const char *cors_orig_cfg =
  13045. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  13046. const char *cors_origin =
  13047. get_header(ri->http_headers, ri->num_headers, "Origin");
  13048. const char *cors_acrm = get_header(ri->http_headers,
  13049. ri->num_headers,
  13050. "Access-Control-Request-Method");
  13051. /* Todo: check if cors_origin is in cors_orig_cfg.
  13052. * Or, let the client check this. */
  13053. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  13054. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  13055. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  13056. /* This is a valid CORS preflight, and the server is configured
  13057. * to handle it automatically. */
  13058. const char *cors_acrh =
  13059. get_header(ri->http_headers,
  13060. ri->num_headers,
  13061. "Access-Control-Request-Headers");
  13062. const char *cors_cred_cfg =
  13063. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  13064. const char *cors_exphdr_cfg =
  13065. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  13066. gmt_time_string(date, sizeof(date), &curtime);
  13067. mg_printf(conn,
  13068. "HTTP/1.1 200 OK\r\n"
  13069. "Date: %s\r\n"
  13070. "Access-Control-Allow-Origin: %s\r\n"
  13071. "Access-Control-Allow-Methods: %s\r\n"
  13072. "Content-Length: 0\r\n"
  13073. "Connection: %s\r\n",
  13074. date,
  13075. cors_orig_cfg,
  13076. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  13077. suggest_connection_header(conn));
  13078. if (cors_cred_cfg && *cors_cred_cfg) {
  13079. mg_printf(conn,
  13080. "Access-Control-Allow-Credentials: %s\r\n",
  13081. cors_cred_cfg);
  13082. }
  13083. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  13084. mg_printf(conn,
  13085. "Access-Control-Expose-Headers: %s\r\n",
  13086. cors_exphdr_cfg);
  13087. }
  13088. if (cors_acrh || (cors_cred_cfg && *cors_cred_cfg)) {
  13089. /* CORS request is asking for additional headers */
  13090. const char *cors_hdr_cfg =
  13091. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  13092. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  13093. /* Allow only if access_control_allow_headers is
  13094. * not NULL and not an empty string. If this
  13095. * configuration is set to *, allow everything.
  13096. * Otherwise this configuration must be a list
  13097. * of allowed HTTP header names. */
  13098. mg_printf(conn,
  13099. "Access-Control-Allow-Headers: %s\r\n",
  13100. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  13101. : cors_hdr_cfg));
  13102. }
  13103. }
  13104. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  13105. mg_printf(conn, "\r\n");
  13106. DEBUG_TRACE("%s", "OPTIONS done");
  13107. return;
  13108. }
  13109. }
  13110. /* 5. interpret the url to find out how the request must be handled
  13111. */
  13112. /* 5.1. first test, if the request targets the regular http(s)://
  13113. * protocol namespace or the websocket ws(s):// protocol namespace.
  13114. */
  13115. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  13116. #if defined(USE_WEBSOCKET)
  13117. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  13118. #else
  13119. handler_type = REQUEST_HANDLER;
  13120. #endif /* defined(USE_WEBSOCKET) */
  13121. if (is_websocket_request) {
  13122. HTTP1_only;
  13123. }
  13124. /* 5.2. check if the request will be handled by a callback */
  13125. if (get_request_handler(conn,
  13126. handler_type,
  13127. &callback_handler,
  13128. &subprotocols,
  13129. &ws_connect_handler,
  13130. &ws_ready_handler,
  13131. &ws_data_handler,
  13132. &ws_close_handler,
  13133. NULL,
  13134. &callback_data,
  13135. &handler_info)) {
  13136. /* 5.2.1. A callback will handle this request. All requests
  13137. * handled by a callback have to be considered as requests
  13138. * to a script resource. */
  13139. is_callback_resource = 1;
  13140. is_script_resource = 1;
  13141. is_put_or_delete_request = is_put_or_delete_method(conn);
  13142. /* Never handle a C callback according to File WebDav rules,
  13143. * even if it is a webdav method */
  13144. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  13145. } else {
  13146. no_callback_resource:
  13147. /* 5.2.2. No callback is responsible for this request. The URI
  13148. * addresses a file based resource (static content or Lua/cgi
  13149. * scripts in the file system). */
  13150. is_callback_resource = 0;
  13151. interpret_uri(conn,
  13152. path,
  13153. sizeof(path),
  13154. &file.stat,
  13155. &is_found,
  13156. &is_script_resource,
  13157. &is_websocket_request,
  13158. &is_put_or_delete_request,
  13159. &is_webdav_request,
  13160. &is_template_text_file);
  13161. }
  13162. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  13163. if (is_webdav_request) {
  13164. /* TODO: Do we need a config option? */
  13165. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  13166. if (webdav_enable[0] != 'y') {
  13167. mg_send_http_error(conn,
  13168. 405,
  13169. "%s method not allowed",
  13170. conn->request_info.request_method);
  13171. DEBUG_TRACE("%s", "webdav rejected");
  13172. return;
  13173. }
  13174. }
  13175. /* 6. authorization check */
  13176. /* 6.1. a custom authorization handler is installed */
  13177. if (get_request_handler(conn,
  13178. AUTH_HANDLER,
  13179. NULL,
  13180. NULL,
  13181. NULL,
  13182. NULL,
  13183. NULL,
  13184. NULL,
  13185. &auth_handler,
  13186. &auth_callback_data,
  13187. NULL)) {
  13188. if (!auth_handler(conn, auth_callback_data)) {
  13189. /* Callback handler will not be used anymore. Release it */
  13190. release_handler_ref(conn, handler_info);
  13191. DEBUG_TRACE("%s", "auth handler rejected request");
  13192. return;
  13193. }
  13194. } else if (is_put_or_delete_request && !is_script_resource
  13195. && !is_callback_resource) {
  13196. HTTP1_only;
  13197. /* 6.2. this request is a PUT/DELETE to a real file */
  13198. /* 6.2.1. thus, the server must have real files */
  13199. #if defined(NO_FILES)
  13200. if (1) {
  13201. #else
  13202. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  13203. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  13204. #endif
  13205. /* This code path will not be called for request handlers */
  13206. DEBUG_ASSERT(handler_info == NULL);
  13207. /* This server does not have any real files, thus the
  13208. * PUT/DELETE methods are not valid. */
  13209. mg_send_http_error(conn,
  13210. 405,
  13211. "%s method not allowed",
  13212. conn->request_info.request_method);
  13213. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  13214. return;
  13215. }
  13216. #if !defined(NO_FILES)
  13217. /* 6.2.2. Check if put authorization for static files is
  13218. * available.
  13219. */
  13220. if (!is_authorized_for_put(conn)) {
  13221. send_authorization_request(conn, NULL);
  13222. DEBUG_TRACE("%s", "file write needs authorization");
  13223. return;
  13224. }
  13225. #endif
  13226. } else {
  13227. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13228. * or it is a PUT or DELETE request to a resource that does not
  13229. * correspond to a file. Check authorization. */
  13230. if (!check_authorization(conn, path)) {
  13231. send_authorization_request(conn, NULL);
  13232. /* Callback handler will not be used anymore. Release it */
  13233. release_handler_ref(conn, handler_info);
  13234. DEBUG_TRACE("%s", "access authorization required");
  13235. return;
  13236. }
  13237. }
  13238. /* request is authorized or does not need authorization */
  13239. /* 7. check if there are request handlers for this uri */
  13240. if (is_callback_resource) {
  13241. HTTP1_only;
  13242. if (!is_websocket_request) {
  13243. i = callback_handler(conn, callback_data);
  13244. /* Callback handler will not be used anymore. Release it */
  13245. release_handler_ref(conn, handler_info);
  13246. if (i > 0) {
  13247. /* Do nothing, callback has served the request. Store
  13248. * then return value as status code for the log and discard
  13249. * all data from the client not used by the callback. */
  13250. conn->status_code = i;
  13251. if (!conn->must_close) {
  13252. discard_unread_request_data(conn);
  13253. }
  13254. } else {
  13255. /* The handler did NOT handle the request. */
  13256. /* Some proper reactions would be:
  13257. * a) close the connections without sending anything
  13258. * b) send a 404 not found
  13259. * c) try if there is a file matching the URI
  13260. * It would be possible to do a, b or c in the callback
  13261. * implementation, and return 1 - we cannot do anything
  13262. * here, that is not possible in the callback.
  13263. *
  13264. * TODO: What would be the best reaction here?
  13265. * (Note: The reaction may change, if there is a better
  13266. * idea.)
  13267. */
  13268. /* For the moment, use option c: We look for a proper file,
  13269. * but since a file request is not always a script resource,
  13270. * the authorization check might be different. */
  13271. callback_handler = NULL;
  13272. /* Here we are at a dead end:
  13273. * According to URI matching, a callback should be
  13274. * responsible for handling the request,
  13275. * we called it, but the callback declared itself
  13276. * not responsible.
  13277. * We use a goto here, to get out of this dead end,
  13278. * and continue with the default handling.
  13279. * A goto here is simpler and better to understand
  13280. * than some curious loop. */
  13281. goto no_callback_resource;
  13282. }
  13283. } else {
  13284. #if defined(USE_WEBSOCKET)
  13285. handle_websocket_request(conn,
  13286. path,
  13287. is_callback_resource,
  13288. subprotocols,
  13289. ws_connect_handler,
  13290. ws_ready_handler,
  13291. ws_data_handler,
  13292. ws_close_handler,
  13293. callback_data);
  13294. #endif
  13295. }
  13296. DEBUG_TRACE("%s", "websocket handling done");
  13297. return;
  13298. }
  13299. /* 8. handle websocket requests */
  13300. #if defined(USE_WEBSOCKET)
  13301. if (is_websocket_request) {
  13302. HTTP1_only;
  13303. if (is_script_resource) {
  13304. if (is_in_script_path(conn, path)) {
  13305. /* Websocket Lua script */
  13306. handle_websocket_request(conn,
  13307. path,
  13308. 0 /* Lua Script */,
  13309. NULL,
  13310. NULL,
  13311. NULL,
  13312. NULL,
  13313. NULL,
  13314. conn->phys_ctx->user_data);
  13315. } else {
  13316. /* Script was in an illegal path */
  13317. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13318. }
  13319. } else {
  13320. mg_send_http_error(conn, 404, "%s", "Not found");
  13321. }
  13322. DEBUG_TRACE("%s", "websocket script done");
  13323. return;
  13324. } else
  13325. #endif
  13326. #if defined(NO_FILES)
  13327. /* 9a. In case the server uses only callbacks, this uri is
  13328. * unknown.
  13329. * Then, all request handling ends here. */
  13330. mg_send_http_error(conn, 404, "%s", "Not Found");
  13331. #else
  13332. /* 9b. This request is either for a static file or resource handled
  13333. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13334. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13335. mg_send_http_error(conn, 404, "%s", "Not Found");
  13336. DEBUG_TRACE("%s", "no document root available");
  13337. return;
  13338. }
  13339. /* 10. Request is handled by a script */
  13340. if (is_script_resource) {
  13341. HTTP1_only;
  13342. handle_file_based_request(conn, path, &file);
  13343. DEBUG_TRACE("%s", "script handling done");
  13344. return;
  13345. }
  13346. /* Request was not handled by a callback or script. It will be
  13347. * handled by a server internal method. */
  13348. /* 11. Handle put/delete/mkcol requests */
  13349. if (is_put_or_delete_request) {
  13350. HTTP1_only;
  13351. /* 11.1. PUT method */
  13352. if (!strcmp(ri->request_method, "PUT")) {
  13353. put_file(conn, path);
  13354. DEBUG_TRACE("handling %s request to %s done",
  13355. ri->request_method,
  13356. path);
  13357. return;
  13358. }
  13359. /* 11.2. DELETE method */
  13360. if (!strcmp(ri->request_method, "DELETE")) {
  13361. delete_file(conn, path);
  13362. DEBUG_TRACE("handling %s request to %s done",
  13363. ri->request_method,
  13364. path);
  13365. return;
  13366. }
  13367. /* 11.3. MKCOL method */
  13368. if (!strcmp(ri->request_method, "MKCOL")) {
  13369. dav_mkcol(conn, path);
  13370. DEBUG_TRACE("handling %s request to %s done",
  13371. ri->request_method,
  13372. path);
  13373. return;
  13374. }
  13375. /* 11.4. MOVE method */
  13376. if (!strcmp(ri->request_method, "MOVE")) {
  13377. dav_move_file(conn, path, 0);
  13378. DEBUG_TRACE("handling %s request to %s done",
  13379. ri->request_method,
  13380. path);
  13381. return;
  13382. }
  13383. if (!strcmp(ri->request_method, "COPY")) {
  13384. dav_move_file(conn, path, 1);
  13385. DEBUG_TRACE("handling %s request to %s done",
  13386. ri->request_method,
  13387. path);
  13388. return;
  13389. }
  13390. /* 11.5. LOCK method */
  13391. if (!strcmp(ri->request_method, "LOCK")) {
  13392. dav_lock_file(conn, path);
  13393. DEBUG_TRACE("handling %s request to %s done",
  13394. ri->request_method,
  13395. path);
  13396. return;
  13397. }
  13398. /* 11.6. UNLOCK method */
  13399. if (!strcmp(ri->request_method, "UNLOCK")) {
  13400. dav_unlock_file(conn, path);
  13401. DEBUG_TRACE("handling %s request to %s done",
  13402. ri->request_method,
  13403. path);
  13404. return;
  13405. }
  13406. /* 11.7. PROPPATCH method */
  13407. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13408. dav_proppatch(conn, path);
  13409. DEBUG_TRACE("handling %s request to %s done",
  13410. ri->request_method,
  13411. path);
  13412. return;
  13413. }
  13414. /* 11.8. Other methods, e.g.: PATCH
  13415. * This method is not supported for static resources,
  13416. * only for scripts (Lua, CGI) and callbacks. */
  13417. mg_send_http_error(conn,
  13418. 405,
  13419. "%s method not allowed",
  13420. conn->request_info.request_method);
  13421. DEBUG_TRACE("method %s on %s is not supported",
  13422. ri->request_method,
  13423. path);
  13424. return;
  13425. }
  13426. /* 11. File does not exist, or it was configured that it should be
  13427. * hidden */
  13428. if (!is_found || (must_hide_file(conn, path))) {
  13429. mg_send_http_error(conn, 404, "%s", "Not found");
  13430. DEBUG_TRACE("handling %s request to %s: file not found",
  13431. ri->request_method,
  13432. path);
  13433. return;
  13434. }
  13435. /* 12. Directory uris should end with a slash */
  13436. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13437. && (ri->local_uri[uri_len - 1] != '/')) {
  13438. /* Path + server root */
  13439. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13440. char *new_path;
  13441. if (ri->query_string) {
  13442. buflen += strlen(ri->query_string);
  13443. }
  13444. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13445. if (!new_path) {
  13446. mg_send_http_error(conn, 500, "out or memory");
  13447. } else {
  13448. mg_get_request_link(conn, new_path, buflen - 1);
  13449. strcat(new_path, "/");
  13450. if (ri->query_string) {
  13451. /* Append ? and query string */
  13452. strcat(new_path, "?");
  13453. strcat(new_path, ri->query_string);
  13454. }
  13455. mg_send_http_redirect(conn, new_path, 301);
  13456. mg_free(new_path);
  13457. }
  13458. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13459. ri->request_method,
  13460. path);
  13461. return;
  13462. }
  13463. /* 13. Handle other methods than GET/HEAD */
  13464. /* 13.1. Handle PROPFIND */
  13465. if (!strcmp(ri->request_method, "PROPFIND")) {
  13466. handle_propfind(conn, path, &file.stat);
  13467. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13468. return;
  13469. }
  13470. /* 13.2. Handle OPTIONS for files */
  13471. if (!strcmp(ri->request_method, "OPTIONS")) {
  13472. /* This standard handler is only used for real files.
  13473. * Scripts should support the OPTIONS method themselves, to allow a
  13474. * maximum flexibility.
  13475. * Lua and CGI scripts may fully support CORS this way (including
  13476. * preflights). */
  13477. send_options(conn);
  13478. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13479. return;
  13480. }
  13481. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13482. if ((0 != strcmp(ri->request_method, "GET"))
  13483. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13484. mg_send_http_error(conn,
  13485. 405,
  13486. "%s method not allowed",
  13487. conn->request_info.request_method);
  13488. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13489. return;
  13490. }
  13491. /* 14. directories */
  13492. if (file.stat.is_directory) {
  13493. /* Substitute files have already been handled above. */
  13494. /* Here we can either generate and send a directory listing,
  13495. * or send an "access denied" error. */
  13496. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13497. "yes")) {
  13498. handle_directory_request(conn, path);
  13499. } else {
  13500. mg_send_http_error(conn,
  13501. 403,
  13502. "%s",
  13503. "Error: Directory listing denied");
  13504. }
  13505. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13506. return;
  13507. }
  13508. /* 15. Files with search/replace patterns: LSP and SSI */
  13509. if (is_template_text_file) {
  13510. HTTP1_only;
  13511. handle_file_based_request(conn, path, &file);
  13512. DEBUG_TRACE("handling %s request to %s done (template)",
  13513. ri->request_method,
  13514. path);
  13515. return;
  13516. }
  13517. /* 16. Static file - maybe cached */
  13518. #if !defined(NO_CACHING)
  13519. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13520. /* Send 304 "Not Modified" - this must not send any body data */
  13521. handle_not_modified_static_file_request(conn, &file);
  13522. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13523. ri->request_method,
  13524. path);
  13525. return;
  13526. }
  13527. #endif /* !NO_CACHING */
  13528. /* 17. Static file - not cached */
  13529. handle_static_file_request(conn, path, &file, NULL, NULL);
  13530. DEBUG_TRACE("handling %s request to %s done (static)",
  13531. ri->request_method,
  13532. path);
  13533. #endif /* !defined(NO_FILES) */
  13534. }
  13535. #if !defined(NO_FILESYSTEMS)
  13536. static void
  13537. handle_file_based_request(struct mg_connection *conn,
  13538. const char *path,
  13539. struct mg_file *file)
  13540. {
  13541. #if !defined(NO_CGI)
  13542. int cgi_config_idx, inc, max;
  13543. #endif
  13544. if (!conn || !conn->dom_ctx) {
  13545. return;
  13546. }
  13547. #if defined(USE_LUA)
  13548. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13549. path)
  13550. > 0) {
  13551. if (is_in_script_path(conn, path)) {
  13552. /* Lua server page: an SSI like page containing mostly plain
  13553. * html code plus some tags with server generated contents. */
  13554. handle_lsp_request(conn, path, file, NULL);
  13555. } else {
  13556. /* Script was in an illegal path */
  13557. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13558. }
  13559. return;
  13560. }
  13561. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13562. > 0) {
  13563. if (is_in_script_path(conn, path)) {
  13564. /* Lua in-server module script: a CGI like script used to
  13565. * generate the entire reply. */
  13566. mg_exec_lua_script(conn, path, NULL);
  13567. } else {
  13568. /* Script was in an illegal path */
  13569. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13570. }
  13571. return;
  13572. }
  13573. #endif
  13574. #if defined(USE_DUKTAPE)
  13575. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13576. path)
  13577. > 0) {
  13578. if (is_in_script_path(conn, path)) {
  13579. /* Call duktape to generate the page */
  13580. mg_exec_duktape_script(conn, path);
  13581. } else {
  13582. /* Script was in an illegal path */
  13583. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13584. }
  13585. return;
  13586. }
  13587. #endif
  13588. #if !defined(NO_CGI)
  13589. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13590. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13591. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13592. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13593. if (match_prefix_strlen(
  13594. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13595. path)
  13596. > 0) {
  13597. if (is_in_script_path(conn, path)) {
  13598. /* CGI scripts may support all HTTP methods */
  13599. handle_cgi_request(conn, path, cgi_config_idx);
  13600. } else {
  13601. /* Script was in an illegal path */
  13602. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13603. }
  13604. return;
  13605. }
  13606. }
  13607. }
  13608. #endif /* !NO_CGI */
  13609. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13610. if (is_in_script_path(conn, path)) {
  13611. handle_ssi_file_request(conn, path, file);
  13612. } else {
  13613. /* Script was in an illegal path */
  13614. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13615. }
  13616. return;
  13617. }
  13618. #if !defined(NO_CACHING)
  13619. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13620. /* Send 304 "Not Modified" - this must not send any body data */
  13621. handle_not_modified_static_file_request(conn, file);
  13622. return;
  13623. }
  13624. #endif /* !NO_CACHING */
  13625. handle_static_file_request(conn, path, file, NULL, NULL);
  13626. }
  13627. #endif /* NO_FILESYSTEMS */
  13628. static void
  13629. close_all_listening_sockets(struct mg_context *ctx)
  13630. {
  13631. unsigned int i;
  13632. if (!ctx) {
  13633. return;
  13634. }
  13635. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13636. closesocket(ctx->listening_sockets[i].sock);
  13637. #if defined(USE_X_DOM_SOCKET)
  13638. /* For unix domain sockets, the socket name represents a file that has
  13639. * to be deleted. */
  13640. /* See
  13641. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13642. */
  13643. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13644. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13645. IGNORE_UNUSED_RESULT(
  13646. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13647. }
  13648. #endif
  13649. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13650. }
  13651. mg_free(ctx->listening_sockets);
  13652. ctx->listening_sockets = NULL;
  13653. mg_free(ctx->listening_socket_fds);
  13654. ctx->listening_socket_fds = NULL;
  13655. }
  13656. /* Valid listening port specification is: [ip_address:]port[s]
  13657. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13658. * Examples for IPv6: [::]:80, [::1]:80,
  13659. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13660. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13661. * In order to bind to both, IPv4 and IPv6, you can either add
  13662. * both ports using 8080,[::]:8080, or the short form +8080.
  13663. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13664. * one only accepting IPv4 the other only IPv6. +8080 creates
  13665. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13666. * environment, they might work differently, or might not work
  13667. * at all - it must be tested what options work best in the
  13668. * relevant network environment.
  13669. */
  13670. static int
  13671. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13672. {
  13673. unsigned int a, b, c, d;
  13674. unsigned port;
  13675. unsigned long portUL;
  13676. int len;
  13677. const char *cb;
  13678. char *endptr;
  13679. #if defined(USE_IPV6)
  13680. char buf[100] = {0};
  13681. #endif
  13682. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13683. * Also, all-zeroes in the socket address means binding to all addresses
  13684. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13685. memset(so, 0, sizeof(*so));
  13686. so->lsa.sin.sin_family = AF_INET;
  13687. *ip_version = 0;
  13688. /* Initialize len as invalid. */
  13689. port = 0;
  13690. len = 0;
  13691. /* Test for different ways to format this string */
  13692. if (sscanf(vec->ptr,
  13693. "%u.%u.%u.%u:%u%n",
  13694. &a,
  13695. &b,
  13696. &c,
  13697. &d,
  13698. &port,
  13699. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13700. // to an integer value, but function will not report
  13701. // conversion errors; consider using 'strtol' instead
  13702. == 5) {
  13703. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13704. so->lsa.sin.sin_addr.s_addr =
  13705. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13706. so->lsa.sin.sin_port = htons((uint16_t)port);
  13707. *ip_version = 4;
  13708. #if defined(USE_IPV6)
  13709. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13710. && ((size_t)len <= vec->len)
  13711. && mg_inet_pton(
  13712. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13713. /* IPv6 address, examples: see above */
  13714. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13715. */
  13716. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13717. *ip_version = 6;
  13718. #endif
  13719. } else if ((vec->ptr[0] == '+')
  13720. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13721. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13722. // string to an integer value, but function will not
  13723. // report conversion errors; consider using 'strtol'
  13724. // instead
  13725. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13726. /* Add 1 to len for the + character we skipped before */
  13727. len++;
  13728. #if defined(USE_IPV6)
  13729. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13730. so->lsa.sin6.sin6_family = AF_INET6;
  13731. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13732. *ip_version = 4 + 6;
  13733. #else
  13734. /* Bind to IPv4 only, since IPv6 is not built in. */
  13735. so->lsa.sin.sin_port = htons((uint16_t)port);
  13736. *ip_version = 4;
  13737. #endif
  13738. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13739. && (vec->ptr != endptr)) {
  13740. len = (int)(endptr - vec->ptr);
  13741. port = (uint16_t)portUL;
  13742. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13743. so->lsa.sin.sin_port = htons((uint16_t)port);
  13744. *ip_version = 4;
  13745. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13746. /* String could be a hostname. This check algorithm
  13747. * will only work for RFC 952 compliant hostnames,
  13748. * starting with a letter, containing only letters,
  13749. * digits and hyphen ('-'). Newer specs may allow
  13750. * more, but this is not guaranteed here, since it
  13751. * may interfere with rules for port option lists. */
  13752. /* According to RFC 1035, hostnames are restricted to 255 characters
  13753. * in total (63 between two dots). */
  13754. char hostname[256];
  13755. size_t hostnlen = (size_t)(cb - vec->ptr);
  13756. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13757. /* This would be invalid in any case */
  13758. *ip_version = 0;
  13759. return 0;
  13760. }
  13761. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13762. if (mg_inet_pton(
  13763. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13764. if (sscanf(cb + 1, "%u%n", &port, &len)
  13765. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13766. // string to an integer value, but function will not
  13767. // report conversion errors; consider using 'strtol'
  13768. // instead
  13769. *ip_version = 4;
  13770. so->lsa.sin.sin_port = htons((uint16_t)port);
  13771. len += (int)(hostnlen + 1);
  13772. } else {
  13773. len = 0;
  13774. }
  13775. #if defined(USE_IPV6)
  13776. } else if (mg_inet_pton(AF_INET6,
  13777. hostname,
  13778. &so->lsa.sin6,
  13779. sizeof(so->lsa.sin6),
  13780. 1)) {
  13781. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13782. *ip_version = 6;
  13783. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13784. len += (int)(hostnlen + 1);
  13785. } else {
  13786. len = 0;
  13787. }
  13788. #endif
  13789. } else {
  13790. len = 0;
  13791. }
  13792. #if defined(USE_X_DOM_SOCKET)
  13793. } else if (vec->ptr[0] == 'x') {
  13794. /* unix (linux) domain socket */
  13795. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13796. len = vec->len;
  13797. so->lsa.sun.sun_family = AF_UNIX;
  13798. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13799. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13800. port = 0;
  13801. *ip_version = 99;
  13802. } else {
  13803. /* String too long */
  13804. len = 0;
  13805. }
  13806. #endif
  13807. } else {
  13808. /* Parsing failure. */
  13809. len = 0;
  13810. }
  13811. /* sscanf and the option splitting code ensure the following condition
  13812. * Make sure the port is valid and vector ends with the port, 'o', 's', or
  13813. * 'r' */
  13814. if ((len > 0) && (is_valid_port(port))) {
  13815. int bad_suffix = 0;
  13816. size_t i;
  13817. /* Parse any suffix character(s) after the port number */
  13818. for (i = len; i < vec->len; i++) {
  13819. unsigned char *opt = NULL;
  13820. switch (vec->ptr[i]) {
  13821. case 'o':
  13822. opt = &so->is_optional;
  13823. break;
  13824. case 'r':
  13825. opt = &so->ssl_redir;
  13826. break;
  13827. case 's':
  13828. opt = &so->is_ssl;
  13829. break;
  13830. default: /* empty */
  13831. break;
  13832. }
  13833. if ((opt) && (*opt == 0))
  13834. *opt = 1;
  13835. else {
  13836. bad_suffix = 1;
  13837. break;
  13838. }
  13839. }
  13840. if ((bad_suffix == 0) && ((so->is_ssl == 0) || (so->ssl_redir == 0))) {
  13841. return 1;
  13842. }
  13843. }
  13844. /* Reset ip_version to 0 if there is an error */
  13845. *ip_version = 0;
  13846. return 0;
  13847. }
  13848. /* Is there any SSL port in use? */
  13849. static int
  13850. is_ssl_port_used(const char *ports)
  13851. {
  13852. if (ports) {
  13853. /* There are several different allowed syntax variants:
  13854. * - "80" for a single port using every network interface
  13855. * - "localhost:80" for a single port using only localhost
  13856. * - "80,localhost:8080" for two ports, one bound to localhost
  13857. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13858. * to IPv4 localhost, one to IPv6 localhost
  13859. * - "+80" use port 80 for IPv4 and IPv6
  13860. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13861. * for both: IPv4 and IPv4
  13862. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13863. * additionally port 8080 bound to localhost connections
  13864. *
  13865. * If we just look for 's' anywhere in the string, "localhost:80"
  13866. * will be detected as SSL (false positive).
  13867. * Looking for 's' after a digit may cause false positives in
  13868. * "my24service:8080".
  13869. * Looking from 's' backward if there are only ':' and numbers
  13870. * before will not work for "24service:8080" (non SSL, port 8080)
  13871. * or "24s" (SSL, port 24).
  13872. *
  13873. * Remark: Initially hostnames were not allowed to start with a
  13874. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13875. * Section 2.1).
  13876. *
  13877. * To get this correct, the entire string must be parsed as a whole,
  13878. * reading it as a list element for element and parsing with an
  13879. * algorithm equivalent to parse_port_string.
  13880. *
  13881. * In fact, we use local interface names here, not arbitrary
  13882. * hostnames, so in most cases the only name will be "localhost".
  13883. *
  13884. * So, for now, we use this simple algorithm, that may still return
  13885. * a false positive in bizarre cases.
  13886. */
  13887. int i;
  13888. int portslen = (int)strlen(ports);
  13889. char prevIsNumber = 0;
  13890. for (i = 0; i < portslen; i++) {
  13891. if (prevIsNumber) {
  13892. int suffixCharIdx = (ports[i] == 'o')
  13893. ? (i + 1)
  13894. : i; /* allow "os" and "or" suffixes */
  13895. if (ports[suffixCharIdx] == 's'
  13896. || ports[suffixCharIdx] == 'r') {
  13897. return 1;
  13898. }
  13899. }
  13900. if (ports[i] >= '0' && ports[i] <= '9') {
  13901. prevIsNumber = 1;
  13902. } else {
  13903. prevIsNumber = 0;
  13904. }
  13905. }
  13906. }
  13907. return 0;
  13908. }
  13909. static int
  13910. set_ports_option(struct mg_context *phys_ctx)
  13911. {
  13912. const char *list;
  13913. int on = 1;
  13914. #if defined(USE_IPV6)
  13915. int off = 0;
  13916. #endif
  13917. struct vec vec;
  13918. struct socket so, *ptr;
  13919. struct mg_pollfd *pfd;
  13920. union usa usa;
  13921. socklen_t len;
  13922. int ip_version;
  13923. int portsTotal = 0;
  13924. int portsOk = 0;
  13925. const char *opt_txt;
  13926. long opt_listen_backlog;
  13927. if (!phys_ctx) {
  13928. return 0;
  13929. }
  13930. memset(&so, 0, sizeof(so));
  13931. memset(&usa, 0, sizeof(usa));
  13932. len = sizeof(usa);
  13933. list = phys_ctx->dd.config[LISTENING_PORTS];
  13934. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13935. portsTotal++;
  13936. if (!parse_port_string(&vec, &so, &ip_version)) {
  13937. mg_cry_ctx_internal(
  13938. phys_ctx,
  13939. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13940. (int)vec.len,
  13941. vec.ptr,
  13942. portsTotal,
  13943. "[IP_ADDRESS:]PORT[s|r]");
  13944. continue;
  13945. }
  13946. #if !defined(NO_SSL)
  13947. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13948. mg_cry_ctx_internal(phys_ctx,
  13949. "Cannot add SSL socket (entry %i)",
  13950. portsTotal);
  13951. continue;
  13952. }
  13953. #endif
  13954. /* Create socket. */
  13955. /* For a list of protocol numbers (e.g., TCP==6) see:
  13956. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13957. */
  13958. if ((so.sock =
  13959. socket(so.lsa.sa.sa_family,
  13960. SOCK_STREAM,
  13961. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13962. == INVALID_SOCKET) {
  13963. mg_cry_ctx_internal(phys_ctx,
  13964. "cannot create socket (entry %i)",
  13965. portsTotal);
  13966. continue;
  13967. }
  13968. #if defined(_WIN32)
  13969. /* Windows SO_REUSEADDR lets many procs binds to a
  13970. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13971. * if someone already has the socket -- DTL */
  13972. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13973. * Windows might need a few seconds before
  13974. * the same port can be used again in the
  13975. * same process, so a short Sleep may be
  13976. * required between mg_stop and mg_start.
  13977. */
  13978. if (setsockopt(so.sock,
  13979. SOL_SOCKET,
  13980. SO_EXCLUSIVEADDRUSE,
  13981. (SOCK_OPT_TYPE)&on,
  13982. sizeof(on))
  13983. != 0) {
  13984. /* Set reuse option, but don't abort on errors. */
  13985. mg_cry_ctx_internal(
  13986. phys_ctx,
  13987. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13988. portsTotal);
  13989. }
  13990. #else
  13991. if (setsockopt(so.sock,
  13992. SOL_SOCKET,
  13993. SO_REUSEADDR,
  13994. (SOCK_OPT_TYPE)&on,
  13995. sizeof(on))
  13996. != 0) {
  13997. /* Set reuse option, but don't abort on errors. */
  13998. mg_cry_ctx_internal(
  13999. phys_ctx,
  14000. "cannot set socket option SO_REUSEADDR (entry %i)",
  14001. portsTotal);
  14002. }
  14003. #endif
  14004. #if defined(USE_X_DOM_SOCKET)
  14005. if (ip_version == 99) {
  14006. /* Unix domain socket */
  14007. } else
  14008. #endif
  14009. if (ip_version > 4) {
  14010. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  14011. #if defined(USE_IPV6)
  14012. if (ip_version > 6) {
  14013. if (so.lsa.sa.sa_family == AF_INET6
  14014. && setsockopt(so.sock,
  14015. IPPROTO_IPV6,
  14016. IPV6_V6ONLY,
  14017. (void *)&off,
  14018. sizeof(off))
  14019. != 0) {
  14020. /* Set IPv6 only option, but don't abort on errors. */
  14021. mg_cry_ctx_internal(phys_ctx,
  14022. "cannot set socket option "
  14023. "IPV6_V6ONLY=off (entry %i)",
  14024. portsTotal);
  14025. }
  14026. } else {
  14027. if (so.lsa.sa.sa_family == AF_INET6
  14028. && setsockopt(so.sock,
  14029. IPPROTO_IPV6,
  14030. IPV6_V6ONLY,
  14031. (void *)&on,
  14032. sizeof(on))
  14033. != 0) {
  14034. /* Set IPv6 only option, but don't abort on errors. */
  14035. mg_cry_ctx_internal(phys_ctx,
  14036. "cannot set socket option "
  14037. "IPV6_V6ONLY=on (entry %i)",
  14038. portsTotal);
  14039. }
  14040. }
  14041. #else
  14042. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  14043. closesocket(so.sock);
  14044. so.sock = INVALID_SOCKET;
  14045. continue;
  14046. #endif
  14047. }
  14048. if (so.lsa.sa.sa_family == AF_INET) {
  14049. len = sizeof(so.lsa.sin);
  14050. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14051. mg_cry_ctx_internal(phys_ctx,
  14052. "cannot bind to %.*s: %d (%s)",
  14053. (int)vec.len,
  14054. vec.ptr,
  14055. (int)ERRNO,
  14056. strerror(errno));
  14057. closesocket(so.sock);
  14058. so.sock = INVALID_SOCKET;
  14059. if (so.is_optional) {
  14060. portsOk++; /* it's okay if we couldn't bind, this port is
  14061. optional anyway */
  14062. }
  14063. continue;
  14064. }
  14065. }
  14066. #if defined(USE_IPV6)
  14067. else if (so.lsa.sa.sa_family == AF_INET6) {
  14068. len = sizeof(so.lsa.sin6);
  14069. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14070. mg_cry_ctx_internal(phys_ctx,
  14071. "cannot bind to IPv6 %.*s: %d (%s)",
  14072. (int)vec.len,
  14073. vec.ptr,
  14074. (int)ERRNO,
  14075. strerror(errno));
  14076. closesocket(so.sock);
  14077. so.sock = INVALID_SOCKET;
  14078. if (so.is_optional) {
  14079. portsOk++; /* it's okay if we couldn't bind, this port is
  14080. optional anyway */
  14081. }
  14082. continue;
  14083. }
  14084. }
  14085. #endif
  14086. #if defined(USE_X_DOM_SOCKET)
  14087. else if (so.lsa.sa.sa_family == AF_UNIX) {
  14088. len = sizeof(so.lsa.sun);
  14089. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14090. mg_cry_ctx_internal(phys_ctx,
  14091. "cannot bind to unix socket %s: %d (%s)",
  14092. so.lsa.sun.sun_path,
  14093. (int)ERRNO,
  14094. strerror(errno));
  14095. closesocket(so.sock);
  14096. so.sock = INVALID_SOCKET;
  14097. if (so.is_optional) {
  14098. portsOk++; /* it's okay if we couldn't bind, this port is
  14099. optional anyway */
  14100. }
  14101. continue;
  14102. }
  14103. }
  14104. #endif
  14105. else {
  14106. mg_cry_ctx_internal(
  14107. phys_ctx,
  14108. "cannot bind: address family not supported (entry %i)",
  14109. portsTotal);
  14110. closesocket(so.sock);
  14111. so.sock = INVALID_SOCKET;
  14112. continue;
  14113. }
  14114. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  14115. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  14116. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  14117. mg_cry_ctx_internal(phys_ctx,
  14118. "%s value \"%s\" is invalid",
  14119. config_options[LISTEN_BACKLOG_SIZE].name,
  14120. opt_txt);
  14121. closesocket(so.sock);
  14122. so.sock = INVALID_SOCKET;
  14123. continue;
  14124. }
  14125. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  14126. mg_cry_ctx_internal(phys_ctx,
  14127. "cannot listen to %.*s: %d (%s)",
  14128. (int)vec.len,
  14129. vec.ptr,
  14130. (int)ERRNO,
  14131. strerror(errno));
  14132. closesocket(so.sock);
  14133. so.sock = INVALID_SOCKET;
  14134. continue;
  14135. }
  14136. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  14137. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  14138. int err = (int)ERRNO;
  14139. mg_cry_ctx_internal(phys_ctx,
  14140. "call to getsockname failed %.*s: %d (%s)",
  14141. (int)vec.len,
  14142. vec.ptr,
  14143. err,
  14144. strerror(errno));
  14145. closesocket(so.sock);
  14146. so.sock = INVALID_SOCKET;
  14147. continue;
  14148. }
  14149. /* Update lsa port in case of random free ports */
  14150. #if defined(USE_IPV6)
  14151. if (so.lsa.sa.sa_family == AF_INET6) {
  14152. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  14153. } else
  14154. #endif
  14155. {
  14156. so.lsa.sin.sin_port = usa.sin.sin_port;
  14157. }
  14158. if ((ptr = (struct socket *)
  14159. mg_realloc_ctx(phys_ctx->listening_sockets,
  14160. (phys_ctx->num_listening_sockets + 1)
  14161. * sizeof(phys_ctx->listening_sockets[0]),
  14162. phys_ctx))
  14163. == NULL) {
  14164. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14165. closesocket(so.sock);
  14166. so.sock = INVALID_SOCKET;
  14167. continue;
  14168. }
  14169. /* The +2 below includes the original +1 (for the socket we're about to
  14170. * add), plus another +1 for the thread_shutdown_notification_socket
  14171. * that we'll also want to poll() on so that mg_stop() can return
  14172. * quickly
  14173. */
  14174. if ((pfd = (struct mg_pollfd *)
  14175. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  14176. (phys_ctx->num_listening_sockets + 2)
  14177. * sizeof(phys_ctx->listening_socket_fds[0]),
  14178. phys_ctx))
  14179. == NULL) {
  14180. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14181. closesocket(so.sock);
  14182. so.sock = INVALID_SOCKET;
  14183. mg_free(ptr);
  14184. continue;
  14185. }
  14186. set_close_on_exec(so.sock, NULL, phys_ctx);
  14187. phys_ctx->listening_sockets = ptr;
  14188. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  14189. phys_ctx->listening_socket_fds = pfd;
  14190. phys_ctx->num_listening_sockets++;
  14191. portsOk++;
  14192. }
  14193. if (portsOk != portsTotal) {
  14194. close_all_listening_sockets(phys_ctx);
  14195. portsOk = 0;
  14196. }
  14197. return portsOk;
  14198. }
  14199. static const char *
  14200. header_val(const struct mg_connection *conn, const char *header)
  14201. {
  14202. const char *header_value;
  14203. if ((header_value = mg_get_header(conn, header)) == NULL) {
  14204. return "-";
  14205. } else {
  14206. return header_value;
  14207. }
  14208. }
  14209. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  14210. #include "external_log_access.inl"
  14211. #elif !defined(NO_FILESYSTEMS)
  14212. static void
  14213. log_access(const struct mg_connection *conn)
  14214. {
  14215. const struct mg_request_info *ri;
  14216. struct mg_file fi;
  14217. char date[64], src_addr[IP_ADDR_STR_LEN];
  14218. #if defined(REENTRANT_TIME)
  14219. struct tm _tm;
  14220. struct tm *tm = &_tm;
  14221. #else
  14222. struct tm *tm;
  14223. #endif
  14224. const char *referer;
  14225. const char *user_agent;
  14226. char log_buf[4096];
  14227. if (!conn || !conn->dom_ctx) {
  14228. return;
  14229. }
  14230. /* Set log message to "empty" */
  14231. log_buf[0] = 0;
  14232. #if defined(USE_LUA)
  14233. if (conn->phys_ctx->lua_bg_log_available) {
  14234. int ret;
  14235. struct mg_context *ctx = conn->phys_ctx;
  14236. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14237. pthread_mutex_lock(&ctx->lua_bg_mutex);
  14238. /* call "log()" in Lua */
  14239. lua_getglobal(lstate, "log");
  14240. prepare_lua_request_info_inner(conn, lstate);
  14241. push_lua_response_log_data(conn, lstate);
  14242. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  14243. if (ret == 0) {
  14244. int t = lua_type(lstate, -1);
  14245. if (t == LUA_TBOOLEAN) {
  14246. if (lua_toboolean(lstate, -1) == 0) {
  14247. /* log() returned false: do not log */
  14248. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14249. return;
  14250. }
  14251. /* log returned true: continue logging */
  14252. } else if (t == LUA_TSTRING) {
  14253. size_t len;
  14254. const char *txt = lua_tolstring(lstate, -1, &len);
  14255. if ((len == 0) || (*txt == 0)) {
  14256. /* log() returned empty string: do not log */
  14257. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14258. return;
  14259. }
  14260. /* Copy test from Lua into log_buf */
  14261. if (len >= sizeof(log_buf)) {
  14262. len = sizeof(log_buf) - 1;
  14263. }
  14264. memcpy(log_buf, txt, len);
  14265. log_buf[len] = 0;
  14266. }
  14267. } else {
  14268. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14269. }
  14270. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14271. }
  14272. #endif
  14273. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14274. if (mg_fopen(conn,
  14275. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14276. MG_FOPEN_MODE_APPEND,
  14277. &fi)
  14278. == 0) {
  14279. fi.access.fp = NULL;
  14280. }
  14281. } else {
  14282. fi.access.fp = NULL;
  14283. }
  14284. /* Log is written to a file and/or a callback. If both are not set,
  14285. * executing the rest of the function is pointless. */
  14286. if ((fi.access.fp == NULL)
  14287. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14288. return;
  14289. }
  14290. /* If we did not get a log message from Lua, create it here. */
  14291. if (!log_buf[0]) {
  14292. #if defined(REENTRANT_TIME)
  14293. localtime_r(&conn->conn_birth_time, tm);
  14294. #else
  14295. tm = localtime(&conn->conn_birth_time);
  14296. #endif
  14297. if (tm != NULL) {
  14298. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14299. } else {
  14300. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14301. }
  14302. ri = &conn->request_info;
  14303. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14304. referer = header_val(conn, "Referer");
  14305. user_agent = header_val(conn, "User-Agent");
  14306. mg_snprintf(conn,
  14307. NULL, /* Ignore truncation in access log */
  14308. log_buf,
  14309. sizeof(log_buf),
  14310. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14311. " %s %s",
  14312. src_addr,
  14313. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14314. date,
  14315. ri->request_method ? ri->request_method : "-",
  14316. ri->request_uri ? ri->request_uri : "-",
  14317. ri->query_string ? "?" : "",
  14318. ri->query_string ? ri->query_string : "",
  14319. ri->http_version,
  14320. conn->status_code,
  14321. conn->num_bytes_sent,
  14322. referer,
  14323. user_agent);
  14324. }
  14325. /* Here we have a log message in log_buf. Call the callback */
  14326. if (conn->phys_ctx->callbacks.log_access) {
  14327. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14328. /* do not log if callback returns non-zero */
  14329. if (fi.access.fp) {
  14330. mg_fclose(&fi.access);
  14331. }
  14332. return;
  14333. }
  14334. }
  14335. /* Store in file */
  14336. if (fi.access.fp) {
  14337. int ok = 1;
  14338. flockfile(fi.access.fp);
  14339. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14340. ok = 0;
  14341. }
  14342. if (fflush(fi.access.fp) != 0) {
  14343. ok = 0;
  14344. }
  14345. funlockfile(fi.access.fp);
  14346. if (mg_fclose(&fi.access) != 0) {
  14347. ok = 0;
  14348. }
  14349. if (!ok) {
  14350. mg_cry_internal(conn,
  14351. "Error writing log file %s",
  14352. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14353. }
  14354. }
  14355. }
  14356. #else
  14357. #error "Either enable filesystems or provide a custom log_access implementation"
  14358. #endif /* Externally provided function */
  14359. /* Verify given socket address against the ACL.
  14360. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14361. */
  14362. static int
  14363. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14364. {
  14365. int allowed, flag, matched;
  14366. struct vec vec;
  14367. if (phys_ctx) {
  14368. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14369. /* If any ACL is set, deny by default */
  14370. allowed = (list == NULL) ? '+' : '-';
  14371. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14372. flag = vec.ptr[0];
  14373. matched = -1;
  14374. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14375. vec.ptr++;
  14376. vec.len--;
  14377. matched = parse_match_net(&vec, sa, 1);
  14378. }
  14379. if (matched < 0) {
  14380. mg_cry_ctx_internal(phys_ctx,
  14381. "%s: subnet must be [+|-]IP-addr[/x]",
  14382. __func__);
  14383. return -1;
  14384. }
  14385. if (matched) {
  14386. allowed = flag;
  14387. }
  14388. }
  14389. return allowed == '+';
  14390. }
  14391. return -1;
  14392. }
  14393. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14394. static int
  14395. set_uid_option(struct mg_context *phys_ctx)
  14396. {
  14397. int success = 0;
  14398. if (phys_ctx) {
  14399. /* We are currently running as curr_uid. */
  14400. const uid_t curr_uid = getuid();
  14401. /* If set, we want to run as run_as_user. */
  14402. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14403. const struct passwd *to_pw = NULL;
  14404. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14405. /* run_as_user does not exist on the system. We can't proceed
  14406. * further. */
  14407. mg_cry_ctx_internal(phys_ctx,
  14408. "%s: unknown user [%s]",
  14409. __func__,
  14410. run_as_user);
  14411. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14412. /* There was either no request to change user, or we're already
  14413. * running as run_as_user. Nothing else to do.
  14414. */
  14415. success = 1;
  14416. } else {
  14417. /* Valid change request. */
  14418. if (setgid(to_pw->pw_gid) == -1) {
  14419. mg_cry_ctx_internal(phys_ctx,
  14420. "%s: setgid(%s): %s",
  14421. __func__,
  14422. run_as_user,
  14423. strerror(errno));
  14424. } else if (setgroups(0, NULL) == -1) {
  14425. mg_cry_ctx_internal(phys_ctx,
  14426. "%s: setgroups(): %s",
  14427. __func__,
  14428. strerror(errno));
  14429. } else if (setuid(to_pw->pw_uid) == -1) {
  14430. mg_cry_ctx_internal(phys_ctx,
  14431. "%s: setuid(%s): %s",
  14432. __func__,
  14433. run_as_user,
  14434. strerror(errno));
  14435. } else {
  14436. success = 1;
  14437. }
  14438. }
  14439. }
  14440. return success;
  14441. }
  14442. #endif /* !_WIN32 */
  14443. static void
  14444. tls_dtor(void *key)
  14445. {
  14446. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14447. /* key == pthread_getspecific(sTlsKey); */
  14448. if (tls) {
  14449. if (tls->is_master == 2) {
  14450. tls->is_master = -3; /* Mark memory as dead */
  14451. mg_free(tls);
  14452. }
  14453. }
  14454. pthread_setspecific(sTlsKey, NULL);
  14455. }
  14456. #if defined(USE_MBEDTLS)
  14457. /* Check if SSL is required.
  14458. * If so, set up ctx->ssl_ctx pointer. */
  14459. static int
  14460. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14461. {
  14462. if (!phys_ctx) {
  14463. return 0;
  14464. }
  14465. if (!dom_ctx) {
  14466. dom_ctx = &(phys_ctx->dd);
  14467. }
  14468. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14469. /* No SSL port is set. No need to setup SSL. */
  14470. return 1;
  14471. }
  14472. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14473. if (dom_ctx->ssl_ctx == NULL) {
  14474. fprintf(stderr, "ssl_ctx malloc failed\n");
  14475. return 0;
  14476. }
  14477. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14478. == 0
  14479. ? 1
  14480. : 0;
  14481. }
  14482. #elif defined(USE_GNUTLS)
  14483. /* Check if SSL is required.
  14484. * If so, set up ctx->ssl_ctx pointer. */
  14485. static int
  14486. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14487. {
  14488. if (!phys_ctx) {
  14489. return 0;
  14490. }
  14491. if (!dom_ctx) {
  14492. dom_ctx = &(phys_ctx->dd);
  14493. }
  14494. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14495. /* No SSL port is set. No need to setup SSL. */
  14496. return 1;
  14497. }
  14498. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14499. if (dom_ctx->ssl_ctx == NULL) {
  14500. fprintf(stderr, "ssl_ctx malloc failed\n");
  14501. return 0;
  14502. }
  14503. return gtls_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14504. == 0
  14505. ? 1
  14506. : 0;
  14507. }
  14508. #elif !defined(NO_SSL)
  14509. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14510. struct mg_domain_context *dom_ctx,
  14511. const char *pem,
  14512. const char *chain);
  14513. static const char *ssl_error(void);
  14514. static int
  14515. refresh_trust(struct mg_connection *conn)
  14516. {
  14517. struct stat cert_buf;
  14518. int64_t t = 0;
  14519. const char *pem;
  14520. const char *chain;
  14521. int should_verify_peer;
  14522. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14523. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14524. * refresh_trust still can not work. */
  14525. return 0;
  14526. }
  14527. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14528. if (chain == NULL) {
  14529. /* pem is not NULL here */
  14530. chain = pem;
  14531. }
  14532. if (*chain == 0) {
  14533. chain = NULL;
  14534. }
  14535. if (stat(pem, &cert_buf) != -1) {
  14536. t = (int64_t)cert_buf.st_mtime;
  14537. }
  14538. mg_lock_context(conn->phys_ctx);
  14539. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14540. conn->dom_ctx->ssl_cert_last_mtime = t;
  14541. should_verify_peer = 0;
  14542. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14543. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14544. == 0) {
  14545. should_verify_peer = 1;
  14546. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14547. "optional")
  14548. == 0) {
  14549. should_verify_peer = 1;
  14550. }
  14551. }
  14552. if (should_verify_peer) {
  14553. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14554. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14555. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14556. ca_file,
  14557. ca_path)
  14558. != 1) {
  14559. mg_unlock_context(conn->phys_ctx);
  14560. mg_cry_ctx_internal(
  14561. conn->phys_ctx,
  14562. "SSL_CTX_load_verify_locations error: %s "
  14563. "ssl_verify_peer requires setting "
  14564. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14565. "present in "
  14566. "the .conf file?",
  14567. ssl_error());
  14568. return 0;
  14569. }
  14570. }
  14571. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14572. mg_unlock_context(conn->phys_ctx);
  14573. return 0;
  14574. }
  14575. }
  14576. mg_unlock_context(conn->phys_ctx);
  14577. return 1;
  14578. }
  14579. #if defined(OPENSSL_API_1_1)
  14580. #else
  14581. static pthread_mutex_t *ssl_mutexes;
  14582. #endif /* OPENSSL_API_1_1 */
  14583. static int
  14584. sslize(struct mg_connection *conn,
  14585. int (*func)(SSL *),
  14586. const struct mg_client_options *client_options)
  14587. {
  14588. int ret, err;
  14589. int short_trust;
  14590. unsigned timeout = 1024;
  14591. unsigned i;
  14592. if (!conn) {
  14593. return 0;
  14594. }
  14595. short_trust =
  14596. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14597. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14598. if (short_trust) {
  14599. int trust_ret = refresh_trust(conn);
  14600. if (!trust_ret) {
  14601. return trust_ret;
  14602. }
  14603. }
  14604. mg_lock_context(conn->phys_ctx);
  14605. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14606. mg_unlock_context(conn->phys_ctx);
  14607. if (conn->ssl == NULL) {
  14608. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14609. OPENSSL_REMOVE_THREAD_STATE();
  14610. return 0;
  14611. }
  14612. SSL_set_app_data(conn->ssl, (char *)conn);
  14613. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14614. if (ret != 1) {
  14615. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14616. SSL_free(conn->ssl);
  14617. conn->ssl = NULL;
  14618. OPENSSL_REMOVE_THREAD_STATE();
  14619. return 0;
  14620. }
  14621. if (client_options) {
  14622. if (client_options->host_name) {
  14623. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14624. }
  14625. }
  14626. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14627. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14628. /* NOTE: The loop below acts as a back-off, so we can end
  14629. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14630. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14631. if (to >= 0) {
  14632. timeout = (unsigned)to;
  14633. }
  14634. }
  14635. /* SSL functions may fail and require to be called again:
  14636. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14637. * Here "func" could be SSL_connect or SSL_accept. */
  14638. for (i = 0; i <= timeout; i += 50) {
  14639. ERR_clear_error();
  14640. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14641. ret = func(conn->ssl);
  14642. if (ret != 1) {
  14643. err = SSL_get_error(conn->ssl, ret);
  14644. if ((err == SSL_ERROR_WANT_CONNECT)
  14645. || (err == SSL_ERROR_WANT_ACCEPT)
  14646. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14647. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14648. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14649. /* Don't wait if the server is going to be stopped. */
  14650. break;
  14651. }
  14652. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14653. /* Simply retry the function call. */
  14654. mg_sleep(50);
  14655. } else {
  14656. /* Need to retry the function call "later".
  14657. * See https://linux.die.net/man/3/ssl_get_error
  14658. * This is typical for non-blocking sockets. */
  14659. struct mg_pollfd pfd[2];
  14660. int pollres;
  14661. unsigned int num_sock = 1;
  14662. pfd[0].fd = conn->client.sock;
  14663. pfd[0].events = ((err == SSL_ERROR_WANT_CONNECT)
  14664. || (err == SSL_ERROR_WANT_WRITE))
  14665. ? POLLOUT
  14666. : POLLIN;
  14667. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14668. pfd[num_sock].fd =
  14669. conn->phys_ctx->thread_shutdown_notification_socket;
  14670. pfd[num_sock].events = POLLIN;
  14671. num_sock++;
  14672. }
  14673. pollres = mg_poll(pfd,
  14674. num_sock,
  14675. 50,
  14676. &(conn->phys_ctx->stop_flag));
  14677. if (pollres < 0) {
  14678. /* Break if error occurred (-1)
  14679. * or server shutdown (-2) */
  14680. break;
  14681. }
  14682. }
  14683. } else if (err == SSL_ERROR_SYSCALL) {
  14684. /* This is an IO error. Look at errno. */
  14685. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14686. break;
  14687. } else {
  14688. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14689. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14690. break;
  14691. }
  14692. } else {
  14693. /* success */
  14694. break;
  14695. }
  14696. }
  14697. ERR_clear_error();
  14698. if (ret != 1) {
  14699. SSL_free(conn->ssl);
  14700. conn->ssl = NULL;
  14701. OPENSSL_REMOVE_THREAD_STATE();
  14702. return 0;
  14703. }
  14704. return 1;
  14705. }
  14706. /* Return OpenSSL error message (from CRYPTO lib) */
  14707. static const char *
  14708. ssl_error(void)
  14709. {
  14710. unsigned long err;
  14711. err = ERR_get_error();
  14712. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14713. }
  14714. static int
  14715. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14716. {
  14717. int i;
  14718. const char hexdigit[] = "0123456789abcdef";
  14719. if ((memlen <= 0) || (buflen <= 0)) {
  14720. return 0;
  14721. }
  14722. if (buflen < (3 * memlen)) {
  14723. return 0;
  14724. }
  14725. for (i = 0; i < memlen; i++) {
  14726. if (i > 0) {
  14727. buf[3 * i - 1] = ' ';
  14728. }
  14729. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14730. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14731. }
  14732. buf[3 * memlen - 1] = 0;
  14733. return 1;
  14734. }
  14735. static int
  14736. ssl_get_client_cert_info(const struct mg_connection *conn,
  14737. struct mg_client_cert *client_cert)
  14738. {
  14739. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14740. if (cert) {
  14741. char str_buf[1024];
  14742. unsigned char buf[256];
  14743. char *str_serial = NULL;
  14744. unsigned int ulen;
  14745. int ilen;
  14746. unsigned char *tmp_buf;
  14747. unsigned char *tmp_p;
  14748. /* Handle to algorithm used for fingerprint */
  14749. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14750. /* Get Subject and issuer */
  14751. X509_NAME *subj = X509_get_subject_name(cert);
  14752. X509_NAME *iss = X509_get_issuer_name(cert);
  14753. /* Get serial number */
  14754. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14755. /* Translate serial number to a hex string */
  14756. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14757. if (serial_bn) {
  14758. str_serial = BN_bn2hex(serial_bn);
  14759. BN_free(serial_bn);
  14760. }
  14761. client_cert->serial =
  14762. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14763. /* Translate subject and issuer to a string */
  14764. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14765. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14766. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14767. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14768. /* Calculate SHA1 fingerprint and store as a hex string */
  14769. ulen = 0;
  14770. /* ASN1_digest is deprecated. Do the calculation manually,
  14771. * using EVP_Digest. */
  14772. ilen = i2d_X509(cert, NULL);
  14773. tmp_buf = (ilen > 0)
  14774. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14775. conn->phys_ctx)
  14776. : NULL;
  14777. if (tmp_buf) {
  14778. tmp_p = tmp_buf;
  14779. (void)i2d_X509(cert, &tmp_p);
  14780. if (!EVP_Digest(
  14781. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14782. ulen = 0;
  14783. }
  14784. mg_free(tmp_buf);
  14785. }
  14786. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14787. *str_buf = 0;
  14788. }
  14789. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14790. client_cert->peer_cert = (void *)cert;
  14791. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14792. * see https://linux.die.net/man/3/bn_bn2hex */
  14793. OPENSSL_free(str_serial);
  14794. return 1;
  14795. }
  14796. return 0;
  14797. }
  14798. #if defined(OPENSSL_API_1_1)
  14799. #else
  14800. static void
  14801. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14802. {
  14803. (void)line;
  14804. (void)file;
  14805. if (mode & 1) {
  14806. /* 1 is CRYPTO_LOCK */
  14807. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14808. } else {
  14809. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14810. }
  14811. }
  14812. #endif /* OPENSSL_API_1_1 */
  14813. #if !defined(NO_SSL_DL)
  14814. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14815. static void *
  14816. load_tls_dll(char *ebuf,
  14817. size_t ebuf_len,
  14818. const char *dll_name,
  14819. struct ssl_func *sw,
  14820. int *feature_missing)
  14821. {
  14822. union {
  14823. void *p;
  14824. void (*fp)(void);
  14825. } u;
  14826. void *dll_handle;
  14827. struct ssl_func *fp;
  14828. int ok;
  14829. int truncated = 0;
  14830. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14831. mg_snprintf(NULL,
  14832. NULL, /* No truncation check for ebuf */
  14833. ebuf,
  14834. ebuf_len,
  14835. "%s: cannot load %s",
  14836. __func__,
  14837. dll_name);
  14838. return NULL;
  14839. }
  14840. ok = 1;
  14841. for (fp = sw; fp->name != NULL; fp++) {
  14842. #if defined(_WIN32)
  14843. /* GetProcAddress() returns pointer to function */
  14844. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14845. #else
  14846. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14847. * pointers to function pointers. We need to use a union to make a
  14848. * cast. */
  14849. u.p = dlsym(dll_handle, fp->name);
  14850. #endif /* _WIN32 */
  14851. /* Set pointer (might be NULL) */
  14852. fp->ptr = u.fp;
  14853. if (u.fp == NULL) {
  14854. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14855. if (feature_missing) {
  14856. feature_missing[fp->required]++;
  14857. }
  14858. if (fp->required == TLS_Mandatory) {
  14859. /* Mandatory function is missing */
  14860. if (ok) {
  14861. /* This is the first missing function.
  14862. * Create a new error message. */
  14863. mg_snprintf(NULL,
  14864. &truncated,
  14865. ebuf,
  14866. ebuf_len,
  14867. "%s: %s: cannot find %s",
  14868. __func__,
  14869. dll_name,
  14870. fp->name);
  14871. ok = 0;
  14872. } else {
  14873. /* This is yet anothermissing function.
  14874. * Append existing error message. */
  14875. size_t cur_len = strlen(ebuf);
  14876. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14877. mg_snprintf(NULL,
  14878. &truncated,
  14879. ebuf + cur_len,
  14880. ebuf_len - cur_len - 3,
  14881. ", %s",
  14882. fp->name);
  14883. if (truncated) {
  14884. /* If truncated, add "..." */
  14885. strcat(ebuf, "...");
  14886. }
  14887. }
  14888. }
  14889. }
  14890. }
  14891. }
  14892. if (!ok) {
  14893. (void)dlclose(dll_handle);
  14894. return NULL;
  14895. }
  14896. return dll_handle;
  14897. }
  14898. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14899. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14900. #endif /* NO_SSL_DL */
  14901. #if defined(SSL_ALREADY_INITIALIZED)
  14902. static volatile ptrdiff_t cryptolib_users =
  14903. 1; /* Reference counter for crypto library. */
  14904. #else
  14905. static volatile ptrdiff_t cryptolib_users =
  14906. 0; /* Reference counter for crypto library. */
  14907. #endif
  14908. static int
  14909. initialize_openssl(char *ebuf, size_t ebuf_len)
  14910. {
  14911. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14912. int i, num_locks;
  14913. size_t size;
  14914. #endif
  14915. if (ebuf_len > 0) {
  14916. ebuf[0] = 0;
  14917. }
  14918. #if !defined(NO_SSL_DL)
  14919. if (!cryptolib_dll_handle) {
  14920. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14921. cryptolib_dll_handle = load_tls_dll(
  14922. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14923. if (!cryptolib_dll_handle) {
  14924. mg_snprintf(NULL,
  14925. NULL, /* No truncation check for ebuf */
  14926. ebuf,
  14927. ebuf_len,
  14928. "%s: error loading library %s",
  14929. __func__,
  14930. CRYPTO_LIB);
  14931. DEBUG_TRACE("%s", ebuf);
  14932. return 0;
  14933. }
  14934. }
  14935. #endif /* NO_SSL_DL */
  14936. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14937. return 1;
  14938. }
  14939. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14940. /* Initialize locking callbacks, needed for thread safety.
  14941. * http://www.openssl.org/support/faq.html#PROG1
  14942. */
  14943. num_locks = CRYPTO_num_locks();
  14944. if (num_locks < 0) {
  14945. num_locks = 0;
  14946. }
  14947. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14948. /* allocate mutex array, if required */
  14949. if (num_locks == 0) {
  14950. /* No mutex array required */
  14951. ssl_mutexes = NULL;
  14952. } else {
  14953. /* Mutex array required - allocate it */
  14954. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14955. /* Check OOM */
  14956. if (ssl_mutexes == NULL) {
  14957. mg_snprintf(NULL,
  14958. NULL, /* No truncation check for ebuf */
  14959. ebuf,
  14960. ebuf_len,
  14961. "%s: cannot allocate mutexes: %s",
  14962. __func__,
  14963. ssl_error());
  14964. DEBUG_TRACE("%s", ebuf);
  14965. return 0;
  14966. }
  14967. /* initialize mutex array */
  14968. for (i = 0; i < num_locks; i++) {
  14969. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14970. mg_snprintf(NULL,
  14971. NULL, /* No truncation check for ebuf */
  14972. ebuf,
  14973. ebuf_len,
  14974. "%s: error initializing mutex %i of %i",
  14975. __func__,
  14976. i,
  14977. num_locks);
  14978. DEBUG_TRACE("%s", ebuf);
  14979. mg_free(ssl_mutexes);
  14980. return 0;
  14981. }
  14982. }
  14983. }
  14984. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14985. CRYPTO_set_id_callback(&mg_current_thread_id);
  14986. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14987. #if !defined(NO_SSL_DL)
  14988. if (!ssllib_dll_handle) {
  14989. ssllib_dll_handle =
  14990. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14991. if (!ssllib_dll_handle) {
  14992. #if !defined(OPENSSL_API_1_1)
  14993. mg_free(ssl_mutexes);
  14994. #endif
  14995. DEBUG_TRACE("%s", ebuf);
  14996. return 0;
  14997. }
  14998. }
  14999. #endif /* NO_SSL_DL */
  15000. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15001. && !defined(NO_SSL_DL)
  15002. /* Initialize SSL library */
  15003. OPENSSL_init_ssl(0, NULL);
  15004. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  15005. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  15006. NULL);
  15007. #else
  15008. /* Initialize SSL library */
  15009. SSL_library_init();
  15010. SSL_load_error_strings();
  15011. #endif
  15012. return 1;
  15013. }
  15014. static int
  15015. ssl_use_pem_file(struct mg_context *phys_ctx,
  15016. struct mg_domain_context *dom_ctx,
  15017. const char *pem,
  15018. const char *chain)
  15019. {
  15020. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15021. mg_cry_ctx_internal(phys_ctx,
  15022. "%s: cannot open certificate file %s: %s",
  15023. __func__,
  15024. pem,
  15025. ssl_error());
  15026. return 0;
  15027. }
  15028. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  15029. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15030. mg_cry_ctx_internal(phys_ctx,
  15031. "%s: cannot open private key file %s: %s",
  15032. __func__,
  15033. pem,
  15034. ssl_error());
  15035. return 0;
  15036. }
  15037. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  15038. mg_cry_ctx_internal(phys_ctx,
  15039. "%s: certificate and private key do not match: %s",
  15040. __func__,
  15041. pem);
  15042. return 0;
  15043. }
  15044. /* In contrast to OpenSSL, wolfSSL does not support certificate
  15045. * chain files that contain private keys and certificates in
  15046. * SSL_CTX_use_certificate_chain_file.
  15047. * The CivetWeb-Server used pem-Files that contained both information.
  15048. * In order to make wolfSSL work, it is split in two files.
  15049. * One file that contains key and certificate used by the server and
  15050. * an optional chain file for the ssl stack.
  15051. */
  15052. if (chain) {
  15053. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  15054. mg_cry_ctx_internal(phys_ctx,
  15055. "%s: cannot use certificate chain file %s: %s",
  15056. __func__,
  15057. chain,
  15058. ssl_error());
  15059. return 0;
  15060. }
  15061. }
  15062. return 1;
  15063. }
  15064. #if defined(OPENSSL_API_1_1)
  15065. static unsigned long
  15066. ssl_get_protocol(int version_id)
  15067. {
  15068. long unsigned ret = (long unsigned)SSL_OP_ALL;
  15069. if (version_id > 0)
  15070. ret |= SSL_OP_NO_SSLv2;
  15071. if (version_id > 1)
  15072. ret |= SSL_OP_NO_SSLv3;
  15073. if (version_id > 2)
  15074. ret |= SSL_OP_NO_TLSv1;
  15075. if (version_id > 3)
  15076. ret |= SSL_OP_NO_TLSv1_1;
  15077. if (version_id > 4)
  15078. ret |= SSL_OP_NO_TLSv1_2;
  15079. #if defined(SSL_OP_NO_TLSv1_3)
  15080. if (version_id > 5)
  15081. ret |= SSL_OP_NO_TLSv1_3;
  15082. #endif
  15083. return ret;
  15084. }
  15085. #else
  15086. static long
  15087. ssl_get_protocol(int version_id)
  15088. {
  15089. unsigned long ret = (unsigned long)SSL_OP_ALL;
  15090. if (version_id > 0)
  15091. ret |= SSL_OP_NO_SSLv2;
  15092. if (version_id > 1)
  15093. ret |= SSL_OP_NO_SSLv3;
  15094. if (version_id > 2)
  15095. ret |= SSL_OP_NO_TLSv1;
  15096. if (version_id > 3)
  15097. ret |= SSL_OP_NO_TLSv1_1;
  15098. if (version_id > 4)
  15099. ret |= SSL_OP_NO_TLSv1_2;
  15100. #if defined(SSL_OP_NO_TLSv1_3)
  15101. if (version_id > 5)
  15102. ret |= SSL_OP_NO_TLSv1_3;
  15103. #endif
  15104. return (long)ret;
  15105. }
  15106. #endif /* OPENSSL_API_1_1 */
  15107. /* SSL callback documentation:
  15108. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  15109. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  15110. * https://linux.die.net/man/3/ssl_set_info_callback */
  15111. /* Note: There is no "const" for the first argument in the documentation
  15112. * examples, however some (maybe most, but not all) headers of OpenSSL
  15113. * versions / OpenSSL compatibility layers have it. Having a different
  15114. * definition will cause a warning in C and an error in C++. Use "const SSL
  15115. * *", while automatic conversion from "SSL *" works for all compilers,
  15116. * but not other way around */
  15117. static void
  15118. ssl_info_callback(const SSL *ssl, int what, int ret)
  15119. {
  15120. (void)ret;
  15121. if (what & SSL_CB_HANDSHAKE_START) {
  15122. SSL_get_app_data(ssl);
  15123. }
  15124. if (what & SSL_CB_HANDSHAKE_DONE) {
  15125. /* TODO: check for openSSL 1.1 */
  15126. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  15127. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  15128. }
  15129. }
  15130. static int
  15131. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  15132. {
  15133. #if defined(GCC_DIAGNOSTIC)
  15134. #pragma GCC diagnostic push
  15135. #pragma GCC diagnostic ignored "-Wcast-align"
  15136. #endif /* defined(GCC_DIAGNOSTIC) */
  15137. /* We used an aligned pointer in SSL_set_app_data */
  15138. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  15139. #if defined(GCC_DIAGNOSTIC)
  15140. #pragma GCC diagnostic pop
  15141. #endif /* defined(GCC_DIAGNOSTIC) */
  15142. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15143. (void)ad;
  15144. (void)arg;
  15145. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15146. DEBUG_ASSERT(0);
  15147. return SSL_TLSEXT_ERR_NOACK;
  15148. }
  15149. conn->dom_ctx = &(conn->phys_ctx->dd);
  15150. /* Old clients (Win XP) will not support SNI. Then, there
  15151. * is no server name available in the request - we can
  15152. * only work with the default certificate.
  15153. * Multiple HTTPS hosts on one IP+port are only possible
  15154. * with a certificate containing all alternative names.
  15155. */
  15156. if ((servername == NULL) || (*servername == 0)) {
  15157. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  15158. mg_lock_context(conn->phys_ctx);
  15159. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15160. mg_unlock_context(conn->phys_ctx);
  15161. return SSL_TLSEXT_ERR_NOACK;
  15162. }
  15163. DEBUG_TRACE("TLS connection to host %s", servername);
  15164. while (conn->dom_ctx) {
  15165. if (!mg_strcasecmp(servername,
  15166. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  15167. /* Found matching domain */
  15168. DEBUG_TRACE("TLS domain %s found",
  15169. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  15170. break;
  15171. }
  15172. mg_lock_context(conn->phys_ctx);
  15173. conn->dom_ctx = conn->dom_ctx->next;
  15174. mg_unlock_context(conn->phys_ctx);
  15175. }
  15176. if (conn->dom_ctx == NULL) {
  15177. /* Default domain */
  15178. DEBUG_TRACE("TLS default domain %s used",
  15179. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  15180. conn->dom_ctx = &(conn->phys_ctx->dd);
  15181. }
  15182. mg_lock_context(conn->phys_ctx);
  15183. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15184. mg_unlock_context(conn->phys_ctx);
  15185. return SSL_TLSEXT_ERR_OK;
  15186. }
  15187. #if defined(USE_ALPN)
  15188. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  15189. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  15190. alpn_proto_list + 3 + 8,
  15191. NULL};
  15192. #if defined(USE_HTTP2)
  15193. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  15194. alpn_proto_list + 3,
  15195. alpn_proto_list + 3 + 8,
  15196. NULL};
  15197. #endif
  15198. static int
  15199. alpn_select_cb(SSL *ssl,
  15200. const unsigned char **out,
  15201. unsigned char *outlen,
  15202. const unsigned char *in,
  15203. unsigned int inlen,
  15204. void *arg)
  15205. {
  15206. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15207. unsigned int i, j, enable_http2 = 0;
  15208. const char **alpn_proto_order = alpn_proto_order_http1;
  15209. struct mg_workerTLS *tls =
  15210. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  15211. (void)ssl;
  15212. if (tls == NULL) {
  15213. /* Need to store protocol in Thread Local Storage */
  15214. /* If there is no Thread Local Storage, don't use ALPN */
  15215. return SSL_TLSEXT_ERR_NOACK;
  15216. }
  15217. #if defined(USE_HTTP2)
  15218. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  15219. if (enable_http2) {
  15220. alpn_proto_order = alpn_proto_order_http2;
  15221. }
  15222. #endif
  15223. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  15224. /* check all accepted protocols in this order */
  15225. const char *alpn_proto = alpn_proto_order[j];
  15226. /* search input for matching protocol */
  15227. for (i = 0; i < inlen; i++) {
  15228. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  15229. *out = in + i + 1;
  15230. *outlen = in[i];
  15231. tls->alpn_proto = alpn_proto;
  15232. return SSL_TLSEXT_ERR_OK;
  15233. }
  15234. }
  15235. }
  15236. /* Nothing found */
  15237. return SSL_TLSEXT_ERR_NOACK;
  15238. }
  15239. static int
  15240. next_protos_advertised_cb(SSL *ssl,
  15241. const unsigned char **data,
  15242. unsigned int *len,
  15243. void *arg)
  15244. {
  15245. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15246. *data = (const unsigned char *)alpn_proto_list;
  15247. *len = (unsigned int)strlen((const char *)data);
  15248. (void)ssl;
  15249. (void)dom_ctx;
  15250. return SSL_TLSEXT_ERR_OK;
  15251. }
  15252. static int
  15253. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15254. {
  15255. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  15256. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  15257. (const unsigned char *)alpn_proto_list,
  15258. alpn_len);
  15259. if (ret != 0) {
  15260. mg_cry_ctx_internal(phys_ctx,
  15261. "SSL_CTX_set_alpn_protos error: %s",
  15262. ssl_error());
  15263. }
  15264. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  15265. alpn_select_cb,
  15266. (void *)dom_ctx);
  15267. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  15268. next_protos_advertised_cb,
  15269. (void *)dom_ctx);
  15270. return ret;
  15271. }
  15272. #endif
  15273. /* Setup SSL CTX as required by CivetWeb */
  15274. static int
  15275. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  15276. struct mg_domain_context *dom_ctx,
  15277. const char *pem,
  15278. const char *chain)
  15279. {
  15280. int callback_ret;
  15281. int should_verify_peer;
  15282. int peer_certificate_optional;
  15283. const char *ca_path;
  15284. const char *ca_file;
  15285. int use_default_verify_paths;
  15286. int verify_depth;
  15287. struct timespec now_mt;
  15288. md5_byte_t ssl_context_id[16];
  15289. md5_state_t md5state;
  15290. int protocol_ver;
  15291. int ssl_cache_timeout;
  15292. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15293. && !defined(NO_SSL_DL)
  15294. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15295. mg_cry_ctx_internal(phys_ctx,
  15296. "SSL_CTX_new (server) error: %s",
  15297. ssl_error());
  15298. return 0;
  15299. }
  15300. #else
  15301. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15302. mg_cry_ctx_internal(phys_ctx,
  15303. "SSL_CTX_new (server) error: %s",
  15304. ssl_error());
  15305. return 0;
  15306. }
  15307. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15308. #if defined(SSL_OP_NO_TLSv1_3)
  15309. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15310. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15311. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15312. | SSL_OP_NO_TLSv1_3);
  15313. #else
  15314. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15315. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15316. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15317. #endif
  15318. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15319. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15320. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15321. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15322. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15323. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15324. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15325. #if defined(SSL_OP_NO_RENEGOTIATION)
  15326. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15327. #endif
  15328. #if !defined(NO_SSL_DL)
  15329. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15330. #endif /* NO_SSL_DL */
  15331. /* In SSL documentation examples callback defined without const
  15332. * specifier 'void (*)(SSL *, int, int)' See:
  15333. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15334. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15335. * But in the source code const SSL is used:
  15336. * 'void (*)(const SSL *, int, int)' See:
  15337. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15338. * Problem about wrong documentation described, but not resolved:
  15339. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15340. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15341. * But when compiled with modern C++ compiler, correct const should be
  15342. * provided
  15343. */
  15344. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15345. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15346. ssl_servername_callback);
  15347. /* If a callback has been specified, call it. */
  15348. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15349. ? 0
  15350. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15351. phys_ctx->user_data));
  15352. /* If callback returns 0, civetweb sets up the SSL certificate.
  15353. * If it returns 1, civetweb assumes the callback already did this.
  15354. * If it returns -1, initializing ssl fails. */
  15355. if (callback_ret < 0) {
  15356. mg_cry_ctx_internal(phys_ctx,
  15357. "SSL callback returned error: %i",
  15358. callback_ret);
  15359. return 0;
  15360. }
  15361. if (callback_ret > 0) {
  15362. /* Callback did everything. */
  15363. return 1;
  15364. }
  15365. /* If a domain callback has been specified, call it. */
  15366. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15367. ? 0
  15368. : (phys_ctx->callbacks.init_ssl_domain(
  15369. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15370. dom_ctx->ssl_ctx,
  15371. phys_ctx->user_data));
  15372. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15373. * If it returns 1, civetweb assumes the callback already did this.
  15374. * If it returns -1, initializing ssl fails. */
  15375. if (callback_ret < 0) {
  15376. mg_cry_ctx_internal(phys_ctx,
  15377. "Domain SSL callback returned error: %i",
  15378. callback_ret);
  15379. return 0;
  15380. }
  15381. if (callback_ret > 0) {
  15382. /* Domain callback did everything. */
  15383. return 1;
  15384. }
  15385. /* Use some combination of start time, domain and port as a SSL
  15386. * context ID. This should be unique on the current machine. */
  15387. md5_init(&md5state);
  15388. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15389. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15390. md5_append(&md5state,
  15391. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15392. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15393. md5_append(&md5state,
  15394. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15395. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15396. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15397. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15398. md5_finish(&md5state, ssl_context_id);
  15399. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15400. (unsigned char *)ssl_context_id,
  15401. sizeof(ssl_context_id));
  15402. if (pem != NULL) {
  15403. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15404. return 0;
  15405. }
  15406. }
  15407. /* Should we support client certificates? */
  15408. /* Default is "no". */
  15409. should_verify_peer = 0;
  15410. peer_certificate_optional = 0;
  15411. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15412. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15413. /* Yes, they are mandatory */
  15414. should_verify_peer = 1;
  15415. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15416. "optional")
  15417. == 0) {
  15418. /* Yes, they are optional */
  15419. should_verify_peer = 1;
  15420. peer_certificate_optional = 1;
  15421. }
  15422. }
  15423. use_default_verify_paths =
  15424. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15425. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15426. == 0);
  15427. if (should_verify_peer) {
  15428. ca_path = dom_ctx->config[SSL_CA_PATH];
  15429. ca_file = dom_ctx->config[SSL_CA_FILE];
  15430. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15431. != 1) {
  15432. mg_cry_ctx_internal(phys_ctx,
  15433. "SSL_CTX_load_verify_locations error: %s "
  15434. "ssl_verify_peer requires setting "
  15435. "either ssl_ca_path or ssl_ca_file. "
  15436. "Is any of them present in the "
  15437. ".conf file?",
  15438. ssl_error());
  15439. return 0;
  15440. }
  15441. if (peer_certificate_optional) {
  15442. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15443. } else {
  15444. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15445. SSL_VERIFY_PEER
  15446. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15447. NULL);
  15448. }
  15449. if (use_default_verify_paths
  15450. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15451. mg_cry_ctx_internal(phys_ctx,
  15452. "SSL_CTX_set_default_verify_paths error: %s",
  15453. ssl_error());
  15454. return 0;
  15455. }
  15456. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15457. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15458. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15459. }
  15460. }
  15461. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15462. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15463. dom_ctx->config[SSL_CIPHER_LIST])
  15464. != 1) {
  15465. mg_cry_ctx_internal(phys_ctx,
  15466. "SSL_CTX_set_cipher_list error: %s",
  15467. ssl_error());
  15468. }
  15469. }
  15470. /* SSL session caching */
  15471. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15472. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15473. : 0);
  15474. if (ssl_cache_timeout > 0) {
  15475. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15476. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15477. * default */
  15478. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15479. }
  15480. #if defined(USE_ALPN)
  15481. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15482. #if !defined(NO_SSL_DL)
  15483. if (!tls_feature_missing[TLS_ALPN])
  15484. #endif
  15485. {
  15486. init_alpn(phys_ctx, dom_ctx);
  15487. }
  15488. #endif
  15489. return 1;
  15490. }
  15491. /* Check if SSL is required.
  15492. * If so, dynamically load SSL library
  15493. * and set up ctx->ssl_ctx pointer. */
  15494. static int
  15495. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15496. {
  15497. void *ssl_ctx = 0;
  15498. int callback_ret;
  15499. const char *pem;
  15500. const char *chain;
  15501. char ebuf[128];
  15502. if (!phys_ctx) {
  15503. return 0;
  15504. }
  15505. if (!dom_ctx) {
  15506. dom_ctx = &(phys_ctx->dd);
  15507. }
  15508. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15509. /* No SSL port is set. No need to setup SSL. */
  15510. return 1;
  15511. }
  15512. /* Check for external SSL_CTX */
  15513. callback_ret =
  15514. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15515. ? 0
  15516. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15517. phys_ctx->user_data));
  15518. if (callback_ret < 0) {
  15519. /* Callback exists and returns <0: Initializing failed. */
  15520. mg_cry_ctx_internal(phys_ctx,
  15521. "external_ssl_ctx callback returned error: %i",
  15522. callback_ret);
  15523. return 0;
  15524. } else if (callback_ret > 0) {
  15525. /* Callback exists and returns >0: Initializing complete,
  15526. * civetweb should not modify the SSL context. */
  15527. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15528. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15529. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15530. return 0;
  15531. }
  15532. return 1;
  15533. }
  15534. /* If the callback does not exist or return 0, civetweb must initialize
  15535. * the SSL context. Handle "domain" callback next. */
  15536. /* Check for external domain SSL_CTX callback. */
  15537. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15538. ? 0
  15539. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15540. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15541. &ssl_ctx,
  15542. phys_ctx->user_data));
  15543. if (callback_ret < 0) {
  15544. /* Callback < 0: Error. Abort init. */
  15545. mg_cry_ctx_internal(
  15546. phys_ctx,
  15547. "external_ssl_ctx_domain callback returned error: %i",
  15548. callback_ret);
  15549. return 0;
  15550. } else if (callback_ret > 0) {
  15551. /* Callback > 0: Consider init done. */
  15552. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15553. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15554. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15555. return 0;
  15556. }
  15557. return 1;
  15558. }
  15559. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15560. * 0, CivetWeb should continue initializing SSL */
  15561. /* If PEM file is not specified and the init_ssl callbacks
  15562. * are not specified, setup will fail. */
  15563. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15564. && (phys_ctx->callbacks.init_ssl == NULL)
  15565. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15566. /* No certificate and no init_ssl callbacks:
  15567. * Essential data to set up TLS is missing.
  15568. */
  15569. mg_cry_ctx_internal(phys_ctx,
  15570. "Initializing SSL failed: -%s is not set",
  15571. config_options[SSL_CERTIFICATE].name);
  15572. return 0;
  15573. }
  15574. /* If a certificate chain is configured, use it. */
  15575. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15576. if (chain == NULL) {
  15577. /* Default: certificate chain in PEM file */
  15578. chain = pem;
  15579. }
  15580. if ((chain != NULL) && (*chain == 0)) {
  15581. /* If the chain is an empty string, don't use it. */
  15582. chain = NULL;
  15583. }
  15584. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15585. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15586. return 0;
  15587. }
  15588. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15589. }
  15590. static void
  15591. uninitialize_openssl(void)
  15592. {
  15593. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15594. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15595. /* Shutdown according to
  15596. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15597. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15598. */
  15599. CONF_modules_unload(1);
  15600. #else
  15601. int i;
  15602. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15603. /* Shutdown according to
  15604. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15605. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15606. */
  15607. CRYPTO_set_locking_callback(NULL);
  15608. CRYPTO_set_id_callback(NULL);
  15609. ENGINE_cleanup();
  15610. CONF_modules_unload(1);
  15611. ERR_free_strings();
  15612. EVP_cleanup();
  15613. CRYPTO_cleanup_all_ex_data();
  15614. OPENSSL_REMOVE_THREAD_STATE();
  15615. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15616. pthread_mutex_destroy(&ssl_mutexes[i]);
  15617. }
  15618. mg_free(ssl_mutexes);
  15619. ssl_mutexes = NULL;
  15620. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15621. }
  15622. }
  15623. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) */
  15624. #if !defined(NO_FILESYSTEMS)
  15625. static int
  15626. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15627. {
  15628. if (phys_ctx) {
  15629. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15630. const char *path;
  15631. struct mg_connection fc;
  15632. if (!dom_ctx) {
  15633. dom_ctx = &(phys_ctx->dd);
  15634. }
  15635. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15636. if ((path != NULL)
  15637. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15638. mg_cry_ctx_internal(phys_ctx,
  15639. "Cannot open %s: %s",
  15640. path,
  15641. strerror(ERRNO));
  15642. return 0;
  15643. }
  15644. return 1;
  15645. }
  15646. return 0;
  15647. }
  15648. #endif /* NO_FILESYSTEMS */
  15649. static int
  15650. set_acl_option(struct mg_context *phys_ctx)
  15651. {
  15652. union usa sa;
  15653. memset(&sa, 0, sizeof(sa));
  15654. #if defined(USE_IPV6)
  15655. sa.sin6.sin6_family = AF_INET6;
  15656. #else
  15657. sa.sin.sin_family = AF_INET;
  15658. #endif
  15659. return check_acl(phys_ctx, &sa) != -1;
  15660. }
  15661. static void
  15662. reset_per_request_attributes(struct mg_connection *conn)
  15663. {
  15664. if (!conn) {
  15665. return;
  15666. }
  15667. conn->num_bytes_sent = conn->consumed_content = 0;
  15668. conn->path_info = NULL;
  15669. conn->status_code = -1;
  15670. conn->content_len = -1;
  15671. conn->is_chunked = 0;
  15672. conn->must_close = 0;
  15673. conn->request_len = 0;
  15674. conn->request_state = 0;
  15675. conn->throttle = 0;
  15676. conn->accept_gzip = 0;
  15677. conn->response_info.content_length = conn->request_info.content_length = -1;
  15678. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15679. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15680. conn->response_info.status_text = NULL;
  15681. conn->response_info.status_code = 0;
  15682. conn->request_info.remote_user = NULL;
  15683. conn->request_info.request_method = NULL;
  15684. conn->request_info.request_uri = NULL;
  15685. /* Free cleaned local URI (if any) */
  15686. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15687. mg_free((void *)conn->request_info.local_uri);
  15688. conn->request_info.local_uri = NULL;
  15689. }
  15690. conn->request_info.local_uri = NULL;
  15691. #if defined(USE_SERVER_STATS)
  15692. conn->processing_time = 0;
  15693. #endif
  15694. }
  15695. static int
  15696. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15697. {
  15698. if ((so->lsa.sa.sa_family == AF_INET)
  15699. || (so->lsa.sa.sa_family == AF_INET6)) {
  15700. /* Only for TCP sockets */
  15701. if (setsockopt(so->sock,
  15702. IPPROTO_TCP,
  15703. TCP_NODELAY,
  15704. (SOCK_OPT_TYPE)&nodelay_on,
  15705. sizeof(nodelay_on))
  15706. != 0) {
  15707. /* Error */
  15708. return 1;
  15709. }
  15710. }
  15711. /* OK */
  15712. return 0;
  15713. }
  15714. #if !defined(__ZEPHYR__)
  15715. static void
  15716. close_socket_gracefully(struct mg_connection *conn)
  15717. {
  15718. #if defined(_WIN32)
  15719. char buf[MG_BUF_LEN];
  15720. int n;
  15721. #endif
  15722. struct linger linger;
  15723. int error_code = 0;
  15724. int linger_timeout = -2;
  15725. socklen_t opt_len = sizeof(error_code);
  15726. if (!conn) {
  15727. return;
  15728. }
  15729. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15730. * "Note that enabling a nonzero timeout on a nonblocking socket
  15731. * is not recommended.", so set it to blocking now */
  15732. set_blocking_mode(conn->client.sock);
  15733. /* Send FIN to the client */
  15734. shutdown(conn->client.sock, SHUTDOWN_WR);
  15735. #if defined(_WIN32)
  15736. /* Read and discard pending incoming data. If we do not do that and
  15737. * close
  15738. * the socket, the data in the send buffer may be discarded. This
  15739. * behaviour is seen on Windows, when client keeps sending data
  15740. * when server decides to close the connection; then when client
  15741. * does recv() it gets no data back. */
  15742. do {
  15743. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15744. } while (n > 0);
  15745. #endif
  15746. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15747. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15748. }
  15749. /* Set linger option according to configuration */
  15750. if (linger_timeout >= 0) {
  15751. /* Set linger option to avoid socket hanging out after close. This
  15752. * prevent ephemeral port exhaust problem under high QPS. */
  15753. linger.l_onoff = 1;
  15754. #if defined(_MSC_VER)
  15755. #pragma warning(push)
  15756. #pragma warning(disable : 4244)
  15757. #endif
  15758. #if defined(GCC_DIAGNOSTIC)
  15759. #pragma GCC diagnostic push
  15760. #pragma GCC diagnostic ignored "-Wconversion"
  15761. #endif
  15762. /* Data type of linger structure elements may differ,
  15763. * so we don't know what cast we need here.
  15764. * Disable type conversion warnings. */
  15765. linger.l_linger = (linger_timeout + 999) / 1000;
  15766. #if defined(GCC_DIAGNOSTIC)
  15767. #pragma GCC diagnostic pop
  15768. #endif
  15769. #if defined(_MSC_VER)
  15770. #pragma warning(pop)
  15771. #endif
  15772. } else {
  15773. linger.l_onoff = 0;
  15774. linger.l_linger = 0;
  15775. }
  15776. if (linger_timeout < -1) {
  15777. /* Default: don't configure any linger */
  15778. } else if (getsockopt(conn->client.sock,
  15779. SOL_SOCKET,
  15780. SO_ERROR,
  15781. #if defined(_WIN32) /* WinSock uses different data type here */
  15782. (char *)&error_code,
  15783. #else
  15784. &error_code,
  15785. #endif
  15786. &opt_len)
  15787. != 0) {
  15788. /* Cannot determine if socket is already closed. This should
  15789. * not occur and never did in a test. Log an error message
  15790. * and continue. */
  15791. mg_cry_internal(conn,
  15792. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15793. __func__,
  15794. strerror(ERRNO));
  15795. #if defined(_WIN32)
  15796. } else if (error_code == WSAECONNRESET) {
  15797. #else
  15798. } else if (error_code == ECONNRESET) {
  15799. #endif
  15800. /* Socket already closed by client/peer, close socket without linger
  15801. */
  15802. } else {
  15803. /* Set linger timeout */
  15804. if (setsockopt(conn->client.sock,
  15805. SOL_SOCKET,
  15806. SO_LINGER,
  15807. (char *)&linger,
  15808. sizeof(linger))
  15809. != 0) {
  15810. mg_cry_internal(
  15811. conn,
  15812. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15813. __func__,
  15814. linger.l_onoff,
  15815. linger.l_linger,
  15816. strerror(ERRNO));
  15817. }
  15818. }
  15819. /* Now we know that our FIN is ACK-ed, safe to close */
  15820. closesocket(conn->client.sock);
  15821. conn->client.sock = INVALID_SOCKET;
  15822. }
  15823. #endif
  15824. static void
  15825. close_connection(struct mg_connection *conn)
  15826. {
  15827. #if defined(USE_SERVER_STATS)
  15828. conn->conn_state = 6; /* to close */
  15829. #endif
  15830. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15831. if (conn->lua_websocket_state) {
  15832. lua_websocket_close(conn, conn->lua_websocket_state);
  15833. conn->lua_websocket_state = NULL;
  15834. }
  15835. #endif
  15836. mg_lock_connection(conn);
  15837. /* Set close flag, so keep-alive loops will stop */
  15838. conn->must_close = 1;
  15839. /* call the connection_close callback if assigned */
  15840. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15841. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15842. conn->phys_ctx->callbacks.connection_close(conn);
  15843. }
  15844. }
  15845. /* Reset user data, after close callback is called.
  15846. * Do not reuse it. If the user needs a destructor,
  15847. * it must be done in the connection_close callback. */
  15848. mg_set_user_connection_data(conn, NULL);
  15849. #if defined(USE_SERVER_STATS)
  15850. conn->conn_state = 7; /* closing */
  15851. #endif
  15852. #if defined(USE_MBEDTLS)
  15853. if (conn->ssl != NULL) {
  15854. mbed_ssl_close(conn->ssl);
  15855. conn->ssl = NULL;
  15856. }
  15857. #elif defined(USE_GNUTLS)
  15858. if (conn->ssl != NULL) {
  15859. gtls_ssl_close(conn->ssl);
  15860. conn->ssl = NULL;
  15861. }
  15862. #elif !defined(NO_SSL)
  15863. if (conn->ssl != NULL) {
  15864. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15865. */
  15866. SSL_shutdown(conn->ssl);
  15867. SSL_free(conn->ssl);
  15868. OPENSSL_REMOVE_THREAD_STATE();
  15869. conn->ssl = NULL;
  15870. }
  15871. #endif
  15872. if (conn->client.sock != INVALID_SOCKET) {
  15873. #if defined(__ZEPHYR__)
  15874. closesocket(conn->client.sock);
  15875. #else
  15876. close_socket_gracefully(conn);
  15877. #endif
  15878. conn->client.sock = INVALID_SOCKET;
  15879. }
  15880. /* call the connection_closed callback if assigned */
  15881. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15882. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15883. conn->phys_ctx->callbacks.connection_closed(conn);
  15884. }
  15885. }
  15886. mg_unlock_connection(conn);
  15887. #if defined(USE_SERVER_STATS)
  15888. conn->conn_state = 8; /* closed */
  15889. #endif
  15890. }
  15891. CIVETWEB_API void
  15892. mg_close_connection(struct mg_connection *conn)
  15893. {
  15894. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15895. return;
  15896. }
  15897. #if defined(USE_WEBSOCKET)
  15898. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15899. if (conn->in_websocket_handling) {
  15900. /* Set close flag, so the server thread can exit. */
  15901. conn->must_close = 1;
  15902. return;
  15903. }
  15904. }
  15905. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15906. unsigned int i;
  15907. /* client context: loops must end */
  15908. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15909. conn->must_close = 1;
  15910. /* We need to get the client thread out of the select/recv call
  15911. * here. */
  15912. /* Since we use a sleep quantum of some seconds to check for recv
  15913. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15914. /* join worker thread */
  15915. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15916. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15917. }
  15918. }
  15919. #endif /* defined(USE_WEBSOCKET) */
  15920. close_connection(conn);
  15921. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) // TODO: mbedTLS client
  15922. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15923. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15924. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15925. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15926. }
  15927. #endif
  15928. #if defined(USE_WEBSOCKET)
  15929. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15930. mg_free(conn->phys_ctx->worker_threadids);
  15931. (void)pthread_mutex_destroy(&conn->mutex);
  15932. mg_free(conn);
  15933. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15934. (void)pthread_mutex_destroy(&conn->mutex);
  15935. mg_free(conn);
  15936. }
  15937. #else
  15938. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15939. (void)pthread_mutex_destroy(&conn->mutex);
  15940. mg_free(conn);
  15941. }
  15942. #endif /* defined(USE_WEBSOCKET) */
  15943. }
  15944. static struct mg_connection *
  15945. mg_connect_client_impl(const struct mg_client_options *client_options,
  15946. int use_ssl,
  15947. struct mg_init_data *init,
  15948. struct mg_error_data *error)
  15949. {
  15950. struct mg_connection *conn = NULL;
  15951. SOCKET sock;
  15952. union usa sa;
  15953. struct sockaddr *psa;
  15954. socklen_t len;
  15955. unsigned max_req_size =
  15956. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15957. /* Size of structures, aligned to 8 bytes */
  15958. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15959. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15960. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15961. (void)init; /* TODO: Implement required options */
  15962. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15963. if (error != NULL) {
  15964. error->code = MG_ERROR_DATA_CODE_OK;
  15965. error->code_sub = 0;
  15966. if (error->text_buffer_size > 0) {
  15967. error->text[0] = 0;
  15968. }
  15969. }
  15970. if (conn == NULL) {
  15971. if (error != NULL) {
  15972. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15973. error->code_sub = (unsigned)alloc_size;
  15974. mg_snprintf(NULL,
  15975. NULL, /* No truncation check for ebuf */
  15976. error->text,
  15977. error->text_buffer_size,
  15978. "calloc(): %s",
  15979. strerror(ERRNO));
  15980. }
  15981. return NULL;
  15982. }
  15983. #if defined(GCC_DIAGNOSTIC)
  15984. #pragma GCC diagnostic push
  15985. #pragma GCC diagnostic ignored "-Wcast-align"
  15986. #endif /* defined(GCC_DIAGNOSTIC) */
  15987. /* conn_size is aligned to 8 bytes */
  15988. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15989. #if defined(GCC_DIAGNOSTIC)
  15990. #pragma GCC diagnostic pop
  15991. #endif /* defined(GCC_DIAGNOSTIC) */
  15992. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15993. conn->buf_size = (int)max_req_size;
  15994. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15995. conn->dom_ctx = &(conn->phys_ctx->dd);
  15996. if (!connect_socket(conn->phys_ctx,
  15997. client_options->host,
  15998. client_options->port,
  15999. use_ssl,
  16000. error,
  16001. &sock,
  16002. &sa)) {
  16003. /* "error" will be set by connect_socket. */
  16004. /* free all memory and return NULL; */
  16005. mg_free(conn);
  16006. return NULL;
  16007. }
  16008. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16009. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  16010. && !defined(NO_SSL_DL)
  16011. if (use_ssl
  16012. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  16013. == NULL) {
  16014. if (error != NULL) {
  16015. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16016. mg_snprintf(NULL,
  16017. NULL, /* No truncation check for ebuf */
  16018. error->text,
  16019. error->text_buffer_size,
  16020. "SSL_CTX_new error: %s",
  16021. ssl_error());
  16022. }
  16023. closesocket(sock);
  16024. mg_free(conn);
  16025. return NULL;
  16026. }
  16027. #else
  16028. if (use_ssl
  16029. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  16030. == NULL) {
  16031. if (error != NULL) {
  16032. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16033. mg_snprintf(NULL,
  16034. NULL, /* No truncation check for ebuf */
  16035. error->text,
  16036. error->text_buffer_size,
  16037. "SSL_CTX_new error: %s",
  16038. ssl_error());
  16039. }
  16040. closesocket(sock);
  16041. mg_free(conn);
  16042. return NULL;
  16043. }
  16044. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  16045. #endif /* NO_SSL */
  16046. #if defined(USE_IPV6)
  16047. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  16048. : sizeof(conn->client.rsa.sin6);
  16049. psa = (sa.sa.sa_family == AF_INET)
  16050. ? (struct sockaddr *)&(conn->client.rsa.sin)
  16051. : (struct sockaddr *)&(conn->client.rsa.sin6);
  16052. #else
  16053. len = sizeof(conn->client.rsa.sin);
  16054. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  16055. #endif
  16056. conn->client.sock = sock;
  16057. conn->client.lsa = sa;
  16058. if (getsockname(sock, psa, &len) != 0) {
  16059. mg_cry_internal(conn,
  16060. "%s: getsockname() failed: %s",
  16061. __func__,
  16062. strerror(ERRNO));
  16063. }
  16064. conn->client.is_ssl = use_ssl ? 1 : 0;
  16065. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16066. if (error != NULL) {
  16067. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  16068. error->code_sub = (unsigned)ERRNO;
  16069. mg_snprintf(NULL,
  16070. NULL, /* No truncation check for ebuf */
  16071. error->text,
  16072. error->text_buffer_size,
  16073. "Can not create mutex");
  16074. }
  16075. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16076. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16077. #endif
  16078. closesocket(sock);
  16079. mg_free(conn);
  16080. return NULL;
  16081. }
  16082. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16083. if (use_ssl) {
  16084. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  16085. * SSL_CTX_set_verify call is needed to switch off server
  16086. * certificate checking, which is off by default in OpenSSL and
  16087. * on in yaSSL. */
  16088. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  16089. * SSL_VERIFY_PEER, verify_ssl_server); */
  16090. if (client_options->client_cert) {
  16091. if (!ssl_use_pem_file(conn->phys_ctx,
  16092. conn->dom_ctx,
  16093. client_options->client_cert,
  16094. NULL)) {
  16095. if (error != NULL) {
  16096. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  16097. mg_snprintf(NULL,
  16098. NULL, /* No truncation check for ebuf */
  16099. error->text,
  16100. error->text_buffer_size,
  16101. "Can not use SSL client certificate");
  16102. }
  16103. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16104. closesocket(sock);
  16105. mg_free(conn);
  16106. return NULL;
  16107. }
  16108. }
  16109. if (client_options->server_cert) {
  16110. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  16111. client_options->server_cert,
  16112. NULL)
  16113. != 1) {
  16114. if (error != NULL) {
  16115. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  16116. mg_snprintf(NULL,
  16117. NULL, /* No truncation check for ebuf */
  16118. error->text,
  16119. error->text_buffer_size,
  16120. "SSL_CTX_load_verify_locations error: %s",
  16121. ssl_error());
  16122. }
  16123. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16124. closesocket(sock);
  16125. mg_free(conn);
  16126. return NULL;
  16127. }
  16128. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  16129. } else {
  16130. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  16131. }
  16132. if (!sslize(conn, SSL_connect, client_options)) {
  16133. if (error != NULL) {
  16134. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  16135. mg_snprintf(NULL,
  16136. NULL, /* No truncation check for ebuf */
  16137. error->text,
  16138. error->text_buffer_size,
  16139. "SSL connection error");
  16140. }
  16141. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16142. closesocket(sock);
  16143. mg_free(conn);
  16144. return NULL;
  16145. }
  16146. }
  16147. #endif
  16148. return conn;
  16149. }
  16150. CIVETWEB_API struct mg_connection *
  16151. mg_connect_client_secure(const struct mg_client_options *client_options,
  16152. char *error_buffer,
  16153. size_t error_buffer_size)
  16154. {
  16155. struct mg_init_data init;
  16156. struct mg_error_data error;
  16157. memset(&init, 0, sizeof(init));
  16158. memset(&error, 0, sizeof(error));
  16159. error.text_buffer_size = error_buffer_size;
  16160. error.text = error_buffer;
  16161. return mg_connect_client_impl(client_options, 1, &init, &error);
  16162. }
  16163. CIVETWEB_API struct mg_connection *
  16164. mg_connect_client(const char *host,
  16165. int port,
  16166. int use_ssl,
  16167. char *error_buffer,
  16168. size_t error_buffer_size)
  16169. {
  16170. struct mg_client_options opts;
  16171. struct mg_init_data init;
  16172. struct mg_error_data error;
  16173. memset(&init, 0, sizeof(init));
  16174. memset(&error, 0, sizeof(error));
  16175. error.text_buffer_size = error_buffer_size;
  16176. error.text = error_buffer;
  16177. memset(&opts, 0, sizeof(opts));
  16178. opts.host = host;
  16179. opts.port = port;
  16180. if (use_ssl) {
  16181. opts.host_name = host;
  16182. }
  16183. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  16184. }
  16185. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16186. CIVETWEB_API struct mg_connection *
  16187. mg_connect_client2(const char *host,
  16188. const char *protocol,
  16189. int port,
  16190. const char *path,
  16191. struct mg_init_data *init,
  16192. struct mg_error_data *error)
  16193. {
  16194. (void)path;
  16195. int is_ssl, is_ws;
  16196. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  16197. if (error != NULL) {
  16198. error->code = MG_ERROR_DATA_CODE_OK;
  16199. error->code_sub = 0;
  16200. if (error->text_buffer_size > 0) {
  16201. *error->text = 0;
  16202. }
  16203. }
  16204. if ((host == NULL) || (protocol == NULL)) {
  16205. if (error != NULL) {
  16206. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16207. mg_snprintf(NULL,
  16208. NULL, /* No truncation check for error buffers */
  16209. error->text,
  16210. error->text_buffer_size,
  16211. "%s",
  16212. "Invalid parameters");
  16213. }
  16214. return NULL;
  16215. }
  16216. /* check all known protocols */
  16217. if (!mg_strcasecmp(protocol, "http")) {
  16218. is_ssl = 0;
  16219. is_ws = 0;
  16220. } else if (!mg_strcasecmp(protocol, "https")) {
  16221. is_ssl = 1;
  16222. is_ws = 0;
  16223. #if defined(USE_WEBSOCKET)
  16224. } else if (!mg_strcasecmp(protocol, "ws")) {
  16225. is_ssl = 0;
  16226. is_ws = 1;
  16227. } else if (!mg_strcasecmp(protocol, "wss")) {
  16228. is_ssl = 1;
  16229. is_ws = 1;
  16230. #endif
  16231. } else {
  16232. if (error != NULL) {
  16233. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16234. mg_snprintf(NULL,
  16235. NULL, /* No truncation check for error buffers */
  16236. error->text,
  16237. error->text_buffer_size,
  16238. "Protocol %s not supported",
  16239. protocol);
  16240. }
  16241. return NULL;
  16242. }
  16243. /* TODO: The current implementation here just calls the old
  16244. * implementations, without using any new options. This is just a first
  16245. * step to test the new interfaces. */
  16246. #if defined(USE_WEBSOCKET)
  16247. if (is_ws) {
  16248. /* TODO: implement all options */
  16249. return mg_connect_websocket_client(
  16250. host,
  16251. port,
  16252. is_ssl,
  16253. ((error != NULL) ? error->text : NULL),
  16254. ((error != NULL) ? error->text_buffer_size : 0),
  16255. (path ? path : ""),
  16256. NULL /* TODO: origin */,
  16257. experimental_websocket_client_data_wrapper,
  16258. experimental_websocket_client_close_wrapper,
  16259. (void *)init->callbacks);
  16260. }
  16261. #else
  16262. (void)is_ws;
  16263. #endif
  16264. /* TODO: all additional options */
  16265. struct mg_client_options opts;
  16266. memset(&opts, 0, sizeof(opts));
  16267. opts.host = host;
  16268. opts.port = port;
  16269. return mg_connect_client_impl(&opts, is_ssl, init, error);
  16270. }
  16271. #endif
  16272. static const struct {
  16273. const char *proto;
  16274. size_t proto_len;
  16275. unsigned default_port;
  16276. } abs_uri_protocols[] = {{"http://", 7, 80},
  16277. {"https://", 8, 443},
  16278. {"ws://", 5, 80},
  16279. {"wss://", 6, 443},
  16280. {NULL, 0, 0}};
  16281. /* Check if the uri is valid.
  16282. * return 0 for invalid uri,
  16283. * return 1 for *,
  16284. * return 2 for relative uri,
  16285. * return 3 for absolute uri without port,
  16286. * return 4 for absolute uri with port */
  16287. static int
  16288. get_uri_type(const char *uri)
  16289. {
  16290. int i;
  16291. const char *hostend, *portbegin;
  16292. char *portend;
  16293. unsigned long port;
  16294. /* According to the HTTP standard
  16295. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  16296. * URI can be an asterisk (*) or should start with slash (relative uri),
  16297. * or it should start with the protocol (absolute uri). */
  16298. if ((uri[0] == '*') && (uri[1] == '\0')) {
  16299. /* asterisk */
  16300. return 1;
  16301. }
  16302. /* Valid URIs according to RFC 3986
  16303. * (https://www.ietf.org/rfc/rfc3986.txt)
  16304. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16305. * and unreserved characters A-Z a-z 0-9 and -._~
  16306. * and % encoded symbols.
  16307. */
  16308. for (i = 0; uri[i] != 0; i++) {
  16309. if ((unsigned char)uri[i] < 33) {
  16310. /* control characters and spaces are invalid */
  16311. return 0;
  16312. }
  16313. /* Allow everything else here (See #894) */
  16314. }
  16315. /* A relative uri starts with a / character */
  16316. if (uri[0] == '/') {
  16317. /* relative uri */
  16318. return 2;
  16319. }
  16320. /* It could be an absolute uri: */
  16321. /* This function only checks if the uri is valid, not if it is
  16322. * addressing the current server. So civetweb can also be used
  16323. * as a proxy server. */
  16324. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16325. if (mg_strncasecmp(uri,
  16326. abs_uri_protocols[i].proto,
  16327. abs_uri_protocols[i].proto_len)
  16328. == 0) {
  16329. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16330. if (!hostend) {
  16331. return 0;
  16332. }
  16333. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16334. if (!portbegin) {
  16335. return 3;
  16336. }
  16337. port = strtoul(portbegin + 1, &portend, 10);
  16338. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16339. return 0;
  16340. }
  16341. return 4;
  16342. }
  16343. }
  16344. return 0;
  16345. }
  16346. /* Return NULL or the relative uri at the current server */
  16347. static const char *
  16348. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16349. {
  16350. const char *server_domain;
  16351. size_t server_domain_len;
  16352. size_t request_domain_len = 0;
  16353. unsigned long port = 0;
  16354. int i, auth_domain_check_enabled;
  16355. const char *hostbegin = NULL;
  16356. const char *hostend = NULL;
  16357. const char *portbegin;
  16358. char *portend;
  16359. auth_domain_check_enabled =
  16360. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16361. /* DNS is case insensitive, so use case insensitive string compare here
  16362. */
  16363. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16364. if (mg_strncasecmp(uri,
  16365. abs_uri_protocols[i].proto,
  16366. abs_uri_protocols[i].proto_len)
  16367. == 0) {
  16368. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16369. hostend = strchr(hostbegin, '/');
  16370. if (!hostend) {
  16371. return 0;
  16372. }
  16373. portbegin = strchr(hostbegin, ':');
  16374. if ((!portbegin) || (portbegin > hostend)) {
  16375. port = abs_uri_protocols[i].default_port;
  16376. request_domain_len = (size_t)(hostend - hostbegin);
  16377. } else {
  16378. port = strtoul(portbegin + 1, &portend, 10);
  16379. if ((portend != hostend) || (port <= 0)
  16380. || !is_valid_port(port)) {
  16381. return 0;
  16382. }
  16383. request_domain_len = (size_t)(portbegin - hostbegin);
  16384. }
  16385. /* protocol found, port set */
  16386. break;
  16387. }
  16388. }
  16389. if (!port) {
  16390. /* port remains 0 if the protocol is not found */
  16391. return 0;
  16392. }
  16393. /* Check if the request is directed to a different server. */
  16394. /* First check if the port is the same. */
  16395. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16396. /* Request is directed to a different port */
  16397. return 0;
  16398. }
  16399. /* Finally check if the server corresponds to the authentication
  16400. * domain of the server (the server domain).
  16401. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16402. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16403. * but do not allow substrings (like
  16404. * http://notmydomain.com/path/file.ext
  16405. * or http://mydomain.com.fake/path/file.ext).
  16406. */
  16407. if (auth_domain_check_enabled) {
  16408. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16409. server_domain_len = strlen(server_domain);
  16410. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16411. return 0;
  16412. }
  16413. if ((request_domain_len == server_domain_len)
  16414. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16415. /* Request is directed to this server - full name match. */
  16416. } else {
  16417. if (request_domain_len < (server_domain_len + 2)) {
  16418. /* Request is directed to another server: The server name
  16419. * is longer than the request name.
  16420. * Drop this case here to avoid overflows in the
  16421. * following checks. */
  16422. return 0;
  16423. }
  16424. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16425. /* Request is directed to another server: It could be a
  16426. * substring
  16427. * like notmyserver.com */
  16428. return 0;
  16429. }
  16430. if (0
  16431. != memcmp(server_domain,
  16432. hostbegin + request_domain_len - server_domain_len,
  16433. server_domain_len)) {
  16434. /* Request is directed to another server:
  16435. * The server name is different. */
  16436. return 0;
  16437. }
  16438. }
  16439. }
  16440. return hostend;
  16441. }
  16442. static int
  16443. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16444. {
  16445. if (ebuf_len > 0) {
  16446. ebuf[0] = '\0';
  16447. }
  16448. *err = 0;
  16449. reset_per_request_attributes(conn);
  16450. if (!conn) {
  16451. mg_snprintf(conn,
  16452. NULL, /* No truncation check for ebuf */
  16453. ebuf,
  16454. ebuf_len,
  16455. "%s",
  16456. "Internal error");
  16457. *err = 500;
  16458. return 0;
  16459. }
  16460. /* Set the time the request was received. This value should be used for
  16461. * timeouts. */
  16462. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16463. conn->request_len =
  16464. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16465. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16466. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16467. mg_snprintf(conn,
  16468. NULL, /* No truncation check for ebuf */
  16469. ebuf,
  16470. ebuf_len,
  16471. "%s",
  16472. "Invalid message size");
  16473. *err = 500;
  16474. return 0;
  16475. }
  16476. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16477. mg_snprintf(conn,
  16478. NULL, /* No truncation check for ebuf */
  16479. ebuf,
  16480. ebuf_len,
  16481. "%s",
  16482. "Message too large");
  16483. *err = 413;
  16484. return 0;
  16485. }
  16486. if (conn->request_len <= 0) {
  16487. if (conn->data_len > 0) {
  16488. mg_snprintf(conn,
  16489. NULL, /* No truncation check for ebuf */
  16490. ebuf,
  16491. ebuf_len,
  16492. "%s",
  16493. conn->request_len == -3 ? "Request timeout"
  16494. : "Malformed message");
  16495. *err = 400;
  16496. } else {
  16497. /* Server did not recv anything -> just close the connection */
  16498. conn->must_close = 1;
  16499. mg_snprintf(conn,
  16500. NULL, /* No truncation check for ebuf */
  16501. ebuf,
  16502. ebuf_len,
  16503. "%s",
  16504. "No data received");
  16505. *err = 0;
  16506. }
  16507. return 0;
  16508. }
  16509. return 1;
  16510. }
  16511. static int
  16512. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16513. {
  16514. const char *cl;
  16515. conn->connection_type =
  16516. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16517. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16518. return 0;
  16519. }
  16520. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16521. <= 0) {
  16522. mg_snprintf(conn,
  16523. NULL, /* No truncation check for ebuf */
  16524. ebuf,
  16525. ebuf_len,
  16526. "%s",
  16527. "Bad request");
  16528. *err = 400;
  16529. return 0;
  16530. }
  16531. /* Message is a valid request */
  16532. if (!switch_domain_context(conn)) {
  16533. mg_snprintf(conn,
  16534. NULL, /* No truncation check for ebuf */
  16535. ebuf,
  16536. ebuf_len,
  16537. "%s",
  16538. "Bad request: Host mismatch");
  16539. *err = 400;
  16540. return 0;
  16541. }
  16542. #if USE_ZLIB
  16543. if (((cl = get_header(conn->request_info.http_headers,
  16544. conn->request_info.num_headers,
  16545. "Accept-Encoding"))
  16546. != NULL)
  16547. && strstr(cl, "gzip")) {
  16548. conn->accept_gzip = 1;
  16549. }
  16550. #endif
  16551. if (((cl = get_header(conn->request_info.http_headers,
  16552. conn->request_info.num_headers,
  16553. "Transfer-Encoding"))
  16554. != NULL)
  16555. && mg_strcasecmp(cl, "identity")) {
  16556. if (mg_strcasecmp(cl, "chunked")) {
  16557. mg_snprintf(conn,
  16558. NULL, /* No truncation check for ebuf */
  16559. ebuf,
  16560. ebuf_len,
  16561. "%s",
  16562. "Bad request");
  16563. *err = 400;
  16564. return 0;
  16565. }
  16566. conn->is_chunked = 1;
  16567. conn->content_len = 0; /* not yet read */
  16568. } else if ((cl = get_header(conn->request_info.http_headers,
  16569. conn->request_info.num_headers,
  16570. "Content-Length"))
  16571. != NULL) {
  16572. /* Request has content length set */
  16573. char *endptr = NULL;
  16574. conn->content_len = strtoll(cl, &endptr, 10);
  16575. if ((endptr == cl) || (conn->content_len < 0)) {
  16576. mg_snprintf(conn,
  16577. NULL, /* No truncation check for ebuf */
  16578. ebuf,
  16579. ebuf_len,
  16580. "%s",
  16581. "Bad request");
  16582. *err = 411;
  16583. return 0;
  16584. }
  16585. /* Publish the content length back to the request info. */
  16586. conn->request_info.content_length = conn->content_len;
  16587. } else {
  16588. /* There is no exception, see RFC7230. */
  16589. conn->content_len = 0;
  16590. }
  16591. return 1;
  16592. }
  16593. /* conn is assumed to be valid in this internal function */
  16594. static int
  16595. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16596. {
  16597. const char *cl;
  16598. conn->connection_type =
  16599. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16600. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16601. return 0;
  16602. }
  16603. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16604. <= 0) {
  16605. mg_snprintf(conn,
  16606. NULL, /* No truncation check for ebuf */
  16607. ebuf,
  16608. ebuf_len,
  16609. "%s",
  16610. "Bad response");
  16611. *err = 400;
  16612. return 0;
  16613. }
  16614. /* Message is a valid response */
  16615. if (((cl = get_header(conn->response_info.http_headers,
  16616. conn->response_info.num_headers,
  16617. "Transfer-Encoding"))
  16618. != NULL)
  16619. && mg_strcasecmp(cl, "identity")) {
  16620. if (mg_strcasecmp(cl, "chunked")) {
  16621. mg_snprintf(conn,
  16622. NULL, /* No truncation check for ebuf */
  16623. ebuf,
  16624. ebuf_len,
  16625. "%s",
  16626. "Bad request");
  16627. *err = 400;
  16628. return 0;
  16629. }
  16630. conn->is_chunked = 1;
  16631. conn->content_len = 0; /* not yet read */
  16632. } else if ((cl = get_header(conn->response_info.http_headers,
  16633. conn->response_info.num_headers,
  16634. "Content-Length"))
  16635. != NULL) {
  16636. char *endptr = NULL;
  16637. conn->content_len = strtoll(cl, &endptr, 10);
  16638. if ((endptr == cl) || (conn->content_len < 0)) {
  16639. mg_snprintf(conn,
  16640. NULL, /* No truncation check for ebuf */
  16641. ebuf,
  16642. ebuf_len,
  16643. "%s",
  16644. "Bad request");
  16645. *err = 411;
  16646. return 0;
  16647. }
  16648. /* Publish the content length back to the response info. */
  16649. conn->response_info.content_length = conn->content_len;
  16650. /* TODO: check if it is still used in response_info */
  16651. conn->request_info.content_length = conn->content_len;
  16652. /* TODO: we should also consider HEAD method */
  16653. if (conn->response_info.status_code == 304) {
  16654. conn->content_len = 0;
  16655. }
  16656. } else {
  16657. /* TODO: we should also consider HEAD method */
  16658. if (((conn->response_info.status_code >= 100)
  16659. && (conn->response_info.status_code <= 199))
  16660. || (conn->response_info.status_code == 204)
  16661. || (conn->response_info.status_code == 304)) {
  16662. conn->content_len = 0;
  16663. } else {
  16664. conn->content_len = -1; /* unknown content length */
  16665. }
  16666. }
  16667. return 1;
  16668. }
  16669. CIVETWEB_API int
  16670. mg_get_response(struct mg_connection *conn,
  16671. char *ebuf,
  16672. size_t ebuf_len,
  16673. int timeout)
  16674. {
  16675. int err, ret;
  16676. char txt[32]; /* will not overflow */
  16677. char *save_timeout;
  16678. char *new_timeout;
  16679. if (ebuf_len > 0) {
  16680. ebuf[0] = '\0';
  16681. }
  16682. if (!conn) {
  16683. mg_snprintf(conn,
  16684. NULL, /* No truncation check for ebuf */
  16685. ebuf,
  16686. ebuf_len,
  16687. "%s",
  16688. "Parameter error");
  16689. return -1;
  16690. }
  16691. /* Reset the previous responses */
  16692. conn->data_len = 0;
  16693. /* Implementation of API function for HTTP clients */
  16694. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16695. if (timeout >= 0) {
  16696. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16697. new_timeout = txt;
  16698. } else {
  16699. new_timeout = NULL;
  16700. }
  16701. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16702. ret = get_response(conn, ebuf, ebuf_len, &err);
  16703. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16704. /* TODO: here, the URI is the http response code */
  16705. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16706. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16707. /* TODO (mid): Define proper return values - maybe return length?
  16708. * For the first test use <0 for error and >0 for OK */
  16709. return (ret == 0) ? -1 : +1;
  16710. }
  16711. CIVETWEB_API struct mg_connection *
  16712. mg_download(const char *host,
  16713. int port,
  16714. int use_ssl,
  16715. char *ebuf,
  16716. size_t ebuf_len,
  16717. const char *fmt,
  16718. ...)
  16719. {
  16720. struct mg_connection *conn;
  16721. va_list ap;
  16722. int i;
  16723. int reqerr;
  16724. if (ebuf_len > 0) {
  16725. ebuf[0] = '\0';
  16726. }
  16727. va_start(ap, fmt);
  16728. /* open a connection */
  16729. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16730. if (conn != NULL) {
  16731. i = mg_vprintf(conn, fmt, ap);
  16732. if (i <= 0) {
  16733. mg_snprintf(conn,
  16734. NULL, /* No truncation check for ebuf */
  16735. ebuf,
  16736. ebuf_len,
  16737. "%s",
  16738. "Error sending request");
  16739. } else {
  16740. /* make sure the buffer is clear */
  16741. conn->data_len = 0;
  16742. get_response(conn, ebuf, ebuf_len, &reqerr);
  16743. /* TODO: here, the URI is the http response code */
  16744. conn->request_info.local_uri = conn->request_info.request_uri;
  16745. }
  16746. }
  16747. /* if an error occurred, close the connection */
  16748. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16749. mg_close_connection(conn);
  16750. conn = NULL;
  16751. }
  16752. va_end(ap);
  16753. return conn;
  16754. }
  16755. struct websocket_client_thread_data {
  16756. struct mg_connection *conn;
  16757. mg_websocket_data_handler data_handler;
  16758. mg_websocket_close_handler close_handler;
  16759. void *callback_data;
  16760. };
  16761. #if defined(USE_WEBSOCKET)
  16762. #if defined(_WIN32)
  16763. static unsigned __stdcall websocket_client_thread(void *data)
  16764. #else
  16765. static void *
  16766. websocket_client_thread(void *data)
  16767. #endif
  16768. {
  16769. struct websocket_client_thread_data *cdata =
  16770. (struct websocket_client_thread_data *)data;
  16771. void *user_thread_ptr = NULL;
  16772. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16773. struct sigaction sa;
  16774. /* Ignore SIGPIPE */
  16775. memset(&sa, 0, sizeof(sa));
  16776. sa.sa_handler = SIG_IGN;
  16777. sigaction(SIGPIPE, &sa, NULL);
  16778. #endif
  16779. mg_set_thread_name("ws-clnt");
  16780. if (cdata->conn->phys_ctx) {
  16781. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16782. /* 3 indicates a websocket client thread */
  16783. /* TODO: check if conn->phys_ctx can be set */
  16784. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16785. cdata->conn->phys_ctx, 3);
  16786. }
  16787. }
  16788. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16789. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16790. if (cdata->close_handler != NULL) {
  16791. cdata->close_handler(cdata->conn, cdata->callback_data);
  16792. }
  16793. /* The websocket_client context has only this thread. If it runs out,
  16794. set the stop_flag to 2 (= "stopped"). */
  16795. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16796. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16797. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16798. 3,
  16799. user_thread_ptr);
  16800. }
  16801. mg_free((void *)cdata);
  16802. #if defined(_WIN32)
  16803. return 0;
  16804. #else
  16805. return NULL;
  16806. #endif
  16807. }
  16808. #endif
  16809. #if defined(USE_WEBSOCKET)
  16810. static void
  16811. generate_websocket_magic(char *magic25)
  16812. {
  16813. uint64_t rnd;
  16814. unsigned char buffer[2 * sizeof(rnd)];
  16815. rnd = get_random();
  16816. memcpy(buffer, &rnd, sizeof(rnd));
  16817. rnd = get_random();
  16818. memcpy(buffer + sizeof(rnd), &rnd, sizeof(rnd));
  16819. size_t dst_len = 24 + 1;
  16820. mg_base64_encode(buffer, sizeof(buffer), magic25, &dst_len);
  16821. }
  16822. #endif
  16823. static struct mg_connection *
  16824. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16825. int use_ssl,
  16826. char *error_buffer,
  16827. size_t error_buffer_size,
  16828. const char *path,
  16829. const char *origin,
  16830. const char *extensions,
  16831. mg_websocket_data_handler data_func,
  16832. mg_websocket_close_handler close_func,
  16833. void *user_data)
  16834. {
  16835. struct mg_connection *conn = NULL;
  16836. #if defined(USE_WEBSOCKET)
  16837. struct websocket_client_thread_data *thread_data;
  16838. char magic[32];
  16839. generate_websocket_magic(magic);
  16840. const char *host = client_options->host;
  16841. int i;
  16842. struct mg_init_data init;
  16843. struct mg_error_data error;
  16844. memset(&init, 0, sizeof(init));
  16845. memset(&error, 0, sizeof(error));
  16846. error.text_buffer_size = error_buffer_size;
  16847. error.text = error_buffer;
  16848. #if defined(__clang__)
  16849. #pragma clang diagnostic push
  16850. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16851. #endif
  16852. /* Establish the client connection and request upgrade */
  16853. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16854. /* Connection object will be null if something goes wrong */
  16855. if (conn == NULL) {
  16856. /* error_buffer should be already filled ... */
  16857. if (!error_buffer[0]) {
  16858. /* ... if not add an error message */
  16859. mg_snprintf(conn,
  16860. NULL, /* No truncation check for ebuf */
  16861. error_buffer,
  16862. error_buffer_size,
  16863. "Unexpected error");
  16864. }
  16865. return NULL;
  16866. }
  16867. if (origin != NULL) {
  16868. if (extensions != NULL) {
  16869. i = mg_printf(conn,
  16870. "GET %s HTTP/1.1\r\n"
  16871. "Host: %s\r\n"
  16872. "Upgrade: websocket\r\n"
  16873. "Connection: Upgrade\r\n"
  16874. "Sec-WebSocket-Key: %s\r\n"
  16875. "Sec-WebSocket-Version: 13\r\n"
  16876. "Sec-WebSocket-Extensions: %s\r\n"
  16877. "Origin: %s\r\n"
  16878. "\r\n",
  16879. path,
  16880. host,
  16881. magic,
  16882. extensions,
  16883. origin);
  16884. } else {
  16885. i = mg_printf(conn,
  16886. "GET %s HTTP/1.1\r\n"
  16887. "Host: %s\r\n"
  16888. "Upgrade: websocket\r\n"
  16889. "Connection: Upgrade\r\n"
  16890. "Sec-WebSocket-Key: %s\r\n"
  16891. "Sec-WebSocket-Version: 13\r\n"
  16892. "Origin: %s\r\n"
  16893. "\r\n",
  16894. path,
  16895. host,
  16896. magic,
  16897. origin);
  16898. }
  16899. } else {
  16900. if (extensions != NULL) {
  16901. i = mg_printf(conn,
  16902. "GET %s HTTP/1.1\r\n"
  16903. "Host: %s\r\n"
  16904. "Upgrade: websocket\r\n"
  16905. "Connection: Upgrade\r\n"
  16906. "Sec-WebSocket-Key: %s\r\n"
  16907. "Sec-WebSocket-Version: 13\r\n"
  16908. "Sec-WebSocket-Extensions: %s\r\n"
  16909. "\r\n",
  16910. path,
  16911. host,
  16912. magic,
  16913. extensions);
  16914. } else {
  16915. i = mg_printf(conn,
  16916. "GET %s HTTP/1.1\r\n"
  16917. "Host: %s\r\n"
  16918. "Upgrade: websocket\r\n"
  16919. "Connection: Upgrade\r\n"
  16920. "Sec-WebSocket-Key: %s\r\n"
  16921. "Sec-WebSocket-Version: 13\r\n"
  16922. "\r\n",
  16923. path,
  16924. host,
  16925. magic);
  16926. }
  16927. }
  16928. if (i <= 0) {
  16929. mg_snprintf(conn,
  16930. NULL, /* No truncation check for ebuf */
  16931. error_buffer,
  16932. error_buffer_size,
  16933. "%s",
  16934. "Error sending request");
  16935. mg_close_connection(conn);
  16936. return NULL;
  16937. }
  16938. conn->data_len = 0;
  16939. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16940. mg_close_connection(conn);
  16941. return NULL;
  16942. }
  16943. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16944. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16945. #if defined(__clang__)
  16946. #pragma clang diagnostic pop
  16947. #endif
  16948. if (conn->response_info.status_code != 101) {
  16949. /* We sent an "upgrade" request. For a correct websocket
  16950. * protocol handshake, we expect a "101 Continue" response.
  16951. * Otherwise it is a protocol violation. Maybe the HTTP
  16952. * Server does not know websockets. */
  16953. if (!*error_buffer) {
  16954. /* set an error, if not yet set */
  16955. mg_snprintf(conn,
  16956. NULL, /* No truncation check for ebuf */
  16957. error_buffer,
  16958. error_buffer_size,
  16959. "Unexpected server reply");
  16960. }
  16961. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16962. mg_close_connection(conn);
  16963. return NULL;
  16964. }
  16965. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16966. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16967. if (!thread_data) {
  16968. DEBUG_TRACE("%s\r\n", "Out of memory");
  16969. mg_close_connection(conn);
  16970. return NULL;
  16971. }
  16972. thread_data->conn = conn;
  16973. thread_data->data_handler = data_func;
  16974. thread_data->close_handler = close_func;
  16975. thread_data->callback_data = user_data;
  16976. conn->phys_ctx->worker_threadids =
  16977. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16978. if (!conn->phys_ctx->worker_threadids) {
  16979. DEBUG_TRACE("%s\r\n", "Out of memory");
  16980. mg_free(thread_data);
  16981. mg_close_connection(conn);
  16982. return NULL;
  16983. }
  16984. /* Now upgrade to ws/wss client context */
  16985. conn->phys_ctx->user_data = user_data;
  16986. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16987. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  16988. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  16989. /* Start a thread to read the websocket client connection
  16990. * This thread will automatically stop when mg_disconnect is
  16991. * called on the client connection */
  16992. if (mg_start_thread_with_id(websocket_client_thread,
  16993. thread_data,
  16994. conn->phys_ctx->worker_threadids)
  16995. != 0) {
  16996. conn->phys_ctx->spawned_worker_threads = 0;
  16997. mg_free(thread_data);
  16998. mg_close_connection(conn);
  16999. conn = NULL;
  17000. DEBUG_TRACE("%s",
  17001. "Websocket client connect thread could not be started\r\n");
  17002. }
  17003. #else
  17004. /* Appease "unused parameter" warnings */
  17005. (void)client_options;
  17006. (void)use_ssl;
  17007. (void)error_buffer;
  17008. (void)error_buffer_size;
  17009. (void)path;
  17010. (void)origin;
  17011. (void)extensions;
  17012. (void)user_data;
  17013. (void)data_func;
  17014. (void)close_func;
  17015. #endif
  17016. return conn;
  17017. }
  17018. CIVETWEB_API struct mg_connection *
  17019. mg_connect_websocket_client(const char *host,
  17020. int port,
  17021. int use_ssl,
  17022. char *error_buffer,
  17023. size_t error_buffer_size,
  17024. const char *path,
  17025. const char *origin,
  17026. mg_websocket_data_handler data_func,
  17027. mg_websocket_close_handler close_func,
  17028. void *user_data)
  17029. {
  17030. struct mg_client_options client_options;
  17031. memset(&client_options, 0, sizeof(client_options));
  17032. client_options.host = host;
  17033. client_options.port = port;
  17034. if (use_ssl) {
  17035. client_options.host_name = host;
  17036. }
  17037. return mg_connect_websocket_client_impl(&client_options,
  17038. use_ssl,
  17039. error_buffer,
  17040. error_buffer_size,
  17041. path,
  17042. origin,
  17043. NULL,
  17044. data_func,
  17045. close_func,
  17046. user_data);
  17047. }
  17048. CIVETWEB_API struct mg_connection *
  17049. mg_connect_websocket_client_secure(
  17050. const struct mg_client_options *client_options,
  17051. char *error_buffer,
  17052. size_t error_buffer_size,
  17053. const char *path,
  17054. const char *origin,
  17055. mg_websocket_data_handler data_func,
  17056. mg_websocket_close_handler close_func,
  17057. void *user_data)
  17058. {
  17059. if (!client_options) {
  17060. return NULL;
  17061. }
  17062. return mg_connect_websocket_client_impl(client_options,
  17063. 1,
  17064. error_buffer,
  17065. error_buffer_size,
  17066. path,
  17067. origin,
  17068. NULL,
  17069. data_func,
  17070. close_func,
  17071. user_data);
  17072. }
  17073. CIVETWEB_API struct mg_connection *
  17074. mg_connect_websocket_client_extensions(const char *host,
  17075. int port,
  17076. int use_ssl,
  17077. char *error_buffer,
  17078. size_t error_buffer_size,
  17079. const char *path,
  17080. const char *origin,
  17081. const char *extensions,
  17082. mg_websocket_data_handler data_func,
  17083. mg_websocket_close_handler close_func,
  17084. void *user_data)
  17085. {
  17086. struct mg_client_options client_options;
  17087. memset(&client_options, 0, sizeof(client_options));
  17088. client_options.host = host;
  17089. client_options.port = port;
  17090. return mg_connect_websocket_client_impl(&client_options,
  17091. use_ssl,
  17092. error_buffer,
  17093. error_buffer_size,
  17094. path,
  17095. origin,
  17096. extensions,
  17097. data_func,
  17098. close_func,
  17099. user_data);
  17100. }
  17101. CIVETWEB_API struct mg_connection *
  17102. mg_connect_websocket_client_secure_extensions(
  17103. const struct mg_client_options *client_options,
  17104. char *error_buffer,
  17105. size_t error_buffer_size,
  17106. const char *path,
  17107. const char *origin,
  17108. const char *extensions,
  17109. mg_websocket_data_handler data_func,
  17110. mg_websocket_close_handler close_func,
  17111. void *user_data)
  17112. {
  17113. if (!client_options) {
  17114. return NULL;
  17115. }
  17116. return mg_connect_websocket_client_impl(client_options,
  17117. 1,
  17118. error_buffer,
  17119. error_buffer_size,
  17120. path,
  17121. origin,
  17122. extensions,
  17123. data_func,
  17124. close_func,
  17125. user_data);
  17126. }
  17127. /* Prepare connection data structure */
  17128. static void
  17129. init_connection(struct mg_connection *conn)
  17130. {
  17131. /* Is keep alive allowed by the server */
  17132. int keep_alive_enabled =
  17133. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  17134. if (!keep_alive_enabled) {
  17135. conn->must_close = 1;
  17136. }
  17137. /* Important: on new connection, reset the receiving buffer. Credit
  17138. * goes to crule42. */
  17139. conn->data_len = 0;
  17140. conn->handled_requests = 0;
  17141. conn->connection_type = CONNECTION_TYPE_INVALID;
  17142. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  17143. mg_set_user_connection_data(conn, NULL);
  17144. #if defined(USE_SERVER_STATS)
  17145. conn->conn_state = 2; /* init */
  17146. #endif
  17147. /* call the init_connection callback if assigned */
  17148. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  17149. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  17150. void *conn_data = NULL;
  17151. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  17152. mg_set_user_connection_data(conn, conn_data);
  17153. }
  17154. }
  17155. }
  17156. /* Process a connection - may handle multiple requests
  17157. * using the same connection.
  17158. * Must be called with a valid connection (conn and
  17159. * conn->phys_ctx must be valid).
  17160. */
  17161. static void
  17162. process_new_connection(struct mg_connection *conn)
  17163. {
  17164. struct mg_request_info *ri = &conn->request_info;
  17165. int keep_alive, discard_len;
  17166. char ebuf[100];
  17167. const char *hostend;
  17168. int reqerr, uri_type;
  17169. #if defined(USE_SERVER_STATS)
  17170. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  17171. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  17172. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  17173. #endif
  17174. DEBUG_TRACE("Start processing connection from %s",
  17175. conn->request_info.remote_addr);
  17176. /* Loop over multiple requests sent using the same connection
  17177. * (while "keep alive"). */
  17178. do {
  17179. DEBUG_TRACE("calling get_request (%i times for this connection)",
  17180. conn->handled_requests + 1);
  17181. #if defined(USE_SERVER_STATS)
  17182. conn->conn_state = 3; /* ready */
  17183. #endif
  17184. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  17185. /* The request sent by the client could not be understood by
  17186. * the server, or it was incomplete or a timeout. Send an
  17187. * error message and close the connection. */
  17188. if (reqerr > 0) {
  17189. DEBUG_ASSERT(ebuf[0] != '\0');
  17190. mg_send_http_error(conn, reqerr, "%s", ebuf);
  17191. }
  17192. } else if (strcmp(ri->http_version, "1.0")
  17193. && strcmp(ri->http_version, "1.1")) {
  17194. /* HTTP/2 is not allowed here */
  17195. mg_snprintf(conn,
  17196. NULL, /* No truncation check for ebuf */
  17197. ebuf,
  17198. sizeof(ebuf),
  17199. "Bad HTTP version: [%s]",
  17200. ri->http_version);
  17201. mg_send_http_error(conn, 505, "%s", ebuf);
  17202. }
  17203. if (ebuf[0] == '\0') {
  17204. uri_type = get_uri_type(conn->request_info.request_uri);
  17205. switch (uri_type) {
  17206. case 1:
  17207. /* Asterisk */
  17208. conn->request_info.local_uri_raw = 0;
  17209. /* TODO: Deal with '*'. */
  17210. break;
  17211. case 2:
  17212. /* relative uri */
  17213. conn->request_info.local_uri_raw =
  17214. conn->request_info.request_uri;
  17215. break;
  17216. case 3:
  17217. case 4:
  17218. /* absolute uri (with/without port) */
  17219. hostend = get_rel_url_at_current_server(
  17220. conn->request_info.request_uri, conn);
  17221. if (hostend) {
  17222. conn->request_info.local_uri_raw = hostend;
  17223. } else {
  17224. conn->request_info.local_uri_raw = NULL;
  17225. }
  17226. break;
  17227. default:
  17228. mg_snprintf(conn,
  17229. NULL, /* No truncation check for ebuf */
  17230. ebuf,
  17231. sizeof(ebuf),
  17232. "Invalid URI");
  17233. mg_send_http_error(conn, 400, "%s", ebuf);
  17234. conn->request_info.local_uri_raw = NULL;
  17235. break;
  17236. }
  17237. conn->request_info.local_uri =
  17238. (char *)conn->request_info.local_uri_raw;
  17239. }
  17240. if (ebuf[0] != '\0') {
  17241. conn->protocol_type = -1;
  17242. } else {
  17243. /* HTTP/1 allows protocol upgrade */
  17244. conn->protocol_type = should_switch_to_protocol(conn);
  17245. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  17246. /* This will occur, if a HTTP/1.1 request should be upgraded
  17247. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  17248. * Since most (all?) major browsers only support HTTP/2 using
  17249. * ALPN, this is hard to test and very low priority.
  17250. * Deactivate it (at least for now).
  17251. */
  17252. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17253. }
  17254. }
  17255. DEBUG_TRACE("http: %s, error: %s",
  17256. (ri->http_version ? ri->http_version : "none"),
  17257. (ebuf[0] ? ebuf : "none"));
  17258. if (ebuf[0] == '\0') {
  17259. if (conn->request_info.local_uri) {
  17260. /* handle request to local server */
  17261. handle_request_stat_log(conn);
  17262. } else {
  17263. /* TODO: handle non-local request (PROXY) */
  17264. conn->must_close = 1;
  17265. }
  17266. } else {
  17267. conn->must_close = 1;
  17268. }
  17269. /* Response complete. Free header buffer */
  17270. free_buffered_response_header_list(conn);
  17271. if (ri->remote_user != NULL) {
  17272. mg_free((void *)ri->remote_user);
  17273. /* Important! When having connections with and without auth
  17274. * would cause double free and then crash */
  17275. ri->remote_user = NULL;
  17276. }
  17277. /* NOTE(lsm): order is important here. should_keep_alive() call
  17278. * is using parsed request, which will be invalid after
  17279. * memmove's below.
  17280. * Therefore, memorize should_keep_alive() result now for later
  17281. * use in loop exit condition. */
  17282. /* Enable it only if this request is completely discardable. */
  17283. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  17284. && should_keep_alive(conn) && (conn->content_len >= 0)
  17285. && (conn->request_len > 0)
  17286. && ((conn->is_chunked == 4)
  17287. || (!conn->is_chunked
  17288. && ((conn->consumed_content == conn->content_len)
  17289. || ((conn->request_len + conn->content_len)
  17290. <= conn->data_len))))
  17291. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  17292. if (keep_alive) {
  17293. /* Discard all buffered data for this request */
  17294. discard_len =
  17295. ((conn->request_len + conn->content_len) < conn->data_len)
  17296. ? (int)(conn->request_len + conn->content_len)
  17297. : conn->data_len;
  17298. conn->data_len -= discard_len;
  17299. if (conn->data_len > 0) {
  17300. DEBUG_TRACE("discard_len = %d", discard_len);
  17301. memmove(conn->buf,
  17302. conn->buf + discard_len,
  17303. (size_t)conn->data_len);
  17304. }
  17305. }
  17306. DEBUG_ASSERT(conn->data_len >= 0);
  17307. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  17308. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  17309. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  17310. (long int)conn->data_len,
  17311. (long int)conn->buf_size);
  17312. break;
  17313. }
  17314. conn->handled_requests++;
  17315. } while (keep_alive);
  17316. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  17317. conn->request_info.remote_addr,
  17318. difftime(time(NULL), conn->conn_birth_time));
  17319. close_connection(conn);
  17320. #if defined(USE_SERVER_STATS)
  17321. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17322. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17323. #endif
  17324. }
  17325. static int
  17326. mg_start_worker_thread(struct mg_context *ctx,
  17327. int only_if_no_idle_threads); /* forward declaration */
  17328. #if defined(ALTERNATIVE_QUEUE)
  17329. static void
  17330. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17331. {
  17332. unsigned int i;
  17333. (void)mg_start_worker_thread(
  17334. ctx, 1); /* will start a worker-thread only if there aren't currently
  17335. any idle worker-threads */
  17336. while (!ctx->stop_flag) {
  17337. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17338. /* find a free worker slot and signal it */
  17339. if (ctx->client_socks[i].in_use == 2) {
  17340. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17341. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17342. ctx->client_socks[i] = *sp;
  17343. ctx->client_socks[i].in_use = 1;
  17344. /* socket has been moved to the consumer */
  17345. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17346. (void)event_signal(ctx->client_wait_events[i]);
  17347. return;
  17348. }
  17349. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17350. }
  17351. }
  17352. /* queue is full */
  17353. mg_sleep(1);
  17354. }
  17355. /* must consume */
  17356. set_blocking_mode(sp->sock);
  17357. closesocket(sp->sock);
  17358. }
  17359. static int
  17360. consume_socket(struct mg_context *ctx,
  17361. struct socket *sp,
  17362. int thread_index,
  17363. int counter_was_preincremented)
  17364. {
  17365. DEBUG_TRACE("%s", "going idle");
  17366. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17367. if (counter_was_preincremented
  17368. == 0) { /* first call only: the master-thread pre-incremented this
  17369. before he spawned us */
  17370. ctx->idle_worker_thread_count++;
  17371. }
  17372. ctx->client_socks[thread_index].in_use = 2;
  17373. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17374. event_wait(ctx->client_wait_events[thread_index]);
  17375. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17376. *sp = ctx->client_socks[thread_index];
  17377. if (ctx->stop_flag) {
  17378. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17379. if (sp->in_use == 1) {
  17380. /* must consume */
  17381. set_blocking_mode(sp->sock);
  17382. closesocket(sp->sock);
  17383. }
  17384. return 0;
  17385. }
  17386. ctx->idle_worker_thread_count--;
  17387. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17388. if (sp->in_use == 1) {
  17389. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17390. return 1;
  17391. }
  17392. /* must not reach here */
  17393. DEBUG_ASSERT(0);
  17394. return 0;
  17395. }
  17396. #else /* ALTERNATIVE_QUEUE */
  17397. /* Worker threads take accepted socket from the queue */
  17398. static int
  17399. consume_socket(struct mg_context *ctx,
  17400. struct socket *sp,
  17401. int thread_index,
  17402. int counter_was_preincremented)
  17403. {
  17404. (void)thread_index;
  17405. DEBUG_TRACE("%s", "going idle");
  17406. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17407. if (counter_was_preincremented
  17408. == 0) { /* first call only: the master-thread pre-incremented this
  17409. before he spawned us */
  17410. ctx->idle_worker_thread_count++;
  17411. }
  17412. /* If the queue is empty, wait. We're idle at this point. */
  17413. while ((ctx->sq_head == ctx->sq_tail)
  17414. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17415. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17416. }
  17417. /* If we're stopping, sq_head may be equal to sq_tail. */
  17418. if (ctx->sq_head > ctx->sq_tail) {
  17419. /* Copy socket from the queue and increment tail */
  17420. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17421. ctx->sq_tail++;
  17422. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17423. /* Wrap pointers if needed */
  17424. while (ctx->sq_tail > ctx->sq_size) {
  17425. ctx->sq_tail -= ctx->sq_size;
  17426. ctx->sq_head -= ctx->sq_size;
  17427. }
  17428. }
  17429. (void)pthread_cond_signal(&ctx->sq_empty);
  17430. ctx->idle_worker_thread_count--;
  17431. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17432. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17433. }
  17434. /* Master thread adds accepted socket to a queue */
  17435. static void
  17436. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17437. {
  17438. int queue_filled;
  17439. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17440. queue_filled = ctx->sq_head - ctx->sq_tail;
  17441. /* If the queue is full, wait */
  17442. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17443. && (queue_filled >= ctx->sq_size)) {
  17444. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17445. #if defined(USE_SERVER_STATS)
  17446. if (queue_filled > ctx->sq_max_fill) {
  17447. ctx->sq_max_fill = queue_filled;
  17448. }
  17449. #endif
  17450. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17451. ctx->sq_blocked = 0; /* Not blocked now */
  17452. queue_filled = ctx->sq_head - ctx->sq_tail;
  17453. }
  17454. if (queue_filled < ctx->sq_size) {
  17455. /* Copy socket to the queue and increment head */
  17456. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17457. ctx->sq_head++;
  17458. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17459. }
  17460. queue_filled = ctx->sq_head - ctx->sq_tail;
  17461. #if defined(USE_SERVER_STATS)
  17462. if (queue_filled > ctx->sq_max_fill) {
  17463. ctx->sq_max_fill = queue_filled;
  17464. }
  17465. #endif
  17466. (void)pthread_cond_signal(&ctx->sq_full);
  17467. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17468. (void)mg_start_worker_thread(
  17469. ctx, 1); /* will start a worker-thread only if there aren't currently
  17470. any idle worker-threads */
  17471. }
  17472. #endif /* ALTERNATIVE_QUEUE */
  17473. static void
  17474. worker_thread_run(struct mg_connection *conn)
  17475. {
  17476. struct mg_context *ctx = conn->phys_ctx;
  17477. int thread_index;
  17478. struct mg_workerTLS tls;
  17479. int first_call_to_consume_socket = 1;
  17480. mg_set_thread_name("worker");
  17481. tls.is_master = 0;
  17482. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17483. #if defined(_WIN32)
  17484. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17485. #endif
  17486. /* Initialize thread local storage before calling any callback */
  17487. pthread_setspecific(sTlsKey, &tls);
  17488. /* Check if there is a user callback */
  17489. if (ctx->callbacks.init_thread) {
  17490. /* call init_thread for a worker thread (type 1), and store the
  17491. * return value */
  17492. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17493. } else {
  17494. /* No callback: set user pointer to NULL */
  17495. tls.user_ptr = NULL;
  17496. }
  17497. /* Connection structure has been pre-allocated */
  17498. thread_index = (int)(conn - ctx->worker_connections);
  17499. if ((thread_index < 0)
  17500. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17501. mg_cry_ctx_internal(ctx,
  17502. "Internal error: Invalid worker index %i",
  17503. thread_index);
  17504. return;
  17505. }
  17506. /* Request buffers are not pre-allocated. They are private to the
  17507. * request and do not contain any state information that might be
  17508. * of interest to anyone observing a server status. */
  17509. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17510. if (conn->buf == NULL) {
  17511. mg_cry_ctx_internal(
  17512. ctx,
  17513. "Out of memory: Cannot allocate buffer for worker %i",
  17514. thread_index);
  17515. return;
  17516. }
  17517. conn->buf_size = (int)ctx->max_request_size;
  17518. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17519. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17520. conn->request_info.user_data = ctx->user_data;
  17521. /* Allocate a mutex for this connection to allow communication both
  17522. * within the request handler and from elsewhere in the application
  17523. */
  17524. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17525. mg_free(conn->buf);
  17526. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17527. return;
  17528. }
  17529. #if defined(USE_SERVER_STATS)
  17530. conn->conn_state = 1; /* not consumed */
  17531. #endif
  17532. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17533. * signal sq_empty condvar to wake up the master waiting in
  17534. * produce_socket() */
  17535. while (consume_socket(
  17536. ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17537. first_call_to_consume_socket = 0;
  17538. /* New connections must start with new protocol negotiation */
  17539. tls.alpn_proto = NULL;
  17540. #if defined(USE_SERVER_STATS)
  17541. conn->conn_close_time = 0;
  17542. #endif
  17543. conn->conn_birth_time = time(NULL);
  17544. /* Fill in IP, port info early so even if SSL setup below fails,
  17545. * error handler would have the corresponding info.
  17546. * Thanks to Johannes Winkelmann for the patch.
  17547. */
  17548. conn->request_info.remote_port =
  17549. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17550. conn->request_info.server_port =
  17551. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17552. sockaddr_to_string(conn->request_info.remote_addr,
  17553. sizeof(conn->request_info.remote_addr),
  17554. &conn->client.rsa);
  17555. DEBUG_TRACE("Incoming %sconnection from %s",
  17556. (conn->client.is_ssl ? "SSL " : ""),
  17557. conn->request_info.remote_addr);
  17558. conn->request_info.is_ssl = conn->client.is_ssl;
  17559. if (conn->client.is_ssl) {
  17560. #if defined(USE_MBEDTLS)
  17561. /* HTTPS connection */
  17562. if (mbed_ssl_accept(&(conn->ssl),
  17563. conn->dom_ctx->ssl_ctx,
  17564. (int *)&(conn->client.sock),
  17565. conn->phys_ctx)
  17566. == 0) {
  17567. /* conn->dom_ctx is set in get_request */
  17568. /* process HTTPS connection */
  17569. init_connection(conn);
  17570. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17571. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17572. process_new_connection(conn);
  17573. } else {
  17574. /* make sure the connection is cleaned up on SSL failure */
  17575. close_connection(conn);
  17576. }
  17577. #elif defined(USE_GNUTLS)
  17578. /* HTTPS connection */
  17579. if (gtls_ssl_accept(&(conn->ssl),
  17580. conn->dom_ctx->ssl_ctx,
  17581. conn->client.sock,
  17582. conn->phys_ctx)
  17583. == 0) {
  17584. /* conn->dom_ctx is set in get_request */
  17585. /* process HTTPS connection */
  17586. init_connection(conn);
  17587. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17588. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17589. process_new_connection(conn);
  17590. } else {
  17591. /* make sure the connection is cleaned up on SSL failure */
  17592. close_connection(conn);
  17593. }
  17594. #elif !defined(NO_SSL)
  17595. /* HTTPS connection */
  17596. if (sslize(conn, SSL_accept, NULL)) {
  17597. /* conn->dom_ctx is set in get_request */
  17598. /* Get SSL client certificate information (if set) */
  17599. struct mg_client_cert client_cert;
  17600. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17601. conn->request_info.client_cert = &client_cert;
  17602. }
  17603. /* process HTTPS connection */
  17604. #if defined(USE_HTTP2)
  17605. if ((tls.alpn_proto != NULL)
  17606. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17607. /* process HTTPS/2 connection */
  17608. init_connection(conn);
  17609. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17610. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17611. conn->content_len =
  17612. -1; /* content length is not predefined */
  17613. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17614. process_new_http2_connection(conn);
  17615. } else
  17616. #endif
  17617. {
  17618. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17619. init_connection(conn);
  17620. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17621. /* Start with HTTP, WS will be an "upgrade" request later */
  17622. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17623. process_new_connection(conn);
  17624. }
  17625. /* Free client certificate info */
  17626. if (conn->request_info.client_cert) {
  17627. mg_free((void *)(conn->request_info.client_cert->subject));
  17628. mg_free((void *)(conn->request_info.client_cert->issuer));
  17629. mg_free((void *)(conn->request_info.client_cert->serial));
  17630. mg_free((void *)(conn->request_info.client_cert->finger));
  17631. /* Free certificate memory */
  17632. X509_free(
  17633. (X509 *)conn->request_info.client_cert->peer_cert);
  17634. conn->request_info.client_cert->peer_cert = 0;
  17635. conn->request_info.client_cert->subject = 0;
  17636. conn->request_info.client_cert->issuer = 0;
  17637. conn->request_info.client_cert->serial = 0;
  17638. conn->request_info.client_cert->finger = 0;
  17639. conn->request_info.client_cert = 0;
  17640. }
  17641. } else {
  17642. /* make sure the connection is cleaned up on SSL failure */
  17643. close_connection(conn);
  17644. }
  17645. #endif
  17646. } else {
  17647. /* process HTTP connection */
  17648. init_connection(conn);
  17649. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17650. /* Start with HTTP, WS will be an "upgrade" request later */
  17651. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17652. process_new_connection(conn);
  17653. }
  17654. DEBUG_TRACE("%s", "Connection closed");
  17655. #if defined(USE_SERVER_STATS)
  17656. conn->conn_close_time = time(NULL);
  17657. #endif
  17658. }
  17659. /* Call exit thread user callback */
  17660. if (ctx->callbacks.exit_thread) {
  17661. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17662. }
  17663. /* delete thread local storage objects */
  17664. pthread_setspecific(sTlsKey, NULL);
  17665. #if defined(_WIN32)
  17666. CloseHandle(tls.pthread_cond_helper_mutex);
  17667. #endif
  17668. pthread_mutex_destroy(&conn->mutex);
  17669. /* Free the request buffer. */
  17670. conn->buf_size = 0;
  17671. mg_free(conn->buf);
  17672. conn->buf = NULL;
  17673. /* Free cleaned URI (if any) */
  17674. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17675. mg_free((void *)conn->request_info.local_uri);
  17676. conn->request_info.local_uri = NULL;
  17677. }
  17678. #if defined(USE_SERVER_STATS)
  17679. conn->conn_state = 9; /* done */
  17680. #endif
  17681. DEBUG_TRACE("%s", "exiting");
  17682. }
  17683. /* Threads have different return types on Windows and Unix. */
  17684. #if defined(_WIN32)
  17685. static unsigned __stdcall worker_thread(void *thread_func_param)
  17686. {
  17687. worker_thread_run((struct mg_connection *)thread_func_param);
  17688. return 0;
  17689. }
  17690. #else
  17691. static void *
  17692. worker_thread(void *thread_func_param)
  17693. {
  17694. #if !defined(__ZEPHYR__)
  17695. struct sigaction sa;
  17696. /* Ignore SIGPIPE */
  17697. memset(&sa, 0, sizeof(sa));
  17698. sa.sa_handler = SIG_IGN;
  17699. sigaction(SIGPIPE, &sa, NULL);
  17700. #endif
  17701. worker_thread_run((struct mg_connection *)thread_func_param);
  17702. return NULL;
  17703. }
  17704. #endif /* _WIN32 */
  17705. /* This is an internal function, thus all arguments are expected to be
  17706. * valid - a NULL check is not required. */
  17707. static void
  17708. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17709. {
  17710. struct socket so;
  17711. char src_addr[IP_ADDR_STR_LEN];
  17712. socklen_t len = sizeof(so.rsa);
  17713. #if !defined(__ZEPHYR__)
  17714. int on = 1;
  17715. #endif
  17716. memset(&so, 0, sizeof(so));
  17717. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17718. == INVALID_SOCKET) {
  17719. } else if (check_acl(ctx, &so.rsa) != 1) {
  17720. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17721. mg_cry_ctx_internal(ctx,
  17722. "%s: %s is not allowed to connect",
  17723. __func__,
  17724. src_addr);
  17725. closesocket(so.sock);
  17726. } else {
  17727. /* Put so socket structure into the queue */
  17728. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17729. set_close_on_exec(so.sock, NULL, ctx);
  17730. so.is_ssl = listener->is_ssl;
  17731. so.ssl_redir = listener->ssl_redir;
  17732. so.is_optional = listener->is_optional;
  17733. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17734. mg_cry_ctx_internal(ctx,
  17735. "%s: getsockname() failed: %s",
  17736. __func__,
  17737. strerror(ERRNO));
  17738. }
  17739. #if !defined(__ZEPHYR__)
  17740. if ((so.lsa.sa.sa_family == AF_INET)
  17741. || (so.lsa.sa.sa_family == AF_INET6)) {
  17742. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17743. * This is needed because if HTTP-level keep-alive
  17744. * is enabled, and client resets the connection, server won't get
  17745. * TCP FIN or RST and will keep the connection open forever. With
  17746. * TCP keep-alive, next keep-alive handshake will figure out that
  17747. * the client is down and will close the server end.
  17748. * Thanks to Igor Klopov who suggested the patch. */
  17749. if (setsockopt(so.sock,
  17750. SOL_SOCKET,
  17751. SO_KEEPALIVE,
  17752. (SOCK_OPT_TYPE)&on,
  17753. sizeof(on))
  17754. != 0) {
  17755. mg_cry_ctx_internal(
  17756. ctx,
  17757. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17758. __func__,
  17759. strerror(ERRNO));
  17760. }
  17761. }
  17762. #endif
  17763. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17764. * to effectively fill up the underlying IP packet payload and
  17765. * reduce the overhead of sending lots of small buffers. However
  17766. * this hurts the server's throughput (ie. operations per second)
  17767. * when HTTP 1.1 persistent connections are used and the responses
  17768. * are relatively small (eg. less than 1400 bytes).
  17769. */
  17770. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17771. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17772. if (set_tcp_nodelay(&so, 1) != 0) {
  17773. mg_cry_ctx_internal(
  17774. ctx,
  17775. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17776. __func__,
  17777. strerror(ERRNO));
  17778. }
  17779. }
  17780. /* The "non blocking" property should already be
  17781. * inherited from the parent socket. Set it for
  17782. * non-compliant socket implementations. */
  17783. set_non_blocking_mode(so.sock);
  17784. so.in_use = 0;
  17785. produce_socket(ctx, &so);
  17786. }
  17787. }
  17788. static void
  17789. master_thread_run(struct mg_context *ctx)
  17790. {
  17791. struct mg_workerTLS tls;
  17792. struct mg_pollfd *pfd;
  17793. unsigned int i;
  17794. unsigned int workerthreadcount;
  17795. if (!ctx) {
  17796. return;
  17797. }
  17798. mg_set_thread_name("master");
  17799. /* Increase priority of the master thread */
  17800. #if defined(_WIN32)
  17801. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17802. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17803. int min_prio = sched_get_priority_min(SCHED_RR);
  17804. int max_prio = sched_get_priority_max(SCHED_RR);
  17805. if ((min_prio >= 0) && (max_prio >= 0)
  17806. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17807. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17808. struct sched_param sched_param = {0};
  17809. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17810. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17811. }
  17812. #endif
  17813. /* Initialize thread local storage */
  17814. #if defined(_WIN32)
  17815. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17816. #endif
  17817. tls.is_master = 1;
  17818. pthread_setspecific(sTlsKey, &tls);
  17819. if (ctx->callbacks.init_thread) {
  17820. /* Callback for the master thread (type 0) */
  17821. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17822. } else {
  17823. tls.user_ptr = NULL;
  17824. }
  17825. /* Lua background script "start" event */
  17826. #if defined(USE_LUA)
  17827. if (ctx->lua_background_state) {
  17828. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17829. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17830. /* call "start()" in Lua */
  17831. lua_getglobal(lstate, "start");
  17832. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17833. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17834. if (ret != 0) {
  17835. struct mg_connection fc;
  17836. lua_cry(fake_connection(&fc, ctx),
  17837. ret,
  17838. lstate,
  17839. "lua_background_script",
  17840. "start");
  17841. }
  17842. } else {
  17843. lua_pop(lstate, 1);
  17844. }
  17845. /* determine if there is a "log()" function in Lua background script */
  17846. lua_getglobal(lstate, "log");
  17847. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17848. ctx->lua_bg_log_available = 1;
  17849. }
  17850. lua_pop(lstate, 1);
  17851. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17852. }
  17853. #endif
  17854. /* Server starts *now* */
  17855. ctx->start_time = time(NULL);
  17856. /* Server accept loop */
  17857. pfd = ctx->listening_socket_fds;
  17858. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17859. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17860. pfd[i].fd = ctx->listening_sockets[i].sock;
  17861. pfd[i].events = POLLIN;
  17862. }
  17863. /* We listen on this socket just so that mg_stop() can cause mg_poll()
  17864. * to return ASAP. Don't worry, we did allocate an extra slot at the end
  17865. * of listening_socket_fds[] just to hold this
  17866. */
  17867. pfd[ctx->num_listening_sockets].fd =
  17868. ctx->thread_shutdown_notification_socket;
  17869. pfd[ctx->num_listening_sockets].events = POLLIN;
  17870. if (mg_poll(pfd,
  17871. ctx->num_listening_sockets
  17872. + 1, // +1 for the thread_shutdown_notification_socket
  17873. SOCKET_TIMEOUT_QUANTUM,
  17874. &(ctx->stop_flag))
  17875. > 0) {
  17876. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17877. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17878. * successful poll, and POLLIN is defined as
  17879. * (POLLRDNORM | POLLRDBAND)
  17880. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17881. * pfd[i].revents == POLLIN. */
  17882. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17883. && (pfd[i].revents & POLLIN)) {
  17884. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17885. }
  17886. }
  17887. }
  17888. }
  17889. /* Here stop_flag is 1 - Initiate shutdown. */
  17890. DEBUG_TRACE("%s", "stopping workers");
  17891. /* Stop signal received: somebody called mg_stop. Quit. */
  17892. close_all_listening_sockets(ctx);
  17893. /* Wakeup workers that are waiting for connections to handle. */
  17894. #if defined(ALTERNATIVE_QUEUE)
  17895. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17896. event_signal(ctx->client_wait_events[i]);
  17897. }
  17898. #else
  17899. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17900. pthread_cond_broadcast(&ctx->sq_full);
  17901. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17902. #endif
  17903. /* Join all worker threads to avoid leaking threads. */
  17904. workerthreadcount = ctx->spawned_worker_threads;
  17905. for (i = 0; i < workerthreadcount; i++) {
  17906. if (ctx->worker_threadids[i] != 0) {
  17907. mg_join_thread(ctx->worker_threadids[i]);
  17908. }
  17909. }
  17910. #if defined(USE_LUA)
  17911. /* Free Lua state of lua background task */
  17912. if (ctx->lua_background_state) {
  17913. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17914. ctx->lua_bg_log_available = 0;
  17915. /* call "stop()" in Lua */
  17916. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17917. lua_getglobal(lstate, "stop");
  17918. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17919. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17920. if (ret != 0) {
  17921. struct mg_connection fc;
  17922. lua_cry(fake_connection(&fc, ctx),
  17923. ret,
  17924. lstate,
  17925. "lua_background_script",
  17926. "stop");
  17927. }
  17928. }
  17929. DEBUG_TRACE("Close Lua background state %p", lstate);
  17930. lua_close(lstate);
  17931. ctx->lua_background_state = 0;
  17932. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17933. }
  17934. #endif
  17935. DEBUG_TRACE("%s", "exiting");
  17936. /* call exit thread callback */
  17937. if (ctx->callbacks.exit_thread) {
  17938. /* Callback for the master thread (type 0) */
  17939. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17940. }
  17941. #if defined(_WIN32)
  17942. CloseHandle(tls.pthread_cond_helper_mutex);
  17943. #endif
  17944. pthread_setspecific(sTlsKey, NULL);
  17945. /* Signal mg_stop() that we're done.
  17946. * WARNING: This must be the very last thing this
  17947. * thread does, as ctx becomes invalid after this line. */
  17948. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17949. }
  17950. /* Threads have different return types on Windows and Unix. */
  17951. #if defined(_WIN32)
  17952. static unsigned __stdcall master_thread(void *thread_func_param)
  17953. {
  17954. master_thread_run((struct mg_context *)thread_func_param);
  17955. return 0;
  17956. }
  17957. #else
  17958. static void *
  17959. master_thread(void *thread_func_param)
  17960. {
  17961. #if !defined(__ZEPHYR__)
  17962. struct sigaction sa;
  17963. /* Ignore SIGPIPE */
  17964. memset(&sa, 0, sizeof(sa));
  17965. sa.sa_handler = SIG_IGN;
  17966. sigaction(SIGPIPE, &sa, NULL);
  17967. #endif
  17968. master_thread_run((struct mg_context *)thread_func_param);
  17969. return NULL;
  17970. }
  17971. #endif /* _WIN32 */
  17972. static void
  17973. free_context(struct mg_context *ctx)
  17974. {
  17975. int i;
  17976. struct mg_handler_info *tmp_rh;
  17977. if (ctx == NULL) {
  17978. return;
  17979. }
  17980. /* Call user callback */
  17981. if (ctx->callbacks.exit_context) {
  17982. ctx->callbacks.exit_context(ctx);
  17983. }
  17984. /* All threads exited, no sync is needed. Destroy thread mutex and
  17985. * condvars
  17986. */
  17987. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17988. #if defined(ALTERNATIVE_QUEUE)
  17989. mg_free(ctx->client_socks);
  17990. if (ctx->client_wait_events != NULL) {
  17991. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  17992. event_destroy(ctx->client_wait_events[i]);
  17993. }
  17994. mg_free(ctx->client_wait_events);
  17995. }
  17996. #else
  17997. (void)pthread_cond_destroy(&ctx->sq_empty);
  17998. (void)pthread_cond_destroy(&ctx->sq_full);
  17999. mg_free(ctx->squeue);
  18000. #endif
  18001. /* Destroy other context global data structures mutex */
  18002. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  18003. #if defined(USE_LUA)
  18004. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  18005. #endif
  18006. /* Deallocate shutdown-triggering socket-pair */
  18007. if (ctx->user_shutdown_notification_socket >= 0) {
  18008. closesocket(ctx->user_shutdown_notification_socket);
  18009. }
  18010. if (ctx->thread_shutdown_notification_socket >= 0) {
  18011. closesocket(ctx->thread_shutdown_notification_socket);
  18012. }
  18013. /* Deallocate config parameters */
  18014. for (i = 0; i < NUM_OPTIONS; i++) {
  18015. if (ctx->dd.config[i] != NULL) {
  18016. #if defined(_MSC_VER)
  18017. #pragma warning(suppress : 6001)
  18018. #endif
  18019. mg_free(ctx->dd.config[i]);
  18020. }
  18021. }
  18022. /* Deallocate request handlers */
  18023. while (ctx->dd.handlers) {
  18024. tmp_rh = ctx->dd.handlers;
  18025. ctx->dd.handlers = tmp_rh->next;
  18026. mg_free(tmp_rh->uri);
  18027. mg_free(tmp_rh);
  18028. }
  18029. #if defined(USE_MBEDTLS)
  18030. if (ctx->dd.ssl_ctx != NULL) {
  18031. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  18032. mg_free(ctx->dd.ssl_ctx);
  18033. ctx->dd.ssl_ctx = NULL;
  18034. }
  18035. #elif defined(USE_GNUTLS)
  18036. if (ctx->dd.ssl_ctx != NULL) {
  18037. gtls_sslctx_uninit(ctx->dd.ssl_ctx);
  18038. mg_free(ctx->dd.ssl_ctx);
  18039. ctx->dd.ssl_ctx = NULL;
  18040. }
  18041. #elif !defined(NO_SSL)
  18042. /* Deallocate SSL context */
  18043. if (ctx->dd.ssl_ctx != NULL) {
  18044. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  18045. int callback_ret =
  18046. (ctx->callbacks.external_ssl_ctx == NULL)
  18047. ? 0
  18048. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  18049. if (callback_ret == 0) {
  18050. SSL_CTX_free(ctx->dd.ssl_ctx);
  18051. }
  18052. /* else: ignore error and omit SSL_CTX_free in case
  18053. * callback_ret is 1 */
  18054. }
  18055. #endif /* !NO_SSL */
  18056. /* Deallocate worker thread ID array */
  18057. mg_free(ctx->worker_threadids);
  18058. /* Deallocate worker thread ID array */
  18059. mg_free(ctx->worker_connections);
  18060. /* deallocate system name string */
  18061. mg_free(ctx->systemName);
  18062. /* Deallocate context itself */
  18063. mg_free(ctx);
  18064. }
  18065. CIVETWEB_API void
  18066. mg_stop(struct mg_context *ctx)
  18067. {
  18068. pthread_t mt;
  18069. if (!ctx) {
  18070. return;
  18071. }
  18072. /* We don't use a lock here. Calling mg_stop with the same ctx from
  18073. * two threads is not allowed. */
  18074. mt = ctx->masterthreadid;
  18075. if (mt == 0) {
  18076. return;
  18077. }
  18078. ctx->masterthreadid = 0;
  18079. /* Set stop flag, so all threads know they have to exit. */
  18080. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  18081. /* Closing this socket will cause mg_poll() in all the I/O threads to return
  18082. * immediately */
  18083. closesocket(ctx->user_shutdown_notification_socket);
  18084. ctx->user_shutdown_notification_socket =
  18085. -1; /* to avoid calling closesocket() again in free_context() */
  18086. /* Join timer thread */
  18087. #if defined(USE_TIMERS)
  18088. timers_exit(ctx);
  18089. #endif
  18090. /* Wait until everything has stopped. */
  18091. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  18092. (void)mg_sleep(10);
  18093. }
  18094. /* Wait to stop master thread */
  18095. mg_join_thread(mt);
  18096. /* Close remaining Lua states */
  18097. #if defined(USE_LUA)
  18098. lua_ctx_exit(ctx);
  18099. #endif
  18100. /* Free memory */
  18101. free_context(ctx);
  18102. }
  18103. static void
  18104. get_system_name(char **sysName)
  18105. {
  18106. #if defined(_WIN32)
  18107. char name[128];
  18108. DWORD dwVersion = 0;
  18109. DWORD dwMajorVersion = 0;
  18110. DWORD dwMinorVersion = 0;
  18111. DWORD dwBuild = 0;
  18112. BOOL wowRet, isWoW = FALSE;
  18113. #if defined(_MSC_VER)
  18114. #pragma warning(push)
  18115. /* GetVersion was declared deprecated */
  18116. #pragma warning(disable : 4996)
  18117. #endif
  18118. dwVersion = GetVersion();
  18119. #if defined(_MSC_VER)
  18120. #pragma warning(pop)
  18121. #endif
  18122. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18123. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18124. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  18125. (void)dwBuild;
  18126. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  18127. sprintf(name,
  18128. "Windows %u.%u%s",
  18129. (unsigned)dwMajorVersion,
  18130. (unsigned)dwMinorVersion,
  18131. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  18132. *sysName = mg_strdup(name);
  18133. #elif defined(__rtems__)
  18134. *sysName = mg_strdup("RTEMS");
  18135. #elif defined(__ZEPHYR__)
  18136. *sysName = mg_strdup("Zephyr OS");
  18137. #else
  18138. struct utsname name;
  18139. memset(&name, 0, sizeof(name));
  18140. uname(&name);
  18141. *sysName = mg_strdup(name.sysname);
  18142. #endif
  18143. }
  18144. static void
  18145. legacy_init(const char **options)
  18146. {
  18147. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  18148. if (options) {
  18149. const char **run_options = options;
  18150. const char *optname = config_options[LISTENING_PORTS].name;
  18151. /* Try to find the "listening_ports" option */
  18152. while (*run_options) {
  18153. if (!strcmp(*run_options, optname)) {
  18154. ports_option = run_options[1];
  18155. }
  18156. run_options += 2;
  18157. }
  18158. }
  18159. if (is_ssl_port_used(ports_option)) {
  18160. /* Initialize with SSL support */
  18161. mg_init_library(MG_FEATURES_TLS);
  18162. } else {
  18163. /* Initialize without SSL support */
  18164. mg_init_library(MG_FEATURES_DEFAULT);
  18165. }
  18166. }
  18167. /* we'll assume it's only Windows that doesn't have socketpair() available */
  18168. #if !defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  18169. #define HAVE_SOCKETPAIR 1
  18170. #endif
  18171. static int
  18172. mg_socketpair(int *sockA, int *sockB)
  18173. {
  18174. int temp[2] = {-1, -1};
  18175. int asock = -1;
  18176. /** Default to unallocated */
  18177. *sockA = -1;
  18178. *sockB = -1;
  18179. #if defined(HAVE_SOCKETPAIR)
  18180. int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, temp);
  18181. if (ret == 0) {
  18182. *sockA = temp[0];
  18183. *sockB = temp[1];
  18184. set_close_on_exec(*sockA, NULL, NULL);
  18185. set_close_on_exec(*sockB, NULL, NULL);
  18186. }
  18187. (void)asock; /* not used */
  18188. return ret;
  18189. #else
  18190. /** No socketpair() call is available, so we'll have to roll our own
  18191. * implementation */
  18192. asock = socket(PF_INET, SOCK_STREAM, 0);
  18193. if (asock >= 0) {
  18194. struct sockaddr_in addr;
  18195. struct sockaddr *pa = (struct sockaddr *)&addr;
  18196. socklen_t addrLen = sizeof(addr);
  18197. memset(&addr, 0, sizeof(addr));
  18198. addr.sin_family = AF_INET;
  18199. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18200. addr.sin_port = 0;
  18201. if ((bind(asock, pa, sizeof(addr)) == 0)
  18202. && (getsockname(asock, pa, &addrLen) == 0)
  18203. && (listen(asock, 1) == 0)) {
  18204. temp[0] = socket(PF_INET, SOCK_STREAM, 0);
  18205. if ((temp[0] >= 0) && (connect(temp[0], pa, sizeof(addr)) == 0)) {
  18206. temp[1] = accept(asock, pa, &addrLen);
  18207. if (temp[1] >= 0) {
  18208. closesocket(asock);
  18209. *sockA = temp[0];
  18210. *sockB = temp[1];
  18211. set_close_on_exec(*sockA, NULL, NULL);
  18212. set_close_on_exec(*sockB, NULL, NULL);
  18213. return 0; /* success! */
  18214. }
  18215. }
  18216. }
  18217. }
  18218. /* Cleanup */
  18219. if (asock >= 0)
  18220. closesocket(asock);
  18221. if (temp[0] >= 0)
  18222. closesocket(temp[0]);
  18223. if (temp[1] >= 0)
  18224. closesocket(temp[1]);
  18225. return -1; /* fail! */
  18226. #endif
  18227. }
  18228. static int
  18229. mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads)
  18230. {
  18231. const unsigned int i = ctx->spawned_worker_threads;
  18232. if (i >= ctx->cfg_max_worker_threads) {
  18233. return -1; /* Oops, we hit our worker-thread limit! No more worker
  18234. threads, ever! */
  18235. }
  18236. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18237. #if defined(ALTERNATIVE_QUEUE)
  18238. if ((only_if_no_idle_threads) && (ctx->idle_worker_thread_count > 0)) {
  18239. #else
  18240. if ((only_if_no_idle_threads)
  18241. && (ctx->idle_worker_thread_count
  18242. > (unsigned)(ctx->sq_head - ctx->sq_tail))) {
  18243. #endif
  18244. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18245. return -2; /* There are idle threads available, so no need to spawn a
  18246. new worker thread now */
  18247. }
  18248. ctx->idle_worker_thread_count++; /* we do this here to avoid a race
  18249. condition while the thread is starting
  18250. up */
  18251. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18252. ctx->worker_connections[i].phys_ctx = ctx;
  18253. int ret = mg_start_thread_with_id(worker_thread,
  18254. &ctx->worker_connections[i],
  18255. &ctx->worker_threadids[i]);
  18256. if (ret == 0) {
  18257. ctx->spawned_worker_threads++; /* note that we've filled another slot in
  18258. the table */
  18259. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  18260. } else {
  18261. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18262. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  18263. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18264. }
  18265. return ret;
  18266. }
  18267. CIVETWEB_API struct mg_context *
  18268. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  18269. {
  18270. struct mg_context *ctx;
  18271. const char *name, *value, *default_value;
  18272. int idx, ok, prespawnthreadcount, workerthreadcount;
  18273. unsigned int i;
  18274. int itmp;
  18275. void (*exit_callback)(const struct mg_context *ctx) = 0;
  18276. const char **options =
  18277. ((init != NULL) ? (init->configuration_options) : (NULL));
  18278. struct mg_workerTLS tls;
  18279. if (error != NULL) {
  18280. error->code = MG_ERROR_DATA_CODE_OK;
  18281. error->code_sub = 0;
  18282. if (error->text_buffer_size > 0) {
  18283. *error->text = 0;
  18284. }
  18285. }
  18286. if (mg_init_library_called == 0) {
  18287. /* Legacy INIT, if mg_start is called without mg_init_library.
  18288. * Note: This will cause a memory leak when unloading the library.
  18289. */
  18290. legacy_init(options);
  18291. }
  18292. if (mg_init_library_called == 0) {
  18293. if (error != NULL) {
  18294. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  18295. mg_snprintf(NULL,
  18296. NULL, /* No truncation check for error buffers */
  18297. error->text,
  18298. error->text_buffer_size,
  18299. "%s",
  18300. "Library uninitialized");
  18301. }
  18302. return NULL;
  18303. }
  18304. /* Allocate context and initialize reasonable general case defaults. */
  18305. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  18306. if (ctx == NULL) {
  18307. if (error != NULL) {
  18308. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18309. error->code_sub = (unsigned)sizeof(*ctx);
  18310. mg_snprintf(NULL,
  18311. NULL, /* No truncation check for error buffers */
  18312. error->text,
  18313. error->text_buffer_size,
  18314. "%s",
  18315. "Out of memory");
  18316. }
  18317. return NULL;
  18318. }
  18319. /* Random number generator will initialize at the first call */
  18320. ctx->dd.auth_nonce_mask =
  18321. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  18322. /* Save started thread index to reuse in other external API calls
  18323. * For the sake of thread synchronization all non-civetweb threads
  18324. * can be considered as single external thread */
  18325. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  18326. tls.is_master = -1; /* Thread calling mg_start */
  18327. tls.thread_idx = ctx->starter_thread_idx;
  18328. #if defined(_WIN32)
  18329. tls.pthread_cond_helper_mutex = NULL;
  18330. #endif
  18331. pthread_setspecific(sTlsKey, &tls);
  18332. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  18333. #if !defined(ALTERNATIVE_QUEUE)
  18334. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  18335. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  18336. ctx->sq_blocked = 0;
  18337. #endif
  18338. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  18339. #if defined(USE_LUA)
  18340. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  18341. #endif
  18342. /** mg_stop() will close the user_shutdown_notification_socket, and that
  18343. * will cause poll() to return immediately in the master-thread, so that
  18344. * mg_stop() can also return immediately.
  18345. */
  18346. ok &= (0
  18347. == mg_socketpair(&ctx->user_shutdown_notification_socket,
  18348. &ctx->thread_shutdown_notification_socket));
  18349. if (!ok) {
  18350. unsigned error_id = (unsigned)ERRNO;
  18351. const char *err_msg =
  18352. "Cannot initialize thread synchronization objects";
  18353. /* Fatal error - abort start. However, this situation should never
  18354. * occur in practice. */
  18355. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18356. if (error != NULL) {
  18357. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18358. error->code_sub = error_id;
  18359. mg_snprintf(NULL,
  18360. NULL, /* No truncation check for error buffers */
  18361. error->text,
  18362. error->text_buffer_size,
  18363. "%s",
  18364. err_msg);
  18365. }
  18366. mg_free(ctx);
  18367. pthread_setspecific(sTlsKey, NULL);
  18368. return NULL;
  18369. }
  18370. if ((init != NULL) && (init->callbacks != NULL)) {
  18371. /* Set all callbacks except exit_context. */
  18372. ctx->callbacks = *init->callbacks;
  18373. exit_callback = init->callbacks->exit_context;
  18374. /* The exit callback is activated once the context is successfully
  18375. * created. It should not be called, if an incomplete context object
  18376. * is deleted during a failed initialization. */
  18377. ctx->callbacks.exit_context = 0;
  18378. }
  18379. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  18380. ctx->dd.handlers = NULL;
  18381. ctx->dd.next = NULL;
  18382. #if defined(USE_LUA)
  18383. lua_ctx_init(ctx);
  18384. #endif
  18385. /* Store options */
  18386. while (options && (name = *options++) != NULL) {
  18387. idx = get_option_index(name);
  18388. if (idx == -1) {
  18389. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18390. if (error != NULL) {
  18391. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18392. error->code_sub = (unsigned)-1;
  18393. mg_snprintf(NULL,
  18394. NULL, /* No truncation check for error buffers */
  18395. error->text,
  18396. error->text_buffer_size,
  18397. "Invalid configuration option: %s",
  18398. name);
  18399. }
  18400. free_context(ctx);
  18401. pthread_setspecific(sTlsKey, NULL);
  18402. return NULL;
  18403. } else if ((value = *options++) == NULL) {
  18404. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18405. if (error != NULL) {
  18406. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18407. error->code_sub = (unsigned)idx;
  18408. mg_snprintf(NULL,
  18409. NULL, /* No truncation check for error buffers */
  18410. error->text,
  18411. error->text_buffer_size,
  18412. "Invalid configuration option value: %s",
  18413. name);
  18414. }
  18415. free_context(ctx);
  18416. pthread_setspecific(sTlsKey, NULL);
  18417. return NULL;
  18418. }
  18419. if (ctx->dd.config[idx] != NULL) {
  18420. /* A duplicate configuration option is not an error - the last
  18421. * option value will be used. */
  18422. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18423. mg_free(ctx->dd.config[idx]);
  18424. }
  18425. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  18426. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18427. }
  18428. /* Set default value if needed */
  18429. for (i = 0; config_options[i].name != NULL; i++) {
  18430. default_value = config_options[i].default_value;
  18431. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  18432. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  18433. }
  18434. }
  18435. /* Request size option */
  18436. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  18437. if (itmp < 1024) {
  18438. mg_cry_ctx_internal(ctx,
  18439. "%s too small",
  18440. config_options[MAX_REQUEST_SIZE].name);
  18441. if (error != NULL) {
  18442. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18443. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  18444. mg_snprintf(NULL,
  18445. NULL, /* No truncation check for error buffers */
  18446. error->text,
  18447. error->text_buffer_size,
  18448. "Invalid configuration option value: %s",
  18449. config_options[MAX_REQUEST_SIZE].name);
  18450. }
  18451. free_context(ctx);
  18452. pthread_setspecific(sTlsKey, NULL);
  18453. return NULL;
  18454. }
  18455. ctx->max_request_size = (unsigned)itmp;
  18456. /* Queue length */
  18457. #if !defined(ALTERNATIVE_QUEUE)
  18458. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  18459. if (itmp < 1) {
  18460. mg_cry_ctx_internal(ctx,
  18461. "%s too small",
  18462. config_options[CONNECTION_QUEUE_SIZE].name);
  18463. if (error != NULL) {
  18464. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18465. error->code_sub = CONNECTION_QUEUE_SIZE;
  18466. mg_snprintf(NULL,
  18467. NULL, /* No truncation check for error buffers */
  18468. error->text,
  18469. error->text_buffer_size,
  18470. "Invalid configuration option value: %s",
  18471. config_options[CONNECTION_QUEUE_SIZE].name);
  18472. }
  18473. free_context(ctx);
  18474. pthread_setspecific(sTlsKey, NULL);
  18475. return NULL;
  18476. }
  18477. ctx->squeue =
  18478. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  18479. if (ctx->squeue == NULL) {
  18480. mg_cry_ctx_internal(ctx,
  18481. "Out of memory: Cannot allocate %s",
  18482. config_options[CONNECTION_QUEUE_SIZE].name);
  18483. if (error != NULL) {
  18484. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18485. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  18486. mg_snprintf(NULL,
  18487. NULL, /* No truncation check for error buffers */
  18488. error->text,
  18489. error->text_buffer_size,
  18490. "Out of memory: Cannot allocate %s",
  18491. config_options[CONNECTION_QUEUE_SIZE].name);
  18492. }
  18493. free_context(ctx);
  18494. pthread_setspecific(sTlsKey, NULL);
  18495. return NULL;
  18496. }
  18497. ctx->sq_size = itmp;
  18498. #endif
  18499. /* Worker thread count option */
  18500. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18501. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18502. if ((prespawnthreadcount < 0)
  18503. || (prespawnthreadcount > workerthreadcount)) {
  18504. prespawnthreadcount =
  18505. workerthreadcount; /* can't prespawn more than all of them! */
  18506. }
  18507. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18508. if (workerthreadcount <= 0) {
  18509. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18510. } else {
  18511. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18512. }
  18513. if (error != NULL) {
  18514. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18515. error->code_sub = NUM_THREADS;
  18516. mg_snprintf(NULL,
  18517. NULL, /* No truncation check for error buffers */
  18518. error->text,
  18519. error->text_buffer_size,
  18520. "Invalid configuration option value: %s",
  18521. config_options[NUM_THREADS].name);
  18522. }
  18523. free_context(ctx);
  18524. pthread_setspecific(sTlsKey, NULL);
  18525. return NULL;
  18526. }
  18527. /* Document root */
  18528. #if defined(NO_FILES)
  18529. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18530. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18531. if (error != NULL) {
  18532. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18533. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18534. mg_snprintf(NULL,
  18535. NULL, /* No truncation check for error buffers */
  18536. error->text,
  18537. error->text_buffer_size,
  18538. "Invalid configuration option value: %s",
  18539. config_options[DOCUMENT_ROOT].name);
  18540. }
  18541. free_context(ctx);
  18542. pthread_setspecific(sTlsKey, NULL);
  18543. return NULL;
  18544. }
  18545. #endif
  18546. get_system_name(&ctx->systemName);
  18547. #if defined(USE_LUA)
  18548. /* If a Lua background script has been configured, start it. */
  18549. ctx->lua_bg_log_available = 0;
  18550. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18551. char ebuf[256];
  18552. struct vec opt_vec;
  18553. struct vec eq_vec;
  18554. const char *sparams;
  18555. memset(ebuf, 0, sizeof(ebuf));
  18556. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18557. /* Create a Lua state, load all standard libraries and the mg table */
  18558. lua_State *state = mg_lua_context_script_prepare(
  18559. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18560. if (!state) {
  18561. mg_cry_ctx_internal(ctx,
  18562. "lua_background_script load error: %s",
  18563. ebuf);
  18564. if (error != NULL) {
  18565. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18566. mg_snprintf(NULL,
  18567. NULL, /* No truncation check for error buffers */
  18568. error->text,
  18569. error->text_buffer_size,
  18570. "Error in script %s: %s",
  18571. config_options[LUA_BACKGROUND_SCRIPT].name,
  18572. ebuf);
  18573. }
  18574. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18575. free_context(ctx);
  18576. pthread_setspecific(sTlsKey, NULL);
  18577. return NULL;
  18578. }
  18579. /* Add a table with parameters into mg.params */
  18580. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18581. if (sparams && sparams[0]) {
  18582. lua_getglobal(state, "mg");
  18583. lua_pushstring(state, "params");
  18584. lua_newtable(state);
  18585. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18586. != NULL) {
  18587. reg_llstring(
  18588. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18589. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18590. break;
  18591. }
  18592. lua_rawset(state, -3);
  18593. lua_pop(state, 1);
  18594. }
  18595. /* Call script */
  18596. state = mg_lua_context_script_run(state,
  18597. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18598. ctx,
  18599. ebuf,
  18600. sizeof(ebuf));
  18601. if (!state) {
  18602. mg_cry_ctx_internal(ctx,
  18603. "lua_background_script start error: %s",
  18604. ebuf);
  18605. if (error != NULL) {
  18606. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18607. mg_snprintf(NULL,
  18608. NULL, /* No truncation check for error buffers */
  18609. error->text,
  18610. error->text_buffer_size,
  18611. "Error in script %s: %s",
  18612. config_options[DOCUMENT_ROOT].name,
  18613. ebuf);
  18614. }
  18615. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18616. free_context(ctx);
  18617. pthread_setspecific(sTlsKey, NULL);
  18618. return NULL;
  18619. }
  18620. /* state remains valid */
  18621. ctx->lua_background_state = (void *)state;
  18622. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18623. } else {
  18624. ctx->lua_background_state = 0;
  18625. }
  18626. #endif
  18627. /* Step by step initialization of ctx - depending on build options */
  18628. #if !defined(NO_FILESYSTEMS)
  18629. if (!set_gpass_option(ctx, NULL)) {
  18630. const char *err_msg = "Invalid global password file";
  18631. /* Fatal error - abort start. */
  18632. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18633. if (error != NULL) {
  18634. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18635. mg_snprintf(NULL,
  18636. NULL, /* No truncation check for error buffers */
  18637. error->text,
  18638. error->text_buffer_size,
  18639. "%s",
  18640. err_msg);
  18641. }
  18642. free_context(ctx);
  18643. pthread_setspecific(sTlsKey, NULL);
  18644. return NULL;
  18645. }
  18646. #endif
  18647. #if defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  18648. if (!mg_sslctx_init(ctx, NULL)) {
  18649. const char *err_msg = "Error initializing SSL context";
  18650. /* Fatal error - abort start. */
  18651. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18652. if (error != NULL) {
  18653. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18654. mg_snprintf(NULL,
  18655. NULL, /* No truncation check for error buffers */
  18656. error->text,
  18657. error->text_buffer_size,
  18658. "%s",
  18659. err_msg);
  18660. }
  18661. free_context(ctx);
  18662. pthread_setspecific(sTlsKey, NULL);
  18663. return NULL;
  18664. }
  18665. #elif !defined(NO_SSL)
  18666. if (!init_ssl_ctx(ctx, NULL)) {
  18667. const char *err_msg = "Error initializing SSL context";
  18668. /* Fatal error - abort start. */
  18669. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18670. if (error != NULL) {
  18671. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18672. mg_snprintf(NULL,
  18673. NULL, /* No truncation check for error buffers */
  18674. error->text,
  18675. error->text_buffer_size,
  18676. "%s",
  18677. err_msg);
  18678. }
  18679. free_context(ctx);
  18680. pthread_setspecific(sTlsKey, NULL);
  18681. return NULL;
  18682. }
  18683. #endif
  18684. if (!set_ports_option(ctx)) {
  18685. const char *err_msg = "Failed to setup server ports";
  18686. /* Fatal error - abort start. */
  18687. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18688. if (error != NULL) {
  18689. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18690. mg_snprintf(NULL,
  18691. NULL, /* No truncation check for error buffers */
  18692. error->text,
  18693. error->text_buffer_size,
  18694. "%s",
  18695. err_msg);
  18696. }
  18697. free_context(ctx);
  18698. pthread_setspecific(sTlsKey, NULL);
  18699. return NULL;
  18700. }
  18701. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18702. if (!set_uid_option(ctx)) {
  18703. const char *err_msg = "Failed to run as configured user";
  18704. /* Fatal error - abort start. */
  18705. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18706. if (error != NULL) {
  18707. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18708. mg_snprintf(NULL,
  18709. NULL, /* No truncation check for error buffers */
  18710. error->text,
  18711. error->text_buffer_size,
  18712. "%s",
  18713. err_msg);
  18714. }
  18715. free_context(ctx);
  18716. pthread_setspecific(sTlsKey, NULL);
  18717. return NULL;
  18718. }
  18719. #endif
  18720. if (!set_acl_option(ctx)) {
  18721. const char *err_msg = "Failed to setup access control list";
  18722. /* Fatal error - abort start. */
  18723. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18724. if (error != NULL) {
  18725. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18726. mg_snprintf(NULL,
  18727. NULL, /* No truncation check for error buffers */
  18728. error->text,
  18729. error->text_buffer_size,
  18730. "%s",
  18731. err_msg);
  18732. }
  18733. free_context(ctx);
  18734. pthread_setspecific(sTlsKey, NULL);
  18735. return NULL;
  18736. }
  18737. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18738. ctx->worker_threadids =
  18739. (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18740. sizeof(pthread_t),
  18741. ctx);
  18742. if (ctx->worker_threadids == NULL) {
  18743. const char *err_msg = "Not enough memory for worker thread ID array";
  18744. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18745. if (error != NULL) {
  18746. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18747. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18748. * (unsigned)sizeof(pthread_t);
  18749. mg_snprintf(NULL,
  18750. NULL, /* No truncation check for error buffers */
  18751. error->text,
  18752. error->text_buffer_size,
  18753. "%s",
  18754. err_msg);
  18755. }
  18756. free_context(ctx);
  18757. pthread_setspecific(sTlsKey, NULL);
  18758. return NULL;
  18759. }
  18760. ctx->worker_connections =
  18761. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18762. sizeof(struct mg_connection),
  18763. ctx);
  18764. if (ctx->worker_connections == NULL) {
  18765. const char *err_msg =
  18766. "Not enough memory for worker thread connection array";
  18767. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18768. if (error != NULL) {
  18769. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18770. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18771. * (unsigned)sizeof(struct mg_connection);
  18772. mg_snprintf(NULL,
  18773. NULL, /* No truncation check for error buffers */
  18774. error->text,
  18775. error->text_buffer_size,
  18776. "%s",
  18777. err_msg);
  18778. }
  18779. free_context(ctx);
  18780. pthread_setspecific(sTlsKey, NULL);
  18781. return NULL;
  18782. }
  18783. #if defined(ALTERNATIVE_QUEUE)
  18784. ctx->client_wait_events =
  18785. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18786. sizeof(ctx->client_wait_events[0]),
  18787. ctx);
  18788. if (ctx->client_wait_events == NULL) {
  18789. const char *err_msg = "Not enough memory for worker event array";
  18790. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18791. mg_free(ctx->worker_threadids);
  18792. if (error != NULL) {
  18793. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18794. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18795. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18796. mg_snprintf(NULL,
  18797. NULL, /* No truncation check for error buffers */
  18798. error->text,
  18799. error->text_buffer_size,
  18800. "%s",
  18801. err_msg);
  18802. }
  18803. free_context(ctx);
  18804. pthread_setspecific(sTlsKey, NULL);
  18805. return NULL;
  18806. }
  18807. ctx->client_socks =
  18808. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18809. sizeof(ctx->client_socks[0]),
  18810. ctx);
  18811. if (ctx->client_socks == NULL) {
  18812. const char *err_msg = "Not enough memory for worker socket array";
  18813. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18814. mg_free(ctx->client_wait_events);
  18815. mg_free(ctx->worker_threadids);
  18816. if (error != NULL) {
  18817. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18818. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18819. * (unsigned)sizeof(ctx->client_socks[0]);
  18820. mg_snprintf(NULL,
  18821. NULL, /* No truncation check for error buffers */
  18822. error->text,
  18823. error->text_buffer_size,
  18824. "%s",
  18825. err_msg);
  18826. }
  18827. free_context(ctx);
  18828. pthread_setspecific(sTlsKey, NULL);
  18829. return NULL;
  18830. }
  18831. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18832. ctx->client_wait_events[i] = event_create();
  18833. if (ctx->client_wait_events[i] == 0) {
  18834. const char *err_msg = "Error creating worker event %i";
  18835. mg_cry_ctx_internal(ctx, err_msg, i);
  18836. while (i > 0) {
  18837. i--;
  18838. event_destroy(ctx->client_wait_events[i]);
  18839. }
  18840. mg_free(ctx->client_socks);
  18841. mg_free(ctx->client_wait_events);
  18842. mg_free(ctx->worker_threadids);
  18843. if (error != NULL) {
  18844. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18845. error->code_sub = (unsigned)ERRNO;
  18846. mg_snprintf(NULL,
  18847. NULL, /* No truncation check for error buffers */
  18848. error->text,
  18849. error->text_buffer_size,
  18850. err_msg,
  18851. i);
  18852. }
  18853. free_context(ctx);
  18854. pthread_setspecific(sTlsKey, NULL);
  18855. return NULL;
  18856. }
  18857. }
  18858. #endif
  18859. #if defined(USE_TIMERS)
  18860. if (timers_init(ctx) != 0) {
  18861. const char *err_msg = "Error creating timers";
  18862. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18863. if (error != NULL) {
  18864. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18865. error->code_sub = (unsigned)ERRNO;
  18866. mg_snprintf(NULL,
  18867. NULL, /* No truncation check for error buffers */
  18868. error->text,
  18869. error->text_buffer_size,
  18870. "%s",
  18871. err_msg);
  18872. }
  18873. free_context(ctx);
  18874. pthread_setspecific(sTlsKey, NULL);
  18875. return NULL;
  18876. }
  18877. #endif
  18878. /* Context has been created - init user libraries */
  18879. if (ctx->callbacks.init_context) {
  18880. ctx->callbacks.init_context(ctx);
  18881. }
  18882. /* From now, the context is successfully created.
  18883. * When it is destroyed, the exit callback should be called. */
  18884. ctx->callbacks.exit_context = exit_callback;
  18885. ctx->context_type = CONTEXT_SERVER; /* server context */
  18886. /* Start worker threads */
  18887. for (i = 0; (int)i < prespawnthreadcount; i++) {
  18888. /* worker_thread sets up the other fields */
  18889. if (mg_start_worker_thread(ctx, 0) != 0) {
  18890. long error_no = (long)ERRNO;
  18891. /* thread was not created */
  18892. if (ctx->spawned_worker_threads > 0) {
  18893. /* If the second, third, ... thread cannot be created, set a
  18894. * warning, but keep running. */
  18895. mg_cry_ctx_internal(ctx,
  18896. "Cannot start worker thread %i: error %ld",
  18897. ctx->spawned_worker_threads + 1,
  18898. error_no);
  18899. /* If the server initialization should stop here, all
  18900. * threads that have already been created must be stopped
  18901. * first, before any free_context(ctx) call.
  18902. */
  18903. } else {
  18904. /* If the first worker thread cannot be created, stop
  18905. * initialization and free the entire server context. */
  18906. mg_cry_ctx_internal(ctx,
  18907. "Cannot create threads: error %ld",
  18908. error_no);
  18909. if (error != NULL) {
  18910. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18911. error->code_sub = (unsigned)error_no;
  18912. mg_snprintf(
  18913. NULL,
  18914. NULL, /* No truncation check for error buffers */
  18915. error->text,
  18916. error->text_buffer_size,
  18917. "Cannot create first worker thread: error %ld",
  18918. error_no);
  18919. }
  18920. free_context(ctx);
  18921. pthread_setspecific(sTlsKey, NULL);
  18922. return NULL;
  18923. }
  18924. break;
  18925. }
  18926. }
  18927. /* Start master (listening) thread */
  18928. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18929. pthread_setspecific(sTlsKey, NULL);
  18930. return ctx;
  18931. }
  18932. CIVETWEB_API struct mg_context *
  18933. mg_start(const struct mg_callbacks *callbacks,
  18934. void *user_data,
  18935. const char **options)
  18936. {
  18937. struct mg_init_data init = {0};
  18938. init.callbacks = callbacks;
  18939. init.user_data = user_data;
  18940. init.configuration_options = options;
  18941. return mg_start2(&init, NULL);
  18942. }
  18943. /* Add an additional domain to an already running web server. */
  18944. CIVETWEB_API int
  18945. mg_start_domain2(struct mg_context *ctx,
  18946. const char **options,
  18947. struct mg_error_data *error)
  18948. {
  18949. const char *name;
  18950. const char *value;
  18951. const char *default_value;
  18952. struct mg_domain_context *new_dom;
  18953. struct mg_domain_context *dom;
  18954. int idx, i;
  18955. if (error != NULL) {
  18956. error->code = MG_ERROR_DATA_CODE_OK;
  18957. error->code_sub = 0;
  18958. if (error->text_buffer_size > 0) {
  18959. *error->text = 0;
  18960. }
  18961. }
  18962. if ((ctx == NULL) || (options == NULL)) {
  18963. if (error != NULL) {
  18964. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18965. mg_snprintf(NULL,
  18966. NULL, /* No truncation check for error buffers */
  18967. error->text,
  18968. error->text_buffer_size,
  18969. "%s",
  18970. "Invalid parameters");
  18971. }
  18972. return -1;
  18973. }
  18974. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18975. if (error != NULL) {
  18976. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18977. mg_snprintf(NULL,
  18978. NULL, /* No truncation check for error buffers */
  18979. error->text,
  18980. error->text_buffer_size,
  18981. "%s",
  18982. "Server already stopped");
  18983. }
  18984. return -7;
  18985. }
  18986. new_dom = (struct mg_domain_context *)
  18987. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18988. if (!new_dom) {
  18989. /* Out of memory */
  18990. if (error != NULL) {
  18991. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18992. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18993. mg_snprintf(NULL,
  18994. NULL, /* No truncation check for error buffers */
  18995. error->text,
  18996. error->text_buffer_size,
  18997. "%s",
  18998. "Out or memory");
  18999. }
  19000. return -6;
  19001. }
  19002. /* Store options - TODO: unite duplicate code */
  19003. while (options && (name = *options++) != NULL) {
  19004. idx = get_option_index(name);
  19005. if (idx == -1) {
  19006. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  19007. if (error != NULL) {
  19008. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19009. error->code_sub = (unsigned)-1;
  19010. mg_snprintf(NULL,
  19011. NULL, /* No truncation check for error buffers */
  19012. error->text,
  19013. error->text_buffer_size,
  19014. "Invalid option: %s",
  19015. name);
  19016. }
  19017. mg_free(new_dom);
  19018. return -2;
  19019. } else if ((value = *options++) == NULL) {
  19020. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  19021. if (error != NULL) {
  19022. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19023. error->code_sub = (unsigned)idx;
  19024. mg_snprintf(NULL,
  19025. NULL, /* No truncation check for error buffers */
  19026. error->text,
  19027. error->text_buffer_size,
  19028. "Invalid option value: %s",
  19029. name);
  19030. }
  19031. mg_free(new_dom);
  19032. return -2;
  19033. }
  19034. if (new_dom->config[idx] != NULL) {
  19035. /* Duplicate option: Later values overwrite earlier ones. */
  19036. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  19037. mg_free(new_dom->config[idx]);
  19038. }
  19039. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  19040. DEBUG_TRACE("[%s] -> [%s]", name, value);
  19041. }
  19042. /* Authentication domain is mandatory */
  19043. /* TODO: Maybe use a new option hostname? */
  19044. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  19045. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  19046. if (error != NULL) {
  19047. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  19048. error->code_sub = AUTHENTICATION_DOMAIN;
  19049. mg_snprintf(NULL,
  19050. NULL, /* No truncation check for error buffers */
  19051. error->text,
  19052. error->text_buffer_size,
  19053. "Mandatory option %s missing",
  19054. config_options[AUTHENTICATION_DOMAIN].name);
  19055. }
  19056. mg_free(new_dom);
  19057. return -4;
  19058. }
  19059. /* Set default value if needed. Take the config value from
  19060. * ctx as a default value. */
  19061. for (i = 0; config_options[i].name != NULL; i++) {
  19062. default_value = ctx->dd.config[i];
  19063. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  19064. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  19065. }
  19066. }
  19067. new_dom->handlers = NULL;
  19068. new_dom->next = NULL;
  19069. new_dom->nonce_count = 0;
  19070. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  19071. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  19072. new_dom->shared_lua_websockets = NULL;
  19073. #endif
  19074. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  19075. if (!init_ssl_ctx(ctx, new_dom)) {
  19076. /* Init SSL failed */
  19077. if (error != NULL) {
  19078. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  19079. mg_snprintf(NULL,
  19080. NULL, /* No truncation check for error buffers */
  19081. error->text,
  19082. error->text_buffer_size,
  19083. "%s",
  19084. "Initializing SSL context failed");
  19085. }
  19086. mg_free(new_dom);
  19087. return -3;
  19088. }
  19089. #endif
  19090. /* Add element to linked list. */
  19091. mg_lock_context(ctx);
  19092. idx = 0;
  19093. dom = &(ctx->dd);
  19094. for (;;) {
  19095. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  19096. dom->config[AUTHENTICATION_DOMAIN])) {
  19097. /* Domain collision */
  19098. mg_cry_ctx_internal(ctx,
  19099. "domain %s already in use",
  19100. new_dom->config[AUTHENTICATION_DOMAIN]);
  19101. if (error != NULL) {
  19102. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  19103. mg_snprintf(NULL,
  19104. NULL, /* No truncation check for error buffers */
  19105. error->text,
  19106. error->text_buffer_size,
  19107. "Domain %s specified by %s is already in use",
  19108. new_dom->config[AUTHENTICATION_DOMAIN],
  19109. config_options[AUTHENTICATION_DOMAIN].name);
  19110. }
  19111. mg_free(new_dom);
  19112. mg_unlock_context(ctx);
  19113. return -5;
  19114. }
  19115. /* Count number of domains */
  19116. idx++;
  19117. if (dom->next == NULL) {
  19118. dom->next = new_dom;
  19119. break;
  19120. }
  19121. dom = dom->next;
  19122. }
  19123. mg_unlock_context(ctx);
  19124. /* Return domain number */
  19125. return idx;
  19126. }
  19127. CIVETWEB_API int
  19128. mg_start_domain(struct mg_context *ctx, const char **options)
  19129. {
  19130. return mg_start_domain2(ctx, options, NULL);
  19131. }
  19132. /* Feature check API function */
  19133. CIVETWEB_API unsigned
  19134. mg_check_feature(unsigned feature)
  19135. {
  19136. static const unsigned feature_set = 0
  19137. /* Set bits for available features according to API documentation.
  19138. * This bit mask is created at compile time, according to the active
  19139. * preprocessor defines. It is a single const value at runtime. */
  19140. #if !defined(NO_FILES)
  19141. | MG_FEATURES_FILES
  19142. #endif
  19143. #if !defined(NO_SSL) || defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  19144. | MG_FEATURES_SSL
  19145. #endif
  19146. #if !defined(NO_CGI)
  19147. | MG_FEATURES_CGI
  19148. #endif
  19149. #if defined(USE_IPV6)
  19150. | MG_FEATURES_IPV6
  19151. #endif
  19152. #if defined(USE_WEBSOCKET)
  19153. | MG_FEATURES_WEBSOCKET
  19154. #endif
  19155. #if defined(USE_LUA)
  19156. | MG_FEATURES_LUA
  19157. #endif
  19158. #if defined(USE_DUKTAPE)
  19159. | MG_FEATURES_SSJS
  19160. #endif
  19161. #if !defined(NO_CACHING)
  19162. | MG_FEATURES_CACHE
  19163. #endif
  19164. #if defined(USE_SERVER_STATS)
  19165. | MG_FEATURES_STATS
  19166. #endif
  19167. #if defined(USE_ZLIB)
  19168. | MG_FEATURES_COMPRESSION
  19169. #endif
  19170. #if defined(USE_HTTP2)
  19171. | MG_FEATURES_HTTP2
  19172. #endif
  19173. #if defined(USE_X_DOM_SOCKET)
  19174. | MG_FEATURES_X_DOMAIN_SOCKET
  19175. #endif
  19176. /* Set some extra bits not defined in the API documentation.
  19177. * These bits may change without further notice. */
  19178. #if defined(MG_LEGACY_INTERFACE)
  19179. | 0x80000000u
  19180. #endif
  19181. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19182. | 0x40000000u
  19183. #endif
  19184. #if !defined(NO_RESPONSE_BUFFERING)
  19185. | 0x20000000u
  19186. #endif
  19187. #if defined(MEMORY_DEBUGGING)
  19188. | 0x10000000u
  19189. #endif
  19190. ;
  19191. return (feature & feature_set);
  19192. }
  19193. static size_t
  19194. mg_str_append(char **dst, char *end, const char *src)
  19195. {
  19196. size_t len = strlen(src);
  19197. if (*dst != end) {
  19198. /* Append src if enough space, or close dst. */
  19199. if ((size_t)(end - *dst) > len) {
  19200. strcpy(*dst, src);
  19201. *dst += len;
  19202. } else {
  19203. *dst = end;
  19204. }
  19205. }
  19206. return len;
  19207. }
  19208. /* Get system information. It can be printed or stored by the caller.
  19209. * Return the size of available information. */
  19210. CIVETWEB_API int
  19211. mg_get_system_info(char *buffer, int buflen)
  19212. {
  19213. char *end, *append_eoobj = NULL, block[256];
  19214. size_t system_info_length = 0;
  19215. #if defined(_WIN32)
  19216. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19217. #else
  19218. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19219. #endif
  19220. if ((buffer == NULL) || (buflen < 1)) {
  19221. buflen = 0;
  19222. end = buffer;
  19223. } else {
  19224. *buffer = 0;
  19225. end = buffer + buflen;
  19226. }
  19227. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19228. /* has enough space to append eoobj */
  19229. append_eoobj = buffer;
  19230. if (end) {
  19231. end -= sizeof(eoobj) - 1;
  19232. }
  19233. }
  19234. system_info_length += mg_str_append(&buffer, end, "{");
  19235. /* Server version */
  19236. {
  19237. const char *version = mg_version();
  19238. mg_snprintf(NULL,
  19239. NULL,
  19240. block,
  19241. sizeof(block),
  19242. "%s\"version\" : \"%s\"",
  19243. eol,
  19244. version);
  19245. system_info_length += mg_str_append(&buffer, end, block);
  19246. }
  19247. /* System info */
  19248. {
  19249. #if defined(_WIN32)
  19250. DWORD dwVersion = 0;
  19251. DWORD dwMajorVersion = 0;
  19252. DWORD dwMinorVersion = 0;
  19253. SYSTEM_INFO si;
  19254. GetSystemInfo(&si);
  19255. #if defined(_MSC_VER)
  19256. #pragma warning(push)
  19257. /* GetVersion was declared deprecated */
  19258. #pragma warning(disable : 4996)
  19259. #endif
  19260. dwVersion = GetVersion();
  19261. #if defined(_MSC_VER)
  19262. #pragma warning(pop)
  19263. #endif
  19264. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  19265. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  19266. mg_snprintf(NULL,
  19267. NULL,
  19268. block,
  19269. sizeof(block),
  19270. ",%s\"os\" : \"Windows %u.%u\"",
  19271. eol,
  19272. (unsigned)dwMajorVersion,
  19273. (unsigned)dwMinorVersion);
  19274. system_info_length += mg_str_append(&buffer, end, block);
  19275. mg_snprintf(NULL,
  19276. NULL,
  19277. block,
  19278. sizeof(block),
  19279. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  19280. eol,
  19281. (unsigned)si.wProcessorArchitecture,
  19282. (unsigned)si.dwNumberOfProcessors,
  19283. (unsigned)si.dwActiveProcessorMask);
  19284. system_info_length += mg_str_append(&buffer, end, block);
  19285. #elif defined(__rtems__)
  19286. mg_snprintf(NULL,
  19287. NULL,
  19288. block,
  19289. sizeof(block),
  19290. ",%s\"os\" : \"%s %s\"",
  19291. eol,
  19292. "RTEMS",
  19293. rtems_version());
  19294. system_info_length += mg_str_append(&buffer, end, block);
  19295. #elif defined(__ZEPHYR__)
  19296. mg_snprintf(NULL,
  19297. NULL,
  19298. block,
  19299. sizeof(block),
  19300. ",%s\"os\" : \"%s\"",
  19301. eol,
  19302. "Zephyr OS",
  19303. ZEPHYR_VERSION);
  19304. system_info_length += mg_str_append(&buffer, end, block);
  19305. #else
  19306. struct utsname name;
  19307. memset(&name, 0, sizeof(name));
  19308. uname(&name);
  19309. mg_snprintf(NULL,
  19310. NULL,
  19311. block,
  19312. sizeof(block),
  19313. ",%s\"os\" : \"%s %s (%s) - %s\"",
  19314. eol,
  19315. name.sysname,
  19316. name.version,
  19317. name.release,
  19318. name.machine);
  19319. system_info_length += mg_str_append(&buffer, end, block);
  19320. #endif
  19321. }
  19322. /* Features */
  19323. {
  19324. mg_snprintf(NULL,
  19325. NULL,
  19326. block,
  19327. sizeof(block),
  19328. ",%s\"features\" : %lu"
  19329. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  19330. eol,
  19331. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  19332. eol,
  19333. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  19334. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  19335. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  19336. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  19337. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  19338. : "",
  19339. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  19340. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  19341. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  19342. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  19343. system_info_length += mg_str_append(&buffer, end, block);
  19344. #if defined(USE_LUA)
  19345. mg_snprintf(NULL,
  19346. NULL,
  19347. block,
  19348. sizeof(block),
  19349. ",%s\"lua_version\" : \"%u (%s)\"",
  19350. eol,
  19351. (unsigned)LUA_VERSION_NUM,
  19352. LUA_RELEASE);
  19353. system_info_length += mg_str_append(&buffer, end, block);
  19354. #endif
  19355. #if defined(USE_DUKTAPE)
  19356. mg_snprintf(NULL,
  19357. NULL,
  19358. block,
  19359. sizeof(block),
  19360. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  19361. eol,
  19362. (unsigned)DUK_VERSION / 10000,
  19363. ((unsigned)DUK_VERSION / 100) % 100,
  19364. (unsigned)DUK_VERSION % 100);
  19365. system_info_length += mg_str_append(&buffer, end, block);
  19366. #endif
  19367. }
  19368. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  19369. {
  19370. #if defined(BUILD_DATE)
  19371. const char *bd = BUILD_DATE;
  19372. #else
  19373. #if defined(GCC_DIAGNOSTIC)
  19374. #if GCC_VERSION >= 40900
  19375. #pragma GCC diagnostic push
  19376. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  19377. * does not work in some versions. If "BUILD_DATE" is defined to some
  19378. * string, it is used instead of __DATE__. */
  19379. #pragma GCC diagnostic ignored "-Wdate-time"
  19380. #endif
  19381. #endif
  19382. const char *bd = __DATE__;
  19383. #if defined(GCC_DIAGNOSTIC)
  19384. #if GCC_VERSION >= 40900
  19385. #pragma GCC diagnostic pop
  19386. #endif
  19387. #endif
  19388. #endif
  19389. mg_snprintf(
  19390. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  19391. system_info_length += mg_str_append(&buffer, end, block);
  19392. }
  19393. /* Compiler information */
  19394. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  19395. {
  19396. #if defined(_MSC_VER)
  19397. mg_snprintf(NULL,
  19398. NULL,
  19399. block,
  19400. sizeof(block),
  19401. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  19402. eol,
  19403. (unsigned)_MSC_VER,
  19404. (unsigned)_MSC_FULL_VER);
  19405. system_info_length += mg_str_append(&buffer, end, block);
  19406. #elif defined(__MINGW64__)
  19407. mg_snprintf(NULL,
  19408. NULL,
  19409. block,
  19410. sizeof(block),
  19411. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  19412. eol,
  19413. (unsigned)__MINGW64_VERSION_MAJOR,
  19414. (unsigned)__MINGW64_VERSION_MINOR);
  19415. system_info_length += mg_str_append(&buffer, end, block);
  19416. mg_snprintf(NULL,
  19417. NULL,
  19418. block,
  19419. sizeof(block),
  19420. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19421. eol,
  19422. (unsigned)__MINGW32_MAJOR_VERSION,
  19423. (unsigned)__MINGW32_MINOR_VERSION);
  19424. system_info_length += mg_str_append(&buffer, end, block);
  19425. #elif defined(__MINGW32__)
  19426. mg_snprintf(NULL,
  19427. NULL,
  19428. block,
  19429. sizeof(block),
  19430. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19431. eol,
  19432. (unsigned)__MINGW32_MAJOR_VERSION,
  19433. (unsigned)__MINGW32_MINOR_VERSION);
  19434. system_info_length += mg_str_append(&buffer, end, block);
  19435. #elif defined(__clang__)
  19436. mg_snprintf(NULL,
  19437. NULL,
  19438. block,
  19439. sizeof(block),
  19440. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  19441. eol,
  19442. __clang_major__,
  19443. __clang_minor__,
  19444. __clang_patchlevel__,
  19445. __clang_version__);
  19446. system_info_length += mg_str_append(&buffer, end, block);
  19447. #elif defined(__GNUC__)
  19448. mg_snprintf(NULL,
  19449. NULL,
  19450. block,
  19451. sizeof(block),
  19452. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  19453. eol,
  19454. (unsigned)__GNUC__,
  19455. (unsigned)__GNUC_MINOR__,
  19456. (unsigned)__GNUC_PATCHLEVEL__);
  19457. system_info_length += mg_str_append(&buffer, end, block);
  19458. #elif defined(__INTEL_COMPILER)
  19459. mg_snprintf(NULL,
  19460. NULL,
  19461. block,
  19462. sizeof(block),
  19463. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  19464. eol,
  19465. (unsigned)__INTEL_COMPILER);
  19466. system_info_length += mg_str_append(&buffer, end, block);
  19467. #elif defined(__BORLANDC__)
  19468. mg_snprintf(NULL,
  19469. NULL,
  19470. block,
  19471. sizeof(block),
  19472. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  19473. eol,
  19474. (unsigned)__BORLANDC__);
  19475. system_info_length += mg_str_append(&buffer, end, block);
  19476. #elif defined(__SUNPRO_C)
  19477. mg_snprintf(NULL,
  19478. NULL,
  19479. block,
  19480. sizeof(block),
  19481. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  19482. eol,
  19483. (unsigned)__SUNPRO_C);
  19484. system_info_length += mg_str_append(&buffer, end, block);
  19485. #else
  19486. mg_snprintf(NULL,
  19487. NULL,
  19488. block,
  19489. sizeof(block),
  19490. ",%s\"compiler\" : \"other\"",
  19491. eol);
  19492. system_info_length += mg_str_append(&buffer, end, block);
  19493. #endif
  19494. }
  19495. /* Determine 32/64 bit data mode.
  19496. * see https://en.wikipedia.org/wiki/64-bit_computing */
  19497. {
  19498. mg_snprintf(NULL,
  19499. NULL,
  19500. block,
  19501. sizeof(block),
  19502. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  19503. "char:%u/%u, "
  19504. "ptr:%u, size:%u, time:%u\"",
  19505. eol,
  19506. (unsigned)sizeof(short),
  19507. (unsigned)sizeof(int),
  19508. (unsigned)sizeof(long),
  19509. (unsigned)sizeof(long long),
  19510. (unsigned)sizeof(float),
  19511. (unsigned)sizeof(double),
  19512. (unsigned)sizeof(long double),
  19513. (unsigned)sizeof(char),
  19514. (unsigned)sizeof(wchar_t),
  19515. (unsigned)sizeof(void *),
  19516. (unsigned)sizeof(size_t),
  19517. (unsigned)sizeof(time_t));
  19518. system_info_length += mg_str_append(&buffer, end, block);
  19519. }
  19520. /* Terminate string */
  19521. if (append_eoobj) {
  19522. strcat(append_eoobj, eoobj);
  19523. }
  19524. system_info_length += sizeof(eoobj) - 1;
  19525. return (int)system_info_length;
  19526. }
  19527. /* Get context information. It can be printed or stored by the caller.
  19528. * Return the size of available information. */
  19529. CIVETWEB_API int
  19530. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19531. {
  19532. #if defined(USE_SERVER_STATS)
  19533. char *end, *append_eoobj = NULL, block[256];
  19534. size_t context_info_length = 0;
  19535. #if defined(_WIN32)
  19536. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19537. #else
  19538. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19539. #endif
  19540. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19541. if ((buffer == NULL) || (buflen < 1)) {
  19542. buflen = 0;
  19543. end = buffer;
  19544. } else {
  19545. *buffer = 0;
  19546. end = buffer + buflen;
  19547. }
  19548. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19549. /* has enough space to append eoobj */
  19550. append_eoobj = buffer;
  19551. end -= sizeof(eoobj) - 1;
  19552. }
  19553. context_info_length += mg_str_append(&buffer, end, "{");
  19554. if (ms) { /* <-- should be always true */
  19555. /* Memory information */
  19556. int blockCount = (int)ms->blockCount;
  19557. int64_t totalMemUsed = ms->totalMemUsed;
  19558. int64_t maxMemUsed = ms->maxMemUsed;
  19559. if (totalMemUsed > maxMemUsed) {
  19560. maxMemUsed = totalMemUsed;
  19561. }
  19562. mg_snprintf(NULL,
  19563. NULL,
  19564. block,
  19565. sizeof(block),
  19566. "%s\"memory\" : {%s"
  19567. "\"blocks\" : %i,%s"
  19568. "\"used\" : %" INT64_FMT ",%s"
  19569. "\"maxUsed\" : %" INT64_FMT "%s"
  19570. "}",
  19571. eol,
  19572. eol,
  19573. blockCount,
  19574. eol,
  19575. totalMemUsed,
  19576. eol,
  19577. maxMemUsed,
  19578. eol);
  19579. context_info_length += mg_str_append(&buffer, end, block);
  19580. }
  19581. if (ctx) {
  19582. /* Declare all variables at begin of the block, to comply
  19583. * with old C standards. */
  19584. char start_time_str[64] = {0};
  19585. char now_str[64] = {0};
  19586. time_t start_time = ctx->start_time;
  19587. time_t now = time(NULL);
  19588. int64_t total_data_read, total_data_written;
  19589. int active_connections = (int)ctx->active_connections;
  19590. int max_active_connections = (int)ctx->max_active_connections;
  19591. int total_connections = (int)ctx->total_connections;
  19592. if (active_connections > max_active_connections) {
  19593. max_active_connections = active_connections;
  19594. }
  19595. if (active_connections > total_connections) {
  19596. total_connections = active_connections;
  19597. }
  19598. /* Connections information */
  19599. mg_snprintf(NULL,
  19600. NULL,
  19601. block,
  19602. sizeof(block),
  19603. ",%s\"connections\" : {%s"
  19604. "\"active\" : %i,%s"
  19605. "\"maxActive\" : %i,%s"
  19606. "\"total\" : %i%s"
  19607. "}",
  19608. eol,
  19609. eol,
  19610. active_connections,
  19611. eol,
  19612. max_active_connections,
  19613. eol,
  19614. total_connections,
  19615. eol);
  19616. context_info_length += mg_str_append(&buffer, end, block);
  19617. /* Queue information */
  19618. #if !defined(ALTERNATIVE_QUEUE)
  19619. mg_snprintf(NULL,
  19620. NULL,
  19621. block,
  19622. sizeof(block),
  19623. ",%s\"queue\" : {%s"
  19624. "\"length\" : %i,%s"
  19625. "\"filled\" : %i,%s"
  19626. "\"maxFilled\" : %i,%s"
  19627. "\"full\" : %s%s"
  19628. "}",
  19629. eol,
  19630. eol,
  19631. ctx->sq_size,
  19632. eol,
  19633. ctx->sq_head - ctx->sq_tail,
  19634. eol,
  19635. ctx->sq_max_fill,
  19636. eol,
  19637. (ctx->sq_blocked ? "true" : "false"),
  19638. eol);
  19639. context_info_length += mg_str_append(&buffer, end, block);
  19640. #endif
  19641. /* Requests information */
  19642. mg_snprintf(NULL,
  19643. NULL,
  19644. block,
  19645. sizeof(block),
  19646. ",%s\"requests\" : {%s"
  19647. "\"total\" : %lu%s"
  19648. "}",
  19649. eol,
  19650. eol,
  19651. (unsigned long)ctx->total_requests,
  19652. eol);
  19653. context_info_length += mg_str_append(&buffer, end, block);
  19654. /* Data information */
  19655. total_data_read =
  19656. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19657. total_data_written =
  19658. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19659. mg_snprintf(NULL,
  19660. NULL,
  19661. block,
  19662. sizeof(block),
  19663. ",%s\"data\" : {%s"
  19664. "\"read\" : %" INT64_FMT ",%s"
  19665. "\"written\" : %" INT64_FMT "%s"
  19666. "}",
  19667. eol,
  19668. eol,
  19669. total_data_read,
  19670. eol,
  19671. total_data_written,
  19672. eol);
  19673. context_info_length += mg_str_append(&buffer, end, block);
  19674. /* Execution time information */
  19675. gmt_time_string(start_time_str,
  19676. sizeof(start_time_str) - 1,
  19677. &start_time);
  19678. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19679. mg_snprintf(NULL,
  19680. NULL,
  19681. block,
  19682. sizeof(block),
  19683. ",%s\"time\" : {%s"
  19684. "\"uptime\" : %.0f,%s"
  19685. "\"start\" : \"%s\",%s"
  19686. "\"now\" : \"%s\"%s"
  19687. "}",
  19688. eol,
  19689. eol,
  19690. difftime(now, start_time),
  19691. eol,
  19692. start_time_str,
  19693. eol,
  19694. now_str,
  19695. eol);
  19696. context_info_length += mg_str_append(&buffer, end, block);
  19697. }
  19698. /* Terminate string */
  19699. if (append_eoobj) {
  19700. strcat(append_eoobj, eoobj);
  19701. }
  19702. context_info_length += sizeof(eoobj) - 1;
  19703. return (int)context_info_length;
  19704. #else
  19705. (void)ctx;
  19706. if ((buffer != NULL) && (buflen > 0)) {
  19707. *buffer = 0;
  19708. }
  19709. return 0;
  19710. #endif
  19711. }
  19712. CIVETWEB_API void
  19713. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19714. {
  19715. /* https://github.com/civetweb/civetweb/issues/727 */
  19716. if (conn != NULL) {
  19717. conn->must_close = 1;
  19718. }
  19719. }
  19720. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19721. /* Get connection information. It can be printed or stored by the caller.
  19722. * Return the size of available information. */
  19723. CIVETWEB_API int
  19724. mg_get_connection_info(const struct mg_context *ctx,
  19725. int idx,
  19726. char *buffer,
  19727. int buflen)
  19728. {
  19729. const struct mg_connection *conn;
  19730. const struct mg_request_info *ri;
  19731. char *end, *append_eoobj = NULL, block[256];
  19732. size_t connection_info_length = 0;
  19733. int state = 0;
  19734. const char *state_str = "unknown";
  19735. #if defined(_WIN32)
  19736. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19737. #else
  19738. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19739. #endif
  19740. if ((buffer == NULL) || (buflen < 1)) {
  19741. buflen = 0;
  19742. end = buffer;
  19743. } else {
  19744. *buffer = 0;
  19745. end = buffer + buflen;
  19746. }
  19747. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19748. /* has enough space to append eoobj */
  19749. append_eoobj = buffer;
  19750. end -= sizeof(eoobj) - 1;
  19751. }
  19752. if ((ctx == NULL) || (idx < 0)) {
  19753. /* Parameter error */
  19754. return 0;
  19755. }
  19756. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19757. /* Out of range */
  19758. return 0;
  19759. }
  19760. /* Take connection [idx]. This connection is not locked in
  19761. * any way, so some other thread might use it. */
  19762. conn = (ctx->worker_connections) + idx;
  19763. /* Initialize output string */
  19764. connection_info_length += mg_str_append(&buffer, end, "{");
  19765. /* Init variables */
  19766. ri = &(conn->request_info);
  19767. #if defined(USE_SERVER_STATS)
  19768. state = conn->conn_state;
  19769. /* State as string */
  19770. switch (state) {
  19771. case 0:
  19772. state_str = "undefined";
  19773. break;
  19774. case 1:
  19775. state_str = "not used";
  19776. break;
  19777. case 2:
  19778. state_str = "init";
  19779. break;
  19780. case 3:
  19781. state_str = "ready";
  19782. break;
  19783. case 4:
  19784. state_str = "processing";
  19785. break;
  19786. case 5:
  19787. state_str = "processed";
  19788. break;
  19789. case 6:
  19790. state_str = "to close";
  19791. break;
  19792. case 7:
  19793. state_str = "closing";
  19794. break;
  19795. case 8:
  19796. state_str = "closed";
  19797. break;
  19798. case 9:
  19799. state_str = "done";
  19800. break;
  19801. }
  19802. #endif
  19803. /* Connection info */
  19804. if ((state >= 3) && (state < 9)) {
  19805. mg_snprintf(NULL,
  19806. NULL,
  19807. block,
  19808. sizeof(block),
  19809. "%s\"connection\" : {%s"
  19810. "\"remote\" : {%s"
  19811. "\"protocol\" : \"%s\",%s"
  19812. "\"addr\" : \"%s\",%s"
  19813. "\"port\" : %u%s"
  19814. "},%s"
  19815. "\"handled_requests\" : %u%s"
  19816. "}",
  19817. eol,
  19818. eol,
  19819. eol,
  19820. get_proto_name(conn),
  19821. eol,
  19822. ri->remote_addr,
  19823. eol,
  19824. ri->remote_port,
  19825. eol,
  19826. eol,
  19827. conn->handled_requests,
  19828. eol);
  19829. connection_info_length += mg_str_append(&buffer, end, block);
  19830. }
  19831. /* Request info */
  19832. if ((state >= 4) && (state < 6)) {
  19833. mg_snprintf(NULL,
  19834. NULL,
  19835. block,
  19836. sizeof(block),
  19837. "%s%s\"request_info\" : {%s"
  19838. "\"method\" : \"%s\",%s"
  19839. "\"uri\" : \"%s\",%s"
  19840. "\"query\" : %s%s%s%s"
  19841. "}",
  19842. (connection_info_length > 1 ? "," : ""),
  19843. eol,
  19844. eol,
  19845. ri->request_method,
  19846. eol,
  19847. ri->request_uri,
  19848. eol,
  19849. ri->query_string ? "\"" : "",
  19850. ri->query_string ? ri->query_string : "null",
  19851. ri->query_string ? "\"" : "",
  19852. eol);
  19853. connection_info_length += mg_str_append(&buffer, end, block);
  19854. }
  19855. /* Execution time information */
  19856. if ((state >= 2) && (state < 9)) {
  19857. char start_time_str[64] = {0};
  19858. char close_time_str[64] = {0};
  19859. time_t start_time = conn->conn_birth_time;
  19860. time_t close_time = 0;
  19861. double time_diff;
  19862. gmt_time_string(start_time_str,
  19863. sizeof(start_time_str) - 1,
  19864. &start_time);
  19865. #if defined(USE_SERVER_STATS)
  19866. close_time = conn->conn_close_time;
  19867. #endif
  19868. if (close_time != 0) {
  19869. time_diff = difftime(close_time, start_time);
  19870. gmt_time_string(close_time_str,
  19871. sizeof(close_time_str) - 1,
  19872. &close_time);
  19873. } else {
  19874. time_t now = time(NULL);
  19875. time_diff = difftime(now, start_time);
  19876. close_time_str[0] = 0; /* or use "now" ? */
  19877. }
  19878. mg_snprintf(NULL,
  19879. NULL,
  19880. block,
  19881. sizeof(block),
  19882. "%s%s\"time\" : {%s"
  19883. "\"uptime\" : %.0f,%s"
  19884. "\"start\" : \"%s\",%s"
  19885. "\"closed\" : \"%s\"%s"
  19886. "}",
  19887. (connection_info_length > 1 ? "," : ""),
  19888. eol,
  19889. eol,
  19890. time_diff,
  19891. eol,
  19892. start_time_str,
  19893. eol,
  19894. close_time_str,
  19895. eol);
  19896. connection_info_length += mg_str_append(&buffer, end, block);
  19897. }
  19898. /* Remote user name */
  19899. if ((ri->remote_user) && (state < 9)) {
  19900. mg_snprintf(NULL,
  19901. NULL,
  19902. block,
  19903. sizeof(block),
  19904. "%s%s\"user\" : {%s"
  19905. "\"name\" : \"%s\",%s"
  19906. "}",
  19907. (connection_info_length > 1 ? "," : ""),
  19908. eol,
  19909. eol,
  19910. ri->remote_user,
  19911. eol);
  19912. connection_info_length += mg_str_append(&buffer, end, block);
  19913. }
  19914. /* Data block */
  19915. if (state >= 3) {
  19916. mg_snprintf(NULL,
  19917. NULL,
  19918. block,
  19919. sizeof(block),
  19920. "%s%s\"data\" : {%s"
  19921. "\"read\" : %" INT64_FMT ",%s"
  19922. "\"written\" : %" INT64_FMT "%s"
  19923. "}",
  19924. (connection_info_length > 1 ? "," : ""),
  19925. eol,
  19926. eol,
  19927. conn->consumed_content,
  19928. eol,
  19929. conn->num_bytes_sent,
  19930. eol);
  19931. connection_info_length += mg_str_append(&buffer, end, block);
  19932. }
  19933. /* State */
  19934. mg_snprintf(NULL,
  19935. NULL,
  19936. block,
  19937. sizeof(block),
  19938. "%s%s\"state\" : \"%s\"",
  19939. (connection_info_length > 1 ? "," : ""),
  19940. eol,
  19941. state_str);
  19942. connection_info_length += mg_str_append(&buffer, end, block);
  19943. /* Terminate string */
  19944. if (append_eoobj) {
  19945. strcat(append_eoobj, eoobj);
  19946. }
  19947. connection_info_length += sizeof(eoobj) - 1;
  19948. return (int)connection_info_length;
  19949. }
  19950. #if 0
  19951. /* Get handler information. Not fully implemented. Is it required? */
  19952. CIVETWEB_API int
  19953. mg_get_handler_info(struct mg_context *ctx,
  19954. char *buffer,
  19955. int buflen)
  19956. {
  19957. int handler_info_len = 0;
  19958. struct mg_handler_info *tmp_rh;
  19959. mg_lock_context(ctx);
  19960. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19961. if (buflen > handler_info_len + tmp_rh->uri_len) {
  19962. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19963. }
  19964. handler_info_len += tmp_rh->uri_len;
  19965. switch (tmp_rh->handler_type) {
  19966. case REQUEST_HANDLER:
  19967. (void)tmp_rh->handler;
  19968. break;
  19969. case WEBSOCKET_HANDLER:
  19970. (void)tmp_rh->connect_handler;
  19971. (void)tmp_rh->ready_handler;
  19972. (void)tmp_rh->data_handler;
  19973. (void)tmp_rh->close_handler;
  19974. break;
  19975. case AUTH_HANDLER:
  19976. (void)tmp_rh->auth_handler;
  19977. break;
  19978. }
  19979. (void)cbdata;
  19980. }
  19981. mg_unlock_context(ctx);
  19982. return handler_info_len;
  19983. }
  19984. #endif
  19985. #endif
  19986. /* Initialize this library. This function does not need to be thread safe.
  19987. */
  19988. CIVETWEB_API unsigned
  19989. mg_init_library(unsigned features)
  19990. {
  19991. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19992. unsigned features_inited = features_to_init;
  19993. if (mg_init_library_called <= 0) {
  19994. /* Not initialized yet */
  19995. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19996. return 0;
  19997. }
  19998. }
  19999. mg_global_lock();
  20000. if (mg_init_library_called <= 0) {
  20001. int i;
  20002. size_t len;
  20003. #if defined(_WIN32)
  20004. int file_mutex_init = 1;
  20005. int wsa = 1;
  20006. #else
  20007. int mutexattr_init = 1;
  20008. #endif
  20009. int failed = 1;
  20010. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  20011. if (key_create == 0) {
  20012. #if defined(_WIN32)
  20013. file_mutex_init =
  20014. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  20015. if (file_mutex_init == 0) {
  20016. /* Start WinSock */
  20017. WSADATA data;
  20018. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  20019. }
  20020. #else
  20021. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  20022. if (mutexattr_init == 0) {
  20023. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  20024. PTHREAD_MUTEX_RECURSIVE);
  20025. }
  20026. #endif
  20027. }
  20028. if (failed) {
  20029. #if defined(_WIN32)
  20030. if (wsa == 0) {
  20031. (void)WSACleanup();
  20032. }
  20033. if (file_mutex_init == 0) {
  20034. (void)pthread_mutex_destroy(&global_log_file_lock);
  20035. }
  20036. #else
  20037. if (mutexattr_init == 0) {
  20038. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20039. }
  20040. #endif
  20041. if (key_create == 0) {
  20042. (void)pthread_key_delete(sTlsKey);
  20043. }
  20044. mg_global_unlock();
  20045. (void)pthread_mutex_destroy(&global_lock_mutex);
  20046. return 0;
  20047. }
  20048. len = 1;
  20049. for (i = 0; http_methods[i].name != NULL; i++) {
  20050. size_t sl = strlen(http_methods[i].name);
  20051. len += sl;
  20052. if (i > 0) {
  20053. len += 2;
  20054. }
  20055. }
  20056. all_methods = (char *)mg_malloc(len);
  20057. if (!all_methods) {
  20058. /* Must never happen */
  20059. mg_global_unlock();
  20060. (void)pthread_mutex_destroy(&global_lock_mutex);
  20061. return 0;
  20062. }
  20063. all_methods[0] = 0;
  20064. for (i = 0; http_methods[i].name != NULL; i++) {
  20065. if (i > 0) {
  20066. strcat(all_methods, ", ");
  20067. strcat(all_methods, http_methods[i].name);
  20068. } else {
  20069. strcpy(all_methods, http_methods[i].name);
  20070. }
  20071. }
  20072. }
  20073. #if defined(USE_LUA)
  20074. lua_init_optional_libraries();
  20075. #endif
  20076. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  20077. || defined(OPENSSL_API_3_0)) \
  20078. && !defined(NO_SSL)
  20079. if (features_to_init & MG_FEATURES_SSL) {
  20080. if (!mg_openssl_initialized) {
  20081. char ebuf[128];
  20082. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  20083. mg_openssl_initialized = 1;
  20084. } else {
  20085. (void)ebuf;
  20086. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  20087. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  20088. }
  20089. } else {
  20090. /* ssl already initialized */
  20091. }
  20092. }
  20093. #endif
  20094. if (mg_init_library_called <= 0) {
  20095. mg_init_library_called = 1;
  20096. } else {
  20097. mg_init_library_called++;
  20098. }
  20099. mg_global_unlock();
  20100. return features_inited;
  20101. }
  20102. /* Un-initialize this library. */
  20103. CIVETWEB_API unsigned
  20104. mg_exit_library(void)
  20105. {
  20106. if (mg_init_library_called <= 0) {
  20107. return 0;
  20108. }
  20109. mg_global_lock();
  20110. mg_init_library_called--;
  20111. if (mg_init_library_called == 0) {
  20112. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  20113. if (mg_openssl_initialized) {
  20114. uninitialize_openssl();
  20115. mg_openssl_initialized = 0;
  20116. }
  20117. #endif
  20118. #if defined(_WIN32)
  20119. (void)WSACleanup();
  20120. (void)pthread_mutex_destroy(&global_log_file_lock);
  20121. #else
  20122. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20123. #endif
  20124. (void)pthread_key_delete(sTlsKey);
  20125. #if defined(USE_LUA)
  20126. lua_exit_optional_libraries();
  20127. #endif
  20128. mg_free(all_methods);
  20129. all_methods = NULL;
  20130. mg_global_unlock();
  20131. (void)pthread_mutex_destroy(&global_lock_mutex);
  20132. return 1;
  20133. }
  20134. mg_global_unlock();
  20135. return 1;
  20136. }
  20137. /* End of civetweb.c */