civetweb.c 620 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211
  1. /* Copyright (c) 2013-2024 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #ifndef GCC_VERSION
  24. #define GCC_VERSION \
  25. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  26. #endif
  27. #if GCC_VERSION >= 40500
  28. /* gcc diagnostic pragmas available */
  29. #define GCC_DIAGNOSTIC
  30. #endif
  31. #endif
  32. #if defined(GCC_DIAGNOSTIC)
  33. /* Disable unused macros warnings - not all defines are required
  34. * for all systems and all compilers. */
  35. #pragma GCC diagnostic ignored "-Wunused-macros"
  36. /* A padding warning is just plain useless */
  37. #pragma GCC diagnostic ignored "-Wpadded"
  38. #endif
  39. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  40. /* We must set some flags for the headers we include. These flags
  41. * are reserved ids according to C99, so we need to disable a
  42. * warning for that. */
  43. #pragma GCC diagnostic push
  44. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  45. #endif
  46. #if defined(_WIN32)
  47. #if !defined(_CRT_SECURE_NO_WARNINGS)
  48. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  49. #endif
  50. #if !defined(_WIN32_WINNT) /* Minimum API version */
  51. #define _WIN32_WINNT 0x0601
  52. #endif
  53. #else
  54. #if !defined(_GNU_SOURCE)
  55. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  56. #endif
  57. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  58. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  59. #endif
  60. #if defined(__LSB_VERSION__) || defined(__sun)
  61. #define NEED_TIMEGM
  62. #define NO_THREAD_NAME
  63. #endif
  64. #if !defined(_LARGEFILE_SOURCE)
  65. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  66. #endif
  67. #if !defined(_FILE_OFFSET_BITS)
  68. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  69. #endif
  70. #if !defined(__STDC_FORMAT_MACROS)
  71. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  72. #endif
  73. #if !defined(__STDC_LIMIT_MACROS)
  74. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  75. #endif
  76. #if !defined(_DARWIN_UNLIMITED_SELECT)
  77. #define _DARWIN_UNLIMITED_SELECT
  78. #endif
  79. #if defined(__sun)
  80. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  81. #define __inline inline /* not recognized on older compiler versions */
  82. #endif
  83. #endif
  84. #if defined(__clang__)
  85. /* Enable reserved-id-macro warning again. */
  86. #pragma GCC diagnostic pop
  87. #endif
  88. #if defined(USE_LUA)
  89. #define USE_TIMERS
  90. #endif
  91. #if defined(_MSC_VER)
  92. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  93. #pragma warning(disable : 4306)
  94. /* conditional expression is constant: introduced by FD_SET(..) */
  95. #pragma warning(disable : 4127)
  96. /* non-constant aggregate initializer: issued due to missing C99 support */
  97. #pragma warning(disable : 4204)
  98. /* padding added after data member */
  99. #pragma warning(disable : 4820)
  100. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  101. #pragma warning(disable : 4668)
  102. /* no function prototype given: converting '()' to '(void)' */
  103. #pragma warning(disable : 4255)
  104. /* function has been selected for automatic inline expansion */
  105. #pragma warning(disable : 4711)
  106. #endif
  107. /* This code uses static_assert to check some conditions.
  108. * Unfortunately some compilers still do not support it, so we have a
  109. * replacement function here. */
  110. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  111. #define mg_static_assert _Static_assert
  112. #elif defined(__cplusplus) && __cplusplus >= 201103L
  113. #define mg_static_assert static_assert
  114. #else
  115. char static_assert_replacement[1];
  116. #define mg_static_assert(cond, txt) \
  117. extern char static_assert_replacement[(cond) ? 1 : -1]
  118. #endif
  119. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  120. "int data type size check");
  121. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  122. "pointer data type size check");
  123. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  124. /* Select queue implementation. Diagnosis features originally only implemented
  125. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  126. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  127. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  128. * implementation, since the queue length is independent from the number of
  129. * worker threads there, while the new queue is one element per worker thread.
  130. *
  131. */
  132. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  133. /* The queues are exclusive or - only one can be used. */
  134. #error \
  135. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  136. #endif
  137. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  138. /* Use a default implementation */
  139. #define NO_ALTERNATIVE_QUEUE
  140. #endif
  141. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  142. /* File system access:
  143. * NO_FILES = do not serve any files from the file system automatically.
  144. * However, with NO_FILES CivetWeb may still write log files, read access
  145. * control files, default error page files or use API functions like
  146. * mg_send_file in callbacks to send files from the server local
  147. * file system.
  148. * NO_FILES only disables the automatic mapping between URLs and local
  149. * file names.
  150. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  151. * devices without file system. Logging to files in not available
  152. * (use callbacks instead) and API functions like mg_send_file are not
  153. * available.
  154. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  155. */
  156. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  157. #endif
  158. /* DTL -- including winsock2.h works better if lean and mean */
  159. #if !defined(WIN32_LEAN_AND_MEAN)
  160. #define WIN32_LEAN_AND_MEAN
  161. #endif
  162. #if defined(__SYMBIAN32__)
  163. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  164. * Symbian is no longer maintained since 2014-01-01.
  165. * Support for Symbian has been removed from CivetWeb
  166. */
  167. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  168. #endif /* __SYMBIAN32__ */
  169. #if defined(__rtems__)
  170. #include <rtems/version.h>
  171. #endif
  172. #if defined(__ZEPHYR__)
  173. #include <ctype.h>
  174. #include <fcntl.h>
  175. #include <netdb.h>
  176. #include <poll.h>
  177. #include <pthread.h>
  178. #include <stdio.h>
  179. #include <stdlib.h>
  180. #include <string.h>
  181. #include <sys/socket.h>
  182. #include <time.h>
  183. #include <zephyr/kernel.h>
  184. /* Max worker threads is the max of pthreads minus the main application thread
  185. * and minus the main civetweb thread, thus -2
  186. */
  187. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  188. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  189. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  190. #else
  191. #define ZEPHYR_STACK_SIZE (1024 * 16)
  192. #endif
  193. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  194. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  195. MAX_WORKER_THREADS,
  196. ZEPHYR_STACK_SIZE);
  197. static int zephyr_worker_stack_index;
  198. #endif
  199. #if !defined(CIVETWEB_HEADER_INCLUDED)
  200. /* Include the header file here, so the CivetWeb interface is defined for the
  201. * entire implementation, including the following forward definitions. */
  202. #include "civetweb.h"
  203. #endif
  204. #if !defined(DEBUG_TRACE)
  205. #if defined(DEBUG)
  206. static void DEBUG_TRACE_FUNC(const char *func,
  207. unsigned line,
  208. PRINTF_FORMAT_STRING(const char *fmt),
  209. ...) PRINTF_ARGS(3, 4);
  210. #define DEBUG_TRACE(fmt, ...) \
  211. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  212. #define NEED_DEBUG_TRACE_FUNC
  213. #if !defined(DEBUG_TRACE_STREAM)
  214. #define DEBUG_TRACE_STREAM stdout
  215. #endif
  216. #else
  217. #define DEBUG_TRACE(fmt, ...) \
  218. do { \
  219. } while (0)
  220. #endif /* DEBUG */
  221. #endif /* DEBUG_TRACE */
  222. #if !defined(DEBUG_ASSERT)
  223. #if defined(DEBUG)
  224. #include <stdlib.h>
  225. #define DEBUG_ASSERT(cond) \
  226. do { \
  227. if (!(cond)) { \
  228. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  229. exit(2); /* Exit with error */ \
  230. } \
  231. } while (0)
  232. #else
  233. #define DEBUG_ASSERT(cond)
  234. #endif /* DEBUG */
  235. #endif
  236. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  237. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  238. __attribute__((no_instrument_function));
  239. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  240. __attribute__((no_instrument_function));
  241. void
  242. __cyg_profile_func_enter(void *this_fn, void *call_site)
  243. {
  244. if ((void *)this_fn != (void *)printf) {
  245. printf("E %p %p\n", this_fn, call_site);
  246. }
  247. }
  248. void
  249. __cyg_profile_func_exit(void *this_fn, void *call_site)
  250. {
  251. if ((void *)this_fn != (void *)printf) {
  252. printf("X %p %p\n", this_fn, call_site);
  253. }
  254. }
  255. #endif
  256. #if !defined(IGNORE_UNUSED_RESULT)
  257. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  258. #endif
  259. #if defined(__GNUC__) || defined(__MINGW32__)
  260. /* GCC unused function attribute seems fundamentally broken.
  261. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  262. * OR UNUSED" for individual functions failed.
  263. * Either the compiler creates an "unused-function" warning if a
  264. * function is not marked with __attribute__((unused)).
  265. * On the other hand, if the function is marked with this attribute,
  266. * but is used, the compiler raises a completely idiotic
  267. * "used-but-marked-unused" warning - and
  268. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  269. * raises error: unknown option after "#pragma GCC diagnostic".
  270. * Disable this warning completely, until the GCC guys sober up
  271. * again.
  272. */
  273. #pragma GCC diagnostic ignored "-Wunused-function"
  274. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  275. #else
  276. #define FUNCTION_MAY_BE_UNUSED
  277. #endif
  278. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  279. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  280. #include <errno.h>
  281. #include <fcntl.h>
  282. #include <signal.h>
  283. #include <stdlib.h>
  284. #include <sys/stat.h>
  285. #include <sys/types.h>
  286. #endif /* !_WIN32_WCE */
  287. #if defined(__clang__)
  288. /* When using -Weverything, clang does not accept it's own headers
  289. * in a release build configuration. Disable what is too much in
  290. * -Weverything. */
  291. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  292. #endif
  293. #if defined(__GNUC__) || defined(__MINGW32__)
  294. /* Who on earth came to the conclusion, using __DATE__ should rise
  295. * an "expansion of date or time macro is not reproducible"
  296. * warning. That's exactly what was intended by using this macro.
  297. * Just disable this nonsense warning. */
  298. /* And disabling them does not work either:
  299. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  300. * #pragma clang diagnostic ignored "-Wdate-time"
  301. * So we just have to disable ALL warnings for some lines
  302. * of code.
  303. * This seems to be a known GCC bug, not resolved since 2012:
  304. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  305. */
  306. #endif
  307. #if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
  308. #if defined(__clang__)
  309. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  310. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  311. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  312. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  313. #endif
  314. #endif
  315. #ifndef CLOCK_MONOTONIC
  316. #define CLOCK_MONOTONIC (1)
  317. #endif
  318. #ifndef CLOCK_REALTIME
  319. #define CLOCK_REALTIME (2)
  320. #endif
  321. #include <mach/clock.h>
  322. #include <mach/mach.h>
  323. #include <mach/mach_time.h>
  324. #include <sys/errno.h>
  325. #include <sys/time.h>
  326. /* clock_gettime is not implemented on OSX prior to 10.12 */
  327. static int
  328. _civet_clock_gettime(int clk_id, struct timespec *t)
  329. {
  330. memset(t, 0, sizeof(*t));
  331. if (clk_id == CLOCK_REALTIME) {
  332. struct timeval now;
  333. int rv = gettimeofday(&now, NULL);
  334. if (rv) {
  335. return rv;
  336. }
  337. t->tv_sec = now.tv_sec;
  338. t->tv_nsec = now.tv_usec * 1000;
  339. return 0;
  340. } else if (clk_id == CLOCK_MONOTONIC) {
  341. static uint64_t clock_start_time = 0;
  342. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  343. uint64_t now = mach_absolute_time();
  344. if (clock_start_time == 0) {
  345. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  346. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  347. /* appease "unused variable" warning for release builds */
  348. (void)mach_status;
  349. clock_start_time = now;
  350. }
  351. now = (uint64_t)((double)(now - clock_start_time)
  352. * (double)timebase_ifo.numer
  353. / (double)timebase_ifo.denom);
  354. t->tv_sec = now / 1000000000;
  355. t->tv_nsec = now % 1000000000;
  356. return 0;
  357. }
  358. return -1; /* EINVAL - Clock ID is unknown */
  359. }
  360. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  361. #if defined(__CLOCK_AVAILABILITY)
  362. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  363. * declared but it may be NULL at runtime. So we need to check before using
  364. * it. */
  365. static int
  366. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  367. {
  368. if (clock_gettime) {
  369. return clock_gettime(clk_id, t);
  370. }
  371. return _civet_clock_gettime(clk_id, t);
  372. }
  373. #define clock_gettime _civet_safe_clock_gettime
  374. #else
  375. #define clock_gettime _civet_clock_gettime
  376. #endif
  377. #endif
  378. #if defined(_WIN32)
  379. #define ERROR_TRY_AGAIN(err) ((err) == WSAEWOULDBLOCK)
  380. #else
  381. /* Unix might return different error codes indicating to try again.
  382. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  383. * decades ago, but better check both and let the compiler optimize it. */
  384. #define ERROR_TRY_AGAIN(err) \
  385. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  386. #endif
  387. #if defined(USE_ZLIB)
  388. #include "zconf.h"
  389. #include "zlib.h"
  390. #endif
  391. /********************************************************************/
  392. /* CivetWeb configuration defines */
  393. /********************************************************************/
  394. /* Maximum number of threads that can be configured.
  395. * The number of threads actually created depends on the "num_threads"
  396. * configuration parameter, but this is the upper limit. */
  397. #if !defined(MAX_WORKER_THREADS)
  398. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  399. #endif
  400. /* Timeout interval for select/poll calls.
  401. * The timeouts depend on "*_timeout_ms" configuration values, but long
  402. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  403. * This reduces the time required to stop the server. */
  404. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  405. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  406. #endif
  407. /* Do not try to compress files smaller than this limit. */
  408. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  409. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  410. #endif
  411. #if !defined(PASSWORDS_FILE_NAME)
  412. #define PASSWORDS_FILE_NAME ".htpasswd"
  413. #endif
  414. /* Initial buffer size for all CGI environment variables. In case there is
  415. * not enough space, another block is allocated. */
  416. #if !defined(CGI_ENVIRONMENT_SIZE)
  417. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  418. #endif
  419. /* Maximum number of environment variables. */
  420. #if !defined(MAX_CGI_ENVIR_VARS)
  421. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  422. #endif
  423. /* General purpose buffer size. */
  424. #if !defined(MG_BUF_LEN) /* in bytes */
  425. #define MG_BUF_LEN (1024 * 8)
  426. #endif
  427. /********************************************************************/
  428. /* Helper macros */
  429. #if !defined(ARRAY_SIZE)
  430. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  431. #endif
  432. #include <stdint.h>
  433. /* Standard defines */
  434. #if !defined(INT64_MAX)
  435. #define INT64_MAX (9223372036854775807)
  436. #endif
  437. #define SHUTDOWN_RD (0)
  438. #define SHUTDOWN_WR (1)
  439. #define SHUTDOWN_BOTH (2)
  440. mg_static_assert(MAX_WORKER_THREADS >= 1,
  441. "worker threads must be a positive number");
  442. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  443. "size_t data type size check");
  444. #if defined(_WIN32) /* WINDOWS include block */
  445. #include <malloc.h> /* *alloc( */
  446. #include <stdlib.h> /* *alloc( */
  447. #include <time.h> /* struct timespec */
  448. #include <windows.h>
  449. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  450. #include <ws2tcpip.h>
  451. typedef const char *SOCK_OPT_TYPE;
  452. /* For a detailed description of these *_PATH_MAX defines, see
  453. * https://github.com/civetweb/civetweb/issues/937. */
  454. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  455. * null termination, rounded up to the next 4 bytes boundary */
  456. #define UTF8_PATH_MAX (3 * 260)
  457. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  458. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  459. #define UTF16_PATH_MAX (260)
  460. #if !defined(_IN_PORT_T)
  461. #if !defined(in_port_t)
  462. #define in_port_t u_short
  463. #endif
  464. #endif
  465. #if defined(_WIN32_WCE)
  466. #error "WinCE support has ended"
  467. #endif
  468. #include <direct.h>
  469. #include <io.h>
  470. #include <process.h>
  471. #define MAKEUQUAD(lo, hi) \
  472. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  473. #define RATE_DIFF (10000000) /* 100 nsecs */
  474. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  475. #define SYS2UNIX_TIME(lo, hi) \
  476. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  477. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  478. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  479. * Also use _strtoui64 on modern M$ compilers */
  480. #if defined(_MSC_VER)
  481. #if (_MSC_VER < 1300)
  482. #define STRX(x) #x
  483. #define STR(x) STRX(x)
  484. #define __func__ __FILE__ ":" STR(__LINE__)
  485. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  486. #define strtoll(x, y, z) (_atoi64(x))
  487. #else
  488. #define __func__ __FUNCTION__
  489. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  490. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  491. #endif
  492. #endif /* _MSC_VER */
  493. #define ERRNO ((int)(GetLastError()))
  494. #define NO_SOCKLEN_T
  495. #if defined(_WIN64) || defined(__MINGW64__)
  496. #if !defined(SSL_LIB)
  497. #if defined(OPENSSL_API_3_0)
  498. #define SSL_LIB "libssl-3-x64.dll"
  499. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  500. #endif
  501. #if defined(OPENSSL_API_1_1)
  502. #define SSL_LIB "libssl-1_1-x64.dll"
  503. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  504. #endif /* OPENSSL_API_1_1 */
  505. #if defined(OPENSSL_API_1_0)
  506. #define SSL_LIB "ssleay64.dll"
  507. #define CRYPTO_LIB "libeay64.dll"
  508. #endif /* OPENSSL_API_1_0 */
  509. #endif
  510. #else /* defined(_WIN64) || defined(__MINGW64__) */
  511. #if !defined(SSL_LIB)
  512. #if defined(OPENSSL_API_3_0)
  513. #define SSL_LIB "libssl-3.dll"
  514. #define CRYPTO_LIB "libcrypto-3.dll"
  515. #endif
  516. #if defined(OPENSSL_API_1_1)
  517. #define SSL_LIB "libssl-1_1.dll"
  518. #define CRYPTO_LIB "libcrypto-1_1.dll"
  519. #endif /* OPENSSL_API_1_1 */
  520. #if defined(OPENSSL_API_1_0)
  521. #define SSL_LIB "ssleay32.dll"
  522. #define CRYPTO_LIB "libeay32.dll"
  523. #endif /* OPENSSL_API_1_0 */
  524. #endif /* SSL_LIB */
  525. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  526. #define O_NONBLOCK (0)
  527. #if !defined(W_OK)
  528. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  529. #endif
  530. #define _POSIX_
  531. #define INT64_FMT "I64d"
  532. #define UINT64_FMT "I64u"
  533. #define WINCDECL __cdecl
  534. #define vsnprintf_impl _vsnprintf
  535. #define access _access
  536. #define mg_sleep(x) (Sleep(x))
  537. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  538. #if !defined(popen)
  539. #define popen(x, y) (_popen(x, y))
  540. #endif
  541. #if !defined(pclose)
  542. #define pclose(x) (_pclose(x))
  543. #endif
  544. #define close(x) (_close(x))
  545. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  546. #define RTLD_LAZY (0)
  547. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  548. #define fdopen(x, y) (_fdopen((x), (y)))
  549. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  550. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  551. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  552. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  553. #define sleep(x) (Sleep((x)*1000))
  554. #define rmdir(x) (_rmdir(x))
  555. #if defined(_WIN64) || !defined(__MINGW32__)
  556. /* Only MinGW 32 bit is missing this function */
  557. #define timegm(x) (_mkgmtime(x))
  558. #else
  559. time_t timegm(struct tm *tm);
  560. #define NEED_TIMEGM
  561. #endif
  562. #if !defined(fileno)
  563. #define fileno(x) (_fileno(x))
  564. #endif /* !fileno MINGW #defines fileno */
  565. typedef struct {
  566. CRITICAL_SECTION sec; /* Immovable */
  567. } pthread_mutex_t;
  568. typedef DWORD pthread_key_t;
  569. typedef HANDLE pthread_t;
  570. typedef struct {
  571. pthread_mutex_t threadIdSec;
  572. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  573. } pthread_cond_t;
  574. #if !defined(__clockid_t_defined)
  575. typedef DWORD clockid_t;
  576. #endif
  577. #if !defined(CLOCK_MONOTONIC)
  578. #define CLOCK_MONOTONIC (1)
  579. #endif
  580. #if !defined(CLOCK_REALTIME)
  581. #define CLOCK_REALTIME (2)
  582. #endif
  583. #if !defined(CLOCK_THREAD)
  584. #define CLOCK_THREAD (3)
  585. #endif
  586. #if !defined(CLOCK_PROCESS)
  587. #define CLOCK_PROCESS (4)
  588. #endif
  589. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  590. #define _TIMESPEC_DEFINED
  591. #endif
  592. #if !defined(_TIMESPEC_DEFINED)
  593. struct timespec {
  594. time_t tv_sec; /* seconds */
  595. long tv_nsec; /* nanoseconds */
  596. };
  597. #endif
  598. #if !defined(WIN_PTHREADS_TIME_H)
  599. #define MUST_IMPLEMENT_CLOCK_GETTIME
  600. #endif
  601. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  602. #define clock_gettime mg_clock_gettime
  603. static int
  604. clock_gettime(clockid_t clk_id, struct timespec *tp)
  605. {
  606. FILETIME ft;
  607. ULARGE_INTEGER li, li2;
  608. BOOL ok = FALSE;
  609. double d;
  610. static double perfcnt_per_sec = 0.0;
  611. static BOOL initialized = FALSE;
  612. if (!initialized) {
  613. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  614. perfcnt_per_sec = 1.0 / li.QuadPart;
  615. initialized = TRUE;
  616. }
  617. if (tp) {
  618. memset(tp, 0, sizeof(*tp));
  619. if (clk_id == CLOCK_REALTIME) {
  620. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  621. GetSystemTimeAsFileTime(&ft);
  622. li.LowPart = ft.dwLowDateTime;
  623. li.HighPart = ft.dwHighDateTime;
  624. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  625. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  626. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  627. ok = TRUE;
  628. /* END: CLOCK_REALTIME */
  629. } else if (clk_id == CLOCK_MONOTONIC) {
  630. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  631. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  632. d = li.QuadPart * perfcnt_per_sec;
  633. tp->tv_sec = (time_t)d;
  634. d -= (double)tp->tv_sec;
  635. tp->tv_nsec = (long)(d * 1.0E9);
  636. ok = TRUE;
  637. /* END: CLOCK_MONOTONIC */
  638. } else if (clk_id == CLOCK_THREAD) {
  639. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  640. FILETIME t_create, t_exit, t_kernel, t_user;
  641. if (GetThreadTimes(GetCurrentThread(),
  642. &t_create,
  643. &t_exit,
  644. &t_kernel,
  645. &t_user)) {
  646. li.LowPart = t_user.dwLowDateTime;
  647. li.HighPart = t_user.dwHighDateTime;
  648. li2.LowPart = t_kernel.dwLowDateTime;
  649. li2.HighPart = t_kernel.dwHighDateTime;
  650. li.QuadPart += li2.QuadPart;
  651. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  652. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  653. ok = TRUE;
  654. }
  655. /* END: CLOCK_THREAD */
  656. } else if (clk_id == CLOCK_PROCESS) {
  657. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  658. FILETIME t_create, t_exit, t_kernel, t_user;
  659. if (GetProcessTimes(GetCurrentProcess(),
  660. &t_create,
  661. &t_exit,
  662. &t_kernel,
  663. &t_user)) {
  664. li.LowPart = t_user.dwLowDateTime;
  665. li.HighPart = t_user.dwHighDateTime;
  666. li2.LowPart = t_kernel.dwLowDateTime;
  667. li2.HighPart = t_kernel.dwHighDateTime;
  668. li.QuadPart += li2.QuadPart;
  669. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  670. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  671. ok = TRUE;
  672. }
  673. /* END: CLOCK_PROCESS */
  674. } else {
  675. /* BEGIN: unknown clock */
  676. /* ok = FALSE; already set by init */
  677. /* END: unknown clock */
  678. }
  679. }
  680. return ok ? 0 : -1;
  681. }
  682. #endif
  683. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  684. static int pthread_mutex_lock(pthread_mutex_t *);
  685. static int pthread_mutex_unlock(pthread_mutex_t *);
  686. static void path_to_unicode(const struct mg_connection *conn,
  687. const char *path,
  688. wchar_t *wbuf,
  689. size_t wbuf_len);
  690. /* All file operations need to be rewritten to solve #246. */
  691. struct mg_file;
  692. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  693. /* POSIX dirent interface */
  694. struct dirent {
  695. char d_name[UTF8_PATH_MAX];
  696. };
  697. typedef struct DIR {
  698. HANDLE handle;
  699. WIN32_FIND_DATAW info;
  700. struct dirent result;
  701. } DIR;
  702. #if defined(HAVE_POLL)
  703. #define mg_pollfd pollfd
  704. #else
  705. struct mg_pollfd {
  706. SOCKET fd;
  707. short events;
  708. short revents;
  709. };
  710. #endif
  711. /* Mark required libraries */
  712. #if defined(_MSC_VER)
  713. #pragma comment(lib, "Ws2_32.lib")
  714. #endif
  715. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  716. #include <inttypes.h>
  717. /* Linux & co. internally use UTF8 */
  718. #define UTF8_PATH_MAX (PATH_MAX)
  719. typedef const void *SOCK_OPT_TYPE;
  720. #if defined(ANDROID)
  721. typedef unsigned short int in_port_t;
  722. #endif
  723. #if !defined(__ZEPHYR__)
  724. #include <arpa/inet.h>
  725. #include <ctype.h>
  726. #include <dirent.h>
  727. #include <grp.h>
  728. #include <limits.h>
  729. #include <netdb.h>
  730. #include <netinet/in.h>
  731. #include <netinet/tcp.h>
  732. #include <poll.h>
  733. #include <pthread.h>
  734. #include <pwd.h>
  735. #include <stdarg.h>
  736. #include <stddef.h>
  737. #include <stdio.h>
  738. #include <stdlib.h>
  739. #include <string.h>
  740. #include <sys/socket.h>
  741. #include <sys/time.h>
  742. #if !defined(__rtems__)
  743. #include <sys/utsname.h>
  744. #endif
  745. #include <sys/wait.h>
  746. #include <time.h>
  747. #include <unistd.h>
  748. #if defined(USE_X_DOM_SOCKET)
  749. #include <sys/un.h>
  750. #endif
  751. #endif
  752. #define vsnprintf_impl vsnprintf
  753. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  754. #include <dlfcn.h>
  755. #endif
  756. #if defined(__MACH__) && defined(__APPLE__)
  757. #if defined(OPENSSL_API_3_0)
  758. #define SSL_LIB "libssl.3.dylib"
  759. #define CRYPTO_LIB "libcrypto.3.dylib"
  760. #endif
  761. #if defined(OPENSSL_API_1_1)
  762. #define SSL_LIB "libssl.1.1.dylib"
  763. #define CRYPTO_LIB "libcrypto.1.1.dylib"
  764. #endif /* OPENSSL_API_1_1 */
  765. #if defined(OPENSSL_API_1_0)
  766. #define SSL_LIB "libssl.1.0.dylib"
  767. #define CRYPTO_LIB "libcrypto.1.0.dylib"
  768. #endif /* OPENSSL_API_1_0 */
  769. #else
  770. #if !defined(SSL_LIB)
  771. #define SSL_LIB "libssl.so"
  772. #endif
  773. #if !defined(CRYPTO_LIB)
  774. #define CRYPTO_LIB "libcrypto.so"
  775. #endif
  776. #endif
  777. #if !defined(O_BINARY)
  778. #define O_BINARY (0)
  779. #endif /* O_BINARY */
  780. #define closesocket(a) (close(a))
  781. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  782. #define mg_remove(conn, x) (remove(x))
  783. #define mg_sleep(x) (usleep((x)*1000))
  784. #define mg_opendir(conn, x) (opendir(x))
  785. #define mg_closedir(x) (closedir(x))
  786. #define mg_readdir(x) (readdir(x))
  787. #define ERRNO (errno)
  788. #define INVALID_SOCKET (-1)
  789. #define INT64_FMT PRId64
  790. #define UINT64_FMT PRIu64
  791. typedef int SOCKET;
  792. #define WINCDECL
  793. #if defined(__hpux)
  794. /* HPUX 11 does not have monotonic, fall back to realtime */
  795. #if !defined(CLOCK_MONOTONIC)
  796. #define CLOCK_MONOTONIC CLOCK_REALTIME
  797. #endif
  798. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  799. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  800. * the prototypes use int* rather than socklen_t* which matches the
  801. * actual library expectation. When called with the wrong size arg
  802. * accept() returns a zero client inet addr and check_acl() always
  803. * fails. Since socklen_t is widely used below, just force replace
  804. * their typedef with int. - DTL
  805. */
  806. #define socklen_t int
  807. #endif /* hpux */
  808. #define mg_pollfd pollfd
  809. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  810. /* In case our C library is missing "timegm", provide an implementation */
  811. #if defined(NEED_TIMEGM)
  812. static inline int
  813. is_leap(int y)
  814. {
  815. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  816. }
  817. static inline int
  818. count_leap(int y)
  819. {
  820. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  821. }
  822. static time_t
  823. timegm(struct tm *tm)
  824. {
  825. static const unsigned short ydays[] = {
  826. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  827. int year = tm->tm_year + 1900;
  828. int mon = tm->tm_mon;
  829. int mday = tm->tm_mday - 1;
  830. int hour = tm->tm_hour;
  831. int min = tm->tm_min;
  832. int sec = tm->tm_sec;
  833. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  834. || (mday >= ydays[mon + 1] - ydays[mon]
  835. + (mon == 1 && is_leap(year) ? 1 : 0))
  836. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  837. return -1;
  838. time_t res = year - 1970;
  839. res *= 365;
  840. res += mday;
  841. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  842. res += count_leap(year);
  843. res *= 24;
  844. res += hour;
  845. res *= 60;
  846. res += min;
  847. res *= 60;
  848. res += sec;
  849. return res;
  850. }
  851. #endif /* NEED_TIMEGM */
  852. /* va_copy should always be a macro, C99 and C++11 - DTL */
  853. #if !defined(va_copy)
  854. #define va_copy(x, y) ((x) = (y))
  855. #endif
  856. #if defined(_WIN32)
  857. /* Create substitutes for POSIX functions in Win32. */
  858. #if defined(GCC_DIAGNOSTIC)
  859. /* Show no warning in case system functions are not used. */
  860. #pragma GCC diagnostic push
  861. #pragma GCC diagnostic ignored "-Wunused-function"
  862. #endif
  863. static pthread_mutex_t global_log_file_lock;
  864. FUNCTION_MAY_BE_UNUSED
  865. static DWORD
  866. pthread_self(void)
  867. {
  868. return GetCurrentThreadId();
  869. }
  870. FUNCTION_MAY_BE_UNUSED
  871. static int
  872. pthread_key_create(
  873. pthread_key_t *key,
  874. void (*_ignored)(void *) /* destructor not supported for Windows */
  875. )
  876. {
  877. (void)_ignored;
  878. if ((key != 0)) {
  879. *key = TlsAlloc();
  880. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  881. }
  882. return -2;
  883. }
  884. FUNCTION_MAY_BE_UNUSED
  885. static int
  886. pthread_key_delete(pthread_key_t key)
  887. {
  888. return TlsFree(key) ? 0 : 1;
  889. }
  890. FUNCTION_MAY_BE_UNUSED
  891. static int
  892. pthread_setspecific(pthread_key_t key, void *value)
  893. {
  894. return TlsSetValue(key, value) ? 0 : 1;
  895. }
  896. FUNCTION_MAY_BE_UNUSED
  897. static void *
  898. pthread_getspecific(pthread_key_t key)
  899. {
  900. return TlsGetValue(key);
  901. }
  902. #if defined(GCC_DIAGNOSTIC)
  903. /* Enable unused function warning again */
  904. #pragma GCC diagnostic pop
  905. #endif
  906. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  907. #else
  908. static pthread_mutexattr_t pthread_mutex_attr;
  909. #endif /* _WIN32 */
  910. #if defined(GCC_DIAGNOSTIC)
  911. /* Show no warning in case system functions are not used. */
  912. #pragma GCC diagnostic push
  913. #pragma GCC diagnostic ignored "-Wunused-function"
  914. #endif /* defined(GCC_DIAGNOSTIC) */
  915. #if defined(__clang__)
  916. /* Show no warning in case system functions are not used. */
  917. #pragma clang diagnostic push
  918. #pragma clang diagnostic ignored "-Wunused-function"
  919. #endif
  920. static pthread_mutex_t global_lock_mutex;
  921. FUNCTION_MAY_BE_UNUSED
  922. static void
  923. mg_global_lock(void)
  924. {
  925. (void)pthread_mutex_lock(&global_lock_mutex);
  926. }
  927. FUNCTION_MAY_BE_UNUSED
  928. static void
  929. mg_global_unlock(void)
  930. {
  931. (void)pthread_mutex_unlock(&global_lock_mutex);
  932. }
  933. #if defined(_WIN64)
  934. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  935. #elif defined(_WIN32)
  936. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  937. #endif
  938. /* Atomic functions working on ptrdiff_t ("signed size_t").
  939. * Operations: Increment, Decrement, Add, Maximum.
  940. * Up to size_t, they do not an atomic "load" operation.
  941. */
  942. FUNCTION_MAY_BE_UNUSED
  943. static ptrdiff_t
  944. mg_atomic_inc(volatile ptrdiff_t *addr)
  945. {
  946. ptrdiff_t ret;
  947. #if defined(_WIN64) && !defined(NO_ATOMICS)
  948. ret = InterlockedIncrement64(addr);
  949. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  950. #ifdef __cplusplus
  951. /* For C++ the Microsoft Visual Studio compiler can not decide what
  952. * overloaded function prototpye in the SDC corresponds to "ptrdiff_t". */
  953. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  954. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  955. ret = InterlockedIncrement((LONG *)addr);
  956. #else
  957. ret = InterlockedIncrement(addr);
  958. #endif
  959. #elif defined(__GNUC__) \
  960. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  961. && !defined(NO_ATOMICS)
  962. ret = __sync_add_and_fetch(addr, 1);
  963. #else
  964. mg_global_lock();
  965. ret = (++(*addr));
  966. mg_global_unlock();
  967. #endif
  968. return ret;
  969. }
  970. FUNCTION_MAY_BE_UNUSED
  971. static ptrdiff_t
  972. mg_atomic_dec(volatile ptrdiff_t *addr)
  973. {
  974. ptrdiff_t ret;
  975. #if defined(_WIN64) && !defined(NO_ATOMICS)
  976. ret = InterlockedDecrement64(addr);
  977. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  978. #ifdef __cplusplus
  979. /* see mg_atomic_inc */
  980. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  981. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  982. ret = InterlockedDecrement((LONG *)addr);
  983. #else
  984. ret = InterlockedDecrement(addr);
  985. #endif
  986. #elif defined(__GNUC__) \
  987. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  988. && !defined(NO_ATOMICS)
  989. ret = __sync_sub_and_fetch(addr, 1);
  990. #else
  991. mg_global_lock();
  992. ret = (--(*addr));
  993. mg_global_unlock();
  994. #endif
  995. return ret;
  996. }
  997. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  998. static ptrdiff_t
  999. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1000. {
  1001. ptrdiff_t ret;
  1002. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1003. ret = InterlockedAdd64(addr, value);
  1004. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1005. ret = InterlockedExchangeAdd(addr, value) + value;
  1006. #elif defined(__GNUC__) \
  1007. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1008. && !defined(NO_ATOMICS)
  1009. ret = __sync_add_and_fetch(addr, value);
  1010. #else
  1011. mg_global_lock();
  1012. *addr += value;
  1013. ret = (*addr);
  1014. mg_global_unlock();
  1015. #endif
  1016. return ret;
  1017. }
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static ptrdiff_t
  1020. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1021. ptrdiff_t oldval,
  1022. ptrdiff_t newval)
  1023. {
  1024. ptrdiff_t ret;
  1025. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1026. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1027. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1028. ret = InterlockedCompareExchange(addr, newval, oldval);
  1029. #elif defined(__GNUC__) \
  1030. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1031. && !defined(NO_ATOMICS)
  1032. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1033. #else
  1034. mg_global_lock();
  1035. ret = *addr;
  1036. if ((ret != newval) && (ret == oldval)) {
  1037. *addr = newval;
  1038. }
  1039. mg_global_unlock();
  1040. #endif
  1041. return ret;
  1042. }
  1043. static void
  1044. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1045. {
  1046. register ptrdiff_t tmp = *addr;
  1047. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1048. while (tmp < value) {
  1049. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1050. }
  1051. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1052. while (tmp < value) {
  1053. tmp = InterlockedCompareExchange(addr, value, tmp);
  1054. }
  1055. #elif defined(__GNUC__) \
  1056. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1057. && !defined(NO_ATOMICS)
  1058. while (tmp < value) {
  1059. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1060. }
  1061. #else
  1062. mg_global_lock();
  1063. if (*addr < value) {
  1064. *addr = value;
  1065. }
  1066. mg_global_unlock();
  1067. #endif
  1068. }
  1069. static int64_t
  1070. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1071. {
  1072. int64_t ret;
  1073. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1074. ret = InterlockedAdd64(addr, value);
  1075. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1076. ret = InterlockedExchangeAdd64(addr, value) + value;
  1077. #elif defined(__GNUC__) \
  1078. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1079. && !defined(NO_ATOMICS)
  1080. ret = __sync_add_and_fetch(addr, value);
  1081. #else
  1082. mg_global_lock();
  1083. *addr += value;
  1084. ret = (*addr);
  1085. mg_global_unlock();
  1086. #endif
  1087. return ret;
  1088. }
  1089. #endif
  1090. #if defined(GCC_DIAGNOSTIC)
  1091. /* Show no warning in case system functions are not used. */
  1092. #pragma GCC diagnostic pop
  1093. #endif /* defined(GCC_DIAGNOSTIC) */
  1094. #if defined(__clang__)
  1095. /* Show no warning in case system functions are not used. */
  1096. #pragma clang diagnostic pop
  1097. #endif
  1098. #if defined(USE_SERVER_STATS)
  1099. struct mg_memory_stat {
  1100. volatile ptrdiff_t totalMemUsed;
  1101. volatile ptrdiff_t maxMemUsed;
  1102. volatile ptrdiff_t blockCount;
  1103. };
  1104. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1105. static void *
  1106. mg_malloc_ex(size_t size,
  1107. struct mg_context *ctx,
  1108. const char *file,
  1109. unsigned line)
  1110. {
  1111. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1112. void *memory = 0;
  1113. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1114. #if defined(MEMORY_DEBUGGING)
  1115. char mallocStr[256];
  1116. #else
  1117. (void)file;
  1118. (void)line;
  1119. #endif
  1120. if (data) {
  1121. uintptr_t *tmp = (uintptr_t *)data;
  1122. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1123. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1124. mg_atomic_inc(&mstat->blockCount);
  1125. tmp[0] = size;
  1126. tmp[1] = (uintptr_t)mstat;
  1127. memory = (void *)&tmp[2];
  1128. }
  1129. #if defined(MEMORY_DEBUGGING)
  1130. sprintf(mallocStr,
  1131. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1132. memory,
  1133. (unsigned long)size,
  1134. (unsigned long)mstat->totalMemUsed,
  1135. (unsigned long)mstat->blockCount,
  1136. file,
  1137. line);
  1138. DEBUG_TRACE("%s", mallocStr);
  1139. #endif
  1140. return memory;
  1141. }
  1142. static void *
  1143. mg_calloc_ex(size_t count,
  1144. size_t size,
  1145. struct mg_context *ctx,
  1146. const char *file,
  1147. unsigned line)
  1148. {
  1149. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1150. if (data) {
  1151. memset(data, 0, size * count);
  1152. }
  1153. return data;
  1154. }
  1155. static void
  1156. mg_free_ex(void *memory, const char *file, unsigned line)
  1157. {
  1158. #if defined(MEMORY_DEBUGGING)
  1159. char mallocStr[256];
  1160. #else
  1161. (void)file;
  1162. (void)line;
  1163. #endif
  1164. if (memory) {
  1165. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1166. uintptr_t size = ((uintptr_t *)data)[0];
  1167. struct mg_memory_stat *mstat =
  1168. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1169. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1170. mg_atomic_dec(&mstat->blockCount);
  1171. #if defined(MEMORY_DEBUGGING)
  1172. sprintf(mallocStr,
  1173. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1174. memory,
  1175. (unsigned long)size,
  1176. (unsigned long)mstat->totalMemUsed,
  1177. (unsigned long)mstat->blockCount,
  1178. file,
  1179. line);
  1180. DEBUG_TRACE("%s", mallocStr);
  1181. #endif
  1182. free(data);
  1183. }
  1184. }
  1185. static void *
  1186. mg_realloc_ex(void *memory,
  1187. size_t newsize,
  1188. struct mg_context *ctx,
  1189. const char *file,
  1190. unsigned line)
  1191. {
  1192. void *data;
  1193. void *_realloc;
  1194. uintptr_t oldsize;
  1195. #if defined(MEMORY_DEBUGGING)
  1196. char mallocStr[256];
  1197. #else
  1198. (void)file;
  1199. (void)line;
  1200. #endif
  1201. if (newsize) {
  1202. if (memory) {
  1203. /* Reallocate existing block */
  1204. struct mg_memory_stat *mstat;
  1205. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1206. oldsize = ((uintptr_t *)data)[0];
  1207. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1208. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1209. if (_realloc) {
  1210. data = _realloc;
  1211. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1212. #if defined(MEMORY_DEBUGGING)
  1213. sprintf(mallocStr,
  1214. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1215. memory,
  1216. (unsigned long)oldsize,
  1217. (unsigned long)mstat->totalMemUsed,
  1218. (unsigned long)mstat->blockCount,
  1219. file,
  1220. line);
  1221. DEBUG_TRACE("%s", mallocStr);
  1222. #endif
  1223. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1224. #if defined(MEMORY_DEBUGGING)
  1225. sprintf(mallocStr,
  1226. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1227. memory,
  1228. (unsigned long)newsize,
  1229. (unsigned long)mstat->totalMemUsed,
  1230. (unsigned long)mstat->blockCount,
  1231. file,
  1232. line);
  1233. DEBUG_TRACE("%s", mallocStr);
  1234. #endif
  1235. *(uintptr_t *)data = newsize;
  1236. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1237. } else {
  1238. #if defined(MEMORY_DEBUGGING)
  1239. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1240. #endif
  1241. return _realloc;
  1242. }
  1243. } else {
  1244. /* Allocate new block */
  1245. data = mg_malloc_ex(newsize, ctx, file, line);
  1246. }
  1247. } else {
  1248. /* Free existing block */
  1249. data = 0;
  1250. mg_free_ex(memory, file, line);
  1251. }
  1252. return data;
  1253. }
  1254. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1255. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1256. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1257. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1258. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1259. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1260. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1261. #else /* USE_SERVER_STATS */
  1262. static __inline void *
  1263. mg_malloc(size_t a)
  1264. {
  1265. return malloc(a);
  1266. }
  1267. static __inline void *
  1268. mg_calloc(size_t a, size_t b)
  1269. {
  1270. return calloc(a, b);
  1271. }
  1272. static __inline void *
  1273. mg_realloc(void *a, size_t b)
  1274. {
  1275. return realloc(a, b);
  1276. }
  1277. static __inline void
  1278. mg_free(void *a)
  1279. {
  1280. free(a);
  1281. }
  1282. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1283. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1284. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1285. #define mg_free_ctx(a, c) mg_free(a)
  1286. #endif /* USE_SERVER_STATS */
  1287. static void mg_vsnprintf(const struct mg_connection *conn,
  1288. int *truncated,
  1289. char *buf,
  1290. size_t buflen,
  1291. const char *fmt,
  1292. va_list ap);
  1293. static void mg_snprintf(const struct mg_connection *conn,
  1294. int *truncated,
  1295. char *buf,
  1296. size_t buflen,
  1297. PRINTF_FORMAT_STRING(const char *fmt),
  1298. ...) PRINTF_ARGS(5, 6);
  1299. /* This following lines are just meant as a reminder to use the mg-functions
  1300. * for memory management */
  1301. #if defined(malloc)
  1302. #undef malloc
  1303. #endif
  1304. #if defined(calloc)
  1305. #undef calloc
  1306. #endif
  1307. #if defined(realloc)
  1308. #undef realloc
  1309. #endif
  1310. #if defined(free)
  1311. #undef free
  1312. #endif
  1313. #if defined(snprintf)
  1314. #undef snprintf
  1315. #endif
  1316. #if defined(vsnprintf)
  1317. #undef vsnprintf
  1318. #endif
  1319. #if !defined(NDEBUG)
  1320. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1321. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1322. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1323. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1324. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1325. #endif
  1326. #if defined(_WIN32)
  1327. /* vsnprintf must not be used in any system,
  1328. * but this define only works well for Windows. */
  1329. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1330. #endif
  1331. /* mg_init_library counter */
  1332. static int mg_init_library_called = 0;
  1333. #if !defined(NO_SSL)
  1334. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1335. || defined(OPENSSL_API_3_0)
  1336. static int mg_openssl_initialized = 0;
  1337. #endif
  1338. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1339. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS) \
  1340. && !defined(USE_GNUTLS)
  1341. #error "Please define OPENSSL_API_#_# or USE_MBEDTLS or USE_GNUTLS"
  1342. #endif
  1343. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1344. #error "Multiple OPENSSL_API versions defined"
  1345. #endif
  1346. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1347. #error "Multiple OPENSSL_API versions defined"
  1348. #endif
  1349. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1350. #error "Multiple OPENSSL_API versions defined"
  1351. #endif
  1352. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1353. || defined(OPENSSL_API_3_0)) \
  1354. && (defined(USE_MBEDTLS) || defined(USE_GNUTLS))
  1355. #error "Multiple SSL libraries defined"
  1356. #endif
  1357. #if defined(USE_MBEDTLS) && defined(USE_GNUTLS)
  1358. #error "Multiple SSL libraries defined"
  1359. #endif
  1360. #endif
  1361. static pthread_key_t sTlsKey; /* Thread local storage index */
  1362. static volatile ptrdiff_t thread_idx_max = 0;
  1363. #if defined(MG_LEGACY_INTERFACE)
  1364. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1365. #endif
  1366. struct mg_workerTLS {
  1367. int is_master;
  1368. unsigned long thread_idx;
  1369. void *user_ptr;
  1370. #if defined(_WIN32)
  1371. HANDLE pthread_cond_helper_mutex;
  1372. struct mg_workerTLS *next_waiting_thread;
  1373. #endif
  1374. const char *alpn_proto;
  1375. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1376. char txtbuf[4];
  1377. #endif
  1378. };
  1379. #if defined(GCC_DIAGNOSTIC)
  1380. /* Show no warning in case system functions are not used. */
  1381. #pragma GCC diagnostic push
  1382. #pragma GCC diagnostic ignored "-Wunused-function"
  1383. #endif /* defined(GCC_DIAGNOSTIC) */
  1384. #if defined(__clang__)
  1385. /* Show no warning in case system functions are not used. */
  1386. #pragma clang diagnostic push
  1387. #pragma clang diagnostic ignored "-Wunused-function"
  1388. #endif
  1389. /* Get a unique thread ID as unsigned long, independent from the data type
  1390. * of thread IDs defined by the operating system API.
  1391. * If two calls to mg_current_thread_id return the same value, they calls
  1392. * are done from the same thread. If they return different values, they are
  1393. * done from different threads. (Provided this function is used in the same
  1394. * process context and threads are not repeatedly created and deleted, but
  1395. * CivetWeb does not do that).
  1396. * This function must match the signature required for SSL id callbacks:
  1397. * CRYPTO_set_id_callback
  1398. */
  1399. FUNCTION_MAY_BE_UNUSED
  1400. static unsigned long
  1401. mg_current_thread_id(void)
  1402. {
  1403. #if defined(_WIN32)
  1404. return GetCurrentThreadId();
  1405. #else
  1406. #if defined(__clang__)
  1407. #pragma clang diagnostic push
  1408. #pragma clang diagnostic ignored "-Wunreachable-code"
  1409. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1410. * or not, so one of the two conditions will be unreachable by construction.
  1411. * Unfortunately the C standard does not define a way to check this at
  1412. * compile time, since the #if preprocessor conditions can not use the
  1413. * sizeof operator as an argument. */
  1414. #endif
  1415. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1416. /* This is the problematic case for CRYPTO_set_id_callback:
  1417. * The OS pthread_t can not be cast to unsigned long. */
  1418. struct mg_workerTLS *tls =
  1419. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1420. if (tls == NULL) {
  1421. /* SSL called from an unknown thread: Create some thread index.
  1422. */
  1423. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1424. tls->is_master = -2; /* -2 means "3rd party thread" */
  1425. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1426. pthread_setspecific(sTlsKey, tls);
  1427. }
  1428. return tls->thread_idx;
  1429. } else {
  1430. /* pthread_t may be any data type, so a simple cast to unsigned long
  1431. * can rise a warning/error, depending on the platform.
  1432. * Here memcpy is used as an anything-to-anything cast. */
  1433. unsigned long ret = 0;
  1434. pthread_t t = pthread_self();
  1435. memcpy(&ret, &t, sizeof(pthread_t));
  1436. return ret;
  1437. }
  1438. #if defined(__clang__)
  1439. #pragma clang diagnostic pop
  1440. #endif
  1441. #endif
  1442. }
  1443. FUNCTION_MAY_BE_UNUSED
  1444. static uint64_t
  1445. mg_get_current_time_ns(void)
  1446. {
  1447. struct timespec tsnow;
  1448. clock_gettime(CLOCK_REALTIME, &tsnow);
  1449. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1450. }
  1451. #if defined(GCC_DIAGNOSTIC)
  1452. /* Show no warning in case system functions are not used. */
  1453. #pragma GCC diagnostic pop
  1454. #endif /* defined(GCC_DIAGNOSTIC) */
  1455. #if defined(__clang__)
  1456. /* Show no warning in case system functions are not used. */
  1457. #pragma clang diagnostic pop
  1458. #endif
  1459. #if defined(NEED_DEBUG_TRACE_FUNC)
  1460. static void
  1461. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1462. {
  1463. va_list args;
  1464. struct timespec tsnow;
  1465. /* Get some operating system independent thread id */
  1466. unsigned long thread_id = mg_current_thread_id();
  1467. clock_gettime(CLOCK_REALTIME, &tsnow);
  1468. flockfile(DEBUG_TRACE_STREAM);
  1469. fprintf(DEBUG_TRACE_STREAM,
  1470. "*** %lu.%09lu %lu %s:%u: ",
  1471. (unsigned long)tsnow.tv_sec,
  1472. (unsigned long)tsnow.tv_nsec,
  1473. thread_id,
  1474. func,
  1475. line);
  1476. va_start(args, fmt);
  1477. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1478. va_end(args);
  1479. putc('\n', DEBUG_TRACE_STREAM);
  1480. fflush(DEBUG_TRACE_STREAM);
  1481. funlockfile(DEBUG_TRACE_STREAM);
  1482. }
  1483. #endif /* NEED_DEBUG_TRACE_FUNC */
  1484. #define MD5_STATIC static
  1485. #include "md5.inl"
  1486. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1487. #if defined(NO_SOCKLEN_T)
  1488. typedef int socklen_t;
  1489. #endif /* NO_SOCKLEN_T */
  1490. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1491. #if !defined(MSG_NOSIGNAL)
  1492. #define MSG_NOSIGNAL (0)
  1493. #endif
  1494. /* SSL: mbedTLS vs. GnuTLS vs. no-ssl vs. OpenSSL */
  1495. #if defined(USE_MBEDTLS)
  1496. /* mbedTLS */
  1497. #include "mod_mbedtls.inl"
  1498. #elif defined(USE_GNUTLS)
  1499. /* GnuTLS */
  1500. #include "mod_gnutls.inl"
  1501. #elif defined(NO_SSL)
  1502. /* no SSL */
  1503. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1504. typedef struct SSL_CTX SSL_CTX;
  1505. #elif defined(NO_SSL_DL)
  1506. /* OpenSSL without dynamic loading */
  1507. #include <openssl/bn.h>
  1508. #include <openssl/conf.h>
  1509. #include <openssl/crypto.h>
  1510. #include <openssl/dh.h>
  1511. #include <openssl/engine.h>
  1512. #include <openssl/err.h>
  1513. #include <openssl/opensslv.h>
  1514. #include <openssl/pem.h>
  1515. #include <openssl/ssl.h>
  1516. #include <openssl/tls1.h>
  1517. #include <openssl/x509.h>
  1518. #if defined(WOLFSSL_VERSION)
  1519. /* Additional defines for WolfSSL, see
  1520. * https://github.com/civetweb/civetweb/issues/583 */
  1521. #include "wolfssl_extras.inl"
  1522. #endif
  1523. #if defined(OPENSSL_IS_BORINGSSL)
  1524. /* From boringssl/src/include/openssl/mem.h:
  1525. *
  1526. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1527. * However, that was written in a time before Valgrind and ASAN. Since we now
  1528. * have those tools, the OpenSSL allocation functions are simply macros around
  1529. * the standard memory functions.
  1530. *
  1531. * #define OPENSSL_free free */
  1532. #define free free
  1533. // disable for boringssl
  1534. #define CONF_modules_unload(a) ((void)0)
  1535. #define ENGINE_cleanup() ((void)0)
  1536. #endif
  1537. /* If OpenSSL headers are included, automatically select the API version */
  1538. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1539. #if !defined(OPENSSL_API_3_0)
  1540. #define OPENSSL_API_3_0
  1541. #endif
  1542. #define OPENSSL_REMOVE_THREAD_STATE()
  1543. #else
  1544. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1545. #if !defined(OPENSSL_API_1_1)
  1546. #define OPENSSL_API_1_1
  1547. #endif
  1548. #define OPENSSL_REMOVE_THREAD_STATE()
  1549. #else
  1550. #if !defined(OPENSSL_API_1_0)
  1551. #define OPENSSL_API_1_0
  1552. #endif
  1553. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1554. #endif
  1555. #endif
  1556. #else
  1557. /* SSL loaded dynamically from DLL / shared object */
  1558. /* Add all prototypes here, to be independent from OpenSSL source
  1559. * installation. */
  1560. #include "openssl_dl.inl"
  1561. #endif /* Various SSL bindings */
  1562. #if !defined(NO_CACHING)
  1563. static const char month_names[][4] = {"Jan",
  1564. "Feb",
  1565. "Mar",
  1566. "Apr",
  1567. "May",
  1568. "Jun",
  1569. "Jul",
  1570. "Aug",
  1571. "Sep",
  1572. "Oct",
  1573. "Nov",
  1574. "Dec"};
  1575. #endif /* !NO_CACHING */
  1576. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1577. * the union u. */
  1578. union usa {
  1579. struct sockaddr sa;
  1580. struct sockaddr_in sin;
  1581. #if defined(USE_IPV6)
  1582. struct sockaddr_in6 sin6;
  1583. #endif
  1584. #if defined(USE_X_DOM_SOCKET)
  1585. struct sockaddr_un sun;
  1586. #endif
  1587. };
  1588. #if defined(USE_X_DOM_SOCKET)
  1589. static unsigned short
  1590. USA_IN_PORT_UNSAFE(union usa *s)
  1591. {
  1592. if (s->sa.sa_family == AF_INET)
  1593. return s->sin.sin_port;
  1594. #if defined(USE_IPV6)
  1595. if (s->sa.sa_family == AF_INET6)
  1596. return s->sin6.sin6_port;
  1597. #endif
  1598. return 0;
  1599. }
  1600. #endif
  1601. #if defined(USE_IPV6)
  1602. #define USA_IN_PORT_UNSAFE(s) \
  1603. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1604. #else
  1605. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1606. #endif
  1607. /* Describes a string (chunk of memory). */
  1608. struct vec {
  1609. const char *ptr;
  1610. size_t len;
  1611. };
  1612. struct mg_file_stat {
  1613. /* File properties filled by mg_stat: */
  1614. uint64_t size;
  1615. time_t last_modified;
  1616. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1617. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1618. * case we need a "Content-Eencoding: gzip" header */
  1619. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1620. };
  1621. struct mg_file_access {
  1622. /* File properties filled by mg_fopen: */
  1623. FILE *fp;
  1624. };
  1625. struct mg_file {
  1626. struct mg_file_stat stat;
  1627. struct mg_file_access access;
  1628. };
  1629. #define STRUCT_FILE_INITIALIZER \
  1630. { \
  1631. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1632. { \
  1633. (FILE *)NULL \
  1634. } \
  1635. }
  1636. /* Describes listening socket, or socket which was accept()-ed by the master
  1637. * thread and queued for future handling by the worker thread. */
  1638. struct socket {
  1639. SOCKET sock; /* Listening socket */
  1640. union usa lsa; /* Local socket address */
  1641. union usa rsa; /* Remote socket address */
  1642. unsigned char is_ssl; /* Is port SSL-ed */
  1643. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1644. * port */
  1645. unsigned char
  1646. is_optional; /* Shouldn't cause us to exit if we can't bind to it */
  1647. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1648. };
  1649. /* Enum const for all options must be in sync with
  1650. * static struct mg_option config_options[]
  1651. * This is tested in the unit test (test/private.c)
  1652. * "Private Config Options"
  1653. */
  1654. enum {
  1655. /* Once for each server */
  1656. LISTENING_PORTS,
  1657. NUM_THREADS,
  1658. PRESPAWN_THREADS,
  1659. RUN_AS_USER,
  1660. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1661. * socket option typedef TCP_NODELAY. */
  1662. MAX_REQUEST_SIZE,
  1663. LINGER_TIMEOUT,
  1664. CONNECTION_QUEUE_SIZE,
  1665. LISTEN_BACKLOG_SIZE,
  1666. #if defined(__linux__)
  1667. ALLOW_SENDFILE_CALL,
  1668. #endif
  1669. #if defined(_WIN32)
  1670. CASE_SENSITIVE_FILES,
  1671. #endif
  1672. THROTTLE,
  1673. ENABLE_KEEP_ALIVE,
  1674. REQUEST_TIMEOUT,
  1675. KEEP_ALIVE_TIMEOUT,
  1676. #if defined(USE_WEBSOCKET)
  1677. WEBSOCKET_TIMEOUT,
  1678. ENABLE_WEBSOCKET_PING_PONG,
  1679. #endif
  1680. DECODE_URL,
  1681. DECODE_QUERY_STRING,
  1682. #if defined(USE_LUA)
  1683. LUA_BACKGROUND_SCRIPT,
  1684. LUA_BACKGROUND_SCRIPT_PARAMS,
  1685. #endif
  1686. #if defined(USE_HTTP2)
  1687. ENABLE_HTTP2,
  1688. #endif
  1689. /* Once for each domain */
  1690. DOCUMENT_ROOT,
  1691. FALLBACK_DOCUMENT_ROOT,
  1692. ACCESS_LOG_FILE,
  1693. ERROR_LOG_FILE,
  1694. CGI_EXTENSIONS,
  1695. CGI_ENVIRONMENT,
  1696. CGI_INTERPRETER,
  1697. CGI_INTERPRETER_ARGS,
  1698. #if defined(USE_TIMERS)
  1699. CGI_TIMEOUT,
  1700. #endif
  1701. CGI_BUFFERING,
  1702. CGI2_EXTENSIONS,
  1703. CGI2_ENVIRONMENT,
  1704. CGI2_INTERPRETER,
  1705. CGI2_INTERPRETER_ARGS,
  1706. #if defined(USE_TIMERS)
  1707. CGI2_TIMEOUT,
  1708. #endif
  1709. CGI2_BUFFERING,
  1710. #if defined(USE_4_CGI)
  1711. CGI3_EXTENSIONS,
  1712. CGI3_ENVIRONMENT,
  1713. CGI3_INTERPRETER,
  1714. CGI3_INTERPRETER_ARGS,
  1715. #if defined(USE_TIMERS)
  1716. CGI3_TIMEOUT,
  1717. #endif
  1718. CGI3_BUFFERING,
  1719. CGI4_EXTENSIONS,
  1720. CGI4_ENVIRONMENT,
  1721. CGI4_INTERPRETER,
  1722. CGI4_INTERPRETER_ARGS,
  1723. #if defined(USE_TIMERS)
  1724. CGI4_TIMEOUT,
  1725. #endif
  1726. CGI4_BUFFERING,
  1727. #endif
  1728. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1729. PROTECT_URI,
  1730. AUTHENTICATION_DOMAIN,
  1731. ENABLE_AUTH_DOMAIN_CHECK,
  1732. SSI_EXTENSIONS,
  1733. ENABLE_DIRECTORY_LISTING,
  1734. ENABLE_WEBDAV,
  1735. GLOBAL_PASSWORDS_FILE,
  1736. INDEX_FILES,
  1737. ACCESS_CONTROL_LIST,
  1738. EXTRA_MIME_TYPES,
  1739. SSL_CERTIFICATE,
  1740. SSL_CERTIFICATE_CHAIN,
  1741. URL_REWRITE_PATTERN,
  1742. HIDE_FILES,
  1743. SSL_DO_VERIFY_PEER,
  1744. SSL_CACHE_TIMEOUT,
  1745. SSL_CA_PATH,
  1746. SSL_CA_FILE,
  1747. SSL_VERIFY_DEPTH,
  1748. SSL_DEFAULT_VERIFY_PATHS,
  1749. SSL_CIPHER_LIST,
  1750. SSL_PROTOCOL_VERSION,
  1751. SSL_SHORT_TRUST,
  1752. #if defined(USE_LUA)
  1753. LUA_PRELOAD_FILE,
  1754. LUA_SCRIPT_EXTENSIONS,
  1755. LUA_SERVER_PAGE_EXTENSIONS,
  1756. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1757. LUA_DEBUG_PARAMS,
  1758. #endif
  1759. #endif
  1760. #if defined(USE_DUKTAPE)
  1761. DUKTAPE_SCRIPT_EXTENSIONS,
  1762. #endif
  1763. #if defined(USE_WEBSOCKET)
  1764. WEBSOCKET_ROOT,
  1765. FALLBACK_WEBSOCKET_ROOT,
  1766. #endif
  1767. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1768. LUA_WEBSOCKET_EXTENSIONS,
  1769. #endif
  1770. REPLACE_ASTERISK_WITH_ORIGIN,
  1771. ACCESS_CONTROL_ALLOW_ORIGIN,
  1772. ACCESS_CONTROL_ALLOW_METHODS,
  1773. ACCESS_CONTROL_ALLOW_HEADERS,
  1774. ACCESS_CONTROL_EXPOSE_HEADERS,
  1775. ACCESS_CONTROL_ALLOW_CREDENTIALS,
  1776. ERROR_PAGES,
  1777. #if !defined(NO_CACHING)
  1778. STATIC_FILE_MAX_AGE,
  1779. STATIC_FILE_CACHE_CONTROL,
  1780. #endif
  1781. #if !defined(NO_SSL)
  1782. STRICT_HTTPS_MAX_AGE,
  1783. #endif
  1784. ADDITIONAL_HEADER,
  1785. ALLOW_INDEX_SCRIPT_SUB_RES,
  1786. NUM_OPTIONS
  1787. };
  1788. /* Config option name, config types, default value.
  1789. * Must be in the same order as the enum const above.
  1790. */
  1791. static const struct mg_option config_options[] = {
  1792. /* Once for each server */
  1793. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1794. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1795. {"prespawn_threads", MG_CONFIG_TYPE_NUMBER, "0"},
  1796. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1797. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1798. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1799. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1800. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1801. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1802. #if defined(__linux__)
  1803. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1804. #endif
  1805. #if defined(_WIN32)
  1806. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1807. #endif
  1808. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1809. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1810. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1811. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1812. #if defined(USE_WEBSOCKET)
  1813. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1814. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1815. #endif
  1816. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1817. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1818. #if defined(USE_LUA)
  1819. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1820. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1821. #endif
  1822. #if defined(USE_HTTP2)
  1823. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1824. #endif
  1825. /* Once for each domain */
  1826. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1827. {"fallback_document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1828. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1829. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1830. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1831. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1832. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1833. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1834. #if defined(USE_TIMERS)
  1835. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1836. #endif
  1837. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1838. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1839. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1840. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1841. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1842. #if defined(USE_TIMERS)
  1843. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1844. #endif
  1845. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1846. #if defined(USE_4_CGI)
  1847. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1848. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1849. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1850. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1851. #if defined(USE_TIMERS)
  1852. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1853. #endif
  1854. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1855. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1856. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1857. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1858. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1859. #if defined(USE_TIMERS)
  1860. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1861. #endif
  1862. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1863. #endif
  1864. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1865. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1866. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1867. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1868. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1869. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1870. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1871. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1872. {"index_files",
  1873. MG_CONFIG_TYPE_STRING_LIST,
  1874. #if defined(USE_LUA)
  1875. "index.xhtml,index.html,index.htm,"
  1876. "index.lp,index.lsp,index.lua,index.cgi,"
  1877. "index.shtml,index.php"},
  1878. #else
  1879. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1880. #endif
  1881. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1882. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1883. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1884. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1885. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1886. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1887. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1888. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1889. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1890. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1891. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1892. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1893. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1894. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1895. * as a minimum in 2020 */
  1896. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1897. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1898. #if defined(USE_LUA)
  1899. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1900. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1901. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1902. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1903. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1904. #endif
  1905. #endif
  1906. #if defined(USE_DUKTAPE)
  1907. /* The support for duktape is still in alpha version state.
  1908. * The name of this config option might change. */
  1909. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1910. #endif
  1911. #if defined(USE_WEBSOCKET)
  1912. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1913. {"fallback_websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1914. #endif
  1915. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1916. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1917. #endif
  1918. {"replace_asterisk_with_origin", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1919. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1920. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1921. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1922. {"access_control_expose_headers", MG_CONFIG_TYPE_STRING, ""},
  1923. {"access_control_allow_credentials", MG_CONFIG_TYPE_STRING, ""},
  1924. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1925. #if !defined(NO_CACHING)
  1926. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1927. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1928. #endif
  1929. #if !defined(NO_SSL)
  1930. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1931. #endif
  1932. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1933. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1934. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1935. /* Check if the config_options and the corresponding enum have compatible
  1936. * sizes. */
  1937. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1938. == (NUM_OPTIONS + 1),
  1939. "config_options and enum not sync");
  1940. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1941. struct mg_handler_info {
  1942. /* Name/Pattern of the URI. */
  1943. char *uri;
  1944. size_t uri_len;
  1945. /* handler type */
  1946. int handler_type;
  1947. /* Handler for http/https or requests. */
  1948. mg_request_handler handler;
  1949. unsigned int refcount;
  1950. int removing;
  1951. /* Handler for ws/wss (websocket) requests. */
  1952. mg_websocket_connect_handler connect_handler;
  1953. mg_websocket_ready_handler ready_handler;
  1954. mg_websocket_data_handler data_handler;
  1955. mg_websocket_close_handler close_handler;
  1956. /* accepted subprotocols for ws/wss requests. */
  1957. struct mg_websocket_subprotocols *subprotocols;
  1958. /* Handler for authorization requests */
  1959. mg_authorization_handler auth_handler;
  1960. /* User supplied argument for the handler function. */
  1961. void *cbdata;
  1962. /* next handler in a linked list */
  1963. struct mg_handler_info *next;
  1964. };
  1965. enum {
  1966. CONTEXT_INVALID,
  1967. CONTEXT_SERVER,
  1968. CONTEXT_HTTP_CLIENT,
  1969. CONTEXT_WS_CLIENT
  1970. };
  1971. struct mg_domain_context {
  1972. SSL_CTX *ssl_ctx; /* SSL context */
  1973. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1974. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1975. int64_t ssl_cert_last_mtime;
  1976. /* Server nonce */
  1977. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1978. unsigned long nonce_count; /* Used nonces, used for authentication */
  1979. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1980. /* linked list of shared lua websockets */
  1981. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1982. #endif
  1983. /* Linked list of domains */
  1984. struct mg_domain_context *next;
  1985. };
  1986. /* Stop flag can be "volatile" or require a lock.
  1987. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1988. * states a read operation for int is always atomic. */
  1989. #if defined(STOP_FLAG_NEEDS_LOCK)
  1990. typedef ptrdiff_t volatile stop_flag_t;
  1991. static int
  1992. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1993. {
  1994. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1995. return (sf == 0);
  1996. }
  1997. static int
  1998. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1999. {
  2000. stop_flag_t sf = mg_atomic_add(f, 0);
  2001. return (sf == 2);
  2002. }
  2003. static void
  2004. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2005. {
  2006. stop_flag_t sf = 0;
  2007. do {
  2008. sf = mg_atomic_compare_and_swap(f,
  2009. __atomic_load_n(f, __ATOMIC_SEQ_CST),
  2010. v);
  2011. } while (sf != v);
  2012. }
  2013. #else /* STOP_FLAG_NEEDS_LOCK */
  2014. typedef int volatile stop_flag_t;
  2015. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2016. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2017. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2018. #endif /* STOP_FLAG_NEEDS_LOCK */
  2019. #if !defined(NUM_WEBDAV_LOCKS)
  2020. #define NUM_WEBDAV_LOCKS 10
  2021. #endif
  2022. #if !defined(LOCK_DURATION_S)
  2023. #define LOCK_DURATION_S 60
  2024. #endif
  2025. struct twebdav_lock {
  2026. uint64_t locktime;
  2027. char token[33];
  2028. char path[UTF8_PATH_MAX * 2];
  2029. char user[UTF8_PATH_MAX * 2];
  2030. };
  2031. struct mg_context {
  2032. /* Part 1 - Physical context:
  2033. * This holds threads, ports, timeouts, ...
  2034. * set for the entire server, independent from the
  2035. * addressed hostname.
  2036. */
  2037. /* Connection related */
  2038. int context_type; /* See CONTEXT_* above */
  2039. struct socket *listening_sockets;
  2040. struct mg_pollfd *listening_socket_fds;
  2041. unsigned int num_listening_sockets;
  2042. struct mg_connection *worker_connections; /* The connection struct, pre-
  2043. * allocated for each worker */
  2044. #if defined(USE_SERVER_STATS)
  2045. volatile ptrdiff_t active_connections;
  2046. volatile ptrdiff_t max_active_connections;
  2047. volatile ptrdiff_t total_connections;
  2048. volatile ptrdiff_t total_requests;
  2049. volatile int64_t total_data_read;
  2050. volatile int64_t total_data_written;
  2051. #endif
  2052. /* Thread related */
  2053. stop_flag_t stop_flag; /* Should we stop event loop */
  2054. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2055. pthread_t masterthreadid; /* The master thread ID */
  2056. unsigned int cfg_max_worker_threads; /* How many worker-threads we are
  2057. allowed to create, total */
  2058. unsigned int spawned_worker_threads; /* How many worker-threads currently
  2059. exist (modified by master thread) */
  2060. unsigned int
  2061. idle_worker_thread_count; /* How many worker-threads are currently
  2062. sitting around with nothing to do */
  2063. /* Access to this value MUST be synchronized by thread_mutex */
  2064. pthread_t *worker_threadids; /* The worker thread IDs */
  2065. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2066. /* Connection to thread dispatching */
  2067. #if defined(ALTERNATIVE_QUEUE)
  2068. struct socket *client_socks;
  2069. void **client_wait_events;
  2070. #else
  2071. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2072. worker thread */
  2073. volatile int sq_head; /* Head of the socket queue */
  2074. volatile int sq_tail; /* Tail of the socket queue */
  2075. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2076. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2077. volatile int sq_blocked; /* Status information: sq is full */
  2078. int sq_size; /* No of elements in socket queue */
  2079. #if defined(USE_SERVER_STATS)
  2080. int sq_max_fill;
  2081. #endif /* USE_SERVER_STATS */
  2082. #endif /* ALTERNATIVE_QUEUE */
  2083. /* Memory related */
  2084. unsigned int max_request_size; /* The max request size */
  2085. #if defined(USE_SERVER_STATS)
  2086. struct mg_memory_stat ctx_memory;
  2087. #endif
  2088. /* WebDAV lock structures */
  2089. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2090. /* Operating system related */
  2091. char *systemName; /* What operating system is running */
  2092. time_t start_time; /* Server start time, used for authentication
  2093. * and for diagnstics. */
  2094. #if defined(USE_TIMERS)
  2095. struct ttimers *timers;
  2096. #endif
  2097. /* Lua specific: Background operations and shared websockets */
  2098. #if defined(USE_LUA)
  2099. void *lua_background_state; /* lua_State (here as void *) */
  2100. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2101. int lua_bg_log_available; /* Use Lua background state for access log */
  2102. #endif
  2103. int user_shutdown_notification_socket; /* mg_stop() will close this
  2104. socket... */
  2105. int thread_shutdown_notification_socket; /* to cause poll() in all threads
  2106. to return immediately */
  2107. /* Server nonce */
  2108. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2109. * ssl_cert_last_mtime, nonce_count, and
  2110. * next (linked list) */
  2111. /* Server callbacks */
  2112. struct mg_callbacks callbacks; /* User-defined callback function */
  2113. void *user_data; /* User-defined data */
  2114. /* Part 2 - Logical domain:
  2115. * This holds hostname, TLS certificate, document root, ...
  2116. * set for a domain hosted at the server.
  2117. * There may be multiple domains hosted at one physical server.
  2118. * The default domain "dd" is the first element of a list of
  2119. * domains.
  2120. */
  2121. struct mg_domain_context dd; /* default domain */
  2122. };
  2123. #if defined(USE_SERVER_STATS)
  2124. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2125. static struct mg_memory_stat *
  2126. get_memory_stat(struct mg_context *ctx)
  2127. {
  2128. if (ctx) {
  2129. return &(ctx->ctx_memory);
  2130. }
  2131. return &mg_common_memory;
  2132. }
  2133. #endif
  2134. enum {
  2135. CONNECTION_TYPE_INVALID = 0,
  2136. CONNECTION_TYPE_REQUEST = 1,
  2137. CONNECTION_TYPE_RESPONSE = 2
  2138. };
  2139. enum {
  2140. PROTOCOL_TYPE_HTTP1 = 0,
  2141. PROTOCOL_TYPE_WEBSOCKET = 1,
  2142. PROTOCOL_TYPE_HTTP2 = 2
  2143. };
  2144. #if defined(USE_HTTP2)
  2145. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2146. #define HTTP2_DYN_TABLE_SIZE (256)
  2147. #endif
  2148. struct mg_http2_connection {
  2149. uint32_t stream_id;
  2150. uint32_t dyn_table_size;
  2151. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2152. };
  2153. #endif
  2154. struct mg_connection {
  2155. int connection_type; /* see CONNECTION_TYPE_* above */
  2156. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2157. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2158. fully sent */
  2159. #if defined(USE_HTTP2)
  2160. struct mg_http2_connection http2;
  2161. #endif
  2162. struct mg_request_info request_info;
  2163. struct mg_response_info response_info;
  2164. struct mg_context *phys_ctx;
  2165. struct mg_domain_context *dom_ctx;
  2166. #if defined(USE_SERVER_STATS)
  2167. int conn_state; /* 0 = undef, numerical value may change in different
  2168. * versions. For the current definition, see
  2169. * mg_get_connection_info_impl */
  2170. #endif
  2171. SSL *ssl; /* SSL descriptor */
  2172. struct socket client; /* Connected client */
  2173. time_t conn_birth_time; /* Time (wall clock) when connection was
  2174. * established */
  2175. #if defined(USE_SERVER_STATS)
  2176. time_t conn_close_time; /* Time (wall clock) when connection was
  2177. * closed (or 0 if still open) */
  2178. double processing_time; /* Processing time for one request. */
  2179. #endif
  2180. struct timespec req_time; /* Time (since system start) when the request
  2181. * was received */
  2182. int64_t num_bytes_sent; /* Total bytes sent to client */
  2183. int64_t content_len; /* How many bytes of content can be read
  2184. * !is_chunked: Content-Length header value
  2185. * or -1 (until connection closed,
  2186. * not allowed for a request)
  2187. * is_chunked: >= 0, appended gradually
  2188. */
  2189. int64_t consumed_content; /* How many bytes of content have been read */
  2190. int is_chunked; /* Transfer-Encoding is chunked:
  2191. * 0 = not chunked,
  2192. * 1 = chunked, not yet, or some data read,
  2193. * 2 = chunked, has error,
  2194. * 3 = chunked, all data read except trailer,
  2195. * 4 = chunked, all data read
  2196. */
  2197. char *buf; /* Buffer for received data */
  2198. char *path_info; /* PATH_INFO part of the URL */
  2199. int must_close; /* 1 if connection must be closed */
  2200. int accept_gzip; /* 1 if gzip encoding is accepted */
  2201. int in_error_handler; /* 1 if in handler for user defined error
  2202. * pages */
  2203. #if defined(USE_WEBSOCKET)
  2204. int in_websocket_handling; /* 1 if in read_websocket */
  2205. #endif
  2206. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2207. && defined(MG_EXPERIMENTAL_INTERFACES)
  2208. /* Parameters for websocket data compression according to rfc7692 */
  2209. int websocket_deflate_server_max_windows_bits;
  2210. int websocket_deflate_client_max_windows_bits;
  2211. int websocket_deflate_server_no_context_takeover;
  2212. int websocket_deflate_client_no_context_takeover;
  2213. int websocket_deflate_initialized;
  2214. int websocket_deflate_flush;
  2215. z_stream websocket_deflate_state;
  2216. z_stream websocket_inflate_state;
  2217. #endif
  2218. int handled_requests; /* Number of requests handled by this connection
  2219. */
  2220. int buf_size; /* Buffer size */
  2221. int request_len; /* Size of the request + headers in a buffer */
  2222. int data_len; /* Total size of data in a buffer */
  2223. int status_code; /* HTTP reply status code, e.g. 200 */
  2224. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2225. * throttle */
  2226. time_t last_throttle_time; /* Last time throttled data was sent */
  2227. int last_throttle_bytes; /* Bytes sent this second */
  2228. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2229. * atomic transmissions for websockets */
  2230. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2231. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2232. #endif
  2233. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2234. * for quick access */
  2235. };
  2236. /* Directory entry */
  2237. struct de {
  2238. char *file_name;
  2239. struct mg_file_stat file;
  2240. };
  2241. #define mg_cry_internal(conn, fmt, ...) \
  2242. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2243. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2244. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2245. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2246. struct mg_context *ctx,
  2247. const char *func,
  2248. unsigned line,
  2249. const char *fmt,
  2250. ...) PRINTF_ARGS(5, 6);
  2251. #if !defined(NO_THREAD_NAME)
  2252. #if defined(_WIN32) && defined(_MSC_VER)
  2253. /* Set the thread name for debugging purposes in Visual Studio
  2254. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2255. */
  2256. #pragma pack(push, 8)
  2257. typedef struct tagTHREADNAME_INFO {
  2258. DWORD dwType; /* Must be 0x1000. */
  2259. LPCSTR szName; /* Pointer to name (in user addr space). */
  2260. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2261. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2262. } THREADNAME_INFO;
  2263. #pragma pack(pop)
  2264. #elif defined(__linux__)
  2265. #include <sys/prctl.h>
  2266. #include <sys/sendfile.h>
  2267. #if defined(ALTERNATIVE_QUEUE)
  2268. #include <sys/eventfd.h>
  2269. #endif /* ALTERNATIVE_QUEUE */
  2270. #if defined(ALTERNATIVE_QUEUE)
  2271. static void *
  2272. event_create(void)
  2273. {
  2274. int evhdl = eventfd(0, EFD_CLOEXEC);
  2275. int *ret;
  2276. if (evhdl == -1) {
  2277. /* Linux uses -1 on error, Windows NULL. */
  2278. /* However, Linux does not return 0 on success either. */
  2279. return 0;
  2280. }
  2281. ret = (int *)mg_malloc(sizeof(int));
  2282. if (ret) {
  2283. *ret = evhdl;
  2284. } else {
  2285. (void)close(evhdl);
  2286. }
  2287. return (void *)ret;
  2288. }
  2289. static int
  2290. event_wait(void *eventhdl)
  2291. {
  2292. uint64_t u;
  2293. int evhdl, s;
  2294. if (!eventhdl) {
  2295. /* error */
  2296. return 0;
  2297. }
  2298. evhdl = *(int *)eventhdl;
  2299. s = (int)read(evhdl, &u, sizeof(u));
  2300. if (s != sizeof(u)) {
  2301. /* error */
  2302. return 0;
  2303. }
  2304. (void)u; /* the value is not required */
  2305. return 1;
  2306. }
  2307. static int
  2308. event_signal(void *eventhdl)
  2309. {
  2310. uint64_t u = 1;
  2311. int evhdl, s;
  2312. if (!eventhdl) {
  2313. /* error */
  2314. return 0;
  2315. }
  2316. evhdl = *(int *)eventhdl;
  2317. s = (int)write(evhdl, &u, sizeof(u));
  2318. if (s != sizeof(u)) {
  2319. /* error */
  2320. return 0;
  2321. }
  2322. return 1;
  2323. }
  2324. static void
  2325. event_destroy(void *eventhdl)
  2326. {
  2327. int evhdl;
  2328. if (!eventhdl) {
  2329. /* error */
  2330. return;
  2331. }
  2332. evhdl = *(int *)eventhdl;
  2333. close(evhdl);
  2334. mg_free(eventhdl);
  2335. }
  2336. #endif
  2337. #endif
  2338. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2339. struct posix_event {
  2340. pthread_mutex_t mutex;
  2341. pthread_cond_t cond;
  2342. int signaled;
  2343. };
  2344. static void *
  2345. event_create(void)
  2346. {
  2347. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2348. if (ret == 0) {
  2349. /* out of memory */
  2350. return 0;
  2351. }
  2352. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2353. /* pthread mutex not available */
  2354. mg_free(ret);
  2355. return 0;
  2356. }
  2357. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2358. /* pthread cond not available */
  2359. pthread_mutex_destroy(&(ret->mutex));
  2360. mg_free(ret);
  2361. return 0;
  2362. }
  2363. ret->signaled = 0;
  2364. return (void *)ret;
  2365. }
  2366. static int
  2367. event_wait(void *eventhdl)
  2368. {
  2369. struct posix_event *ev = (struct posix_event *)eventhdl;
  2370. pthread_mutex_lock(&(ev->mutex));
  2371. while (!ev->signaled) {
  2372. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2373. }
  2374. ev->signaled = 0;
  2375. pthread_mutex_unlock(&(ev->mutex));
  2376. return 1;
  2377. }
  2378. static int
  2379. event_signal(void *eventhdl)
  2380. {
  2381. struct posix_event *ev = (struct posix_event *)eventhdl;
  2382. pthread_mutex_lock(&(ev->mutex));
  2383. pthread_cond_signal(&(ev->cond));
  2384. ev->signaled = 1;
  2385. pthread_mutex_unlock(&(ev->mutex));
  2386. return 1;
  2387. }
  2388. static void
  2389. event_destroy(void *eventhdl)
  2390. {
  2391. struct posix_event *ev = (struct posix_event *)eventhdl;
  2392. pthread_cond_destroy(&(ev->cond));
  2393. pthread_mutex_destroy(&(ev->mutex));
  2394. mg_free(ev);
  2395. }
  2396. #endif
  2397. static void
  2398. mg_set_thread_name(const char *name)
  2399. {
  2400. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2401. mg_snprintf(
  2402. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2403. #if defined(_WIN32)
  2404. #if defined(_MSC_VER)
  2405. /* Windows and Visual Studio Compiler */
  2406. __try {
  2407. THREADNAME_INFO info;
  2408. info.dwType = 0x1000;
  2409. info.szName = threadName;
  2410. info.dwThreadID = ~0U;
  2411. info.dwFlags = 0;
  2412. RaiseException(0x406D1388,
  2413. 0,
  2414. sizeof(info) / sizeof(ULONG_PTR),
  2415. (ULONG_PTR *)&info);
  2416. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2417. }
  2418. #elif defined(__MINGW32__)
  2419. /* No option known to set thread name for MinGW known */
  2420. #endif
  2421. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2422. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2423. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2424. #if defined(__MACH__) && defined(__APPLE__)
  2425. /* OS X only current thread name can be changed */
  2426. (void)pthread_setname_np(threadName);
  2427. #else
  2428. (void)pthread_setname_np(pthread_self(), threadName);
  2429. #endif
  2430. #elif defined(__linux__)
  2431. /* On Linux we can use the prctl function.
  2432. * When building for Linux Standard Base (LSB) use
  2433. * NO_THREAD_NAME. However, thread names are a big
  2434. * help for debugging, so the stadard is to set them.
  2435. */
  2436. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2437. #endif
  2438. }
  2439. #else /* !defined(NO_THREAD_NAME) */
  2440. static void
  2441. mg_set_thread_name(const char *threadName)
  2442. {
  2443. }
  2444. #endif
  2445. CIVETWEB_API const struct mg_option *
  2446. mg_get_valid_options(void)
  2447. {
  2448. return config_options;
  2449. }
  2450. /* Do not open file (unused) */
  2451. #define MG_FOPEN_MODE_NONE (0)
  2452. /* Open file for read only access */
  2453. #define MG_FOPEN_MODE_READ (1)
  2454. /* Open file for writing, create and overwrite */
  2455. #define MG_FOPEN_MODE_WRITE (2)
  2456. /* Open file for writing, create and append */
  2457. #define MG_FOPEN_MODE_APPEND (4)
  2458. static int
  2459. is_file_opened(const struct mg_file_access *fileacc)
  2460. {
  2461. if (!fileacc) {
  2462. return 0;
  2463. }
  2464. return (fileacc->fp != NULL);
  2465. }
  2466. #if !defined(NO_FILESYSTEMS)
  2467. static int mg_stat(const struct mg_connection *conn,
  2468. const char *path,
  2469. struct mg_file_stat *filep);
  2470. /* Reject files with special characters (for Windows) */
  2471. static int
  2472. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2473. {
  2474. const uint8_t *c = (const uint8_t *)path;
  2475. (void)conn; /* not used */
  2476. if ((c == NULL) || (c[0] == 0)) {
  2477. /* Null pointer or empty path --> suspicious */
  2478. return 1;
  2479. }
  2480. #if defined(_WIN32)
  2481. while (*c) {
  2482. if (*c < 32) {
  2483. /* Control character */
  2484. return 1;
  2485. }
  2486. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2487. /* stdin/stdout redirection character */
  2488. return 1;
  2489. }
  2490. if ((*c == '*') || (*c == '?')) {
  2491. /* Wildcard character */
  2492. return 1;
  2493. }
  2494. if (*c == '"') {
  2495. /* Windows quotation */
  2496. return 1;
  2497. }
  2498. c++;
  2499. }
  2500. #endif
  2501. /* Nothing suspicious found */
  2502. return 0;
  2503. }
  2504. /* mg_fopen will open a file either in memory or on the disk.
  2505. * The input parameter path is a string in UTF-8 encoding.
  2506. * The input parameter mode is MG_FOPEN_MODE_*
  2507. * On success, fp will be set in the output struct mg_file.
  2508. * All status members will also be set.
  2509. * The function returns 1 on success, 0 on error. */
  2510. static int
  2511. mg_fopen(const struct mg_connection *conn,
  2512. const char *path,
  2513. int mode,
  2514. struct mg_file *filep)
  2515. {
  2516. int found;
  2517. if (!filep) {
  2518. return 0;
  2519. }
  2520. filep->access.fp = NULL;
  2521. if (mg_path_suspicious(conn, path)) {
  2522. return 0;
  2523. }
  2524. /* filep is initialized in mg_stat: all fields with memset to,
  2525. * some fields like size and modification date with values */
  2526. found = mg_stat(conn, path, &(filep->stat));
  2527. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2528. /* file does not exist and will not be created */
  2529. return 0;
  2530. }
  2531. #if defined(_WIN32)
  2532. {
  2533. wchar_t wbuf[UTF16_PATH_MAX];
  2534. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2535. switch (mode) {
  2536. case MG_FOPEN_MODE_READ:
  2537. filep->access.fp = _wfopen(wbuf, L"rb");
  2538. break;
  2539. case MG_FOPEN_MODE_WRITE:
  2540. filep->access.fp = _wfopen(wbuf, L"wb");
  2541. break;
  2542. case MG_FOPEN_MODE_APPEND:
  2543. filep->access.fp = _wfopen(wbuf, L"ab");
  2544. break;
  2545. }
  2546. }
  2547. #else
  2548. /* Linux et al already use unicode. No need to convert. */
  2549. switch (mode) {
  2550. case MG_FOPEN_MODE_READ:
  2551. filep->access.fp = fopen(path, "r");
  2552. break;
  2553. case MG_FOPEN_MODE_WRITE:
  2554. filep->access.fp = fopen(path, "w");
  2555. break;
  2556. case MG_FOPEN_MODE_APPEND:
  2557. filep->access.fp = fopen(path, "a");
  2558. break;
  2559. }
  2560. #endif
  2561. if (!found) {
  2562. /* File did not exist before fopen was called.
  2563. * Maybe it has been created now. Get stat info
  2564. * like creation time now. */
  2565. found = mg_stat(conn, path, &(filep->stat));
  2566. (void)found;
  2567. }
  2568. /* return OK if file is opened */
  2569. return (filep->access.fp != NULL);
  2570. }
  2571. /* return 0 on success, just like fclose */
  2572. static int
  2573. mg_fclose(struct mg_file_access *fileacc)
  2574. {
  2575. int ret = -1;
  2576. if (fileacc != NULL) {
  2577. if (fileacc->fp != NULL) {
  2578. ret = fclose(fileacc->fp);
  2579. }
  2580. /* reset all members of fileacc */
  2581. memset(fileacc, 0, sizeof(*fileacc));
  2582. }
  2583. return ret;
  2584. }
  2585. #endif /* NO_FILESYSTEMS */
  2586. static void
  2587. mg_strlcpy(char *dst, const char *src, size_t n)
  2588. {
  2589. for (; *src != '\0' && n > 1; n--) {
  2590. *dst++ = *src++;
  2591. }
  2592. *dst = '\0';
  2593. }
  2594. static int
  2595. lowercase(const char *s)
  2596. {
  2597. return tolower((unsigned char)*s);
  2598. }
  2599. CIVETWEB_API int
  2600. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2601. {
  2602. int diff = 0;
  2603. if (len > 0) {
  2604. do {
  2605. diff = lowercase(s1++) - lowercase(s2++);
  2606. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2607. }
  2608. return diff;
  2609. }
  2610. CIVETWEB_API int
  2611. mg_strcasecmp(const char *s1, const char *s2)
  2612. {
  2613. int diff;
  2614. do {
  2615. diff = lowercase(s1++) - lowercase(s2++);
  2616. } while (diff == 0 && s1[-1] != '\0');
  2617. return diff;
  2618. }
  2619. static char *
  2620. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2621. {
  2622. char *p;
  2623. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2624. * defined */
  2625. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2626. mg_strlcpy(p, ptr, len + 1);
  2627. }
  2628. return p;
  2629. }
  2630. static char *
  2631. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2632. {
  2633. return mg_strndup_ctx(str, strlen(str), ctx);
  2634. }
  2635. static char *
  2636. mg_strdup(const char *str)
  2637. {
  2638. return mg_strndup_ctx(str, strlen(str), NULL);
  2639. }
  2640. static const char *
  2641. mg_strcasestr(const char *big_str, const char *small_str)
  2642. {
  2643. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2644. if (big_len >= small_len) {
  2645. for (i = 0; i <= (big_len - small_len); i++) {
  2646. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2647. return big_str + i;
  2648. }
  2649. }
  2650. }
  2651. return NULL;
  2652. }
  2653. /* Return null terminated string of given maximum length.
  2654. * Report errors if length is exceeded. */
  2655. static void
  2656. mg_vsnprintf(const struct mg_connection *conn,
  2657. int *truncated,
  2658. char *buf,
  2659. size_t buflen,
  2660. const char *fmt,
  2661. va_list ap)
  2662. {
  2663. int n, ok;
  2664. if (buflen == 0) {
  2665. if (truncated) {
  2666. *truncated = 1;
  2667. }
  2668. return;
  2669. }
  2670. #if defined(__clang__)
  2671. #pragma clang diagnostic push
  2672. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2673. /* Using fmt as a non-literal is intended here, since it is mostly called
  2674. * indirectly by mg_snprintf */
  2675. #endif
  2676. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2677. ok = (n >= 0) && ((size_t)n < buflen);
  2678. #if defined(__clang__)
  2679. #pragma clang diagnostic pop
  2680. #endif
  2681. if (ok) {
  2682. if (truncated) {
  2683. *truncated = 0;
  2684. }
  2685. } else {
  2686. if (truncated) {
  2687. *truncated = 1;
  2688. }
  2689. mg_cry_internal(conn,
  2690. "truncating vsnprintf buffer: [%.*s]",
  2691. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2692. buf);
  2693. n = (int)buflen - 1;
  2694. }
  2695. buf[n] = '\0';
  2696. }
  2697. static void
  2698. mg_snprintf(const struct mg_connection *conn,
  2699. int *truncated,
  2700. char *buf,
  2701. size_t buflen,
  2702. const char *fmt,
  2703. ...)
  2704. {
  2705. va_list ap;
  2706. va_start(ap, fmt);
  2707. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2708. va_end(ap);
  2709. }
  2710. static int
  2711. get_option_index(const char *name)
  2712. {
  2713. int i;
  2714. for (i = 0; config_options[i].name != NULL; i++) {
  2715. if (strcmp(config_options[i].name, name) == 0) {
  2716. return i;
  2717. }
  2718. }
  2719. return -1;
  2720. }
  2721. CIVETWEB_API const char *
  2722. mg_get_option(const struct mg_context *ctx, const char *name)
  2723. {
  2724. int i;
  2725. if ((i = get_option_index(name)) == -1) {
  2726. return NULL;
  2727. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2728. return "";
  2729. } else {
  2730. return ctx->dd.config[i];
  2731. }
  2732. }
  2733. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2734. CIVETWEB_API struct mg_context *
  2735. mg_get_context(const struct mg_connection *conn)
  2736. {
  2737. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2738. }
  2739. CIVETWEB_API void *
  2740. mg_get_user_data(const struct mg_context *ctx)
  2741. {
  2742. return (ctx == NULL) ? NULL : ctx->user_data;
  2743. }
  2744. CIVETWEB_API void *
  2745. mg_get_user_context_data(const struct mg_connection *conn)
  2746. {
  2747. return mg_get_user_data(mg_get_context(conn));
  2748. }
  2749. CIVETWEB_API void *
  2750. mg_get_thread_pointer(const struct mg_connection *conn)
  2751. {
  2752. /* both methods should return the same pointer */
  2753. if (conn) {
  2754. /* quick access, in case conn is known */
  2755. return conn->tls_user_ptr;
  2756. } else {
  2757. /* otherwise get pointer from thread local storage (TLS) */
  2758. struct mg_workerTLS *tls =
  2759. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2760. return tls->user_ptr;
  2761. }
  2762. }
  2763. CIVETWEB_API void
  2764. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2765. {
  2766. if (const_conn != NULL) {
  2767. /* Const cast, since "const struct mg_connection *" does not mean
  2768. * the connection object is not modified. Here "const" is used,
  2769. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2770. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2771. conn->request_info.conn_data = data;
  2772. }
  2773. }
  2774. CIVETWEB_API void *
  2775. mg_get_user_connection_data(const struct mg_connection *conn)
  2776. {
  2777. if (conn != NULL) {
  2778. return conn->request_info.conn_data;
  2779. }
  2780. return NULL;
  2781. }
  2782. CIVETWEB_API int
  2783. mg_get_server_ports(const struct mg_context *ctx,
  2784. int size,
  2785. struct mg_server_port *ports)
  2786. {
  2787. int i, cnt = 0;
  2788. if (size <= 0) {
  2789. return -1;
  2790. }
  2791. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2792. if (!ctx) {
  2793. return -1;
  2794. }
  2795. if (!ctx->listening_sockets) {
  2796. return -1;
  2797. }
  2798. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2799. ports[cnt].port =
  2800. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2801. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2802. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2803. ports[cnt].is_optional = ctx->listening_sockets[i].is_optional;
  2804. ports[cnt].is_bound = ctx->listening_sockets[i].sock != INVALID_SOCKET;
  2805. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2806. /* IPv4 */
  2807. ports[cnt].protocol = 1;
  2808. cnt++;
  2809. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2810. /* IPv6 */
  2811. ports[cnt].protocol = 3;
  2812. cnt++;
  2813. }
  2814. }
  2815. return cnt;
  2816. }
  2817. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2818. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2819. #endif
  2820. static void
  2821. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2822. {
  2823. buf[0] = '\0';
  2824. if (!usa) {
  2825. return;
  2826. }
  2827. if (usa->sa.sa_family == AF_INET) {
  2828. getnameinfo(&usa->sa,
  2829. sizeof(usa->sin),
  2830. buf,
  2831. (unsigned)len,
  2832. NULL,
  2833. 0,
  2834. NI_NUMERICHOST);
  2835. }
  2836. #if defined(USE_IPV6)
  2837. else if (usa->sa.sa_family == AF_INET6) {
  2838. getnameinfo(&usa->sa,
  2839. sizeof(usa->sin6),
  2840. buf,
  2841. (unsigned)len,
  2842. NULL,
  2843. 0,
  2844. NI_NUMERICHOST);
  2845. }
  2846. #endif
  2847. #if defined(USE_X_DOM_SOCKET)
  2848. else if (usa->sa.sa_family == AF_UNIX) {
  2849. /* TODO: Define a remote address for unix domain sockets.
  2850. * This code will always return "localhost", identical to http+tcp:
  2851. getnameinfo(&usa->sa,
  2852. sizeof(usa->sun),
  2853. buf,
  2854. (unsigned)len,
  2855. NULL,
  2856. 0,
  2857. NI_NUMERICHOST);
  2858. */
  2859. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2860. }
  2861. #endif
  2862. }
  2863. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2864. * included in all responses other than 100, 101, 5xx. */
  2865. static void
  2866. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2867. {
  2868. #if !defined(REENTRANT_TIME)
  2869. struct tm *tm;
  2870. tm = ((t != NULL) ? gmtime(t) : NULL);
  2871. if (tm != NULL) {
  2872. #else
  2873. struct tm _tm;
  2874. struct tm *tm = &_tm;
  2875. if (t != NULL) {
  2876. gmtime_r(t, tm);
  2877. #endif
  2878. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2879. } else {
  2880. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2881. }
  2882. }
  2883. /* difftime for struct timespec. Return value is in seconds. */
  2884. static double
  2885. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2886. {
  2887. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2888. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2889. }
  2890. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2891. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2892. const char *func,
  2893. unsigned line,
  2894. const char *fmt,
  2895. va_list ap);
  2896. #include "external_mg_cry_internal_impl.inl"
  2897. #elif !defined(NO_FILESYSTEMS)
  2898. /* Print error message to the opened error log stream. */
  2899. static void
  2900. mg_cry_internal_impl(const struct mg_connection *conn,
  2901. const char *func,
  2902. unsigned line,
  2903. const char *fmt,
  2904. va_list ap)
  2905. {
  2906. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2907. struct mg_file fi;
  2908. time_t timestamp;
  2909. /* Unused, in the RELEASE build */
  2910. (void)func;
  2911. (void)line;
  2912. #if defined(GCC_DIAGNOSTIC)
  2913. #pragma GCC diagnostic push
  2914. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2915. #endif
  2916. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2917. #if defined(GCC_DIAGNOSTIC)
  2918. #pragma GCC diagnostic pop
  2919. #endif
  2920. buf[sizeof(buf) - 1] = 0;
  2921. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2922. if (!conn) {
  2923. puts(buf);
  2924. return;
  2925. }
  2926. /* Do not lock when getting the callback value, here and below.
  2927. * I suppose this is fine, since function cannot disappear in the
  2928. * same way string option can. */
  2929. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2930. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2931. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2932. if (mg_fopen(conn,
  2933. conn->dom_ctx->config[ERROR_LOG_FILE],
  2934. MG_FOPEN_MODE_APPEND,
  2935. &fi)
  2936. == 0) {
  2937. fi.access.fp = NULL;
  2938. }
  2939. } else {
  2940. fi.access.fp = NULL;
  2941. }
  2942. if (fi.access.fp != NULL) {
  2943. flockfile(fi.access.fp);
  2944. timestamp = time(NULL);
  2945. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2946. fprintf(fi.access.fp,
  2947. "[%010lu] [error] [client %s] ",
  2948. (unsigned long)timestamp,
  2949. src_addr);
  2950. if (conn->request_info.request_method != NULL) {
  2951. fprintf(fi.access.fp,
  2952. "%s %s: ",
  2953. conn->request_info.request_method,
  2954. conn->request_info.request_uri
  2955. ? conn->request_info.request_uri
  2956. : "");
  2957. }
  2958. fprintf(fi.access.fp, "%s", buf);
  2959. fputc('\n', fi.access.fp);
  2960. fflush(fi.access.fp);
  2961. funlockfile(fi.access.fp);
  2962. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2963. * mg_cry here anyway ;-) */
  2964. }
  2965. }
  2966. }
  2967. #else
  2968. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2969. #endif /* Externally provided function */
  2970. /* Construct fake connection structure. Used for logging, if connection
  2971. * is not applicable at the moment of logging. */
  2972. static struct mg_connection *
  2973. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2974. {
  2975. static const struct mg_connection conn_zero = {0};
  2976. *fc = conn_zero;
  2977. fc->phys_ctx = ctx;
  2978. fc->dom_ctx = &(ctx->dd);
  2979. return fc;
  2980. }
  2981. static void
  2982. mg_cry_internal_wrap(const struct mg_connection *conn,
  2983. struct mg_context *ctx,
  2984. const char *func,
  2985. unsigned line,
  2986. const char *fmt,
  2987. ...)
  2988. {
  2989. va_list ap;
  2990. va_start(ap, fmt);
  2991. if (!conn && ctx) {
  2992. struct mg_connection fc;
  2993. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2994. } else {
  2995. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2996. }
  2997. va_end(ap);
  2998. }
  2999. CIVETWEB_API void
  3000. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3001. {
  3002. va_list ap;
  3003. va_start(ap, fmt);
  3004. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3005. va_end(ap);
  3006. }
  3007. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3008. CIVETWEB_API const char *
  3009. mg_version(void)
  3010. {
  3011. return CIVETWEB_VERSION;
  3012. }
  3013. CIVETWEB_API const struct mg_request_info *
  3014. mg_get_request_info(const struct mg_connection *conn)
  3015. {
  3016. if (!conn) {
  3017. return NULL;
  3018. }
  3019. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3020. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3021. char txt[16];
  3022. struct mg_workerTLS *tls =
  3023. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3024. sprintf(txt, "%03i", conn->response_info.status_code);
  3025. if (strlen(txt) == 3) {
  3026. memcpy(tls->txtbuf, txt, 4);
  3027. } else {
  3028. strcpy(tls->txtbuf, "ERR");
  3029. }
  3030. ((struct mg_connection *)conn)->request_info.local_uri =
  3031. tls->txtbuf; /* use thread safe buffer */
  3032. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3033. tls->txtbuf; /* use the same thread safe buffer */
  3034. ((struct mg_connection *)conn)->request_info.request_uri =
  3035. tls->txtbuf; /* use the same thread safe buffer */
  3036. ((struct mg_connection *)conn)->request_info.num_headers =
  3037. conn->response_info.num_headers;
  3038. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3039. conn->response_info.http_headers,
  3040. sizeof(conn->response_info.http_headers));
  3041. } else
  3042. #endif
  3043. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3044. return NULL;
  3045. }
  3046. return &conn->request_info;
  3047. }
  3048. CIVETWEB_API const struct mg_response_info *
  3049. mg_get_response_info(const struct mg_connection *conn)
  3050. {
  3051. if (!conn) {
  3052. return NULL;
  3053. }
  3054. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3055. return NULL;
  3056. }
  3057. return &conn->response_info;
  3058. }
  3059. static const char *
  3060. get_proto_name(const struct mg_connection *conn)
  3061. {
  3062. #if defined(__clang__)
  3063. #pragma clang diagnostic push
  3064. #pragma clang diagnostic ignored "-Wunreachable-code"
  3065. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3066. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3067. * unreachable, but splitting into four different #ifdef clauses here is
  3068. * more complicated.
  3069. */
  3070. #endif
  3071. const struct mg_request_info *ri = &conn->request_info;
  3072. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3073. ? (ri->is_ssl ? "wss" : "ws")
  3074. : (ri->is_ssl ? "https" : "http"));
  3075. return proto;
  3076. #if defined(__clang__)
  3077. #pragma clang diagnostic pop
  3078. #endif
  3079. }
  3080. static int
  3081. mg_construct_local_link(const struct mg_connection *conn,
  3082. char *buf,
  3083. size_t buflen,
  3084. const char *define_proto,
  3085. int define_port,
  3086. const char *define_uri)
  3087. {
  3088. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3089. return -1;
  3090. } else {
  3091. int i, j;
  3092. int truncated = 0;
  3093. const struct mg_request_info *ri = &conn->request_info;
  3094. const char *proto =
  3095. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3096. const char *uri =
  3097. (define_uri != NULL)
  3098. ? define_uri
  3099. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3100. int port = (define_port > 0) ? define_port : ri->server_port;
  3101. int default_port = 80;
  3102. char *uri_encoded;
  3103. size_t uri_encoded_len;
  3104. if (uri == NULL) {
  3105. return -1;
  3106. }
  3107. uri_encoded_len = strlen(uri) * 3 + 1;
  3108. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3109. if (uri_encoded == NULL) {
  3110. return -1;
  3111. }
  3112. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3113. /* Directory separator should be preserved. */
  3114. for (i = j = 0; uri_encoded[i]; j++) {
  3115. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3116. uri_encoded[j] = '/';
  3117. i += 3;
  3118. } else {
  3119. uri_encoded[j] = uri_encoded[i++];
  3120. }
  3121. }
  3122. uri_encoded[j] = '\0';
  3123. #if defined(USE_X_DOM_SOCKET)
  3124. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3125. /* TODO: Define and document a link for UNIX domain sockets. */
  3126. /* There seems to be no official standard for this.
  3127. * Common uses seem to be "httpunix://", "http.unix://" or
  3128. * "http+unix://" as a protocol definition string, followed by
  3129. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3130. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3131. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3132. * "" (completely skipping the server name part). In any case, the
  3133. * last part is the server local path. */
  3134. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3135. mg_snprintf(conn,
  3136. &truncated,
  3137. buf,
  3138. buflen,
  3139. "%s.unix://%s%s",
  3140. proto,
  3141. server_name,
  3142. ri->local_uri);
  3143. default_port = 0;
  3144. mg_free(uri_encoded);
  3145. return 0;
  3146. }
  3147. #endif
  3148. if (define_proto) {
  3149. /* If we got a protocol name, use the default port accordingly. */
  3150. if ((0 == strcmp(define_proto, "https"))
  3151. || (0 == strcmp(define_proto, "wss"))) {
  3152. default_port = 443;
  3153. }
  3154. } else if (ri->is_ssl) {
  3155. /* If we did not get a protocol name, use TLS as default if it is
  3156. * already used. */
  3157. default_port = 443;
  3158. }
  3159. {
  3160. #if defined(USE_IPV6)
  3161. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3162. #endif
  3163. int auth_domain_check_enabled =
  3164. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3165. && (!mg_strcasecmp(
  3166. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3167. const char *server_domain =
  3168. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3169. char portstr[16];
  3170. char server_ip[48];
  3171. if (port != default_port) {
  3172. sprintf(portstr, ":%u", (unsigned)port);
  3173. } else {
  3174. portstr[0] = 0;
  3175. }
  3176. if (!auth_domain_check_enabled || !server_domain) {
  3177. sockaddr_to_string(server_ip,
  3178. sizeof(server_ip),
  3179. &conn->client.lsa);
  3180. server_domain = server_ip;
  3181. }
  3182. mg_snprintf(conn,
  3183. &truncated,
  3184. buf,
  3185. buflen,
  3186. #if defined(USE_IPV6)
  3187. "%s://%s%s%s%s%s",
  3188. proto,
  3189. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3190. server_domain,
  3191. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3192. #else
  3193. "%s://%s%s%s",
  3194. proto,
  3195. server_domain,
  3196. #endif
  3197. portstr,
  3198. uri_encoded);
  3199. mg_free(uri_encoded);
  3200. if (truncated) {
  3201. return -1;
  3202. }
  3203. return 0;
  3204. }
  3205. }
  3206. }
  3207. CIVETWEB_API int
  3208. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3209. {
  3210. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3211. }
  3212. /* Skip the characters until one of the delimiters characters found.
  3213. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3214. * Advance pointer to buffer to the next word. Return found 0-terminated
  3215. * word.
  3216. * Delimiters can be quoted with quotechar. */
  3217. static char *
  3218. skip_quoted(char **buf,
  3219. const char *delimiters,
  3220. const char *whitespace,
  3221. char quotechar)
  3222. {
  3223. char *p, *begin_word, *end_word, *end_whitespace;
  3224. begin_word = *buf;
  3225. end_word = begin_word + strcspn(begin_word, delimiters);
  3226. /* Check for quotechar */
  3227. if (end_word > begin_word) {
  3228. p = end_word - 1;
  3229. while (*p == quotechar) {
  3230. /* While the delimiter is quoted, look for the next delimiter. */
  3231. /* This happens, e.g., in calls from parse_auth_header,
  3232. * if the user name contains a " character. */
  3233. /* If there is anything beyond end_word, copy it. */
  3234. if (*end_word != '\0') {
  3235. size_t end_off = strcspn(end_word + 1, delimiters);
  3236. memmove(p, end_word, end_off + 1);
  3237. p += end_off; /* p must correspond to end_word - 1 */
  3238. end_word += end_off + 1;
  3239. } else {
  3240. *p = '\0';
  3241. break;
  3242. }
  3243. }
  3244. for (p++; p < end_word; p++) {
  3245. *p = '\0';
  3246. }
  3247. }
  3248. if (*end_word == '\0') {
  3249. *buf = end_word;
  3250. } else {
  3251. #if defined(GCC_DIAGNOSTIC)
  3252. /* Disable spurious conversion warning for GCC */
  3253. #pragma GCC diagnostic push
  3254. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3255. #endif /* defined(GCC_DIAGNOSTIC) */
  3256. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3257. #if defined(GCC_DIAGNOSTIC)
  3258. #pragma GCC diagnostic pop
  3259. #endif /* defined(GCC_DIAGNOSTIC) */
  3260. for (p = end_word; p < end_whitespace; p++) {
  3261. *p = '\0';
  3262. }
  3263. *buf = end_whitespace;
  3264. }
  3265. return begin_word;
  3266. }
  3267. /* Return HTTP header value, or NULL if not found. */
  3268. static const char *
  3269. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3270. {
  3271. int i;
  3272. for (i = 0; i < num_hdr; i++) {
  3273. if (!mg_strcasecmp(name, hdr[i].name)) {
  3274. return hdr[i].value;
  3275. }
  3276. }
  3277. return NULL;
  3278. }
  3279. /* Retrieve requested HTTP header multiple values, and return the number of
  3280. * found occurrences */
  3281. static int
  3282. get_req_headers(const struct mg_request_info *ri,
  3283. const char *name,
  3284. const char **output,
  3285. int output_max_size)
  3286. {
  3287. int i;
  3288. int cnt = 0;
  3289. if (ri) {
  3290. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3291. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3292. output[cnt++] = ri->http_headers[i].value;
  3293. }
  3294. }
  3295. }
  3296. return cnt;
  3297. }
  3298. CIVETWEB_API const char *
  3299. mg_get_header(const struct mg_connection *conn, const char *name)
  3300. {
  3301. if (!conn) {
  3302. return NULL;
  3303. }
  3304. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3305. return get_header(conn->request_info.http_headers,
  3306. conn->request_info.num_headers,
  3307. name);
  3308. }
  3309. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3310. return get_header(conn->response_info.http_headers,
  3311. conn->response_info.num_headers,
  3312. name);
  3313. }
  3314. return NULL;
  3315. }
  3316. static const char *
  3317. get_http_version(const struct mg_connection *conn)
  3318. {
  3319. if (!conn) {
  3320. return NULL;
  3321. }
  3322. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3323. return conn->request_info.http_version;
  3324. }
  3325. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3326. return conn->response_info.http_version;
  3327. }
  3328. return NULL;
  3329. }
  3330. /* A helper function for traversing a comma separated list of values.
  3331. * It returns a list pointer shifted to the next value, or NULL if the end
  3332. * of the list found.
  3333. * Value is stored in val vector. If value has form "x=y", then eq_val
  3334. * vector is initialized to point to the "y" part, and val vector length
  3335. * is adjusted to point only to "x". */
  3336. static const char *
  3337. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3338. {
  3339. int end;
  3340. reparse:
  3341. if (val == NULL || list == NULL || *list == '\0') {
  3342. /* End of the list */
  3343. return NULL;
  3344. }
  3345. /* Skip over leading LWS */
  3346. while (*list == ' ' || *list == '\t')
  3347. list++;
  3348. val->ptr = list;
  3349. if ((list = strchr(val->ptr, ',')) != NULL) {
  3350. /* Comma found. Store length and shift the list ptr */
  3351. val->len = ((size_t)(list - val->ptr));
  3352. list++;
  3353. } else {
  3354. /* This value is the last one */
  3355. list = val->ptr + strlen(val->ptr);
  3356. val->len = ((size_t)(list - val->ptr));
  3357. }
  3358. /* Adjust length for trailing LWS */
  3359. end = (int)val->len - 1;
  3360. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3361. end--;
  3362. val->len = (size_t)(end) + (size_t)(1);
  3363. if (val->len == 0) {
  3364. /* Ignore any empty entries. */
  3365. goto reparse;
  3366. }
  3367. if (eq_val != NULL) {
  3368. /* Value has form "x=y", adjust pointers and lengths
  3369. * so that val points to "x", and eq_val points to "y". */
  3370. eq_val->len = 0;
  3371. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3372. if (eq_val->ptr != NULL) {
  3373. eq_val->ptr++; /* Skip over '=' character */
  3374. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3375. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3376. }
  3377. }
  3378. return list;
  3379. }
  3380. /* A helper function for checking if a comma separated list of values
  3381. * contains
  3382. * the given option (case insensitvely).
  3383. * 'header' can be NULL, in which case false is returned. */
  3384. static int
  3385. header_has_option(const char *header, const char *option)
  3386. {
  3387. struct vec opt_vec;
  3388. struct vec eq_vec;
  3389. DEBUG_ASSERT(option != NULL);
  3390. DEBUG_ASSERT(option[0] != '\0');
  3391. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3392. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3393. return 1;
  3394. }
  3395. return 0;
  3396. }
  3397. /* Sorting function implemented in a separate file */
  3398. #include "sort.inl"
  3399. /* Pattern matching has been reimplemented in a new file */
  3400. #include "match.inl"
  3401. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3402. * This function must tolerate situations when connection info is not
  3403. * set up, for example if request parsing failed. */
  3404. static int
  3405. should_keep_alive(const struct mg_connection *conn)
  3406. {
  3407. const char *http_version;
  3408. const char *header;
  3409. /* First satisfy needs of the server */
  3410. if ((conn == NULL) || conn->must_close) {
  3411. /* Close, if civetweb framework needs to close */
  3412. return 0;
  3413. }
  3414. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3415. /* Close, if keep alive is not enabled */
  3416. return 0;
  3417. }
  3418. /* Check explicit wish of the client */
  3419. header = mg_get_header(conn, "Connection");
  3420. if (header) {
  3421. /* If there is a connection header from the client, obey */
  3422. if (header_has_option(header, "keep-alive")) {
  3423. return 1;
  3424. }
  3425. return 0;
  3426. }
  3427. /* Use default of the standard */
  3428. http_version = get_http_version(conn);
  3429. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3430. /* HTTP 1.1 default is keep alive */
  3431. return 1;
  3432. }
  3433. /* HTTP 1.0 (and earlier) default is to close the connection */
  3434. return 0;
  3435. }
  3436. static int
  3437. should_decode_url(const struct mg_connection *conn)
  3438. {
  3439. if (!conn || !conn->dom_ctx) {
  3440. return 0;
  3441. }
  3442. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3443. }
  3444. static int
  3445. should_decode_query_string(const struct mg_connection *conn)
  3446. {
  3447. if (!conn || !conn->dom_ctx) {
  3448. return 0;
  3449. }
  3450. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3451. == 0);
  3452. }
  3453. static const char *
  3454. suggest_connection_header(const struct mg_connection *conn)
  3455. {
  3456. return should_keep_alive(conn) ? "keep-alive" : "close";
  3457. }
  3458. #include "response.inl"
  3459. static void
  3460. send_no_cache_header(struct mg_connection *conn)
  3461. {
  3462. /* Send all current and obsolete cache opt-out directives. */
  3463. mg_response_header_add(conn,
  3464. "Cache-Control",
  3465. "no-cache, no-store, "
  3466. "must-revalidate, private, max-age=0",
  3467. -1);
  3468. mg_response_header_add(conn, "Expires", "0", -1);
  3469. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3470. /* Obsolete, but still send it for HTTP/1.0 */
  3471. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3472. }
  3473. }
  3474. static void
  3475. send_static_cache_header(struct mg_connection *conn)
  3476. {
  3477. #if !defined(NO_CACHING)
  3478. int max_age;
  3479. char val[64];
  3480. const char *cache_control =
  3481. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3482. /* If there is a full cache-control option configured,0 use it */
  3483. if (cache_control != NULL) {
  3484. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3485. return;
  3486. }
  3487. /* Read the server config to check how long a file may be cached.
  3488. * The configuration is in seconds. */
  3489. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3490. if (max_age <= 0) {
  3491. /* 0 means "do not cache". All values <0 are reserved
  3492. * and may be used differently in the future. */
  3493. /* If a file should not be cached, do not only send
  3494. * max-age=0, but also pragmas and Expires headers. */
  3495. send_no_cache_header(conn);
  3496. return;
  3497. }
  3498. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3499. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3500. /* See also https://www.mnot.net/cache_docs/ */
  3501. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3502. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3503. * leap
  3504. * year to 31622400 seconds. For the moment, we just send whatever has
  3505. * been configured, still the behavior for >1 year should be considered
  3506. * as undefined. */
  3507. mg_snprintf(
  3508. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3509. mg_response_header_add(conn, "Cache-Control", val, -1);
  3510. #else /* NO_CACHING */
  3511. send_no_cache_header(conn);
  3512. #endif /* !NO_CACHING */
  3513. }
  3514. static void
  3515. send_additional_header(struct mg_connection *conn)
  3516. {
  3517. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3518. #if !defined(NO_SSL)
  3519. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3520. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3521. if (max_age >= 0) {
  3522. char val[64];
  3523. mg_snprintf(conn,
  3524. NULL,
  3525. val,
  3526. sizeof(val),
  3527. "max-age=%lu",
  3528. (unsigned long)max_age);
  3529. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3530. }
  3531. }
  3532. #endif
  3533. // Content-Security-Policy
  3534. if (header && header[0]) {
  3535. mg_response_header_add_lines(conn, header);
  3536. }
  3537. }
  3538. static void
  3539. send_cors_header(struct mg_connection *conn)
  3540. {
  3541. const char *origin_hdr = mg_get_header(conn, "Origin");
  3542. const char *cors_orig_cfg =
  3543. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3544. const char *cors_cred_cfg =
  3545. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  3546. const char *cors_hdr_cfg =
  3547. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  3548. const char *cors_exphdr_cfg =
  3549. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  3550. const char *cors_meth_cfg =
  3551. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  3552. int cors_replace_asterisk_with_origin = mg_strcasecmp(conn->dom_ctx->config[REPLACE_ASTERISK_WITH_ORIGIN], "yes");
  3553. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3554. /* Cross-origin resource sharing (CORS), see
  3555. * http://www.html5rocks.com/en/tutorials/cors/,
  3556. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3557. * CORS preflight is not supported for files. */
  3558. if (cors_replace_asterisk_with_origin == 0 && cors_orig_cfg[0] == '*') {
  3559. mg_response_header_add(conn,
  3560. "Access-Control-Allow-Origin",
  3561. origin_hdr,
  3562. -1);
  3563. } else {
  3564. mg_response_header_add(conn,
  3565. "Access-Control-Allow-Origin",
  3566. cors_orig_cfg,
  3567. -1);
  3568. }
  3569. }
  3570. if (cors_cred_cfg && *cors_cred_cfg && origin_hdr && *origin_hdr) {
  3571. /* Cross-origin resource sharing (CORS), see
  3572. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  3573. */
  3574. mg_response_header_add(conn,
  3575. "Access-Control-Allow-Credentials",
  3576. cors_cred_cfg,
  3577. -1);
  3578. }
  3579. if (cors_hdr_cfg && *cors_hdr_cfg) {
  3580. mg_response_header_add(conn,
  3581. "Access-Control-Allow-Headers",
  3582. cors_hdr_cfg,
  3583. -1);
  3584. }
  3585. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  3586. mg_response_header_add(conn,
  3587. "Access-Control-Expose-Headers",
  3588. cors_exphdr_cfg,
  3589. -1);
  3590. }
  3591. if (cors_meth_cfg && *cors_meth_cfg) {
  3592. mg_response_header_add(conn,
  3593. "Access-Control-Allow-Methods",
  3594. cors_meth_cfg,
  3595. -1);
  3596. }
  3597. }
  3598. #if !defined(NO_FILESYSTEMS)
  3599. static void handle_file_based_request(struct mg_connection *conn,
  3600. const char *path,
  3601. struct mg_file *filep);
  3602. #endif /* NO_FILESYSTEMS */
  3603. CIVETWEB_API const char *
  3604. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3605. {
  3606. /* See IANA HTTP status code assignment:
  3607. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3608. */
  3609. switch (response_code) {
  3610. /* RFC2616 Section 10.1 - Informational 1xx */
  3611. case 100:
  3612. return "Continue"; /* RFC2616 Section 10.1.1 */
  3613. case 101:
  3614. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3615. case 102:
  3616. return "Processing"; /* RFC2518 Section 10.1 */
  3617. /* RFC2616 Section 10.2 - Successful 2xx */
  3618. case 200:
  3619. return "OK"; /* RFC2616 Section 10.2.1 */
  3620. case 201:
  3621. return "Created"; /* RFC2616 Section 10.2.2 */
  3622. case 202:
  3623. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3624. case 203:
  3625. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3626. case 204:
  3627. return "No Content"; /* RFC2616 Section 10.2.5 */
  3628. case 205:
  3629. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3630. case 206:
  3631. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3632. case 207:
  3633. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3634. */
  3635. case 208:
  3636. return "Already Reported"; /* RFC5842 Section 7.1 */
  3637. case 226:
  3638. return "IM used"; /* RFC3229 Section 10.4.1 */
  3639. /* RFC2616 Section 10.3 - Redirection 3xx */
  3640. case 300:
  3641. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3642. case 301:
  3643. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3644. case 302:
  3645. return "Found"; /* RFC2616 Section 10.3.3 */
  3646. case 303:
  3647. return "See Other"; /* RFC2616 Section 10.3.4 */
  3648. case 304:
  3649. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3650. case 305:
  3651. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3652. case 307:
  3653. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3654. case 308:
  3655. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3656. /* RFC2616 Section 10.4 - Client Error 4xx */
  3657. case 400:
  3658. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3659. case 401:
  3660. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3661. case 402:
  3662. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3663. case 403:
  3664. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3665. case 404:
  3666. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3667. case 405:
  3668. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3669. case 406:
  3670. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3671. case 407:
  3672. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3673. case 408:
  3674. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3675. case 409:
  3676. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3677. case 410:
  3678. return "Gone"; /* RFC2616 Section 10.4.11 */
  3679. case 411:
  3680. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3681. case 412:
  3682. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3683. case 413:
  3684. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3685. case 414:
  3686. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3687. case 415:
  3688. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3689. case 416:
  3690. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3691. */
  3692. case 417:
  3693. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3694. case 421:
  3695. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3696. case 422:
  3697. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3698. * Section 11.2 */
  3699. case 423:
  3700. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3701. case 424:
  3702. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3703. * Section 11.4 */
  3704. case 426:
  3705. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3706. case 428:
  3707. return "Precondition Required"; /* RFC 6585, Section 3 */
  3708. case 429:
  3709. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3710. case 431:
  3711. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3712. case 451:
  3713. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3714. * Section 3 */
  3715. /* RFC2616 Section 10.5 - Server Error 5xx */
  3716. case 500:
  3717. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3718. case 501:
  3719. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3720. case 502:
  3721. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3722. case 503:
  3723. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3724. case 504:
  3725. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3726. case 505:
  3727. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3728. case 506:
  3729. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3730. case 507:
  3731. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3732. * Section 11.5 */
  3733. case 508:
  3734. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3735. case 510:
  3736. return "Not Extended"; /* RFC 2774, Section 7 */
  3737. case 511:
  3738. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3739. /* Other status codes, not shown in the IANA HTTP status code
  3740. * assignment.
  3741. * E.g., "de facto" standards due to common use, ... */
  3742. case 418:
  3743. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3744. case 419:
  3745. return "Authentication Timeout"; /* common use */
  3746. case 420:
  3747. return "Enhance Your Calm"; /* common use */
  3748. case 440:
  3749. return "Login Timeout"; /* common use */
  3750. case 509:
  3751. return "Bandwidth Limit Exceeded"; /* common use */
  3752. default:
  3753. /* This error code is unknown. This should not happen. */
  3754. if (conn) {
  3755. mg_cry_internal(conn,
  3756. "Unknown HTTP response code: %u",
  3757. response_code);
  3758. }
  3759. /* Return at least a category according to RFC 2616 Section 10. */
  3760. if (response_code >= 100 && response_code < 200) {
  3761. /* Unknown informational status code */
  3762. return "Information";
  3763. }
  3764. if (response_code >= 200 && response_code < 300) {
  3765. /* Unknown success code */
  3766. return "Success";
  3767. }
  3768. if (response_code >= 300 && response_code < 400) {
  3769. /* Unknown redirection code */
  3770. return "Redirection";
  3771. }
  3772. if (response_code >= 400 && response_code < 500) {
  3773. /* Unknown request error code */
  3774. return "Client Error";
  3775. }
  3776. if (response_code >= 500 && response_code < 600) {
  3777. /* Unknown server error code */
  3778. return "Server Error";
  3779. }
  3780. /* Response code not even within reasonable range */
  3781. return "";
  3782. }
  3783. }
  3784. static int
  3785. mg_send_http_error_impl(struct mg_connection *conn,
  3786. int status,
  3787. const char *fmt,
  3788. va_list args)
  3789. {
  3790. char errmsg_buf[MG_BUF_LEN];
  3791. va_list ap;
  3792. int has_body;
  3793. #if !defined(NO_FILESYSTEMS)
  3794. char path_buf[UTF8_PATH_MAX];
  3795. int len, i, page_handler_found, scope, truncated;
  3796. const char *error_handler = NULL;
  3797. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3798. const char *error_page_file_ext, *tstr;
  3799. #endif /* NO_FILESYSTEMS */
  3800. int handled_by_callback = 0;
  3801. if ((conn == NULL) || (fmt == NULL)) {
  3802. return -2;
  3803. }
  3804. /* Set status (for log) */
  3805. conn->status_code = status;
  3806. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3807. has_body = ((status > 199) && (status != 204) && (status != 304));
  3808. /* Prepare message in buf, if required */
  3809. if (has_body
  3810. || (!conn->in_error_handler
  3811. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3812. /* Store error message in errmsg_buf */
  3813. va_copy(ap, args);
  3814. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3815. va_end(ap);
  3816. /* In a debug build, print all html errors */
  3817. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3818. }
  3819. /* If there is a http_error callback, call it.
  3820. * But don't do it recursively, if callback calls mg_send_http_error again.
  3821. */
  3822. if (!conn->in_error_handler
  3823. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3824. /* Mark in_error_handler to avoid recursion and call user callback. */
  3825. conn->in_error_handler = 1;
  3826. handled_by_callback =
  3827. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3828. == 0);
  3829. conn->in_error_handler = 0;
  3830. }
  3831. if (!handled_by_callback) {
  3832. /* Check for recursion */
  3833. if (conn->in_error_handler) {
  3834. DEBUG_TRACE(
  3835. "Recursion when handling error %u - fall back to default",
  3836. status);
  3837. #if !defined(NO_FILESYSTEMS)
  3838. } else {
  3839. /* Send user defined error pages, if defined */
  3840. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3841. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3842. page_handler_found = 0;
  3843. if (error_handler != NULL) {
  3844. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3845. switch (scope) {
  3846. case 1: /* Handler for specific error, e.g. 404 error */
  3847. mg_snprintf(conn,
  3848. &truncated,
  3849. path_buf,
  3850. sizeof(path_buf) - 32,
  3851. "%serror%03u.",
  3852. error_handler,
  3853. status);
  3854. break;
  3855. case 2: /* Handler for error group, e.g., 5xx error
  3856. * handler
  3857. * for all server errors (500-599) */
  3858. mg_snprintf(conn,
  3859. &truncated,
  3860. path_buf,
  3861. sizeof(path_buf) - 32,
  3862. "%serror%01uxx.",
  3863. error_handler,
  3864. status / 100);
  3865. break;
  3866. default: /* Handler for all errors */
  3867. mg_snprintf(conn,
  3868. &truncated,
  3869. path_buf,
  3870. sizeof(path_buf) - 32,
  3871. "%serror.",
  3872. error_handler);
  3873. break;
  3874. }
  3875. /* String truncation in buf may only occur if
  3876. * error_handler is too long. This string is
  3877. * from the config, not from a client. */
  3878. (void)truncated;
  3879. /* The following code is redundant, but it should avoid
  3880. * false positives in static source code analyzers and
  3881. * vulnerability scanners.
  3882. */
  3883. path_buf[sizeof(path_buf) - 32] = 0;
  3884. len = (int)strlen(path_buf);
  3885. if (len > (int)sizeof(path_buf) - 32) {
  3886. len = (int)sizeof(path_buf) - 32;
  3887. }
  3888. /* Start with the file extension from the configuration. */
  3889. tstr = strchr(error_page_file_ext, '.');
  3890. while (tstr) {
  3891. for (i = 1;
  3892. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3893. i++) {
  3894. /* buffer overrun is not possible here, since
  3895. * (i < 32) && (len < sizeof(path_buf) - 32)
  3896. * ==> (i + len) < sizeof(path_buf) */
  3897. path_buf[len + i - 1] = tstr[i];
  3898. }
  3899. /* buffer overrun is not possible here, since
  3900. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3901. * ==> (i + len) <= sizeof(path_buf) */
  3902. path_buf[len + i - 1] = 0;
  3903. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3904. DEBUG_TRACE("Check error page %s - found",
  3905. path_buf);
  3906. page_handler_found = 1;
  3907. break;
  3908. }
  3909. DEBUG_TRACE("Check error page %s - not found",
  3910. path_buf);
  3911. /* Continue with the next file extension from the
  3912. * configuration (if there is a next one). */
  3913. tstr = strchr(tstr + i, '.');
  3914. }
  3915. }
  3916. }
  3917. if (page_handler_found) {
  3918. conn->in_error_handler = 1;
  3919. handle_file_based_request(conn, path_buf, &error_page_file);
  3920. conn->in_error_handler = 0;
  3921. return 0;
  3922. }
  3923. #endif /* NO_FILESYSTEMS */
  3924. }
  3925. /* No custom error page. Send default error page. */
  3926. conn->must_close = 1;
  3927. mg_response_header_start(conn, status);
  3928. send_no_cache_header(conn);
  3929. send_additional_header(conn);
  3930. send_cors_header(conn);
  3931. if (has_body) {
  3932. mg_response_header_add(conn,
  3933. "Content-Type",
  3934. "text/plain; charset=utf-8",
  3935. -1);
  3936. }
  3937. mg_response_header_send(conn);
  3938. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3939. if (has_body) {
  3940. /* For other errors, send a generic error message. */
  3941. const char *status_text = mg_get_response_code_text(conn, status);
  3942. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3943. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3944. } else {
  3945. /* No body allowed. Close the connection. */
  3946. DEBUG_TRACE("Error %i", status);
  3947. }
  3948. }
  3949. return 0;
  3950. }
  3951. CIVETWEB_API int
  3952. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3953. {
  3954. va_list ap;
  3955. int ret;
  3956. va_start(ap, fmt);
  3957. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3958. va_end(ap);
  3959. return ret;
  3960. }
  3961. CIVETWEB_API int
  3962. mg_send_http_ok(struct mg_connection *conn,
  3963. const char *mime_type,
  3964. long long content_length)
  3965. {
  3966. if ((mime_type == NULL) || (*mime_type == 0)) {
  3967. /* No content type defined: default to text/html */
  3968. mime_type = "text/html";
  3969. }
  3970. mg_response_header_start(conn, 200);
  3971. send_no_cache_header(conn);
  3972. send_additional_header(conn);
  3973. send_cors_header(conn);
  3974. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3975. if (content_length < 0) {
  3976. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3977. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3978. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3979. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3980. }
  3981. } else {
  3982. char len[32];
  3983. int trunc = 0;
  3984. mg_snprintf(conn,
  3985. &trunc,
  3986. len,
  3987. sizeof(len),
  3988. "%" UINT64_FMT,
  3989. (uint64_t)content_length);
  3990. if (!trunc) {
  3991. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3992. * !trunc is always true */
  3993. mg_response_header_add(conn, "Content-Length", len, -1);
  3994. }
  3995. }
  3996. mg_response_header_send(conn);
  3997. return 0;
  3998. }
  3999. CIVETWEB_API int
  4000. mg_send_http_redirect(struct mg_connection *conn,
  4001. const char *target_url,
  4002. int redirect_code)
  4003. {
  4004. /* Send a 30x redirect response.
  4005. *
  4006. * Redirect types (status codes):
  4007. *
  4008. * Status | Perm/Temp | Method | Version
  4009. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4010. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4011. * 303 | temporary | always use GET | HTTP/1.1
  4012. * 307 | temporary | always keep method | HTTP/1.1
  4013. * 308 | permanent | always keep method | HTTP/1.1
  4014. */
  4015. #if defined(MG_SEND_REDIRECT_BODY)
  4016. char redirect_body[MG_BUF_LEN];
  4017. size_t content_len = 0;
  4018. char content_len_text[32];
  4019. #endif
  4020. /* In case redirect_code=0, use 307. */
  4021. if (redirect_code == 0) {
  4022. redirect_code = 307;
  4023. }
  4024. /* In case redirect_code is none of the above, return error. */
  4025. if ((redirect_code != 301) && (redirect_code != 302)
  4026. && (redirect_code != 303) && (redirect_code != 307)
  4027. && (redirect_code != 308)) {
  4028. /* Parameter error */
  4029. return -2;
  4030. }
  4031. /* If target_url is not defined, redirect to "/". */
  4032. if ((target_url == NULL) || (*target_url == 0)) {
  4033. target_url = "/";
  4034. }
  4035. #if defined(MG_SEND_REDIRECT_BODY)
  4036. /* TODO: condition name? */
  4037. /* Prepare a response body with a hyperlink.
  4038. *
  4039. * According to RFC2616 (and RFC1945 before):
  4040. * Unless the request method was HEAD, the entity of the
  4041. * response SHOULD contain a short hypertext note with a hyperlink to
  4042. * the new URI(s).
  4043. *
  4044. * However, this response body is not useful in M2M communication.
  4045. * Probably the original reason in the RFC was, clients not supporting
  4046. * a 30x HTTP redirect could still show the HTML page and let the user
  4047. * press the link. Since current browsers support 30x HTTP, the additional
  4048. * HTML body does not seem to make sense anymore.
  4049. *
  4050. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4051. * but it only notes:
  4052. * The server's response payload usually contains a short
  4053. * hypertext note with a hyperlink to the new URI(s).
  4054. *
  4055. * Deactivated by default. If you need the 30x body, set the define.
  4056. */
  4057. mg_snprintf(
  4058. conn,
  4059. NULL /* ignore truncation */,
  4060. redirect_body,
  4061. sizeof(redirect_body),
  4062. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4063. redirect_text,
  4064. target_url,
  4065. target_url);
  4066. content_len = strlen(reply);
  4067. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4068. #endif
  4069. /* Send all required headers */
  4070. mg_response_header_start(conn, redirect_code);
  4071. mg_response_header_add(conn, "Location", target_url, -1);
  4072. if ((redirect_code == 301) || (redirect_code == 308)) {
  4073. /* Permanent redirect */
  4074. send_static_cache_header(conn);
  4075. } else {
  4076. /* Temporary redirect */
  4077. send_no_cache_header(conn);
  4078. }
  4079. send_additional_header(conn);
  4080. send_cors_header(conn);
  4081. #if defined(MG_SEND_REDIRECT_BODY)
  4082. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4083. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4084. #else
  4085. mg_response_header_add(conn, "Content-Length", "0", 1);
  4086. #endif
  4087. mg_response_header_send(conn);
  4088. #if defined(MG_SEND_REDIRECT_BODY)
  4089. /* Send response body */
  4090. /* ... unless it is a HEAD request */
  4091. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4092. ret = mg_write(conn, redirect_body, content_len);
  4093. }
  4094. #endif
  4095. return 1;
  4096. }
  4097. #if defined(_WIN32)
  4098. /* Create substitutes for POSIX functions in Win32. */
  4099. #if defined(GCC_DIAGNOSTIC)
  4100. /* Show no warning in case system functions are not used. */
  4101. #pragma GCC diagnostic push
  4102. #pragma GCC diagnostic ignored "-Wunused-function"
  4103. #endif
  4104. static int
  4105. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4106. {
  4107. (void)unused;
  4108. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4109. InitializeCriticalSection(&mutex->sec);
  4110. return 0;
  4111. }
  4112. static int
  4113. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4114. {
  4115. DeleteCriticalSection(&mutex->sec);
  4116. return 0;
  4117. }
  4118. static int
  4119. pthread_mutex_lock(pthread_mutex_t *mutex)
  4120. {
  4121. EnterCriticalSection(&mutex->sec);
  4122. return 0;
  4123. }
  4124. static int
  4125. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4126. {
  4127. LeaveCriticalSection(&mutex->sec);
  4128. return 0;
  4129. }
  4130. FUNCTION_MAY_BE_UNUSED
  4131. static int
  4132. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4133. {
  4134. (void)unused;
  4135. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4136. cv->waiting_thread = NULL;
  4137. return 0;
  4138. }
  4139. FUNCTION_MAY_BE_UNUSED
  4140. static int
  4141. pthread_cond_timedwait(pthread_cond_t *cv,
  4142. pthread_mutex_t *mutex,
  4143. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4144. {
  4145. struct mg_workerTLS **ptls,
  4146. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4147. int ok;
  4148. uint64_t nsnow, nswaitabs;
  4149. int64_t nswaitrel;
  4150. DWORD mswaitrel;
  4151. pthread_mutex_lock(&cv->threadIdSec);
  4152. /* Add this thread to cv's waiting list */
  4153. ptls = &cv->waiting_thread;
  4154. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4155. ;
  4156. tls->next_waiting_thread = NULL;
  4157. *ptls = tls;
  4158. pthread_mutex_unlock(&cv->threadIdSec);
  4159. if (abstime) {
  4160. nsnow = mg_get_current_time_ns();
  4161. nswaitabs =
  4162. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4163. nswaitrel = nswaitabs - nsnow;
  4164. if (nswaitrel < 0) {
  4165. nswaitrel = 0;
  4166. }
  4167. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4168. } else {
  4169. mswaitrel = (DWORD)INFINITE;
  4170. }
  4171. pthread_mutex_unlock(mutex);
  4172. ok = (WAIT_OBJECT_0
  4173. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4174. if (!ok) {
  4175. ok = 1;
  4176. pthread_mutex_lock(&cv->threadIdSec);
  4177. ptls = &cv->waiting_thread;
  4178. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4179. if (*ptls == tls) {
  4180. *ptls = tls->next_waiting_thread;
  4181. ok = 0;
  4182. break;
  4183. }
  4184. }
  4185. pthread_mutex_unlock(&cv->threadIdSec);
  4186. if (ok) {
  4187. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4188. (DWORD)INFINITE);
  4189. }
  4190. }
  4191. /* This thread has been removed from cv's waiting list */
  4192. pthread_mutex_lock(mutex);
  4193. return ok ? 0 : -1;
  4194. }
  4195. FUNCTION_MAY_BE_UNUSED
  4196. static int
  4197. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4198. {
  4199. return pthread_cond_timedwait(cv, mutex, NULL);
  4200. }
  4201. FUNCTION_MAY_BE_UNUSED
  4202. static int
  4203. pthread_cond_signal(pthread_cond_t *cv)
  4204. {
  4205. HANDLE wkup = NULL;
  4206. BOOL ok = FALSE;
  4207. pthread_mutex_lock(&cv->threadIdSec);
  4208. if (cv->waiting_thread) {
  4209. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4210. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4211. ok = SetEvent(wkup);
  4212. DEBUG_ASSERT(ok);
  4213. }
  4214. pthread_mutex_unlock(&cv->threadIdSec);
  4215. return ok ? 0 : 1;
  4216. }
  4217. FUNCTION_MAY_BE_UNUSED
  4218. static int
  4219. pthread_cond_broadcast(pthread_cond_t *cv)
  4220. {
  4221. pthread_mutex_lock(&cv->threadIdSec);
  4222. while (cv->waiting_thread) {
  4223. pthread_cond_signal(cv);
  4224. }
  4225. pthread_mutex_unlock(&cv->threadIdSec);
  4226. return 0;
  4227. }
  4228. FUNCTION_MAY_BE_UNUSED
  4229. static int
  4230. pthread_cond_destroy(pthread_cond_t *cv)
  4231. {
  4232. pthread_mutex_lock(&cv->threadIdSec);
  4233. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4234. pthread_mutex_unlock(&cv->threadIdSec);
  4235. pthread_mutex_destroy(&cv->threadIdSec);
  4236. return 0;
  4237. }
  4238. #if defined(ALTERNATIVE_QUEUE)
  4239. FUNCTION_MAY_BE_UNUSED
  4240. static void *
  4241. event_create(void)
  4242. {
  4243. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4244. }
  4245. FUNCTION_MAY_BE_UNUSED
  4246. static int
  4247. event_wait(void *eventhdl)
  4248. {
  4249. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4250. return (res == WAIT_OBJECT_0);
  4251. }
  4252. FUNCTION_MAY_BE_UNUSED
  4253. static int
  4254. event_signal(void *eventhdl)
  4255. {
  4256. return (int)SetEvent((HANDLE)eventhdl);
  4257. }
  4258. FUNCTION_MAY_BE_UNUSED
  4259. static void
  4260. event_destroy(void *eventhdl)
  4261. {
  4262. CloseHandle((HANDLE)eventhdl);
  4263. }
  4264. #endif
  4265. #if defined(GCC_DIAGNOSTIC)
  4266. /* Enable unused function warning again */
  4267. #pragma GCC diagnostic pop
  4268. #endif
  4269. /* For Windows, change all slashes to backslashes in path names. */
  4270. static void
  4271. change_slashes_to_backslashes(char *path)
  4272. {
  4273. int i;
  4274. for (i = 0; path[i] != '\0'; i++) {
  4275. if (path[i] == '/') {
  4276. path[i] = '\\';
  4277. }
  4278. /* remove double backslash (check i > 0 to preserve UNC paths,
  4279. * like \\server\file.txt) */
  4280. if ((i > 0) && (path[i] == '\\')) {
  4281. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4282. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4283. }
  4284. }
  4285. }
  4286. }
  4287. static int
  4288. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4289. {
  4290. int diff;
  4291. do {
  4292. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4293. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4294. s1++;
  4295. s2++;
  4296. } while ((diff == 0) && (s1[-1] != L'\0'));
  4297. return diff;
  4298. }
  4299. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4300. * wbuf and wbuf_len is a target buffer and its length. */
  4301. static void
  4302. path_to_unicode(const struct mg_connection *conn,
  4303. const char *path,
  4304. wchar_t *wbuf,
  4305. size_t wbuf_len)
  4306. {
  4307. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4308. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4309. DWORD long_len, err;
  4310. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4311. mg_strlcpy(buf, path, sizeof(buf));
  4312. change_slashes_to_backslashes(buf);
  4313. /* Convert to Unicode and back. If doubly-converted string does not
  4314. * match the original, something is fishy, reject. */
  4315. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4316. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4317. WideCharToMultiByte(
  4318. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4319. if (strcmp(buf, buf2) != 0) {
  4320. wbuf[0] = L'\0';
  4321. }
  4322. /* Windows file systems are not case sensitive, but you can still use
  4323. * uppercase and lowercase letters (on all modern file systems).
  4324. * The server can check if the URI uses the same upper/lowercase
  4325. * letters an the file system, effectively making Windows servers
  4326. * case sensitive (like Linux servers are). It is still not possible
  4327. * to use two files with the same name in different cases on Windows
  4328. * (like /a and /A) - this would be possible in Linux.
  4329. * As a default, Windows is not case sensitive, but the case sensitive
  4330. * file name check can be activated by an additional configuration. */
  4331. if (conn) {
  4332. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4333. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4334. "yes")) {
  4335. /* Use case sensitive compare function */
  4336. fcompare = wcscmp;
  4337. }
  4338. }
  4339. (void)conn; /* conn is currently unused */
  4340. /* Only accept a full file path, not a Windows short (8.3) path. */
  4341. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4342. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4343. if (long_len == 0) {
  4344. err = GetLastError();
  4345. if (err == ERROR_FILE_NOT_FOUND) {
  4346. /* File does not exist. This is not always a problem here. */
  4347. return;
  4348. }
  4349. }
  4350. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4351. /* Short name is used. */
  4352. wbuf[0] = L'\0';
  4353. }
  4354. }
  4355. #if !defined(NO_FILESYSTEMS)
  4356. /* Get file information, return 1 if file exists, 0 if not */
  4357. static int
  4358. mg_stat(const struct mg_connection *conn,
  4359. const char *path,
  4360. struct mg_file_stat *filep)
  4361. {
  4362. wchar_t wbuf[UTF16_PATH_MAX];
  4363. WIN32_FILE_ATTRIBUTE_DATA info;
  4364. time_t creation_time;
  4365. size_t len;
  4366. if (!filep) {
  4367. return 0;
  4368. }
  4369. memset(filep, 0, sizeof(*filep));
  4370. if (mg_path_suspicious(conn, path)) {
  4371. return 0;
  4372. }
  4373. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4374. /* Windows happily opens files with some garbage at the end of file name.
  4375. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4376. * "a.cgi", despite one would expect an error back. */
  4377. len = strlen(path);
  4378. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4379. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4380. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4381. filep->last_modified =
  4382. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4383. info.ftLastWriteTime.dwHighDateTime);
  4384. /* On Windows, the file creation time can be higher than the
  4385. * modification time, e.g. when a file is copied.
  4386. * Since the Last-Modified timestamp is used for caching
  4387. * it should be based on the most recent timestamp. */
  4388. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4389. info.ftCreationTime.dwHighDateTime);
  4390. if (creation_time > filep->last_modified) {
  4391. filep->last_modified = creation_time;
  4392. }
  4393. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4394. return 1;
  4395. }
  4396. return 0;
  4397. }
  4398. #endif
  4399. static int
  4400. mg_remove(const struct mg_connection *conn, const char *path)
  4401. {
  4402. wchar_t wbuf[UTF16_PATH_MAX];
  4403. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4404. return DeleteFileW(wbuf) ? 0 : -1;
  4405. }
  4406. static int
  4407. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4408. {
  4409. wchar_t wbuf[UTF16_PATH_MAX];
  4410. (void)mode;
  4411. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4412. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4413. }
  4414. /* Create substitutes for POSIX functions in Win32. */
  4415. #if defined(GCC_DIAGNOSTIC)
  4416. /* Show no warning in case system functions are not used. */
  4417. #pragma GCC diagnostic push
  4418. #pragma GCC diagnostic ignored "-Wunused-function"
  4419. #endif
  4420. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4421. FUNCTION_MAY_BE_UNUSED
  4422. static DIR *
  4423. mg_opendir(const struct mg_connection *conn, const char *name)
  4424. {
  4425. DIR *dir = NULL;
  4426. wchar_t wpath[UTF16_PATH_MAX];
  4427. DWORD attrs;
  4428. if (name == NULL) {
  4429. SetLastError(ERROR_BAD_ARGUMENTS);
  4430. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4431. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4432. } else {
  4433. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4434. attrs = GetFileAttributesW(wpath);
  4435. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4436. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4437. (void)wcscat(wpath, L"\\*");
  4438. dir->handle = FindFirstFileW(wpath, &dir->info);
  4439. dir->result.d_name[0] = '\0';
  4440. } else {
  4441. mg_free(dir);
  4442. dir = NULL;
  4443. }
  4444. }
  4445. return dir;
  4446. }
  4447. FUNCTION_MAY_BE_UNUSED
  4448. static int
  4449. mg_closedir(DIR *dir)
  4450. {
  4451. int result = 0;
  4452. if (dir != NULL) {
  4453. if (dir->handle != INVALID_HANDLE_VALUE)
  4454. result = FindClose(dir->handle) ? 0 : -1;
  4455. mg_free(dir);
  4456. } else {
  4457. result = -1;
  4458. SetLastError(ERROR_BAD_ARGUMENTS);
  4459. }
  4460. return result;
  4461. }
  4462. FUNCTION_MAY_BE_UNUSED
  4463. static struct dirent *
  4464. mg_readdir(DIR *dir)
  4465. {
  4466. struct dirent *result = 0;
  4467. if (dir) {
  4468. if (dir->handle != INVALID_HANDLE_VALUE) {
  4469. result = &dir->result;
  4470. (void)WideCharToMultiByte(CP_UTF8,
  4471. 0,
  4472. dir->info.cFileName,
  4473. -1,
  4474. result->d_name,
  4475. sizeof(result->d_name),
  4476. NULL,
  4477. NULL);
  4478. if (!FindNextFileW(dir->handle, &dir->info)) {
  4479. (void)FindClose(dir->handle);
  4480. dir->handle = INVALID_HANDLE_VALUE;
  4481. }
  4482. } else {
  4483. SetLastError(ERROR_FILE_NOT_FOUND);
  4484. }
  4485. } else {
  4486. SetLastError(ERROR_BAD_ARGUMENTS);
  4487. }
  4488. return result;
  4489. }
  4490. #if !defined(HAVE_POLL)
  4491. #undef POLLIN
  4492. #undef POLLPRI
  4493. #undef POLLOUT
  4494. #undef POLLERR
  4495. #define POLLIN (1) /* Data ready - read will not block. */
  4496. #define POLLPRI (2) /* Priority data ready. */
  4497. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4498. #define POLLERR (8) /* Error event */
  4499. FUNCTION_MAY_BE_UNUSED
  4500. static int
  4501. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4502. {
  4503. struct timeval tv;
  4504. fd_set rset;
  4505. fd_set wset;
  4506. fd_set eset;
  4507. unsigned int i;
  4508. int result;
  4509. SOCKET maxfd = 0;
  4510. memset(&tv, 0, sizeof(tv));
  4511. tv.tv_sec = milliseconds / 1000;
  4512. tv.tv_usec = (milliseconds % 1000) * 1000;
  4513. FD_ZERO(&rset);
  4514. FD_ZERO(&wset);
  4515. FD_ZERO(&eset);
  4516. for (i = 0; i < n; i++) {
  4517. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4518. if (pfd[i].events & POLLIN) {
  4519. FD_SET(pfd[i].fd, &rset);
  4520. }
  4521. if (pfd[i].events & POLLOUT) {
  4522. FD_SET(pfd[i].fd, &wset);
  4523. }
  4524. /* Check for errors for any FD in the set */
  4525. FD_SET(pfd[i].fd, &eset);
  4526. }
  4527. pfd[i].revents = 0;
  4528. if (pfd[i].fd > maxfd) {
  4529. maxfd = pfd[i].fd;
  4530. }
  4531. }
  4532. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4533. for (i = 0; i < n; i++) {
  4534. if (FD_ISSET(pfd[i].fd, &rset)) {
  4535. pfd[i].revents |= POLLIN;
  4536. }
  4537. if (FD_ISSET(pfd[i].fd, &wset)) {
  4538. pfd[i].revents |= POLLOUT;
  4539. }
  4540. if (FD_ISSET(pfd[i].fd, &eset)) {
  4541. pfd[i].revents |= POLLERR;
  4542. }
  4543. }
  4544. }
  4545. /* We should subtract the time used in select from remaining
  4546. * "milliseconds", in particular if called from mg_poll with a
  4547. * timeout quantum.
  4548. * Unfortunately, the remaining time is not stored in "tv" in all
  4549. * implementations, so the result in "tv" must be considered undefined.
  4550. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4551. return result;
  4552. }
  4553. #endif /* HAVE_POLL */
  4554. #if defined(GCC_DIAGNOSTIC)
  4555. /* Enable unused function warning again */
  4556. #pragma GCC diagnostic pop
  4557. #endif
  4558. static void
  4559. set_close_on_exec(SOCKET sock,
  4560. const struct mg_connection *conn /* may be null */,
  4561. struct mg_context *ctx /* may be null */)
  4562. {
  4563. (void)conn; /* Unused. */
  4564. (void)ctx;
  4565. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4566. }
  4567. CIVETWEB_API int
  4568. mg_start_thread(mg_thread_func_t f, void *p)
  4569. {
  4570. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4571. /* Compile-time option to control stack size, e.g.
  4572. * -DUSE_STACK_SIZE=16384
  4573. */
  4574. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4575. == ((uintptr_t)(-1L)))
  4576. ? -1
  4577. : 0);
  4578. #else
  4579. return (
  4580. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4581. ? -1
  4582. : 0);
  4583. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4584. }
  4585. /* Start a thread storing the thread context. */
  4586. static int
  4587. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4588. void *p,
  4589. pthread_t *threadidptr)
  4590. {
  4591. uintptr_t uip;
  4592. HANDLE threadhandle;
  4593. int result = -1;
  4594. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4595. threadhandle = (HANDLE)uip;
  4596. if ((uip != 0) && (threadidptr != NULL)) {
  4597. *threadidptr = threadhandle;
  4598. result = 0;
  4599. }
  4600. return result;
  4601. }
  4602. /* Wait for a thread to finish. */
  4603. static int
  4604. mg_join_thread(pthread_t threadid)
  4605. {
  4606. int result;
  4607. DWORD dwevent;
  4608. result = -1;
  4609. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4610. if (dwevent == WAIT_FAILED) {
  4611. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4612. } else {
  4613. if (dwevent == WAIT_OBJECT_0) {
  4614. CloseHandle(threadid);
  4615. result = 0;
  4616. }
  4617. }
  4618. return result;
  4619. }
  4620. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4621. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4622. /* Create substitutes for POSIX functions in Win32. */
  4623. #if defined(GCC_DIAGNOSTIC)
  4624. /* Show no warning in case system functions are not used. */
  4625. #pragma GCC diagnostic push
  4626. #pragma GCC diagnostic ignored "-Wunused-function"
  4627. #endif
  4628. FUNCTION_MAY_BE_UNUSED
  4629. static HANDLE
  4630. dlopen(const char *dll_name, int flags)
  4631. {
  4632. wchar_t wbuf[UTF16_PATH_MAX];
  4633. (void)flags;
  4634. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4635. return LoadLibraryW(wbuf);
  4636. }
  4637. FUNCTION_MAY_BE_UNUSED
  4638. static int
  4639. dlclose(void *handle)
  4640. {
  4641. int result;
  4642. if (FreeLibrary((HMODULE)handle) != 0) {
  4643. result = 0;
  4644. } else {
  4645. result = -1;
  4646. }
  4647. return result;
  4648. }
  4649. #if defined(GCC_DIAGNOSTIC)
  4650. /* Enable unused function warning again */
  4651. #pragma GCC diagnostic pop
  4652. #endif
  4653. #endif
  4654. #if !defined(NO_CGI)
  4655. #define SIGKILL (0)
  4656. static int
  4657. kill(pid_t pid, int sig_num)
  4658. {
  4659. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4660. (void)CloseHandle((HANDLE)pid);
  4661. return 0;
  4662. }
  4663. #if !defined(WNOHANG)
  4664. #define WNOHANG (1)
  4665. #endif
  4666. static pid_t
  4667. waitpid(pid_t pid, int *status, int flags)
  4668. {
  4669. DWORD timeout = INFINITE;
  4670. DWORD waitres;
  4671. (void)status; /* Currently not used by any client here */
  4672. if ((flags | WNOHANG) == WNOHANG) {
  4673. timeout = 0;
  4674. }
  4675. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4676. if (waitres == WAIT_OBJECT_0) {
  4677. return pid;
  4678. }
  4679. if (waitres == WAIT_TIMEOUT) {
  4680. return 0;
  4681. }
  4682. return (pid_t)-1;
  4683. }
  4684. static void
  4685. trim_trailing_whitespaces(char *s)
  4686. {
  4687. char *e = s + strlen(s);
  4688. while ((e > s) && isspace((unsigned char)e[-1])) {
  4689. *(--e) = '\0';
  4690. }
  4691. }
  4692. static pid_t
  4693. spawn_process(struct mg_connection *conn,
  4694. const char *prog,
  4695. char *envblk,
  4696. char *envp[],
  4697. int fdin[2],
  4698. int fdout[2],
  4699. int fderr[2],
  4700. const char *dir,
  4701. int cgi_config_idx)
  4702. {
  4703. HANDLE me;
  4704. char *interp;
  4705. char *interp_arg = 0;
  4706. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4707. int truncated;
  4708. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4709. STARTUPINFOA si;
  4710. PROCESS_INFORMATION pi = {0};
  4711. (void)envp;
  4712. memset(&si, 0, sizeof(si));
  4713. si.cb = sizeof(si);
  4714. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4715. si.wShowWindow = SW_HIDE;
  4716. me = GetCurrentProcess();
  4717. DuplicateHandle(me,
  4718. (HANDLE)_get_osfhandle(fdin[0]),
  4719. me,
  4720. &si.hStdInput,
  4721. 0,
  4722. TRUE,
  4723. DUPLICATE_SAME_ACCESS);
  4724. DuplicateHandle(me,
  4725. (HANDLE)_get_osfhandle(fdout[1]),
  4726. me,
  4727. &si.hStdOutput,
  4728. 0,
  4729. TRUE,
  4730. DUPLICATE_SAME_ACCESS);
  4731. DuplicateHandle(me,
  4732. (HANDLE)_get_osfhandle(fderr[1]),
  4733. me,
  4734. &si.hStdError,
  4735. 0,
  4736. TRUE,
  4737. DUPLICATE_SAME_ACCESS);
  4738. /* Mark handles that should not be inherited. See
  4739. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4740. */
  4741. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4742. HANDLE_FLAG_INHERIT,
  4743. 0);
  4744. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4745. HANDLE_FLAG_INHERIT,
  4746. 0);
  4747. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4748. HANDLE_FLAG_INHERIT,
  4749. 0);
  4750. /* First check, if there is a CGI interpreter configured for all CGI
  4751. * scripts. */
  4752. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4753. if (interp != NULL) {
  4754. /* If there is a configured interpreter, check for additional arguments
  4755. */
  4756. interp_arg =
  4757. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4758. } else {
  4759. /* Otherwise, the interpreter must be stated in the first line of the
  4760. * CGI script file, after a #! (shebang) mark. */
  4761. buf[0] = buf[1] = '\0';
  4762. /* Get the full script path */
  4763. mg_snprintf(
  4764. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4765. if (truncated) {
  4766. pi.hProcess = (pid_t)-1;
  4767. goto spawn_cleanup;
  4768. }
  4769. /* Open the script file, to read the first line */
  4770. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4771. /* Read the first line of the script into the buffer */
  4772. mg_fgets(buf, sizeof(buf), &file);
  4773. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4774. buf[sizeof(buf) - 1] = '\0';
  4775. }
  4776. if ((buf[0] == '#') && (buf[1] == '!')) {
  4777. trim_trailing_whitespaces(buf + 2);
  4778. } else {
  4779. buf[2] = '\0';
  4780. }
  4781. interp = buf + 2;
  4782. }
  4783. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4784. if (interp[0] != '\0') {
  4785. /* This is an interpreted script file. We must call the interpreter. */
  4786. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4787. mg_snprintf(conn,
  4788. &truncated,
  4789. cmdline,
  4790. sizeof(cmdline),
  4791. "\"%s\" %s \"%s\\%s\"",
  4792. interp,
  4793. interp_arg,
  4794. full_dir,
  4795. prog);
  4796. } else {
  4797. mg_snprintf(conn,
  4798. &truncated,
  4799. cmdline,
  4800. sizeof(cmdline),
  4801. "\"%s\" \"%s\\%s\"",
  4802. interp,
  4803. full_dir,
  4804. prog);
  4805. }
  4806. } else {
  4807. /* This is (probably) a compiled program. We call it directly. */
  4808. mg_snprintf(conn,
  4809. &truncated,
  4810. cmdline,
  4811. sizeof(cmdline),
  4812. "\"%s\\%s\"",
  4813. full_dir,
  4814. prog);
  4815. }
  4816. if (truncated) {
  4817. pi.hProcess = (pid_t)-1;
  4818. goto spawn_cleanup;
  4819. }
  4820. DEBUG_TRACE("Running [%s]", cmdline);
  4821. if (CreateProcessA(NULL,
  4822. cmdline,
  4823. NULL,
  4824. NULL,
  4825. TRUE,
  4826. CREATE_NEW_PROCESS_GROUP,
  4827. envblk,
  4828. NULL,
  4829. &si,
  4830. &pi)
  4831. == 0) {
  4832. mg_cry_internal(
  4833. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4834. pi.hProcess = (pid_t)-1;
  4835. /* goto spawn_cleanup; */
  4836. }
  4837. spawn_cleanup:
  4838. (void)CloseHandle(si.hStdOutput);
  4839. (void)CloseHandle(si.hStdError);
  4840. (void)CloseHandle(si.hStdInput);
  4841. if (pi.hThread != NULL) {
  4842. (void)CloseHandle(pi.hThread);
  4843. }
  4844. return (pid_t)pi.hProcess;
  4845. }
  4846. #endif /* !NO_CGI */
  4847. static int
  4848. set_blocking_mode(SOCKET sock)
  4849. {
  4850. unsigned long non_blocking = 0;
  4851. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4852. }
  4853. static int
  4854. set_non_blocking_mode(SOCKET sock)
  4855. {
  4856. unsigned long non_blocking = 1;
  4857. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4858. }
  4859. #else
  4860. #if !defined(NO_FILESYSTEMS)
  4861. static int
  4862. mg_stat(const struct mg_connection *conn,
  4863. const char *path,
  4864. struct mg_file_stat *filep)
  4865. {
  4866. struct stat st;
  4867. if (!filep) {
  4868. return 0;
  4869. }
  4870. memset(filep, 0, sizeof(*filep));
  4871. if (mg_path_suspicious(conn, path)) {
  4872. return 0;
  4873. }
  4874. if (0 == stat(path, &st)) {
  4875. filep->size = (uint64_t)(st.st_size);
  4876. filep->last_modified = st.st_mtime;
  4877. filep->is_directory = S_ISDIR(st.st_mode);
  4878. return 1;
  4879. }
  4880. return 0;
  4881. }
  4882. #endif /* NO_FILESYSTEMS */
  4883. static void
  4884. set_close_on_exec(int fd,
  4885. const struct mg_connection *conn /* may be null */,
  4886. struct mg_context *ctx /* may be null */)
  4887. {
  4888. #if defined(__ZEPHYR__)
  4889. (void)fd;
  4890. (void)conn;
  4891. (void)ctx;
  4892. #else
  4893. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4894. if (conn || ctx) {
  4895. struct mg_connection fc;
  4896. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4897. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4898. __func__,
  4899. strerror(ERRNO));
  4900. }
  4901. }
  4902. #endif
  4903. }
  4904. CIVETWEB_API int
  4905. mg_start_thread(mg_thread_func_t func, void *param)
  4906. {
  4907. pthread_t thread_id;
  4908. pthread_attr_t attr;
  4909. int result;
  4910. (void)pthread_attr_init(&attr);
  4911. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4912. #if defined(__ZEPHYR__)
  4913. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4914. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4915. /* Compile-time option to control stack size,
  4916. * e.g. -DUSE_STACK_SIZE=16384 */
  4917. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4918. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4919. result = pthread_create(&thread_id, &attr, func, param);
  4920. pthread_attr_destroy(&attr);
  4921. return result;
  4922. }
  4923. /* Start a thread storing the thread context. */
  4924. static int
  4925. mg_start_thread_with_id(mg_thread_func_t func,
  4926. void *param,
  4927. pthread_t *threadidptr)
  4928. {
  4929. pthread_t thread_id;
  4930. pthread_attr_t attr;
  4931. int result;
  4932. (void)pthread_attr_init(&attr);
  4933. #if defined(__ZEPHYR__)
  4934. pthread_attr_setstack(&attr,
  4935. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4936. ZEPHYR_STACK_SIZE);
  4937. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4938. /* Compile-time option to control stack size,
  4939. * e.g. -DUSE_STACK_SIZE=16384 */
  4940. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4941. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4942. result = pthread_create(&thread_id, &attr, func, param);
  4943. pthread_attr_destroy(&attr);
  4944. if ((result == 0) && (threadidptr != NULL)) {
  4945. *threadidptr = thread_id;
  4946. }
  4947. return result;
  4948. }
  4949. /* Wait for a thread to finish. */
  4950. static int
  4951. mg_join_thread(pthread_t threadid)
  4952. {
  4953. int result;
  4954. result = pthread_join(threadid, NULL);
  4955. return result;
  4956. }
  4957. #if !defined(NO_CGI)
  4958. static pid_t
  4959. spawn_process(struct mg_connection *conn,
  4960. const char *prog,
  4961. char *envblk,
  4962. char *envp[],
  4963. int fdin[2],
  4964. int fdout[2],
  4965. int fderr[2],
  4966. const char *dir,
  4967. int cgi_config_idx)
  4968. {
  4969. pid_t pid;
  4970. const char *interp;
  4971. (void)envblk;
  4972. if ((pid = fork()) == -1) {
  4973. /* Parent */
  4974. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4975. } else if (pid != 0) {
  4976. /* Make sure children close parent-side descriptors.
  4977. * The caller will close the child-side immediately. */
  4978. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4979. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4980. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4981. } else {
  4982. /* Child */
  4983. if (chdir(dir) != 0) {
  4984. mg_cry_internal(
  4985. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4986. } else if (dup2(fdin[0], 0) == -1) {
  4987. mg_cry_internal(conn,
  4988. "%s: dup2(%d, 0): %s",
  4989. __func__,
  4990. fdin[0],
  4991. strerror(ERRNO));
  4992. } else if (dup2(fdout[1], 1) == -1) {
  4993. mg_cry_internal(conn,
  4994. "%s: dup2(%d, 1): %s",
  4995. __func__,
  4996. fdout[1],
  4997. strerror(ERRNO));
  4998. } else if (dup2(fderr[1], 2) == -1) {
  4999. mg_cry_internal(conn,
  5000. "%s: dup2(%d, 2): %s",
  5001. __func__,
  5002. fderr[1],
  5003. strerror(ERRNO));
  5004. } else {
  5005. struct sigaction sa;
  5006. /* Keep stderr and stdout in two different pipes.
  5007. * Stdout will be sent back to the client,
  5008. * stderr should go into a server error log. */
  5009. (void)close(fdin[0]);
  5010. (void)close(fdout[1]);
  5011. (void)close(fderr[1]);
  5012. /* Close write end fdin and read end fdout and fderr */
  5013. (void)close(fdin[1]);
  5014. (void)close(fdout[0]);
  5015. (void)close(fderr[0]);
  5016. /* After exec, all signal handlers are restored to their default
  5017. * values, with one exception of SIGCHLD. According to
  5018. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5019. * will leave unchanged after exec if it was set to be ignored.
  5020. * Restore it to default action. */
  5021. memset(&sa, 0, sizeof(sa));
  5022. sa.sa_handler = SIG_DFL;
  5023. sigaction(SIGCHLD, &sa, NULL);
  5024. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  5025. if (interp == NULL) {
  5026. /* no interpreter configured, call the program directly */
  5027. (void)execle(prog, prog, NULL, envp);
  5028. mg_cry_internal(conn,
  5029. "%s: execle(%s): %s",
  5030. __func__,
  5031. prog,
  5032. strerror(ERRNO));
  5033. } else {
  5034. /* call the configured interpreter */
  5035. const char *interp_args =
  5036. conn->dom_ctx
  5037. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5038. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5039. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5040. } else {
  5041. (void)execle(interp, interp, prog, NULL, envp);
  5042. }
  5043. mg_cry_internal(conn,
  5044. "%s: execle(%s %s): %s",
  5045. __func__,
  5046. interp,
  5047. prog,
  5048. strerror(ERRNO));
  5049. }
  5050. }
  5051. exit(EXIT_FAILURE);
  5052. }
  5053. return pid;
  5054. }
  5055. #endif /* !NO_CGI */
  5056. static int
  5057. set_non_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 | O_NONBLOCK)) < 0) {
  5064. return -1;
  5065. }
  5066. return 0;
  5067. }
  5068. static int
  5069. set_blocking_mode(SOCKET sock)
  5070. {
  5071. int flags = fcntl(sock, F_GETFL, 0);
  5072. if (flags < 0) {
  5073. return -1;
  5074. }
  5075. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5076. return -1;
  5077. }
  5078. return 0;
  5079. }
  5080. #endif /* _WIN32 / else */
  5081. /* End of initial operating system specific define block. */
  5082. /* Get a random number (independent of C rand function) */
  5083. static uint64_t
  5084. get_random(void)
  5085. {
  5086. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5087. static uint64_t lcg = 0; /* Linear congruential generator */
  5088. uint64_t now = mg_get_current_time_ns();
  5089. if (lfsr == 0) {
  5090. /* lfsr will be only 0 if has not been initialized,
  5091. * so this code is called only once. */
  5092. lfsr = mg_get_current_time_ns();
  5093. lcg = mg_get_current_time_ns();
  5094. } else {
  5095. /* Get the next step of both random number generators. */
  5096. lfsr = (lfsr >> 1)
  5097. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5098. << 63);
  5099. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5100. }
  5101. /* Combining two pseudo-random number generators and a high resolution
  5102. * part
  5103. * of the current server time will make it hard (impossible?) to guess
  5104. * the
  5105. * next number. */
  5106. return (lfsr ^ lcg ^ now);
  5107. }
  5108. static int
  5109. mg_poll(struct mg_pollfd *pfd,
  5110. unsigned int n,
  5111. int milliseconds,
  5112. const stop_flag_t *stop_flag)
  5113. {
  5114. /* Call poll, but only for a maximum time of a few seconds.
  5115. * This will allow to stop the server after some seconds, instead
  5116. * of having to wait for a long socket timeout. */
  5117. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5118. int check_pollerr = 0;
  5119. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5120. /* If we wait for only one file descriptor, wait on error as well */
  5121. pfd[0].events |= POLLERR;
  5122. check_pollerr = 1;
  5123. }
  5124. do {
  5125. int result;
  5126. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5127. /* Shut down signal */
  5128. return -2;
  5129. }
  5130. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5131. ms_now = milliseconds;
  5132. }
  5133. result = poll(pfd, n, ms_now);
  5134. if (result != 0) {
  5135. int err = ERRNO;
  5136. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5137. /* Poll returned either success (1) or error (-1).
  5138. * Forward both to the caller. */
  5139. if ((check_pollerr)
  5140. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5141. == POLLERR)) {
  5142. /* One and only file descriptor returned error */
  5143. return -1;
  5144. }
  5145. return result;
  5146. }
  5147. }
  5148. /* Poll returned timeout (0). */
  5149. if (milliseconds > 0) {
  5150. milliseconds -= ms_now;
  5151. }
  5152. } while (milliseconds > 0);
  5153. /* timeout: return 0 */
  5154. return 0;
  5155. }
  5156. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5157. * descriptor.
  5158. * Return value:
  5159. * >=0 .. number of bytes successfully written
  5160. * -1 .. timeout
  5161. * -2 .. error
  5162. */
  5163. static int
  5164. push_inner(struct mg_context *ctx,
  5165. FILE *fp,
  5166. SOCKET sock,
  5167. SSL *ssl,
  5168. const char *buf,
  5169. int len,
  5170. double timeout)
  5171. {
  5172. uint64_t start = 0, now = 0, timeout_ns = 0;
  5173. int n, err;
  5174. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5175. #if defined(_WIN32)
  5176. typedef int len_t;
  5177. #else
  5178. typedef size_t len_t;
  5179. #endif
  5180. if (timeout > 0) {
  5181. now = mg_get_current_time_ns();
  5182. start = now;
  5183. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5184. }
  5185. if (ctx == NULL) {
  5186. return -2;
  5187. }
  5188. #if defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  5189. if (ssl) {
  5190. return -2;
  5191. }
  5192. #endif
  5193. /* Try to read until it succeeds, fails, times out, or the server
  5194. * shuts down. */
  5195. for (;;) {
  5196. #if defined(USE_MBEDTLS)
  5197. if (ssl != NULL) {
  5198. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5199. if (n <= 0) {
  5200. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5201. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5202. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5203. n = 0;
  5204. } else {
  5205. fprintf(stderr, "SSL write failed, error %d\n", n);
  5206. return -2;
  5207. }
  5208. } else {
  5209. err = 0;
  5210. }
  5211. } else
  5212. #elif defined(USE_GNUTLS)
  5213. if (ssl != NULL) {
  5214. n = gtls_ssl_write(ssl, (const unsigned char *)buf, (size_t)len);
  5215. if (n < 0) {
  5216. fprintf(stderr,
  5217. "SSL write failed (%d): %s",
  5218. n,
  5219. gnutls_strerror(n));
  5220. return -2;
  5221. } else {
  5222. err = 0;
  5223. }
  5224. } else
  5225. #elif !defined(NO_SSL)
  5226. if (ssl != NULL) {
  5227. ERR_clear_error();
  5228. n = SSL_write(ssl, buf, len);
  5229. if (n <= 0) {
  5230. err = SSL_get_error(ssl, n);
  5231. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5232. err = ERRNO;
  5233. } else if ((err == SSL_ERROR_WANT_READ)
  5234. || (err == SSL_ERROR_WANT_WRITE)) {
  5235. n = 0;
  5236. } else {
  5237. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5238. ERR_clear_error();
  5239. return -2;
  5240. }
  5241. ERR_clear_error();
  5242. } else {
  5243. err = 0;
  5244. }
  5245. } else
  5246. #endif
  5247. if (fp != NULL) {
  5248. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5249. if (ferror(fp)) {
  5250. n = -1;
  5251. err = ERRNO;
  5252. } else {
  5253. err = 0;
  5254. }
  5255. } else {
  5256. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5257. err = (n < 0) ? ERRNO : 0;
  5258. if (ERROR_TRY_AGAIN(err)) {
  5259. err = 0;
  5260. n = 0;
  5261. }
  5262. if (n < 0) {
  5263. /* shutdown of the socket at client side */
  5264. return -2;
  5265. }
  5266. }
  5267. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5268. return -2;
  5269. }
  5270. if ((n > 0) || ((n == 0) && (len == 0))) {
  5271. /* some data has been read, or no data was requested */
  5272. return n;
  5273. }
  5274. if (n < 0) {
  5275. /* socket error - check errno */
  5276. DEBUG_TRACE("send() failed, error %d", err);
  5277. /* TODO (mid): error handling depending on the error code.
  5278. * These codes are different between Windows and Linux.
  5279. * Currently there is no problem with failing send calls,
  5280. * if there is a reproducible situation, it should be
  5281. * investigated in detail.
  5282. */
  5283. return -2;
  5284. }
  5285. /* Only in case n=0 (timeout), repeat calling the write function */
  5286. /* If send failed, wait before retry */
  5287. if (fp != NULL) {
  5288. /* For files, just wait a fixed time.
  5289. * Maybe it helps, maybe not. */
  5290. mg_sleep(5);
  5291. } else {
  5292. /* For sockets, wait for the socket using poll */
  5293. struct mg_pollfd pfd[2];
  5294. int pollres;
  5295. unsigned int num_sock = 1;
  5296. pfd[0].fd = sock;
  5297. pfd[0].events = POLLOUT;
  5298. if (ctx->context_type == CONTEXT_SERVER) {
  5299. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  5300. pfd[num_sock].events = POLLIN;
  5301. num_sock++;
  5302. }
  5303. pollres = mg_poll(pfd, num_sock, (int)(ms_wait), &(ctx->stop_flag));
  5304. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5305. return -2;
  5306. }
  5307. if (pollres > 0) {
  5308. continue;
  5309. }
  5310. }
  5311. if (timeout > 0) {
  5312. now = mg_get_current_time_ns();
  5313. if ((now - start) > timeout_ns) {
  5314. /* Timeout */
  5315. break;
  5316. }
  5317. }
  5318. }
  5319. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5320. used */
  5321. return -1;
  5322. }
  5323. static int
  5324. push_all(struct mg_context *ctx,
  5325. FILE *fp,
  5326. SOCKET sock,
  5327. SSL *ssl,
  5328. const char *buf,
  5329. int len)
  5330. {
  5331. double timeout = -1.0;
  5332. int n, nwritten = 0;
  5333. if (ctx == NULL) {
  5334. return -1;
  5335. }
  5336. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5337. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5338. }
  5339. if (timeout <= 0.0) {
  5340. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5341. / 1000.0;
  5342. }
  5343. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5344. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5345. if (n < 0) {
  5346. if (nwritten == 0) {
  5347. nwritten = -1; /* Propagate the error */
  5348. }
  5349. break;
  5350. } else if (n == 0) {
  5351. break; /* No more data to write */
  5352. } else {
  5353. nwritten += n;
  5354. len -= n;
  5355. }
  5356. }
  5357. return nwritten;
  5358. }
  5359. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5360. * Return value:
  5361. * >=0 .. number of bytes successfully read
  5362. * -1 .. timeout
  5363. * -2 .. error
  5364. */
  5365. static int
  5366. pull_inner(FILE *fp,
  5367. struct mg_connection *conn,
  5368. char *buf,
  5369. int len,
  5370. double timeout)
  5371. {
  5372. int nread, err = 0;
  5373. #if defined(_WIN32)
  5374. typedef int len_t;
  5375. #else
  5376. typedef size_t len_t;
  5377. #endif
  5378. /* We need an additional wait loop around this, because in some cases
  5379. * with TLSwe may get data from the socket but not from SSL_read.
  5380. * In this case we need to repeat at least once.
  5381. */
  5382. if (fp != NULL) {
  5383. /* Use read() instead of fread(), because if we're reading from the
  5384. * CGI pipe, fread() may block until IO buffer is filled up. We
  5385. * cannot afford to block and must pass all read bytes immediately
  5386. * to the client. */
  5387. nread = (int)read(fileno(fp), buf, (size_t)len);
  5388. err = (nread < 0) ? ERRNO : 0;
  5389. if ((nread == 0) && (len > 0)) {
  5390. /* Should get data, but got EOL */
  5391. return -2;
  5392. }
  5393. #if defined(USE_MBEDTLS)
  5394. } else if (conn->ssl != NULL) {
  5395. struct mg_pollfd pfd[2];
  5396. int to_read;
  5397. int pollres;
  5398. unsigned int num_sock = 1;
  5399. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5400. if (to_read > 0) {
  5401. /* We already know there is no more data buffered in conn->buf
  5402. * but there is more available in the SSL layer. So don't poll
  5403. * conn->client.sock yet. */
  5404. pollres = 1;
  5405. if (to_read > len)
  5406. to_read = len;
  5407. } else {
  5408. pfd[0].fd = conn->client.sock;
  5409. pfd[0].events = POLLIN;
  5410. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5411. pfd[num_sock].fd =
  5412. conn->phys_ctx->thread_shutdown_notification_socket;
  5413. pfd[num_sock].events = POLLIN;
  5414. num_sock++;
  5415. }
  5416. to_read = len;
  5417. pollres = mg_poll(pfd,
  5418. num_sock,
  5419. (int)(timeout * 1000.0),
  5420. &(conn->phys_ctx->stop_flag));
  5421. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5422. return -2;
  5423. }
  5424. }
  5425. if (pollres > 0) {
  5426. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5427. if (nread <= 0) {
  5428. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5429. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5430. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5431. nread = 0;
  5432. } else {
  5433. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5434. return -2;
  5435. }
  5436. } else {
  5437. err = 0;
  5438. }
  5439. } else if (pollres < 0) {
  5440. /* Error */
  5441. return -2;
  5442. } else {
  5443. /* pollres = 0 means timeout */
  5444. nread = 0;
  5445. }
  5446. #elif defined(USE_GNUTLS)
  5447. } else if (conn->ssl != NULL) {
  5448. struct mg_pollfd pfd[2];
  5449. size_t to_read;
  5450. int pollres;
  5451. unsigned int num_sock = 1;
  5452. to_read = gnutls_record_check_pending(conn->ssl->sess);
  5453. if (to_read > 0) {
  5454. /* We already know there is no more data buffered in conn->buf
  5455. * but there is more available in the SSL layer. So don't poll
  5456. * conn->client.sock yet. */
  5457. pollres = 1;
  5458. if (to_read > (size_t)len)
  5459. to_read = (size_t)len;
  5460. } else {
  5461. pfd[0].fd = conn->client.sock;
  5462. pfd[0].events = POLLIN;
  5463. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5464. pfd[num_sock].fd =
  5465. conn->phys_ctx->thread_shutdown_notification_socket;
  5466. pfd[num_sock].events = POLLIN;
  5467. num_sock++;
  5468. }
  5469. to_read = (size_t)len;
  5470. pollres = mg_poll(pfd,
  5471. num_sock,
  5472. (int)(timeout * 1000.0),
  5473. &(conn->phys_ctx->stop_flag));
  5474. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5475. return -2;
  5476. }
  5477. }
  5478. if (pollres > 0) {
  5479. nread = gtls_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5480. if (nread < 0) {
  5481. fprintf(stderr,
  5482. "SSL read failed (%d): %s",
  5483. nread,
  5484. gnutls_strerror(nread));
  5485. return -2;
  5486. } else {
  5487. err = 0;
  5488. }
  5489. } else if (pollres < 0) {
  5490. /* Error */
  5491. return -2;
  5492. } else {
  5493. /* pollres = 0 means timeout */
  5494. nread = 0;
  5495. }
  5496. #elif !defined(NO_SSL)
  5497. } else if (conn->ssl != NULL) {
  5498. int ssl_pending;
  5499. struct mg_pollfd pfd[2];
  5500. int pollres;
  5501. unsigned int num_sock = 1;
  5502. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5503. /* We already know there is no more data buffered in conn->buf
  5504. * but there is more available in the SSL layer. So don't poll
  5505. * conn->client.sock yet. */
  5506. if (ssl_pending > len) {
  5507. ssl_pending = len;
  5508. }
  5509. pollres = 1;
  5510. } else {
  5511. pfd[0].fd = conn->client.sock;
  5512. pfd[0].events = POLLIN;
  5513. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5514. pfd[num_sock].fd =
  5515. conn->phys_ctx->thread_shutdown_notification_socket;
  5516. pfd[num_sock].events = POLLIN;
  5517. num_sock++;
  5518. }
  5519. pollres = mg_poll(pfd,
  5520. num_sock,
  5521. (int)(timeout * 1000.0),
  5522. &(conn->phys_ctx->stop_flag));
  5523. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5524. return -2;
  5525. }
  5526. }
  5527. if (pollres > 0) {
  5528. ERR_clear_error();
  5529. nread =
  5530. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5531. if (nread <= 0) {
  5532. err = SSL_get_error(conn->ssl, nread);
  5533. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5534. err = ERRNO;
  5535. } else if ((err == SSL_ERROR_WANT_READ)
  5536. || (err == SSL_ERROR_WANT_WRITE)) {
  5537. nread = 0;
  5538. } else {
  5539. /* All errors should return -2 */
  5540. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5541. ERR_clear_error();
  5542. return -2;
  5543. }
  5544. ERR_clear_error();
  5545. } else {
  5546. err = 0;
  5547. }
  5548. } else if (pollres < 0) {
  5549. /* Error */
  5550. return -2;
  5551. } else {
  5552. /* pollres = 0 means timeout */
  5553. nread = 0;
  5554. }
  5555. #endif
  5556. } else {
  5557. struct mg_pollfd pfd[2];
  5558. int pollres;
  5559. unsigned int num_sock = 1;
  5560. pfd[0].fd = conn->client.sock;
  5561. pfd[0].events = POLLIN;
  5562. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5563. pfd[num_sock].fd =
  5564. conn->phys_ctx->thread_shutdown_notification_socket;
  5565. pfd[num_sock].events = POLLIN;
  5566. num_sock++;
  5567. }
  5568. pollres = mg_poll(pfd,
  5569. num_sock,
  5570. (int)(timeout * 1000.0),
  5571. &(conn->phys_ctx->stop_flag));
  5572. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5573. return -2;
  5574. }
  5575. if (pollres > 0) {
  5576. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5577. err = (nread < 0) ? ERRNO : 0;
  5578. if (nread <= 0) {
  5579. /* shutdown of the socket at client side */
  5580. return -2;
  5581. }
  5582. } else if (pollres < 0) {
  5583. /* error calling poll */
  5584. return -2;
  5585. } else {
  5586. /* pollres = 0 means timeout */
  5587. nread = 0;
  5588. }
  5589. }
  5590. if (conn != NULL && !STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5591. return -2;
  5592. }
  5593. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5594. /* some data has been read, or no data was requested */
  5595. return nread;
  5596. }
  5597. if (nread < 0) {
  5598. /* socket error - check errno */
  5599. #if defined(_WIN32)
  5600. if (err == WSAEWOULDBLOCK) {
  5601. /* TODO (low): check if this is still required */
  5602. /* standard case if called from close_socket_gracefully */
  5603. return -2;
  5604. } else if (err == WSAETIMEDOUT) {
  5605. /* TODO (low): check if this is still required */
  5606. /* timeout is handled by the while loop */
  5607. return 0;
  5608. } else if (err == WSAECONNABORTED) {
  5609. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5610. return -2;
  5611. } else {
  5612. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5613. return -2;
  5614. }
  5615. #else
  5616. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5617. * if the timeout is reached and if the socket was set to non-
  5618. * blocking in close_socket_gracefully, so we can not distinguish
  5619. * here. We have to wait for the timeout in both cases for now.
  5620. */
  5621. if (ERROR_TRY_AGAIN(err)) {
  5622. /* TODO (low): check if this is still required */
  5623. /* EAGAIN/EWOULDBLOCK:
  5624. * standard case if called from close_socket_gracefully
  5625. * => should return -1 */
  5626. /* or timeout occurred
  5627. * => the code must stay in the while loop */
  5628. /* EINTR can be generated on a socket with a timeout set even
  5629. * when SA_RESTART is effective for all relevant signals
  5630. * (see signal(7)).
  5631. * => stay in the while loop */
  5632. } else {
  5633. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5634. return -2;
  5635. }
  5636. #endif
  5637. }
  5638. /* Timeout occurred, but no data available. */
  5639. return -1;
  5640. }
  5641. static int
  5642. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5643. {
  5644. int n, nread = 0;
  5645. double timeout = -1.0;
  5646. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5647. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5648. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5649. }
  5650. if (timeout <= 0.0) {
  5651. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5652. / 1000.0;
  5653. }
  5654. start_time = mg_get_current_time_ns();
  5655. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5656. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5657. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5658. if (n == -2) {
  5659. if (nread == 0) {
  5660. nread = -1; /* Propagate the error */
  5661. }
  5662. break;
  5663. } else if (n == -1) {
  5664. /* timeout */
  5665. if (timeout >= 0.0) {
  5666. now = mg_get_current_time_ns();
  5667. if ((now - start_time) <= timeout_ns) {
  5668. continue;
  5669. }
  5670. }
  5671. break;
  5672. } else if (n == 0) {
  5673. break; /* No more data to read */
  5674. } else {
  5675. nread += n;
  5676. len -= n;
  5677. }
  5678. }
  5679. return nread;
  5680. }
  5681. static void
  5682. discard_unread_request_data(struct mg_connection *conn)
  5683. {
  5684. char buf[MG_BUF_LEN];
  5685. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5686. ;
  5687. }
  5688. static int
  5689. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5690. {
  5691. int64_t content_len, n, buffered_len, nread;
  5692. int64_t len64 =
  5693. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5694. * int, we may not read more
  5695. * bytes */
  5696. const char *body;
  5697. if (conn == NULL) {
  5698. return 0;
  5699. }
  5700. /* If Content-Length is not set for a response with body data,
  5701. * we do not know in advance how much data should be read. */
  5702. content_len = conn->content_len;
  5703. if (content_len < 0) {
  5704. /* The body data is completed when the connection is closed. */
  5705. content_len = INT64_MAX;
  5706. }
  5707. nread = 0;
  5708. if (conn->consumed_content < content_len) {
  5709. /* Adjust number of bytes to read. */
  5710. int64_t left_to_read = content_len - conn->consumed_content;
  5711. if (left_to_read < len64) {
  5712. /* Do not read more than the total content length of the
  5713. * request.
  5714. */
  5715. len64 = left_to_read;
  5716. }
  5717. /* Return buffered data */
  5718. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5719. - conn->consumed_content;
  5720. if (buffered_len > 0) {
  5721. if (len64 < buffered_len) {
  5722. buffered_len = len64;
  5723. }
  5724. body = conn->buf + conn->request_len + conn->consumed_content;
  5725. memcpy(buf, body, (size_t)buffered_len);
  5726. len64 -= buffered_len;
  5727. conn->consumed_content += buffered_len;
  5728. nread += buffered_len;
  5729. buf = (char *)buf + buffered_len;
  5730. }
  5731. /* We have returned all buffered data. Read new data from the remote
  5732. * socket.
  5733. */
  5734. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5735. conn->consumed_content += n;
  5736. nread += n;
  5737. } else {
  5738. nread = ((nread > 0) ? nread : n);
  5739. }
  5740. }
  5741. return (int)nread;
  5742. }
  5743. /* Forward declarations */
  5744. static void handle_request(struct mg_connection *);
  5745. static void log_access(const struct mg_connection *);
  5746. /* Handle request, update statistics and call access log */
  5747. static void
  5748. handle_request_stat_log(struct mg_connection *conn)
  5749. {
  5750. #if defined(USE_SERVER_STATS)
  5751. struct timespec tnow;
  5752. conn->conn_state = 4; /* processing */
  5753. #endif
  5754. handle_request(conn);
  5755. #if defined(USE_SERVER_STATS)
  5756. conn->conn_state = 5; /* processed */
  5757. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5758. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5759. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5760. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5761. conn->num_bytes_sent);
  5762. #endif
  5763. DEBUG_TRACE("%s", "handle_request done");
  5764. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5765. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5766. DEBUG_TRACE("%s", "end_request callback done");
  5767. }
  5768. log_access(conn);
  5769. }
  5770. #if defined(USE_HTTP2)
  5771. #if defined(NO_SSL)
  5772. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5773. #endif
  5774. #define USE_ALPN
  5775. #include "http2.inl"
  5776. /* Not supported with HTTP/2 */
  5777. #define HTTP1_only \
  5778. { \
  5779. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5780. http2_must_use_http1(conn); \
  5781. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5782. return; \
  5783. } \
  5784. }
  5785. #else
  5786. #define HTTP1_only
  5787. #endif
  5788. CIVETWEB_API int
  5789. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5790. {
  5791. if (len > INT_MAX) {
  5792. len = INT_MAX;
  5793. }
  5794. if (conn == NULL) {
  5795. return 0;
  5796. }
  5797. if (conn->is_chunked) {
  5798. size_t all_read = 0;
  5799. while (len > 0) {
  5800. if (conn->is_chunked >= 3) {
  5801. /* No more data left to read */
  5802. return 0;
  5803. }
  5804. if (conn->is_chunked != 1) {
  5805. /* Has error */
  5806. return -1;
  5807. }
  5808. if (conn->consumed_content != conn->content_len) {
  5809. /* copy from the current chunk */
  5810. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5811. if (read_ret < 1) {
  5812. /* read error */
  5813. conn->is_chunked = 2;
  5814. return -1;
  5815. }
  5816. all_read += (size_t)read_ret;
  5817. len -= (size_t)read_ret;
  5818. if (conn->consumed_content == conn->content_len) {
  5819. /* Add data bytes in the current chunk have been read,
  5820. * so we are expecting \r\n now. */
  5821. char x[2];
  5822. conn->content_len += 2;
  5823. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5824. || (x[1] != '\n')) {
  5825. /* Protocol violation */
  5826. conn->is_chunked = 2;
  5827. return -1;
  5828. }
  5829. }
  5830. } else {
  5831. /* fetch a new chunk */
  5832. size_t i;
  5833. char lenbuf[64];
  5834. char *end = NULL;
  5835. unsigned long chunkSize = 0;
  5836. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5837. conn->content_len++;
  5838. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5839. lenbuf[i] = 0;
  5840. }
  5841. if ((i > 0) && (lenbuf[i] == ';')) {
  5842. // chunk extension --> skip chars until next CR
  5843. //
  5844. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5845. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5846. //
  5847. // chunk = chunk-size [ chunk-extension ] CRLF
  5848. // chunk-data CRLF
  5849. // ...
  5850. // chunk-extension= *( ";" chunk-ext-name [ "="
  5851. // chunk-ext-val ] )
  5852. do
  5853. ++conn->content_len;
  5854. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5855. && lenbuf[i] != '\r');
  5856. }
  5857. if ((i > 0) && (lenbuf[i] == '\r')
  5858. && (lenbuf[i - 1] != '\r')) {
  5859. continue;
  5860. }
  5861. if ((i > 1) && (lenbuf[i] == '\n')
  5862. && (lenbuf[i - 1] == '\r')) {
  5863. lenbuf[i + 1] = 0;
  5864. chunkSize = strtoul(lenbuf, &end, 16);
  5865. if (chunkSize == 0) {
  5866. /* regular end of content */
  5867. conn->is_chunked = 3;
  5868. }
  5869. break;
  5870. }
  5871. if (!isxdigit((unsigned char)lenbuf[i])) {
  5872. /* illegal character for chunk length */
  5873. conn->is_chunked = 2;
  5874. return -1;
  5875. }
  5876. }
  5877. if ((end == NULL) || (*end != '\r')) {
  5878. /* chunksize not set correctly */
  5879. conn->is_chunked = 2;
  5880. return -1;
  5881. }
  5882. if (conn->is_chunked == 3) {
  5883. /* try discarding trailer for keep-alive */
  5884. // We found the last chunk (length 0) including the
  5885. // CRLF that terminates that chunk. Now follows a possibly
  5886. // empty trailer and a final CRLF.
  5887. //
  5888. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5889. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5890. //
  5891. // Chunked-Body = *chunk
  5892. // last-chunk
  5893. // trailer
  5894. // CRLF
  5895. // ...
  5896. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5897. // ...
  5898. // trailer = *(entity-header CRLF)
  5899. int crlf_count = 2; // one CRLF already determined
  5900. while (crlf_count < 4 && conn->is_chunked == 3) {
  5901. ++conn->content_len;
  5902. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5903. if ((crlf_count == 0 || crlf_count == 2)) {
  5904. if (lenbuf[0] == '\r')
  5905. ++crlf_count;
  5906. else
  5907. crlf_count = 0;
  5908. } else {
  5909. // previous character was a CR
  5910. // --> next character must be LF
  5911. if (lenbuf[0] == '\n')
  5912. ++crlf_count;
  5913. else
  5914. conn->is_chunked = 2;
  5915. }
  5916. } else
  5917. // premature end of trailer
  5918. conn->is_chunked = 2;
  5919. }
  5920. if (conn->is_chunked == 2)
  5921. return -1;
  5922. else
  5923. conn->is_chunked = 4;
  5924. break;
  5925. }
  5926. /* append a new chunk */
  5927. conn->content_len += (int64_t)chunkSize;
  5928. }
  5929. }
  5930. return (int)all_read;
  5931. }
  5932. return mg_read_inner(conn, buf, len);
  5933. }
  5934. CIVETWEB_API int
  5935. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5936. {
  5937. time_t now;
  5938. int n, total, allowed;
  5939. if (conn == NULL) {
  5940. return 0;
  5941. }
  5942. if (len > INT_MAX) {
  5943. return -1;
  5944. }
  5945. /* Mark connection as "data sent" */
  5946. conn->request_state = 10;
  5947. #if defined(USE_HTTP2)
  5948. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5949. http2_data_frame_head(conn, len, 0);
  5950. }
  5951. #endif
  5952. if (conn->throttle > 0) {
  5953. if ((now = time(NULL)) != conn->last_throttle_time) {
  5954. conn->last_throttle_time = now;
  5955. conn->last_throttle_bytes = 0;
  5956. }
  5957. allowed = conn->throttle - conn->last_throttle_bytes;
  5958. if (allowed > (int)len) {
  5959. allowed = (int)len;
  5960. }
  5961. total = push_all(conn->phys_ctx,
  5962. NULL,
  5963. conn->client.sock,
  5964. conn->ssl,
  5965. (const char *)buf,
  5966. allowed);
  5967. if (total == allowed) {
  5968. buf = (const char *)buf + total;
  5969. conn->last_throttle_bytes += total;
  5970. while ((total < (int)len)
  5971. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5972. allowed = (conn->throttle > ((int)len - total))
  5973. ? (int)len - total
  5974. : conn->throttle;
  5975. n = push_all(conn->phys_ctx,
  5976. NULL,
  5977. conn->client.sock,
  5978. conn->ssl,
  5979. (const char *)buf,
  5980. allowed);
  5981. if (n != allowed) {
  5982. break;
  5983. }
  5984. sleep(1);
  5985. conn->last_throttle_bytes = allowed;
  5986. conn->last_throttle_time = time(NULL);
  5987. buf = (const char *)buf + n;
  5988. total += n;
  5989. }
  5990. }
  5991. } else {
  5992. total = push_all(conn->phys_ctx,
  5993. NULL,
  5994. conn->client.sock,
  5995. conn->ssl,
  5996. (const char *)buf,
  5997. (int)len);
  5998. }
  5999. if (total > 0) {
  6000. conn->num_bytes_sent += total;
  6001. }
  6002. return total;
  6003. }
  6004. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6005. CIVETWEB_API int
  6006. mg_send_chunk(struct mg_connection *conn,
  6007. const char *chunk,
  6008. unsigned int chunk_len)
  6009. {
  6010. char lenbuf[16];
  6011. size_t lenbuf_len;
  6012. int ret;
  6013. int t;
  6014. /* First store the length information in a text buffer. */
  6015. sprintf(lenbuf, "%x\r\n", chunk_len);
  6016. lenbuf_len = strlen(lenbuf);
  6017. /* Then send length information, chunk and terminating \r\n. */
  6018. ret = mg_write(conn, lenbuf, lenbuf_len);
  6019. if (ret != (int)lenbuf_len) {
  6020. return -1;
  6021. }
  6022. t = ret;
  6023. ret = mg_write(conn, chunk, chunk_len);
  6024. if (ret != (int)chunk_len) {
  6025. return -1;
  6026. }
  6027. t += ret;
  6028. ret = mg_write(conn, "\r\n", 2);
  6029. if (ret != 2) {
  6030. return -1;
  6031. }
  6032. t += ret;
  6033. return t;
  6034. }
  6035. #if defined(GCC_DIAGNOSTIC)
  6036. /* This block forwards format strings to printf implementations,
  6037. * so we need to disable the format-nonliteral warning. */
  6038. #pragma GCC diagnostic push
  6039. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6040. #endif
  6041. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6042. static int
  6043. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6044. {
  6045. va_list ap_copy;
  6046. size_t size = MG_BUF_LEN / 4;
  6047. int len = -1;
  6048. *buf = NULL;
  6049. while (len < 0) {
  6050. if (*buf) {
  6051. mg_free(*buf);
  6052. }
  6053. size *= 4;
  6054. *buf = (char *)mg_malloc(size);
  6055. if (!*buf) {
  6056. break;
  6057. }
  6058. va_copy(ap_copy, ap);
  6059. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6060. va_end(ap_copy);
  6061. (*buf)[size - 1] = 0;
  6062. }
  6063. return len;
  6064. }
  6065. /* Print message to buffer. If buffer is large enough to hold the message,
  6066. * return buffer. If buffer is to small, allocate large enough buffer on
  6067. * heap,
  6068. * and return allocated buffer. */
  6069. static int
  6070. alloc_vprintf(char **out_buf,
  6071. char *prealloc_buf,
  6072. size_t prealloc_size,
  6073. const char *fmt,
  6074. va_list ap)
  6075. {
  6076. va_list ap_copy;
  6077. int len;
  6078. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6079. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6080. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6081. * Therefore, we make two passes: on first pass, get required message
  6082. * length.
  6083. * On second pass, actually print the message. */
  6084. va_copy(ap_copy, ap);
  6085. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6086. va_end(ap_copy);
  6087. if (len < 0) {
  6088. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6089. * Switch to alternative code path that uses incremental
  6090. * allocations.
  6091. */
  6092. va_copy(ap_copy, ap);
  6093. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6094. va_end(ap_copy);
  6095. } else if ((size_t)(len) >= prealloc_size) {
  6096. /* The pre-allocated buffer not large enough. */
  6097. /* Allocate a new buffer. */
  6098. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6099. if (!*out_buf) {
  6100. /* Allocation failed. Return -1 as "out of memory" error. */
  6101. return -1;
  6102. }
  6103. /* Buffer allocation successful. Store the string there. */
  6104. va_copy(ap_copy, ap);
  6105. IGNORE_UNUSED_RESULT(
  6106. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6107. va_end(ap_copy);
  6108. } else {
  6109. /* The pre-allocated buffer is large enough.
  6110. * Use it to store the string and return the address. */
  6111. va_copy(ap_copy, ap);
  6112. IGNORE_UNUSED_RESULT(
  6113. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6114. va_end(ap_copy);
  6115. *out_buf = prealloc_buf;
  6116. }
  6117. return len;
  6118. }
  6119. static int
  6120. alloc_printf(char **out_buf, const char *fmt, ...)
  6121. {
  6122. va_list ap;
  6123. int result;
  6124. va_start(ap, fmt);
  6125. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6126. va_end(ap);
  6127. return result;
  6128. }
  6129. #if defined(GCC_DIAGNOSTIC)
  6130. /* Enable format-nonliteral warning again. */
  6131. #pragma GCC diagnostic pop
  6132. #endif
  6133. static int
  6134. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6135. {
  6136. char mem[MG_BUF_LEN];
  6137. char *buf = NULL;
  6138. int len;
  6139. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6140. len = mg_write(conn, buf, (size_t)len);
  6141. }
  6142. if (buf != mem) {
  6143. mg_free(buf);
  6144. }
  6145. return len;
  6146. }
  6147. CIVETWEB_API int
  6148. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6149. {
  6150. va_list ap;
  6151. int result;
  6152. va_start(ap, fmt);
  6153. result = mg_vprintf(conn, fmt, ap);
  6154. va_end(ap);
  6155. return result;
  6156. }
  6157. CIVETWEB_API int
  6158. mg_url_decode(const char *src,
  6159. int src_len,
  6160. char *dst,
  6161. int dst_len,
  6162. int is_form_url_encoded)
  6163. {
  6164. int i, j, a, b;
  6165. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6166. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6167. if ((i < src_len - 2) && (src[i] == '%')
  6168. && isxdigit((unsigned char)src[i + 1])
  6169. && isxdigit((unsigned char)src[i + 2])) {
  6170. a = tolower((unsigned char)src[i + 1]);
  6171. b = tolower((unsigned char)src[i + 2]);
  6172. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6173. i += 2;
  6174. } else if (is_form_url_encoded && (src[i] == '+')) {
  6175. dst[j] = ' ';
  6176. } else {
  6177. dst[j] = src[i];
  6178. }
  6179. }
  6180. dst[j] = '\0'; /* Null-terminate the destination */
  6181. return (i >= src_len) ? j : -1;
  6182. }
  6183. /* form url decoding of an entire string */
  6184. static void
  6185. url_decode_in_place(char *buf)
  6186. {
  6187. int len = (int)strlen(buf);
  6188. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6189. }
  6190. CIVETWEB_API int
  6191. mg_get_var(const char *data,
  6192. size_t data_len,
  6193. const char *name,
  6194. char *dst,
  6195. size_t dst_len)
  6196. {
  6197. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6198. }
  6199. CIVETWEB_API int
  6200. mg_get_var2(const char *data,
  6201. size_t data_len,
  6202. const char *name,
  6203. char *dst,
  6204. size_t dst_len,
  6205. size_t occurrence)
  6206. {
  6207. const char *p, *e, *s;
  6208. size_t name_len;
  6209. int len;
  6210. if ((dst == NULL) || (dst_len == 0)) {
  6211. len = -2;
  6212. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6213. len = -1;
  6214. dst[0] = '\0';
  6215. } else {
  6216. name_len = strlen(name);
  6217. e = data + data_len;
  6218. len = -1;
  6219. dst[0] = '\0';
  6220. /* data is "var1=val1&var2=val2...". Find variable first */
  6221. for (p = data; p + name_len < e; p++) {
  6222. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6223. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6224. /* Point p to variable value */
  6225. p += name_len + 1;
  6226. /* Point s to the end of the value */
  6227. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6228. if (s == NULL) {
  6229. s = e;
  6230. }
  6231. DEBUG_ASSERT(s >= p);
  6232. if (s < p) {
  6233. return -3;
  6234. }
  6235. /* Decode variable into destination buffer */
  6236. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6237. /* Redirect error code from -1 to -2 (destination buffer too
  6238. * small). */
  6239. if (len == -1) {
  6240. len = -2;
  6241. }
  6242. break;
  6243. }
  6244. }
  6245. }
  6246. return len;
  6247. }
  6248. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6249. CIVETWEB_API int
  6250. mg_split_form_urlencoded(char *data,
  6251. struct mg_header *form_fields,
  6252. unsigned num_form_fields)
  6253. {
  6254. char *b;
  6255. int i;
  6256. int num = 0;
  6257. if (data == NULL) {
  6258. /* parameter error */
  6259. return -1;
  6260. }
  6261. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6262. /* determine the number of expected fields */
  6263. if (data[0] == 0) {
  6264. return 0;
  6265. }
  6266. /* count number of & to return the number of key-value-pairs */
  6267. num = 1;
  6268. while (*data) {
  6269. if (*data == '&') {
  6270. num++;
  6271. }
  6272. data++;
  6273. }
  6274. return num;
  6275. }
  6276. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6277. /* parameter error */
  6278. return -1;
  6279. }
  6280. for (i = 0; i < (int)num_form_fields; i++) {
  6281. /* extract key-value pairs from input data */
  6282. while ((*data == ' ') || (*data == '\t')) {
  6283. /* skip initial spaces */
  6284. data++;
  6285. }
  6286. if (*data == 0) {
  6287. /* end of string reached */
  6288. break;
  6289. }
  6290. form_fields[num].name = data;
  6291. /* find & or = */
  6292. b = data;
  6293. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6294. b++;
  6295. }
  6296. if (*b == 0) {
  6297. /* last key without value */
  6298. form_fields[num].value = NULL;
  6299. } else if (*b == '&') {
  6300. /* mid key without value */
  6301. form_fields[num].value = NULL;
  6302. } else {
  6303. /* terminate string */
  6304. *b = 0;
  6305. /* value starts after '=' */
  6306. data = b + 1;
  6307. form_fields[num].value = data;
  6308. }
  6309. /* new field is stored */
  6310. num++;
  6311. /* find a next key */
  6312. b = strchr(data, '&');
  6313. if (b == 0) {
  6314. /* no more data */
  6315. break;
  6316. } else {
  6317. /* terminate value of last field at '&' */
  6318. *b = 0;
  6319. /* next key-value-pairs starts after '&' */
  6320. data = b + 1;
  6321. }
  6322. }
  6323. /* Decode all values */
  6324. for (i = 0; i < num; i++) {
  6325. if (form_fields[i].name) {
  6326. url_decode_in_place((char *)form_fields[i].name);
  6327. }
  6328. if (form_fields[i].value) {
  6329. url_decode_in_place((char *)form_fields[i].value);
  6330. }
  6331. }
  6332. /* return number of fields found */
  6333. return num;
  6334. }
  6335. /* HCP24: some changes to compare whole var_name */
  6336. CIVETWEB_API int
  6337. mg_get_cookie(const char *cookie_header,
  6338. const char *var_name,
  6339. char *dst,
  6340. size_t dst_size)
  6341. {
  6342. const char *s, *p, *end;
  6343. int name_len, len = -1;
  6344. if ((dst == NULL) || (dst_size == 0)) {
  6345. return -2;
  6346. }
  6347. dst[0] = '\0';
  6348. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6349. return -1;
  6350. }
  6351. name_len = (int)strlen(var_name);
  6352. end = s + strlen(s);
  6353. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6354. if (s[name_len] == '=') {
  6355. /* HCP24: now check is it a substring or a full cookie name */
  6356. if ((s == cookie_header) || (s[-1] == ' ')) {
  6357. s += name_len + 1;
  6358. if ((p = strchr(s, ' ')) == NULL) {
  6359. p = end;
  6360. }
  6361. if (p[-1] == ';') {
  6362. p--;
  6363. }
  6364. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6365. s++;
  6366. p--;
  6367. }
  6368. if ((size_t)(p - s) < dst_size) {
  6369. len = (int)(p - s);
  6370. mg_strlcpy(dst, s, (size_t)len + 1);
  6371. } else {
  6372. len = -3;
  6373. }
  6374. break;
  6375. }
  6376. }
  6377. }
  6378. return len;
  6379. }
  6380. CIVETWEB_API int
  6381. mg_base64_encode(const unsigned char *src,
  6382. size_t src_len,
  6383. char *dst,
  6384. size_t *dst_len)
  6385. {
  6386. static const char *b64 =
  6387. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6388. size_t i, j;
  6389. int a, b, c;
  6390. if (dst_len != NULL) {
  6391. /* Expected length including 0 termination: */
  6392. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6393. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6394. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6395. if (*dst_len < expected_len) {
  6396. if (*dst_len > 0) {
  6397. dst[0] = '\0';
  6398. }
  6399. *dst_len = expected_len;
  6400. return 0;
  6401. }
  6402. }
  6403. for (i = j = 0; i < src_len; i += 3) {
  6404. a = src[i];
  6405. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6406. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6407. dst[j++] = b64[a >> 2];
  6408. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6409. if (i + 1 < src_len) {
  6410. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6411. }
  6412. if (i + 2 < src_len) {
  6413. dst[j++] = b64[c & 63];
  6414. }
  6415. }
  6416. while (j % 4 != 0) {
  6417. dst[j++] = '=';
  6418. }
  6419. dst[j++] = '\0';
  6420. if (dst_len != NULL) {
  6421. *dst_len = (size_t)j;
  6422. }
  6423. /* Return -1 for "OK" */
  6424. return -1;
  6425. }
  6426. static unsigned char
  6427. b64reverse(char letter)
  6428. {
  6429. if ((letter >= 'A') && (letter <= 'Z')) {
  6430. return (unsigned char)(letter - 'A');
  6431. }
  6432. if ((letter >= 'a') && (letter <= 'z')) {
  6433. return (unsigned char)(letter - 'a' + 26);
  6434. }
  6435. if ((letter >= '0') && (letter <= '9')) {
  6436. return (unsigned char)(letter - '0' + 52);
  6437. }
  6438. if (letter == '+') {
  6439. return 62;
  6440. }
  6441. if (letter == '/') {
  6442. return 63;
  6443. }
  6444. if (letter == '=') {
  6445. return 255; /* normal end */
  6446. }
  6447. return 254; /* error */
  6448. }
  6449. CIVETWEB_API int
  6450. mg_base64_decode(const char *src,
  6451. size_t src_len,
  6452. unsigned char *dst,
  6453. size_t *dst_len)
  6454. {
  6455. size_t i;
  6456. unsigned char a, b, c, d;
  6457. size_t dst_len_limit = (size_t)-1;
  6458. size_t dst_len_used = 0;
  6459. if (dst_len != NULL) {
  6460. dst_len_limit = *dst_len;
  6461. *dst_len = 0;
  6462. }
  6463. for (i = 0; i < src_len; i += 4) {
  6464. /* Read 4 characters from BASE64 string */
  6465. a = b64reverse(src[i]);
  6466. if (a >= 254) {
  6467. return (int)i;
  6468. }
  6469. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6470. if (b >= 254) {
  6471. return (int)i + 1;
  6472. }
  6473. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6474. if (c == 254) {
  6475. return (int)i + 2;
  6476. }
  6477. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6478. if (d == 254) {
  6479. return (int)i + 3;
  6480. }
  6481. /* Add first (of 3) decoded character */
  6482. if (dst_len_used < dst_len_limit) {
  6483. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6484. + (unsigned char)(b >> 4));
  6485. }
  6486. dst_len_used++;
  6487. if (c != 255) {
  6488. if (dst_len_used < dst_len_limit) {
  6489. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6490. + (unsigned char)(c >> 2));
  6491. }
  6492. dst_len_used++;
  6493. if (d != 255) {
  6494. if (dst_len_used < dst_len_limit) {
  6495. dst[dst_len_used] =
  6496. (unsigned char)((unsigned char)(c << 6) + d);
  6497. }
  6498. dst_len_used++;
  6499. }
  6500. }
  6501. }
  6502. /* Add terminating zero */
  6503. if (dst_len_used < dst_len_limit) {
  6504. dst[dst_len_used] = '\0';
  6505. }
  6506. dst_len_used++;
  6507. if (dst_len != NULL) {
  6508. *dst_len = dst_len_used;
  6509. }
  6510. if (dst_len_used > dst_len_limit) {
  6511. /* Out of memory */
  6512. return 0;
  6513. }
  6514. /* Return -1 for "OK" */
  6515. return -1;
  6516. }
  6517. static int
  6518. is_put_or_delete_method(const struct mg_connection *conn)
  6519. {
  6520. if (conn) {
  6521. const char *s = conn->request_info.request_method;
  6522. if (s != NULL) {
  6523. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6524. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6525. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6526. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6527. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6528. || !strcmp(s, "COPY"));
  6529. }
  6530. }
  6531. return 0;
  6532. }
  6533. static int
  6534. is_civetweb_webdav_method(const struct mg_connection *conn)
  6535. {
  6536. /* Note: Here we only have to identify the WebDav methods that need special
  6537. * handling in the CivetWeb code - not all methods used in WebDav. In
  6538. * particular, methods used on directories (when using Windows Explorer as
  6539. * WebDav client).
  6540. */
  6541. if (conn) {
  6542. const char *s = conn->request_info.request_method;
  6543. if (s != NULL) {
  6544. /* These are the civetweb builtin DAV methods */
  6545. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6546. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6547. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6548. }
  6549. }
  6550. return 0;
  6551. }
  6552. #if !defined(NO_FILES)
  6553. static int
  6554. extention_matches_script(
  6555. struct mg_connection *conn, /* in: request (must be valid) */
  6556. const char *filename /* in: filename (must be valid) */
  6557. )
  6558. {
  6559. #if !defined(NO_CGI)
  6560. int cgi_config_idx, inc, max;
  6561. #endif
  6562. #if defined(USE_LUA)
  6563. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6564. filename)
  6565. > 0) {
  6566. return 1;
  6567. }
  6568. #endif
  6569. #if defined(USE_DUKTAPE)
  6570. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6571. filename)
  6572. > 0) {
  6573. return 1;
  6574. }
  6575. #endif
  6576. #if !defined(NO_CGI)
  6577. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6578. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6579. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6580. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6581. && (match_prefix_strlen(
  6582. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6583. filename)
  6584. > 0)) {
  6585. return 1;
  6586. }
  6587. }
  6588. #endif
  6589. /* filename and conn could be unused, if all preocessor conditions
  6590. * are false (no script language supported). */
  6591. (void)filename;
  6592. (void)conn;
  6593. return 0;
  6594. }
  6595. static int
  6596. extention_matches_template_text(
  6597. struct mg_connection *conn, /* in: request (must be valid) */
  6598. const char *filename /* in: filename (must be valid) */
  6599. )
  6600. {
  6601. #if defined(USE_LUA)
  6602. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6603. filename)
  6604. > 0) {
  6605. return 1;
  6606. }
  6607. #endif
  6608. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6609. > 0) {
  6610. return 1;
  6611. }
  6612. return 0;
  6613. }
  6614. /* For given directory path, substitute it to valid index file.
  6615. * Return 1 if index file has been found, 0 if not found.
  6616. * If the file is found, it's stats is returned in stp. */
  6617. static int
  6618. substitute_index_file_aux(struct mg_connection *conn,
  6619. char *path,
  6620. size_t path_len,
  6621. struct mg_file_stat *filestat)
  6622. {
  6623. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6624. struct vec filename_vec;
  6625. size_t n = strlen(path);
  6626. int found = 0;
  6627. /* The 'path' given to us points to the directory. Remove all trailing
  6628. * directory separator characters from the end of the path, and
  6629. * then append single directory separator character. */
  6630. while ((n > 0) && (path[n - 1] == '/')) {
  6631. n--;
  6632. }
  6633. path[n] = '/';
  6634. /* Traverse index files list. For each entry, append it to the given
  6635. * path and see if the file exists. If it exists, break the loop */
  6636. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6637. /* Ignore too long entries that may overflow path buffer */
  6638. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6639. continue;
  6640. }
  6641. /* Prepare full path to the index file */
  6642. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6643. /* Does it exist? */
  6644. if (mg_stat(conn, path, filestat)) {
  6645. /* Yes it does, break the loop */
  6646. found = 1;
  6647. break;
  6648. }
  6649. }
  6650. /* If no index file exists, restore directory path */
  6651. if (!found) {
  6652. path[n] = '\0';
  6653. }
  6654. return found;
  6655. }
  6656. /* Same as above, except if the first try fails and a fallback-root is
  6657. * configured, we'll try there also */
  6658. static int
  6659. substitute_index_file(struct mg_connection *conn,
  6660. char *path,
  6661. size_t path_len,
  6662. struct mg_file_stat *filestat)
  6663. {
  6664. int ret = substitute_index_file_aux(conn, path, path_len, filestat);
  6665. if (ret == 0) {
  6666. const char *root_prefix = conn->dom_ctx->config[DOCUMENT_ROOT];
  6667. const char *fallback_root_prefix =
  6668. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT];
  6669. if ((root_prefix) && (fallback_root_prefix)) {
  6670. const size_t root_prefix_len = strlen(root_prefix);
  6671. if ((strncmp(path, root_prefix, root_prefix_len) == 0)) {
  6672. char scratch_path[UTF8_PATH_MAX]; /* separate storage, to avoid
  6673. side effects if we fail */
  6674. size_t sub_path_len;
  6675. const size_t fallback_root_prefix_len =
  6676. strlen(fallback_root_prefix);
  6677. const char *sub_path = path + root_prefix_len;
  6678. while (*sub_path == '/') {
  6679. sub_path++;
  6680. }
  6681. sub_path_len = strlen(sub_path);
  6682. if (((fallback_root_prefix_len + 1 + sub_path_len + 1)
  6683. < sizeof(scratch_path))) {
  6684. /* The concatenations below are all safe because we
  6685. * pre-verified string lengths above */
  6686. char *nul;
  6687. strcpy(scratch_path, fallback_root_prefix);
  6688. nul = strchr(scratch_path, '\0');
  6689. if ((nul > scratch_path) && (*(nul - 1) != '/')) {
  6690. *nul++ = '/';
  6691. *nul = '\0';
  6692. }
  6693. strcat(scratch_path, sub_path);
  6694. if (substitute_index_file_aux(conn,
  6695. scratch_path,
  6696. sizeof(scratch_path),
  6697. filestat)) {
  6698. mg_strlcpy(path, scratch_path, path_len);
  6699. return 1;
  6700. }
  6701. }
  6702. }
  6703. }
  6704. }
  6705. return ret;
  6706. }
  6707. #endif
  6708. static void
  6709. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6710. char *filename, /* out: filename */
  6711. size_t filename_buf_len, /* in: size of filename buffer */
  6712. struct mg_file_stat *filestat, /* out: file status structure */
  6713. int *is_found, /* out: file found (directly) */
  6714. int *is_script_resource, /* out: handled by a script? */
  6715. int *is_websocket_request, /* out: websocket connection? */
  6716. int *is_put_or_delete_request, /* out: put/delete a file? */
  6717. int *is_webdav_request, /* out: webdav request? */
  6718. int *is_template_text /* out: SSI file or LSP file? */
  6719. )
  6720. {
  6721. char const *accept_encoding;
  6722. #if !defined(NO_FILES)
  6723. const char *uri = conn->request_info.local_uri;
  6724. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT],
  6725. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT],
  6726. NULL};
  6727. int fileExists = 0;
  6728. const char *rewrite;
  6729. struct vec a, b;
  6730. ptrdiff_t match_len;
  6731. char gz_path[UTF8_PATH_MAX];
  6732. int truncated;
  6733. int i;
  6734. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6735. char *tmp_str;
  6736. size_t tmp_str_len, sep_pos;
  6737. int allow_substitute_script_subresources;
  6738. #endif
  6739. #else
  6740. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6741. #endif
  6742. /* Step 1: Set all initially unknown outputs to zero */
  6743. memset(filestat, 0, sizeof(*filestat));
  6744. *filename = 0;
  6745. *is_found = 0;
  6746. *is_script_resource = 0;
  6747. *is_template_text = 0;
  6748. /* Step 2: Classify the request method */
  6749. /* Step 2a: Check if the request attempts to modify the file system */
  6750. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6751. /* Step 2b: Check if the request uses WebDav method that requires special
  6752. * handling */
  6753. *is_webdav_request = is_civetweb_webdav_method(conn);
  6754. /* Step 3: Check if it is a websocket request, and modify the document
  6755. * root if required */
  6756. #if defined(USE_WEBSOCKET)
  6757. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6758. #if !defined(NO_FILES)
  6759. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6760. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6761. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6762. }
  6763. #endif /* !NO_FILES */
  6764. #else /* USE_WEBSOCKET */
  6765. *is_websocket_request = 0;
  6766. #endif /* USE_WEBSOCKET */
  6767. /* Step 4: Check if gzip encoded response is allowed */
  6768. conn->accept_gzip = 0;
  6769. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6770. if (strstr(accept_encoding, "gzip") != NULL) {
  6771. conn->accept_gzip = 1;
  6772. }
  6773. }
  6774. #if !defined(NO_FILES)
  6775. /* Step 5: If there is no root directory, don't look for files. */
  6776. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6777. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6778. * config is not required. */
  6779. if (roots[0] == NULL) {
  6780. /* all file related outputs have already been set to 0, just return
  6781. */
  6782. return;
  6783. }
  6784. for (i = 0; roots[i] != NULL; i++) {
  6785. /* Step 6: Determine the local file path from the root path and the
  6786. * request uri. */
  6787. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6788. * part of the path one byte on the right. */
  6789. truncated = 0;
  6790. mg_snprintf(conn,
  6791. &truncated,
  6792. filename,
  6793. filename_buf_len - 1,
  6794. "%s%s",
  6795. roots[i],
  6796. uri);
  6797. if (truncated) {
  6798. goto interpret_cleanup;
  6799. }
  6800. /* Step 7: URI rewriting */
  6801. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6802. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6803. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6804. mg_snprintf(conn,
  6805. &truncated,
  6806. filename,
  6807. filename_buf_len - 1,
  6808. "%.*s%s",
  6809. (int)b.len,
  6810. b.ptr,
  6811. uri + match_len);
  6812. break;
  6813. }
  6814. }
  6815. if (truncated) {
  6816. goto interpret_cleanup;
  6817. }
  6818. /* Step 8: Check if the file exists at the server */
  6819. /* Local file path and name, corresponding to requested URI
  6820. * is now stored in "filename" variable. */
  6821. if (mg_stat(conn, filename, filestat)) {
  6822. fileExists = 1;
  6823. break;
  6824. }
  6825. }
  6826. if (fileExists) {
  6827. int uri_len = (int)strlen(uri);
  6828. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6829. /* 8.1: File exists. */
  6830. *is_found = 1;
  6831. /* 8.2: Check if it is a script type. */
  6832. if (extention_matches_script(conn, filename)) {
  6833. /* The request addresses a CGI resource, Lua script or
  6834. * server-side javascript.
  6835. * The URI corresponds to the script itself (like
  6836. * /path/script.cgi), and there is no additional resource
  6837. * path (like /path/script.cgi/something).
  6838. * Requests that modify (replace or delete) a resource, like
  6839. * PUT and DELETE requests, should replace/delete the script
  6840. * file.
  6841. * Requests that read or write from/to a resource, like GET and
  6842. * POST requests, should call the script and return the
  6843. * generated response. */
  6844. *is_script_resource = (!*is_put_or_delete_request);
  6845. }
  6846. /* 8.3: Check for SSI and LSP files */
  6847. if (extention_matches_template_text(conn, filename)) {
  6848. /* Same as above, but for *.lsp and *.shtml files. */
  6849. /* A "template text" is a file delivered directly to the client,
  6850. * but with some text tags replaced by dynamic content.
  6851. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6852. * (LP, LSP) file. */
  6853. *is_template_text = (!*is_put_or_delete_request);
  6854. }
  6855. /* 8.4: If the request target is a directory, there could be
  6856. * a substitute file (index.html, index.cgi, ...). */
  6857. /* But do not substitute a directory for a WebDav request */
  6858. if (filestat->is_directory && is_uri_end_slash
  6859. && (!*is_webdav_request)) {
  6860. /* Use a local copy here, since substitute_index_file will
  6861. * change the content of the file status */
  6862. struct mg_file_stat tmp_filestat;
  6863. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6864. if (substitute_index_file(
  6865. conn, filename, filename_buf_len, &tmp_filestat)) {
  6866. /* Substitute file found. Copy stat to the output, then
  6867. * check if the file is a script file */
  6868. *filestat = tmp_filestat;
  6869. if (extention_matches_script(conn, filename)) {
  6870. /* Substitute file is a script file */
  6871. *is_script_resource = 1;
  6872. } else if (extention_matches_template_text(conn, filename)) {
  6873. /* Substitute file is a LSP or SSI file */
  6874. *is_template_text = 1;
  6875. } else {
  6876. /* Substitute file is a regular file */
  6877. *is_script_resource = 0;
  6878. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6879. }
  6880. }
  6881. /* If there is no substitute file, the server could return
  6882. * a directory listing in a later step */
  6883. }
  6884. return;
  6885. }
  6886. /* Step 9: Check for zipped files: */
  6887. /* If we can't find the actual file, look for the file
  6888. * with the same name but a .gz extension. If we find it,
  6889. * use that and set the gzipped flag in the file struct
  6890. * to indicate that the response need to have the content-
  6891. * encoding: gzip header.
  6892. * We can only do this if the browser declares support. */
  6893. if (conn->accept_gzip) {
  6894. mg_snprintf(
  6895. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6896. if (truncated) {
  6897. goto interpret_cleanup;
  6898. }
  6899. if (mg_stat(conn, gz_path, filestat)) {
  6900. if (filestat) {
  6901. filestat->is_gzipped = 1;
  6902. *is_found = 1;
  6903. }
  6904. /* Currently gz files can not be scripts. */
  6905. return;
  6906. }
  6907. }
  6908. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6909. /* Step 10: Script resources may handle sub-resources */
  6910. /* Support PATH_INFO for CGI scripts. */
  6911. tmp_str_len = strlen(filename);
  6912. tmp_str =
  6913. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6914. if (!tmp_str) {
  6915. /* Out of memory */
  6916. goto interpret_cleanup;
  6917. }
  6918. memcpy(tmp_str, filename, tmp_str_len + 1);
  6919. /* Check config, if index scripts may have sub-resources */
  6920. allow_substitute_script_subresources =
  6921. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6922. "yes");
  6923. if (*is_webdav_request) {
  6924. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6925. * PROPFIND for their subresources? */
  6926. /* allow_substitute_script_subresources = 0; */
  6927. }
  6928. sep_pos = tmp_str_len;
  6929. while (sep_pos > 0) {
  6930. sep_pos--;
  6931. if (tmp_str[sep_pos] == '/') {
  6932. int is_script = 0, does_exist = 0;
  6933. tmp_str[sep_pos] = 0;
  6934. if (tmp_str[0]) {
  6935. is_script = extention_matches_script(conn, tmp_str);
  6936. does_exist = mg_stat(conn, tmp_str, filestat);
  6937. }
  6938. if (does_exist && is_script) {
  6939. filename[sep_pos] = 0;
  6940. memmove(filename + sep_pos + 2,
  6941. filename + sep_pos + 1,
  6942. strlen(filename + sep_pos + 1) + 1);
  6943. conn->path_info = filename + sep_pos + 1;
  6944. filename[sep_pos + 1] = '/';
  6945. *is_script_resource = 1;
  6946. *is_found = 1;
  6947. break;
  6948. }
  6949. if (allow_substitute_script_subresources) {
  6950. if (substitute_index_file(
  6951. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6952. /* some intermediate directory has an index file */
  6953. if (extention_matches_script(conn, tmp_str)) {
  6954. size_t script_name_len = strlen(tmp_str);
  6955. /* subres_name read before this memory locatio will be
  6956. overwritten */
  6957. char *subres_name = filename + sep_pos;
  6958. size_t subres_name_len = strlen(subres_name);
  6959. DEBUG_TRACE("Substitute script %s serving path %s",
  6960. tmp_str,
  6961. filename);
  6962. /* this index file is a script */
  6963. if ((script_name_len + subres_name_len + 2)
  6964. >= filename_buf_len) {
  6965. mg_free(tmp_str);
  6966. goto interpret_cleanup;
  6967. }
  6968. conn->path_info =
  6969. filename + script_name_len + 1; /* new target */
  6970. memmove(conn->path_info, subres_name, subres_name_len);
  6971. conn->path_info[subres_name_len] = 0;
  6972. memcpy(filename, tmp_str, script_name_len + 1);
  6973. *is_script_resource = 1;
  6974. *is_found = 1;
  6975. break;
  6976. } else {
  6977. DEBUG_TRACE("Substitute file %s serving path %s",
  6978. tmp_str,
  6979. filename);
  6980. /* non-script files will not have sub-resources */
  6981. filename[sep_pos] = 0;
  6982. conn->path_info = 0;
  6983. *is_script_resource = 0;
  6984. *is_found = 0;
  6985. break;
  6986. }
  6987. }
  6988. }
  6989. tmp_str[sep_pos] = '/';
  6990. }
  6991. }
  6992. mg_free(tmp_str);
  6993. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6994. #endif /* !defined(NO_FILES) */
  6995. return;
  6996. #if !defined(NO_FILES)
  6997. /* Reset all outputs */
  6998. interpret_cleanup:
  6999. memset(filestat, 0, sizeof(*filestat));
  7000. *filename = 0;
  7001. *is_found = 0;
  7002. *is_script_resource = 0;
  7003. *is_websocket_request = 0;
  7004. *is_put_or_delete_request = 0;
  7005. #endif /* !defined(NO_FILES) */
  7006. }
  7007. /* Check whether full request is buffered. Return:
  7008. * -1 if request or response is malformed
  7009. * 0 if request or response is not yet fully buffered
  7010. * >0 actual request length, including last \r\n\r\n */
  7011. static int
  7012. get_http_header_len(const char *buf, int buflen)
  7013. {
  7014. int i;
  7015. for (i = 0; i < buflen; i++) {
  7016. /* Do an unsigned comparison in some conditions below */
  7017. const unsigned char c = (unsigned char)buf[i];
  7018. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7019. && !isprint(c)) {
  7020. /* abort scan as soon as one malformed character is found */
  7021. return -1;
  7022. }
  7023. if (i < buflen - 1) {
  7024. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7025. /* Two newline, no carriage return - not standard compliant,
  7026. * but it should be accepted */
  7027. return i + 2;
  7028. }
  7029. }
  7030. if (i < buflen - 3) {
  7031. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7032. && (buf[i + 3] == '\n')) {
  7033. /* Two \r\n - standard compliant */
  7034. return i + 4;
  7035. }
  7036. }
  7037. }
  7038. return 0;
  7039. }
  7040. #if !defined(NO_CACHING)
  7041. /* Convert month to the month number. Return -1 on error, or month number */
  7042. static int
  7043. get_month_index(const char *s)
  7044. {
  7045. size_t i;
  7046. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7047. if (!strcmp(s, month_names[i])) {
  7048. return (int)i;
  7049. }
  7050. }
  7051. return -1;
  7052. }
  7053. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7054. static time_t
  7055. parse_date_string(const char *datetime)
  7056. {
  7057. char month_str[32] = {0};
  7058. int second, minute, hour, day, month, year;
  7059. time_t result = (time_t)0;
  7060. struct tm tm;
  7061. if ((sscanf(datetime,
  7062. "%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. || (sscanf(datetime,
  7080. "%*3s, %d %3s %d %d:%d:%d",
  7081. &day,
  7082. month_str,
  7083. &year,
  7084. &hour,
  7085. &minute,
  7086. &second)
  7087. == 6)
  7088. || (sscanf(datetime,
  7089. "%d-%3s-%d %d:%d:%d",
  7090. &day,
  7091. month_str,
  7092. &year,
  7093. &hour,
  7094. &minute,
  7095. &second)
  7096. == 6)) {
  7097. month = get_month_index(month_str);
  7098. if ((month >= 0) && (year >= 1970)) {
  7099. memset(&tm, 0, sizeof(tm));
  7100. tm.tm_year = year - 1900;
  7101. tm.tm_mon = month;
  7102. tm.tm_mday = day;
  7103. tm.tm_hour = hour;
  7104. tm.tm_min = minute;
  7105. tm.tm_sec = second;
  7106. result = timegm(&tm);
  7107. }
  7108. }
  7109. return result;
  7110. }
  7111. #endif /* !NO_CACHING */
  7112. /* Pre-process URIs according to RFC + protect against directory disclosure
  7113. * attacks by removing '..', excessive '/' and '\' characters */
  7114. static void
  7115. remove_dot_segments(char *inout)
  7116. {
  7117. /* Windows backend protection
  7118. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7119. * in URI by slash */
  7120. char *out_end = inout;
  7121. char *in = inout;
  7122. if (!in) {
  7123. /* Param error. */
  7124. return;
  7125. }
  7126. while (*in) {
  7127. if (*in == '\\') {
  7128. *in = '/';
  7129. }
  7130. in++;
  7131. }
  7132. /* Algorithm "remove_dot_segments" from
  7133. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7134. /* Step 1:
  7135. * The input buffer is initialized.
  7136. * The output buffer is initialized to the empty string.
  7137. */
  7138. in = inout;
  7139. /* Step 2:
  7140. * While the input buffer is not empty, loop as follows:
  7141. */
  7142. /* Less than out_end of the inout buffer is used as output, so keep
  7143. * condition: out_end <= in */
  7144. while (*in) {
  7145. /* Step 2a:
  7146. * If the input buffer begins with a prefix of "../" or "./",
  7147. * then remove that prefix from the input buffer;
  7148. */
  7149. if (!strncmp(in, "../", 3)) {
  7150. in += 3;
  7151. } else if (!strncmp(in, "./", 2)) {
  7152. in += 2;
  7153. }
  7154. /* otherwise */
  7155. /* Step 2b:
  7156. * if the input buffer begins with a prefix of "/./" or "/.",
  7157. * where "." is a complete path segment, then replace that
  7158. * prefix with "/" in the input buffer;
  7159. */
  7160. else if (!strncmp(in, "/./", 3)) {
  7161. in += 2;
  7162. } else if (!strcmp(in, "/.")) {
  7163. in[1] = 0;
  7164. }
  7165. /* otherwise */
  7166. /* Step 2c:
  7167. * if the input buffer begins with a prefix of "/../" or "/..",
  7168. * where ".." is a complete path segment, then replace that
  7169. * prefix with "/" in the input buffer and remove the last
  7170. * segment and its preceding "/" (if any) from the output
  7171. * buffer;
  7172. */
  7173. else if (!strncmp(in, "/../", 4)) {
  7174. in += 3;
  7175. if (inout != out_end) {
  7176. /* remove last segment */
  7177. do {
  7178. out_end--;
  7179. } while ((inout != out_end) && (*out_end != '/'));
  7180. }
  7181. } else if (!strcmp(in, "/..")) {
  7182. in[1] = 0;
  7183. if (inout != out_end) {
  7184. /* remove last segment */
  7185. do {
  7186. out_end--;
  7187. } while ((inout != out_end) && (*out_end != '/'));
  7188. }
  7189. }
  7190. /* otherwise */
  7191. /* Step 2d:
  7192. * if the input buffer consists only of "." or "..", then remove
  7193. * that from the input buffer;
  7194. */
  7195. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7196. *in = 0;
  7197. }
  7198. /* otherwise */
  7199. /* Step 2e:
  7200. * move the first path segment in the input buffer to the end of
  7201. * the output buffer, including the initial "/" character (if
  7202. * any) and any subsequent characters up to, but not including,
  7203. * the next "/" character or the end of the input buffer.
  7204. */
  7205. else {
  7206. do {
  7207. *out_end = *in;
  7208. out_end++;
  7209. in++;
  7210. } while ((*in != 0) && (*in != '/'));
  7211. }
  7212. }
  7213. /* Step 3:
  7214. * Finally, the output buffer is returned as the result of
  7215. * remove_dot_segments.
  7216. */
  7217. /* Terminate output */
  7218. *out_end = 0;
  7219. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7220. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7221. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7222. * or "//" anymore.
  7223. */
  7224. out_end = in = inout;
  7225. while (*in) {
  7226. if (*in == '.') {
  7227. /* remove . at the end or preceding of / */
  7228. char *in_ahead = in;
  7229. do {
  7230. in_ahead++;
  7231. } while (*in_ahead == '.');
  7232. if (*in_ahead == '/') {
  7233. in = in_ahead;
  7234. if ((out_end != inout) && (out_end[-1] == '/')) {
  7235. /* remove generated // */
  7236. out_end--;
  7237. }
  7238. } else if (*in_ahead == 0) {
  7239. in = in_ahead;
  7240. } else {
  7241. do {
  7242. *out_end++ = '.';
  7243. in++;
  7244. } while (in != in_ahead);
  7245. }
  7246. } else if (*in == '/') {
  7247. /* replace // by / */
  7248. *out_end++ = '/';
  7249. do {
  7250. in++;
  7251. } while (*in == '/');
  7252. } else {
  7253. *out_end++ = *in;
  7254. in++;
  7255. }
  7256. }
  7257. *out_end = 0;
  7258. }
  7259. static const struct {
  7260. const char *extension;
  7261. size_t ext_len;
  7262. const char *mime_type;
  7263. } builtin_mime_types[] = {
  7264. /* IANA registered MIME types
  7265. * (http://www.iana.org/assignments/media-types)
  7266. * application types */
  7267. {".bin", 4, "application/octet-stream"},
  7268. {".cer", 4, "application/pkix-cert"},
  7269. {".crl", 4, "application/pkix-crl"},
  7270. {".crt", 4, "application/pkix-cert"},
  7271. {".deb", 4, "application/octet-stream"},
  7272. {".dmg", 4, "application/octet-stream"},
  7273. {".dll", 4, "application/octet-stream"},
  7274. {".doc", 4, "application/msword"},
  7275. {".eps", 4, "application/postscript"},
  7276. {".exe", 4, "application/octet-stream"},
  7277. {".iso", 4, "application/octet-stream"},
  7278. {".js", 3, "application/javascript"},
  7279. {".json", 5, "application/json"},
  7280. {".mjs", 4, "application/javascript"},
  7281. {".msi", 4, "application/octet-stream"},
  7282. {".pem", 4, "application/x-pem-file"},
  7283. {".pdf", 4, "application/pdf"},
  7284. {".ps", 3, "application/postscript"},
  7285. {".rtf", 4, "application/rtf"},
  7286. {".wasm", 5, "application/wasm"},
  7287. {".xhtml", 6, "application/xhtml+xml"},
  7288. {".xsl", 4, "application/xml"},
  7289. {".xslt", 5, "application/xml"},
  7290. /* fonts */
  7291. {".ttf", 4, "application/font-sfnt"},
  7292. {".cff", 4, "application/font-sfnt"},
  7293. {".otf", 4, "application/font-sfnt"},
  7294. {".aat", 4, "application/font-sfnt"},
  7295. {".sil", 4, "application/font-sfnt"},
  7296. {".pfr", 4, "application/font-tdpfr"},
  7297. {".woff", 5, "application/font-woff"},
  7298. {".woff2", 6, "application/font-woff2"},
  7299. /* audio */
  7300. {".mp3", 4, "audio/mpeg"},
  7301. {".oga", 4, "audio/ogg"},
  7302. {".ogg", 4, "audio/ogg"},
  7303. /* image */
  7304. {".gif", 4, "image/gif"},
  7305. {".ief", 4, "image/ief"},
  7306. {".jpeg", 5, "image/jpeg"},
  7307. {".jpg", 4, "image/jpeg"},
  7308. {".jpm", 4, "image/jpm"},
  7309. {".jpx", 4, "image/jpx"},
  7310. {".png", 4, "image/png"},
  7311. {".svg", 4, "image/svg+xml"},
  7312. {".tif", 4, "image/tiff"},
  7313. {".tiff", 5, "image/tiff"},
  7314. /* model */
  7315. {".wrl", 4, "model/vrml"},
  7316. /* text */
  7317. {".css", 4, "text/css"},
  7318. {".csv", 4, "text/csv"},
  7319. {".htm", 4, "text/html"},
  7320. {".html", 5, "text/html"},
  7321. {".sgm", 4, "text/sgml"},
  7322. {".shtm", 5, "text/html"},
  7323. {".shtml", 6, "text/html"},
  7324. {".txt", 4, "text/plain"},
  7325. {".xml", 4, "text/xml"},
  7326. /* video */
  7327. {".mov", 4, "video/quicktime"},
  7328. {".mp4", 4, "video/mp4"},
  7329. {".mpeg", 5, "video/mpeg"},
  7330. {".mpg", 4, "video/mpeg"},
  7331. {".ogv", 4, "video/ogg"},
  7332. {".qt", 3, "video/quicktime"},
  7333. /* not registered types
  7334. * (http://reference.sitepoint.com/html/mime-types-full,
  7335. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7336. {".arj", 4, "application/x-arj-compressed"},
  7337. {".gz", 3, "application/x-gunzip"},
  7338. {".rar", 4, "application/x-arj-compressed"},
  7339. {".swf", 4, "application/x-shockwave-flash"},
  7340. {".tar", 4, "application/x-tar"},
  7341. {".tgz", 4, "application/x-tar-gz"},
  7342. {".torrent", 8, "application/x-bittorrent"},
  7343. {".ppt", 4, "application/x-mspowerpoint"},
  7344. {".xls", 4, "application/x-msexcel"},
  7345. {".zip", 4, "application/x-zip-compressed"},
  7346. {".aac",
  7347. 4,
  7348. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7349. {".flac", 5, "audio/flac"},
  7350. {".aif", 4, "audio/x-aif"},
  7351. {".m3u", 4, "audio/x-mpegurl"},
  7352. {".mid", 4, "audio/x-midi"},
  7353. {".ra", 3, "audio/x-pn-realaudio"},
  7354. {".ram", 4, "audio/x-pn-realaudio"},
  7355. {".wav", 4, "audio/x-wav"},
  7356. {".bmp", 4, "image/bmp"},
  7357. {".ico", 4, "image/x-icon"},
  7358. {".pct", 4, "image/x-pct"},
  7359. {".pict", 5, "image/pict"},
  7360. {".rgb", 4, "image/x-rgb"},
  7361. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7362. {".asf", 4, "video/x-ms-asf"},
  7363. {".avi", 4, "video/x-msvideo"},
  7364. {".m4v", 4, "video/x-m4v"},
  7365. {NULL, 0, NULL}};
  7366. CIVETWEB_API const char *
  7367. mg_get_builtin_mime_type(const char *path)
  7368. {
  7369. const char *ext;
  7370. size_t i, path_len;
  7371. path_len = strlen(path);
  7372. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7373. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7374. if ((path_len > builtin_mime_types[i].ext_len)
  7375. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7376. return builtin_mime_types[i].mime_type;
  7377. }
  7378. }
  7379. return "text/plain";
  7380. }
  7381. /* Look at the "path" extension and figure what mime type it has.
  7382. * Store mime type in the vector. */
  7383. static void
  7384. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7385. {
  7386. struct vec ext_vec, mime_vec;
  7387. const char *list, *ext;
  7388. size_t path_len;
  7389. path_len = strlen(path);
  7390. if ((conn == NULL) || (vec == NULL)) {
  7391. if (vec != NULL) {
  7392. memset(vec, '\0', sizeof(struct vec));
  7393. }
  7394. return;
  7395. }
  7396. /* Scan user-defined mime types first, in case user wants to
  7397. * override default mime types. */
  7398. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7399. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7400. /* ext now points to the path suffix */
  7401. ext = path + path_len - ext_vec.len;
  7402. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7403. *vec = mime_vec;
  7404. return;
  7405. }
  7406. }
  7407. vec->ptr = mg_get_builtin_mime_type(path);
  7408. vec->len = strlen(vec->ptr);
  7409. }
  7410. /* Stringify binary data. Output buffer must be twice as big as input,
  7411. * because each byte takes 2 bytes in string representation */
  7412. static void
  7413. bin2str(char *to, const unsigned char *p, size_t len)
  7414. {
  7415. static const char *hex = "0123456789abcdef";
  7416. for (; len--; p++) {
  7417. *to++ = hex[p[0] >> 4];
  7418. *to++ = hex[p[0] & 0x0f];
  7419. }
  7420. *to = '\0';
  7421. }
  7422. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7423. */
  7424. CIVETWEB_API char *
  7425. mg_md5(char buf[33], ...)
  7426. {
  7427. md5_byte_t hash[16];
  7428. const char *p;
  7429. va_list ap;
  7430. md5_state_t ctx;
  7431. md5_init(&ctx);
  7432. va_start(ap, buf);
  7433. while ((p = va_arg(ap, const char *)) != NULL) {
  7434. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7435. }
  7436. va_end(ap);
  7437. md5_finish(&ctx, hash);
  7438. bin2str(buf, hash, sizeof(hash));
  7439. return buf;
  7440. }
  7441. /* Check the user's password, return 1 if OK */
  7442. static int
  7443. check_password_digest(const char *method,
  7444. const char *ha1,
  7445. const char *uri,
  7446. const char *nonce,
  7447. const char *nc,
  7448. const char *cnonce,
  7449. const char *qop,
  7450. const char *response)
  7451. {
  7452. char ha2[32 + 1], expected_response[32 + 1];
  7453. /* Some of the parameters may be NULL */
  7454. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7455. || (qop == NULL) || (response == NULL)) {
  7456. return 0;
  7457. }
  7458. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7459. if (strlen(response) != 32) {
  7460. return 0;
  7461. }
  7462. mg_md5(ha2, method, ":", uri, NULL);
  7463. mg_md5(expected_response,
  7464. ha1,
  7465. ":",
  7466. nonce,
  7467. ":",
  7468. nc,
  7469. ":",
  7470. cnonce,
  7471. ":",
  7472. qop,
  7473. ":",
  7474. ha2,
  7475. NULL);
  7476. return mg_strcasecmp(response, expected_response) == 0;
  7477. }
  7478. #if !defined(NO_FILESYSTEMS)
  7479. /* Use the global passwords file, if specified by auth_gpass option,
  7480. * or search for .htpasswd in the requested directory. */
  7481. static void
  7482. open_auth_file(struct mg_connection *conn,
  7483. const char *path,
  7484. struct mg_file *filep)
  7485. {
  7486. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7487. char name[UTF8_PATH_MAX];
  7488. const char *p, *e,
  7489. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7490. int truncated;
  7491. if (gpass != NULL) {
  7492. /* Use global passwords file */
  7493. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7494. #if defined(DEBUG)
  7495. /* Use mg_cry_internal here, since gpass has been
  7496. * configured. */
  7497. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7498. #endif
  7499. }
  7500. /* Important: using local struct mg_file to test path for
  7501. * is_directory flag. If filep is used, mg_stat() makes it
  7502. * appear as if auth file was opened.
  7503. * TODO(mid): Check if this is still required after rewriting
  7504. * mg_stat */
  7505. } else if (mg_stat(conn, path, &filep->stat)
  7506. && filep->stat.is_directory) {
  7507. mg_snprintf(conn,
  7508. &truncated,
  7509. name,
  7510. sizeof(name),
  7511. "%s/%s",
  7512. path,
  7513. PASSWORDS_FILE_NAME);
  7514. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7515. #if defined(DEBUG)
  7516. /* Don't use mg_cry_internal here, but only a trace, since
  7517. * this is a typical case. It will occur for every directory
  7518. * without a password file. */
  7519. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7520. #endif
  7521. }
  7522. } else {
  7523. /* Try to find .htpasswd in requested directory. */
  7524. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7525. if (e[0] == '/') {
  7526. break;
  7527. }
  7528. }
  7529. mg_snprintf(conn,
  7530. &truncated,
  7531. name,
  7532. sizeof(name),
  7533. "%.*s/%s",
  7534. (int)(e - p),
  7535. p,
  7536. PASSWORDS_FILE_NAME);
  7537. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7538. #if defined(DEBUG)
  7539. /* Don't use mg_cry_internal here, but only a trace, since
  7540. * this is a typical case. It will occur for every directory
  7541. * without a password file. */
  7542. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7543. #endif
  7544. }
  7545. }
  7546. }
  7547. }
  7548. #endif /* NO_FILESYSTEMS */
  7549. /* Parsed Authorization header */
  7550. struct auth_header {
  7551. char *user;
  7552. int type; /* 1 = basic, 2 = digest */
  7553. char *plain_password; /* Basic only */
  7554. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7555. };
  7556. /* Return 1 on success. Always initializes the auth_header structure. */
  7557. static int
  7558. parse_auth_header(struct mg_connection *conn,
  7559. char *buf,
  7560. size_t buf_size,
  7561. struct auth_header *auth_header)
  7562. {
  7563. char *name, *value, *s;
  7564. const char *ah;
  7565. uint64_t nonce;
  7566. if (!auth_header || !conn) {
  7567. return 0;
  7568. }
  7569. (void)memset(auth_header, 0, sizeof(*auth_header));
  7570. ah = mg_get_header(conn, "Authorization");
  7571. if (ah == NULL) {
  7572. /* No Authorization header at all */
  7573. return 0;
  7574. }
  7575. if (0 == mg_strncasecmp(ah, "Basic ", 6)) {
  7576. /* Basic Auth (we never asked for this, but some client may send it) */
  7577. char *split;
  7578. const char *userpw_b64 = ah + 6;
  7579. size_t userpw_b64_len = strlen(userpw_b64);
  7580. size_t buf_len_r = buf_size;
  7581. if (mg_base64_decode(
  7582. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7583. != -1) {
  7584. return 0; /* decode error */
  7585. }
  7586. split = strchr(buf, ':');
  7587. if (!split) {
  7588. return 0; /* Format error */
  7589. }
  7590. /* Separate string at ':' */
  7591. *split = 0;
  7592. /* User name is before ':', Password is after ':' */
  7593. auth_header->user = buf;
  7594. auth_header->type = 1;
  7595. auth_header->plain_password = split + 1;
  7596. return 1;
  7597. } else if (0 == mg_strncasecmp(ah, "Digest ", 7)) {
  7598. /* Digest Auth ... implemented below */
  7599. auth_header->type = 2;
  7600. } else {
  7601. /* Unknown or invalid Auth method */
  7602. return 0;
  7603. }
  7604. /* Make modifiable copy of the auth header */
  7605. (void)mg_strlcpy(buf, ah + 7, buf_size);
  7606. s = buf;
  7607. /* Parse authorization header */
  7608. for (;;) {
  7609. /* Gobble initial spaces */
  7610. while (isspace((unsigned char)*s)) {
  7611. s++;
  7612. }
  7613. name = skip_quoted(&s, "=", " ", 0);
  7614. /* Value is either quote-delimited, or ends at first comma or space.
  7615. */
  7616. if (s[0] == '\"') {
  7617. s++;
  7618. value = skip_quoted(&s, "\"", " ", '\\');
  7619. if (s[0] == ',') {
  7620. s++;
  7621. }
  7622. } else {
  7623. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7624. * uses spaces */
  7625. }
  7626. if (*name == '\0') {
  7627. break;
  7628. }
  7629. if (!strcmp(name, "username")) {
  7630. auth_header->user = value;
  7631. } else if (!strcmp(name, "cnonce")) {
  7632. auth_header->cnonce = value;
  7633. } else if (!strcmp(name, "response")) {
  7634. auth_header->response = value;
  7635. } else if (!strcmp(name, "uri")) {
  7636. auth_header->uri = value;
  7637. } else if (!strcmp(name, "qop")) {
  7638. auth_header->qop = value;
  7639. } else if (!strcmp(name, "nc")) {
  7640. auth_header->nc = value;
  7641. } else if (!strcmp(name, "nonce")) {
  7642. auth_header->nonce = value;
  7643. }
  7644. }
  7645. #if !defined(NO_NONCE_CHECK)
  7646. /* Read the nonce from the response. */
  7647. if (auth_header->nonce == NULL) {
  7648. return 0;
  7649. }
  7650. s = NULL;
  7651. nonce = strtoull(auth_header->nonce, &s, 10);
  7652. if ((s == NULL) || (*s != 0)) {
  7653. return 0;
  7654. }
  7655. /* Convert the nonce from the client to a number. */
  7656. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7657. /* The converted number corresponds to the time the nounce has been
  7658. * created. This should not be earlier than the server start. */
  7659. /* Server side nonce check is valuable in all situations but one:
  7660. * if the server restarts frequently, but the client should not see
  7661. * that, so the server should accept nonces from previous starts. */
  7662. /* However, the reasonable default is to not accept a nonce from a
  7663. * previous start, so if anyone changed the access rights between
  7664. * two restarts, a new login is required. */
  7665. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7666. /* nonce is from a previous start of the server and no longer valid
  7667. * (replay attack?) */
  7668. return 0;
  7669. }
  7670. /* Check if the nonce is too high, so it has not (yet) been used by the
  7671. * server. */
  7672. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7673. + conn->dom_ctx->nonce_count)) {
  7674. return 0;
  7675. }
  7676. #else
  7677. (void)nonce;
  7678. #endif
  7679. return (auth_header->user != NULL);
  7680. }
  7681. static const char *
  7682. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7683. {
  7684. if (!filep) {
  7685. return NULL;
  7686. }
  7687. if (filep->access.fp != NULL) {
  7688. return fgets(buf, (int)size, filep->access.fp);
  7689. } else {
  7690. return NULL;
  7691. }
  7692. }
  7693. /* Define the initial recursion depth for procesesing htpasswd files that
  7694. * include other htpasswd
  7695. * (or even the same) files. It is not difficult to provide a file or files
  7696. * s.t. they force civetweb
  7697. * to infinitely recurse and then crash.
  7698. */
  7699. #define INITIAL_DEPTH 9
  7700. #if INITIAL_DEPTH <= 0
  7701. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7702. #endif
  7703. #if !defined(NO_FILESYSTEMS)
  7704. struct read_auth_file_struct {
  7705. struct mg_connection *conn;
  7706. struct auth_header auth_header;
  7707. const char *domain;
  7708. char buf[256 + 256 + 40];
  7709. const char *f_user;
  7710. const char *f_domain;
  7711. const char *f_ha1;
  7712. };
  7713. static int
  7714. read_auth_file(struct mg_file *filep,
  7715. struct read_auth_file_struct *workdata,
  7716. int depth)
  7717. {
  7718. int is_authorized = 0;
  7719. struct mg_file fp;
  7720. size_t l;
  7721. if (!filep || !workdata || (0 == depth)) {
  7722. return 0;
  7723. }
  7724. /* Loop over passwords file */
  7725. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7726. l = strlen(workdata->buf);
  7727. while (l > 0) {
  7728. if (isspace((unsigned char)workdata->buf[l - 1])
  7729. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7730. l--;
  7731. workdata->buf[l] = 0;
  7732. } else
  7733. break;
  7734. }
  7735. if (l < 1) {
  7736. continue;
  7737. }
  7738. workdata->f_user = workdata->buf;
  7739. if (workdata->f_user[0] == ':') {
  7740. /* user names may not contain a ':' and may not be empty,
  7741. * so lines starting with ':' may be used for a special purpose
  7742. */
  7743. if (workdata->f_user[1] == '#') {
  7744. /* :# is a comment */
  7745. continue;
  7746. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7747. if (mg_fopen(workdata->conn,
  7748. workdata->f_user + 9,
  7749. MG_FOPEN_MODE_READ,
  7750. &fp)) {
  7751. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7752. (void)mg_fclose(
  7753. &fp.access); /* ignore error on read only file */
  7754. /* No need to continue processing files once we have a
  7755. * match, since nothing will reset it back
  7756. * to 0.
  7757. */
  7758. if (is_authorized) {
  7759. return is_authorized;
  7760. }
  7761. } else {
  7762. mg_cry_internal(workdata->conn,
  7763. "%s: cannot open authorization file: %s",
  7764. __func__,
  7765. workdata->buf);
  7766. }
  7767. continue;
  7768. }
  7769. /* everything is invalid for the moment (might change in the
  7770. * future) */
  7771. mg_cry_internal(workdata->conn,
  7772. "%s: syntax error in authorization file: %s",
  7773. __func__,
  7774. workdata->buf);
  7775. continue;
  7776. }
  7777. workdata->f_domain = strchr(workdata->f_user, ':');
  7778. if (workdata->f_domain == NULL) {
  7779. mg_cry_internal(workdata->conn,
  7780. "%s: syntax error in authorization file: %s",
  7781. __func__,
  7782. workdata->buf);
  7783. continue;
  7784. }
  7785. *(char *)(workdata->f_domain) = 0;
  7786. (workdata->f_domain)++;
  7787. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7788. if (workdata->f_ha1 == NULL) {
  7789. mg_cry_internal(workdata->conn,
  7790. "%s: syntax error in authorization file: %s",
  7791. __func__,
  7792. workdata->buf);
  7793. continue;
  7794. }
  7795. *(char *)(workdata->f_ha1) = 0;
  7796. (workdata->f_ha1)++;
  7797. if (!strcmp(workdata->auth_header.user, workdata->f_user)
  7798. && !strcmp(workdata->domain, workdata->f_domain)) {
  7799. switch (workdata->auth_header.type) {
  7800. case 1: /* Basic */
  7801. {
  7802. char md5[33];
  7803. mg_md5(md5,
  7804. workdata->f_user,
  7805. ":",
  7806. workdata->domain,
  7807. ":",
  7808. workdata->auth_header.plain_password,
  7809. NULL);
  7810. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7811. }
  7812. case 2: /* Digest */
  7813. return check_password_digest(
  7814. workdata->conn->request_info.request_method,
  7815. workdata->f_ha1,
  7816. workdata->auth_header.uri,
  7817. workdata->auth_header.nonce,
  7818. workdata->auth_header.nc,
  7819. workdata->auth_header.cnonce,
  7820. workdata->auth_header.qop,
  7821. workdata->auth_header.response);
  7822. default: /* None/Other/Unknown */
  7823. return 0;
  7824. }
  7825. }
  7826. }
  7827. return is_authorized;
  7828. }
  7829. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7830. static int
  7831. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7832. {
  7833. struct read_auth_file_struct workdata;
  7834. char buf[MG_BUF_LEN];
  7835. if (!conn || !conn->dom_ctx) {
  7836. return 0;
  7837. }
  7838. memset(&workdata, 0, sizeof(workdata));
  7839. workdata.conn = conn;
  7840. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.auth_header)) {
  7841. return 0;
  7842. }
  7843. /* CGI needs it as REMOTE_USER */
  7844. conn->request_info.remote_user =
  7845. mg_strdup_ctx(workdata.auth_header.user, conn->phys_ctx);
  7846. if (realm) {
  7847. workdata.domain = realm;
  7848. } else {
  7849. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7850. }
  7851. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7852. }
  7853. /* Public function to check http digest authentication header */
  7854. CIVETWEB_API int
  7855. mg_check_digest_access_authentication(struct mg_connection *conn,
  7856. const char *realm,
  7857. const char *filename)
  7858. {
  7859. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7860. int auth;
  7861. if (!conn || !filename) {
  7862. return -1;
  7863. }
  7864. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7865. return -2;
  7866. }
  7867. auth = authorize(conn, &file, realm);
  7868. mg_fclose(&file.access);
  7869. return auth;
  7870. }
  7871. #endif /* NO_FILESYSTEMS */
  7872. /* Return 1 if request is authorised, 0 otherwise. */
  7873. static int
  7874. check_authorization(struct mg_connection *conn, const char *path)
  7875. {
  7876. #if !defined(NO_FILESYSTEMS)
  7877. char fname[UTF8_PATH_MAX];
  7878. struct vec uri_vec, filename_vec;
  7879. const char *list;
  7880. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7881. int authorized = 1, truncated;
  7882. if (!conn || !conn->dom_ctx) {
  7883. return 0;
  7884. }
  7885. list = conn->dom_ctx->config[PROTECT_URI];
  7886. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7887. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7888. mg_snprintf(conn,
  7889. &truncated,
  7890. fname,
  7891. sizeof(fname),
  7892. "%.*s",
  7893. (int)filename_vec.len,
  7894. filename_vec.ptr);
  7895. if (truncated
  7896. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7897. mg_cry_internal(conn,
  7898. "%s: cannot open %s: %s",
  7899. __func__,
  7900. fname,
  7901. strerror(errno));
  7902. }
  7903. break;
  7904. }
  7905. }
  7906. if (!is_file_opened(&file.access)) {
  7907. open_auth_file(conn, path, &file);
  7908. }
  7909. if (is_file_opened(&file.access)) {
  7910. authorized = authorize(conn, &file, NULL);
  7911. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7912. }
  7913. return authorized;
  7914. #else
  7915. (void)conn;
  7916. (void)path;
  7917. return 1;
  7918. #endif /* NO_FILESYSTEMS */
  7919. }
  7920. /* Internal function. Assumes conn is valid */
  7921. static void
  7922. send_authorization_request(struct mg_connection *conn, const char *realm)
  7923. {
  7924. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7925. int trunc = 0;
  7926. char buf[128];
  7927. if (!realm) {
  7928. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7929. }
  7930. mg_lock_context(conn->phys_ctx);
  7931. nonce += conn->dom_ctx->nonce_count;
  7932. ++conn->dom_ctx->nonce_count;
  7933. mg_unlock_context(conn->phys_ctx);
  7934. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7935. conn->must_close = 1;
  7936. /* Create 401 response */
  7937. mg_response_header_start(conn, 401);
  7938. send_no_cache_header(conn);
  7939. send_additional_header(conn);
  7940. mg_response_header_add(conn, "Content-Length", "0", -1);
  7941. /* Content for "WWW-Authenticate" header */
  7942. mg_snprintf(conn,
  7943. &trunc,
  7944. buf,
  7945. sizeof(buf),
  7946. "Digest qop=\"auth\", realm=\"%s\", "
  7947. "nonce=\"%" UINT64_FMT "\"",
  7948. realm,
  7949. nonce);
  7950. if (!trunc) {
  7951. /* !trunc should always be true */
  7952. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7953. }
  7954. /* Send all headers */
  7955. mg_response_header_send(conn);
  7956. }
  7957. /* Interface function. Parameters are provided by the user, so do
  7958. * at least some basic checks.
  7959. */
  7960. CIVETWEB_API int
  7961. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7962. const char *realm)
  7963. {
  7964. if (conn && conn->dom_ctx) {
  7965. send_authorization_request(conn, realm);
  7966. return 0;
  7967. }
  7968. return -1;
  7969. }
  7970. #if !defined(NO_FILES)
  7971. static int
  7972. is_authorized_for_put(struct mg_connection *conn)
  7973. {
  7974. int ret = 0;
  7975. if (conn) {
  7976. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7977. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7978. if (passfile != NULL
  7979. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7980. ret = authorize(conn, &file, NULL);
  7981. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7982. }
  7983. }
  7984. DEBUG_TRACE("file write authorization: %i", ret);
  7985. return ret;
  7986. }
  7987. #endif
  7988. CIVETWEB_API int
  7989. mg_modify_passwords_file_ha1(const char *fname,
  7990. const char *domain,
  7991. const char *user,
  7992. const char *ha1)
  7993. {
  7994. int found = 0, i, result = 1;
  7995. char line[512], u[256], d[256], h[256];
  7996. struct stat st = {0};
  7997. FILE *fp = NULL;
  7998. char *temp_file = NULL;
  7999. int temp_file_offs = 0;
  8000. /* Regard empty password as no password - remove user record. */
  8001. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  8002. ha1 = NULL;
  8003. }
  8004. /* Other arguments must not be empty */
  8005. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8006. return 0;
  8007. }
  8008. /* Using the given file format, user name and domain must not contain
  8009. * the ':' character */
  8010. if (strchr(user, ':') != NULL) {
  8011. return 0;
  8012. }
  8013. if (strchr(domain, ':') != NULL) {
  8014. return 0;
  8015. }
  8016. /* Do not allow control characters like newline in user name and domain.
  8017. * Do not allow excessively long names either. */
  8018. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  8019. if (iscntrl((unsigned char)user[i])) {
  8020. return 0;
  8021. }
  8022. }
  8023. if (user[i]) {
  8024. return 0; /* user name too long */
  8025. }
  8026. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  8027. if (iscntrl((unsigned char)domain[i])) {
  8028. return 0;
  8029. }
  8030. }
  8031. if (domain[i]) {
  8032. return 0; /* domain name too long */
  8033. }
  8034. /* The maximum length of the path to the password file is limited */
  8035. if (strlen(fname) >= UTF8_PATH_MAX) {
  8036. return 0;
  8037. }
  8038. /* Check if the file exists, and get file size */
  8039. if (0 == stat(fname, &st)) {
  8040. int temp_buf_len;
  8041. if (st.st_size > 10485760) {
  8042. /* Some funster provided a >10 MB text file */
  8043. return 0;
  8044. }
  8045. /* Add enough space for one more line */
  8046. temp_buf_len = (int)st.st_size + 1024;
  8047. /* Allocate memory (instead of using a temporary file) */
  8048. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  8049. if (!temp_file) {
  8050. /* Out of memory */
  8051. return 0;
  8052. }
  8053. /* File exists. Read it into a memory buffer. */
  8054. fp = fopen(fname, "r");
  8055. if (fp == NULL) {
  8056. /* Cannot read file. No permission? */
  8057. mg_free(temp_file);
  8058. return 0;
  8059. }
  8060. /* Read content and store in memory */
  8061. while ((fgets(line, sizeof(line), fp) != NULL)
  8062. && ((temp_file_offs + 600) < temp_buf_len)) {
  8063. /* file format is "user:domain:hash\n" */
  8064. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  8065. continue;
  8066. }
  8067. u[255] = 0;
  8068. d[255] = 0;
  8069. h[255] = 0;
  8070. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8071. /* Found the user: change the password hash or drop the user
  8072. */
  8073. if ((ha1 != NULL) && (!found)) {
  8074. i = sprintf(temp_file + temp_file_offs,
  8075. "%s:%s:%s\n",
  8076. user,
  8077. domain,
  8078. ha1);
  8079. if (i < 1) {
  8080. fclose(fp);
  8081. mg_free(temp_file);
  8082. return 0;
  8083. }
  8084. temp_file_offs += i;
  8085. }
  8086. found = 1;
  8087. } else {
  8088. /* Copy existing user, including password hash */
  8089. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  8090. if (i < 1) {
  8091. fclose(fp);
  8092. mg_free(temp_file);
  8093. return 0;
  8094. }
  8095. temp_file_offs += i;
  8096. }
  8097. }
  8098. fclose(fp);
  8099. }
  8100. /* Create new file */
  8101. fp = fopen(fname, "w");
  8102. if (!fp) {
  8103. mg_free(temp_file);
  8104. return 0;
  8105. }
  8106. #if !defined(_WIN32)
  8107. /* On Linux & co., restrict file read/write permissions to the owner */
  8108. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  8109. result = 0;
  8110. }
  8111. #endif
  8112. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  8113. /* Store buffered content of old file */
  8114. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  8115. != (size_t)temp_file_offs) {
  8116. result = 0;
  8117. }
  8118. }
  8119. /* If new user, just add it */
  8120. if ((ha1 != NULL) && (!found)) {
  8121. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  8122. result = 0;
  8123. }
  8124. }
  8125. /* All data written */
  8126. if (fclose(fp) != 0) {
  8127. result = 0;
  8128. }
  8129. mg_free(temp_file);
  8130. return result;
  8131. }
  8132. CIVETWEB_API int
  8133. mg_modify_passwords_file(const char *fname,
  8134. const char *domain,
  8135. const char *user,
  8136. const char *pass)
  8137. {
  8138. char ha1buf[33];
  8139. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8140. return 0;
  8141. }
  8142. if ((pass == NULL) || (pass[0] == 0)) {
  8143. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  8144. }
  8145. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  8146. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  8147. }
  8148. static int
  8149. is_valid_port(unsigned long port)
  8150. {
  8151. return (port <= 0xffff);
  8152. }
  8153. static int
  8154. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8155. {
  8156. struct addrinfo hints, *res, *ressave;
  8157. int func_ret = 0;
  8158. int gai_ret;
  8159. memset(&hints, 0, sizeof(struct addrinfo));
  8160. hints.ai_family = af;
  8161. if (!resolve_src) {
  8162. hints.ai_flags = AI_NUMERICHOST;
  8163. }
  8164. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8165. if (gai_ret != 0) {
  8166. /* gai_strerror could be used to convert gai_ret to a string */
  8167. /* POSIX return values: see
  8168. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8169. */
  8170. /* Windows return values: see
  8171. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8172. */
  8173. return 0;
  8174. }
  8175. ressave = res;
  8176. while (res) {
  8177. if ((dstlen >= (size_t)res->ai_addrlen)
  8178. && (res->ai_addr->sa_family == af)) {
  8179. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8180. func_ret = 1;
  8181. }
  8182. res = res->ai_next;
  8183. }
  8184. freeaddrinfo(ressave);
  8185. return func_ret;
  8186. }
  8187. static int
  8188. connect_socket(
  8189. struct mg_context *ctx /* may be NULL */,
  8190. const char *host,
  8191. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  8192. int use_ssl, /* 0 or 1 */
  8193. struct mg_error_data *error,
  8194. SOCKET *sock /* output: socket, must not be NULL */,
  8195. union usa *sa /* output: socket address, must not be NULL */
  8196. )
  8197. {
  8198. int ip_ver = 0;
  8199. int conn_ret = -1;
  8200. int sockerr = 0;
  8201. *sock = INVALID_SOCKET;
  8202. memset(sa, 0, sizeof(*sa));
  8203. if (host == NULL) {
  8204. if (error != NULL) {
  8205. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8206. mg_snprintf(NULL,
  8207. NULL, /* No truncation check for ebuf */
  8208. error->text,
  8209. error->text_buffer_size,
  8210. "%s",
  8211. "NULL host");
  8212. }
  8213. return 0;
  8214. }
  8215. #if defined(USE_X_DOM_SOCKET)
  8216. if (port == -99) {
  8217. /* Unix domain socket */
  8218. size_t hostlen = strlen(host);
  8219. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8220. if (error != NULL) {
  8221. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8222. mg_snprintf(NULL,
  8223. NULL, /* No truncation check for ebuf */
  8224. error->text,
  8225. error->text_buffer_size,
  8226. "%s",
  8227. "host length exceeds limit");
  8228. }
  8229. return 0;
  8230. }
  8231. } else
  8232. #endif
  8233. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8234. if (error != NULL) {
  8235. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8236. mg_snprintf(NULL,
  8237. NULL, /* No truncation check for ebuf */
  8238. error->text,
  8239. error->text_buffer_size,
  8240. "%s",
  8241. "invalid port");
  8242. }
  8243. return 0;
  8244. }
  8245. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) \
  8246. && !defined(NO_SSL_DL)
  8247. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8248. if (use_ssl && (TLS_client_method == NULL)) {
  8249. if (error != NULL) {
  8250. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8251. mg_snprintf(NULL,
  8252. NULL, /* No truncation check for ebuf */
  8253. error->text,
  8254. error->text_buffer_size,
  8255. "%s",
  8256. "SSL is not initialized");
  8257. }
  8258. return 0;
  8259. }
  8260. #else
  8261. if (use_ssl && (SSLv23_client_method == NULL)) {
  8262. if (error != 0) {
  8263. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8264. mg_snprintf(NULL,
  8265. NULL, /* No truncation check for ebuf */
  8266. error->text,
  8267. error->text_buffer_size,
  8268. "%s",
  8269. "SSL is not initialized");
  8270. }
  8271. return 0;
  8272. }
  8273. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8274. #else
  8275. (void)use_ssl;
  8276. #endif /* NO SSL */
  8277. #if defined(USE_X_DOM_SOCKET)
  8278. if (port == -99) {
  8279. size_t hostlen = strlen(host);
  8280. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8281. ip_ver = -99;
  8282. sa->sun.sun_family = AF_UNIX;
  8283. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8284. memcpy(sa->sun.sun_path, host, hostlen);
  8285. } else
  8286. #endif
  8287. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8288. sa->sin.sin_port = htons((uint16_t)port);
  8289. ip_ver = 4;
  8290. #if defined(USE_IPV6)
  8291. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8292. sa->sin6.sin6_port = htons((uint16_t)port);
  8293. ip_ver = 6;
  8294. } else if (host[0] == '[') {
  8295. /* While getaddrinfo on Windows will work with [::1],
  8296. * getaddrinfo on Linux only works with ::1 (without []). */
  8297. size_t l = strlen(host + 1);
  8298. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8299. if (h) {
  8300. h[l - 1] = 0;
  8301. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8302. sa->sin6.sin6_port = htons((uint16_t)port);
  8303. ip_ver = 6;
  8304. }
  8305. mg_free(h);
  8306. }
  8307. #endif
  8308. }
  8309. if (ip_ver == 0) {
  8310. if (error != NULL) {
  8311. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8312. mg_snprintf(NULL,
  8313. NULL, /* No truncation check for ebuf */
  8314. error->text,
  8315. error->text_buffer_size,
  8316. "%s",
  8317. "host not found");
  8318. }
  8319. return 0;
  8320. }
  8321. if (ip_ver == 4) {
  8322. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8323. }
  8324. #if defined(USE_IPV6)
  8325. else if (ip_ver == 6) {
  8326. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8327. }
  8328. #endif
  8329. #if defined(USE_X_DOM_SOCKET)
  8330. else if (ip_ver == -99) {
  8331. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8332. }
  8333. #endif
  8334. if (*sock == INVALID_SOCKET) {
  8335. if (error != NULL) {
  8336. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8337. error->code_sub = (unsigned)ERRNO;
  8338. mg_snprintf(NULL,
  8339. NULL, /* No truncation check for ebuf */
  8340. error->text,
  8341. error->text_buffer_size,
  8342. "socket(): %s",
  8343. strerror(ERRNO));
  8344. }
  8345. return 0;
  8346. }
  8347. if (0 != set_non_blocking_mode(*sock)) {
  8348. if (error != NULL) {
  8349. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8350. error->code_sub = (unsigned)ERRNO;
  8351. mg_snprintf(NULL,
  8352. NULL, /* No truncation check for ebuf */
  8353. error->text,
  8354. error->text_buffer_size,
  8355. "Cannot set socket to non-blocking: %s",
  8356. strerror(ERRNO));
  8357. }
  8358. closesocket(*sock);
  8359. *sock = INVALID_SOCKET;
  8360. return 0;
  8361. }
  8362. set_close_on_exec(*sock, NULL, ctx);
  8363. if (ip_ver == 4) {
  8364. /* connected with IPv4 */
  8365. conn_ret = connect(*sock,
  8366. (struct sockaddr *)((void *)&sa->sin),
  8367. sizeof(sa->sin));
  8368. }
  8369. #if defined(USE_IPV6)
  8370. else if (ip_ver == 6) {
  8371. /* connected with IPv6 */
  8372. conn_ret = connect(*sock,
  8373. (struct sockaddr *)((void *)&sa->sin6),
  8374. sizeof(sa->sin6));
  8375. }
  8376. #endif
  8377. #if defined(USE_X_DOM_SOCKET)
  8378. else if (ip_ver == -99) {
  8379. /* connected to domain socket */
  8380. conn_ret = connect(*sock,
  8381. (struct sockaddr *)((void *)&sa->sun),
  8382. sizeof(sa->sun));
  8383. }
  8384. #endif
  8385. if (conn_ret != 0) {
  8386. sockerr = ERRNO;
  8387. }
  8388. #if defined(_WIN32)
  8389. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8390. #else
  8391. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8392. #endif
  8393. /* Data for getsockopt */
  8394. void *psockerr = &sockerr;
  8395. int ret;
  8396. #if defined(_WIN32)
  8397. int len = (int)sizeof(sockerr);
  8398. #else
  8399. socklen_t len = (socklen_t)sizeof(sockerr);
  8400. #endif
  8401. /* Data for poll */
  8402. struct mg_pollfd pfd[2];
  8403. int pollres;
  8404. int ms_wait = 10000; /* 10 second timeout */
  8405. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8406. unsigned int num_sock = 1; /* use one or two sockets */
  8407. /* For a non-blocking socket, the connect sequence is:
  8408. * 1) call connect (will not block)
  8409. * 2) wait until the socket is ready for writing (select or poll)
  8410. * 3) check connection state with getsockopt
  8411. */
  8412. pfd[0].fd = *sock;
  8413. pfd[0].events = POLLOUT;
  8414. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  8415. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  8416. pfd[num_sock].events = POLLIN;
  8417. num_sock++;
  8418. }
  8419. pollres =
  8420. mg_poll(pfd, num_sock, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8421. if (pollres != 1) {
  8422. /* Not connected */
  8423. if (error != NULL) {
  8424. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8425. mg_snprintf(NULL,
  8426. NULL, /* No truncation check for ebuf */
  8427. error->text,
  8428. error->text_buffer_size,
  8429. "connect(%s:%d): timeout",
  8430. host,
  8431. port);
  8432. }
  8433. closesocket(*sock);
  8434. *sock = INVALID_SOCKET;
  8435. return 0;
  8436. }
  8437. #if defined(_WIN32)
  8438. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8439. #else
  8440. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8441. #endif
  8442. if ((ret == 0) && (sockerr == 0)) {
  8443. conn_ret = 0;
  8444. }
  8445. }
  8446. if (conn_ret != 0) {
  8447. /* Not connected */
  8448. if (error != NULL) {
  8449. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8450. error->code_sub = (unsigned)ERRNO;
  8451. mg_snprintf(NULL,
  8452. NULL, /* No truncation check for ebuf */
  8453. error->text,
  8454. error->text_buffer_size,
  8455. "connect(%s:%d): error %s",
  8456. host,
  8457. port,
  8458. strerror(sockerr));
  8459. }
  8460. closesocket(*sock);
  8461. *sock = INVALID_SOCKET;
  8462. return 0;
  8463. }
  8464. return 1;
  8465. }
  8466. CIVETWEB_API int
  8467. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8468. {
  8469. static const char *dont_escape = "._-$,;~()";
  8470. static const char *hex = "0123456789abcdef";
  8471. char *pos = dst;
  8472. const char *end = dst + dst_len - 1;
  8473. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8474. if (isalnum((unsigned char)*src)
  8475. || (strchr(dont_escape, *src) != NULL)) {
  8476. *pos = *src;
  8477. } else if (pos + 2 < end) {
  8478. pos[0] = '%';
  8479. pos[1] = hex[(unsigned char)*src >> 4];
  8480. pos[2] = hex[(unsigned char)*src & 0xf];
  8481. pos += 2;
  8482. } else {
  8483. break;
  8484. }
  8485. }
  8486. *pos = '\0';
  8487. return (*src == '\0') ? (int)(pos - dst) : -1;
  8488. }
  8489. /* Return 0 on success, non-zero if an error occurs. */
  8490. static int
  8491. print_dir_entry(struct mg_connection *conn, struct de *de)
  8492. {
  8493. size_t namesize, escsize, i;
  8494. char *href, *esc, *p;
  8495. char size[64], mod[64];
  8496. #if defined(REENTRANT_TIME)
  8497. struct tm _tm;
  8498. struct tm *tm = &_tm;
  8499. #else
  8500. struct tm *tm;
  8501. #endif
  8502. /* Estimate worst case size for encoding and escaping */
  8503. namesize = strlen(de->file_name) + 1;
  8504. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8505. href = (char *)mg_malloc(namesize * 3 + escsize);
  8506. if (href == NULL) {
  8507. return -1;
  8508. }
  8509. mg_url_encode(de->file_name, href, namesize * 3);
  8510. esc = NULL;
  8511. if (escsize > 0) {
  8512. /* HTML escaping needed */
  8513. esc = href + namesize * 3;
  8514. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8515. mg_strlcpy(p, de->file_name + i, 2);
  8516. if (*p == '&') {
  8517. strcpy(p, "&amp;");
  8518. } else if (*p == '<') {
  8519. strcpy(p, "&lt;");
  8520. } else if (*p == '>') {
  8521. strcpy(p, "&gt;");
  8522. }
  8523. }
  8524. }
  8525. if (de->file.is_directory) {
  8526. mg_snprintf(conn,
  8527. NULL, /* Buffer is big enough */
  8528. size,
  8529. sizeof(size),
  8530. "%s",
  8531. "[DIRECTORY]");
  8532. } else {
  8533. /* We use (signed) cast below because MSVC 6 compiler cannot
  8534. * convert unsigned __int64 to double. Sigh. */
  8535. if (de->file.size < 1024) {
  8536. mg_snprintf(conn,
  8537. NULL, /* Buffer is big enough */
  8538. size,
  8539. sizeof(size),
  8540. "%d",
  8541. (int)de->file.size);
  8542. } else if (de->file.size < 0x100000) {
  8543. mg_snprintf(conn,
  8544. NULL, /* Buffer is big enough */
  8545. size,
  8546. sizeof(size),
  8547. "%.1fk",
  8548. (double)de->file.size / 1024.0);
  8549. } else if (de->file.size < 0x40000000) {
  8550. mg_snprintf(conn,
  8551. NULL, /* Buffer is big enough */
  8552. size,
  8553. sizeof(size),
  8554. "%.1fM",
  8555. (double)de->file.size / 1048576);
  8556. } else {
  8557. mg_snprintf(conn,
  8558. NULL, /* Buffer is big enough */
  8559. size,
  8560. sizeof(size),
  8561. "%.1fG",
  8562. (double)de->file.size / 1073741824);
  8563. }
  8564. }
  8565. /* Note: mg_snprintf will not cause a buffer overflow above.
  8566. * So, string truncation checks are not required here. */
  8567. #if defined(REENTRANT_TIME)
  8568. localtime_r(&de->file.last_modified, tm);
  8569. #else
  8570. tm = localtime(&de->file.last_modified);
  8571. #endif
  8572. if (tm != NULL) {
  8573. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8574. } else {
  8575. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8576. }
  8577. mg_printf(conn,
  8578. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8579. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8580. href,
  8581. de->file.is_directory ? "/" : "",
  8582. esc ? esc : de->file_name,
  8583. de->file.is_directory ? "/" : "",
  8584. mod,
  8585. size);
  8586. mg_free(href);
  8587. return 0;
  8588. }
  8589. /* This function is called from send_directory() and used for
  8590. * sorting directory entries by size, name, or modification time. */
  8591. static int
  8592. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8593. {
  8594. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8595. if (p1 && p2) {
  8596. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8597. int cmp_result = 0;
  8598. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8599. query_string = "n";
  8600. }
  8601. /* Sort Directories vs Files */
  8602. if (a->file.is_directory && !b->file.is_directory) {
  8603. return -1; /* Always put directories on top */
  8604. } else if (!a->file.is_directory && b->file.is_directory) {
  8605. return 1; /* Always put directories on top */
  8606. }
  8607. /* Sort by size or date */
  8608. if (*query_string == 's') {
  8609. cmp_result = (a->file.size == b->file.size)
  8610. ? 0
  8611. : ((a->file.size > b->file.size) ? 1 : -1);
  8612. } else if (*query_string == 'd') {
  8613. cmp_result =
  8614. (a->file.last_modified == b->file.last_modified)
  8615. ? 0
  8616. : ((a->file.last_modified > b->file.last_modified) ? 1
  8617. : -1);
  8618. }
  8619. /* Sort by name:
  8620. * if (*query_string == 'n') ...
  8621. * but also sort files of same size/date by name as secondary criterion.
  8622. */
  8623. if (cmp_result == 0) {
  8624. cmp_result = strcmp(a->file_name, b->file_name);
  8625. }
  8626. /* For descending order, invert result */
  8627. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8628. }
  8629. return 0;
  8630. }
  8631. static int
  8632. must_hide_file(struct mg_connection *conn, const char *path)
  8633. {
  8634. if (conn && conn->dom_ctx) {
  8635. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8636. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8637. return (match_prefix_strlen(pw_pattern, path) > 0)
  8638. || (match_prefix_strlen(pattern, path) > 0);
  8639. }
  8640. return 0;
  8641. }
  8642. #if !defined(NO_FILESYSTEMS)
  8643. static int
  8644. scan_directory(struct mg_connection *conn,
  8645. const char *dir,
  8646. void *data,
  8647. int (*cb)(struct de *, void *))
  8648. {
  8649. char path[UTF8_PATH_MAX];
  8650. struct dirent *dp;
  8651. DIR *dirp;
  8652. struct de de;
  8653. int truncated;
  8654. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8655. return 0;
  8656. } else {
  8657. while ((dp = mg_readdir(dirp)) != NULL) {
  8658. /* Do not show current dir and hidden files */
  8659. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8660. || must_hide_file(conn, dp->d_name)) {
  8661. continue;
  8662. }
  8663. mg_snprintf(
  8664. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8665. /* If we don't memset stat structure to zero, mtime will have
  8666. * garbage and strftime() will segfault later on in
  8667. * print_dir_entry(). memset is required only if mg_stat()
  8668. * fails. For more details, see
  8669. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8670. memset(&de.file, 0, sizeof(de.file));
  8671. if (truncated) {
  8672. /* If the path is not complete, skip processing. */
  8673. continue;
  8674. }
  8675. if (!mg_stat(conn, path, &de.file)) {
  8676. mg_cry_internal(conn,
  8677. "%s: mg_stat(%s) failed: %s",
  8678. __func__,
  8679. path,
  8680. strerror(ERRNO));
  8681. }
  8682. de.file_name = dp->d_name;
  8683. if (cb(&de, data)) {
  8684. /* stopped */
  8685. break;
  8686. }
  8687. }
  8688. (void)mg_closedir(dirp);
  8689. }
  8690. return 1;
  8691. }
  8692. #endif /* NO_FILESYSTEMS */
  8693. #if !defined(NO_FILES)
  8694. static int
  8695. remove_directory(struct mg_connection *conn, const char *dir)
  8696. {
  8697. char path[UTF8_PATH_MAX];
  8698. struct dirent *dp;
  8699. DIR *dirp;
  8700. struct de de;
  8701. int truncated;
  8702. int ok = 1;
  8703. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8704. return 0;
  8705. } else {
  8706. while ((dp = mg_readdir(dirp)) != NULL) {
  8707. /* Do not show current dir (but show hidden files as they will
  8708. * also be removed) */
  8709. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8710. continue;
  8711. }
  8712. mg_snprintf(
  8713. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8714. /* If we don't memset stat structure to zero, mtime will have
  8715. * garbage and strftime() will segfault later on in
  8716. * print_dir_entry(). memset is required only if mg_stat()
  8717. * fails. For more details, see
  8718. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8719. memset(&de.file, 0, sizeof(de.file));
  8720. if (truncated) {
  8721. /* Do not delete anything shorter */
  8722. ok = 0;
  8723. continue;
  8724. }
  8725. if (!mg_stat(conn, path, &de.file)) {
  8726. mg_cry_internal(conn,
  8727. "%s: mg_stat(%s) failed: %s",
  8728. __func__,
  8729. path,
  8730. strerror(ERRNO));
  8731. ok = 0;
  8732. }
  8733. if (de.file.is_directory) {
  8734. if (remove_directory(conn, path) == 0) {
  8735. ok = 0;
  8736. }
  8737. } else {
  8738. /* This will fail file is the file is in memory */
  8739. if (mg_remove(conn, path) == 0) {
  8740. ok = 0;
  8741. }
  8742. }
  8743. }
  8744. (void)mg_closedir(dirp);
  8745. IGNORE_UNUSED_RESULT(rmdir(dir));
  8746. }
  8747. return ok;
  8748. }
  8749. #endif
  8750. struct dir_scan_data {
  8751. struct de *entries;
  8752. size_t num_entries;
  8753. size_t arr_size;
  8754. };
  8755. #if !defined(NO_FILESYSTEMS)
  8756. static int
  8757. dir_scan_callback(struct de *de, void *data)
  8758. {
  8759. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8760. struct de *entries = dsd->entries;
  8761. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8762. /* Here "entries" is a temporary pointer and can be replaced,
  8763. * "dsd->entries" is the original pointer */
  8764. entries =
  8765. (struct de *)mg_realloc(entries,
  8766. dsd->arr_size * 2 * sizeof(entries[0]));
  8767. if (entries == NULL) {
  8768. /* stop scan */
  8769. return 1;
  8770. }
  8771. dsd->entries = entries;
  8772. dsd->arr_size *= 2;
  8773. }
  8774. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8775. if (entries[dsd->num_entries].file_name == NULL) {
  8776. /* stop scan */
  8777. return 1;
  8778. }
  8779. entries[dsd->num_entries].file = de->file;
  8780. dsd->num_entries++;
  8781. return 0;
  8782. }
  8783. static void
  8784. handle_directory_request(struct mg_connection *conn, const char *dir)
  8785. {
  8786. size_t i;
  8787. int sort_direction;
  8788. struct dir_scan_data data = {NULL, 0, 128};
  8789. char date[64], *esc, *p;
  8790. const char *title;
  8791. time_t curtime = time(NULL);
  8792. if (!conn) {
  8793. return;
  8794. }
  8795. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8796. mg_send_http_error(conn,
  8797. 500,
  8798. "Error: Cannot open directory\nopendir(%s): %s",
  8799. dir,
  8800. strerror(ERRNO));
  8801. return;
  8802. }
  8803. gmt_time_string(date, sizeof(date), &curtime);
  8804. esc = NULL;
  8805. title = conn->request_info.local_uri;
  8806. if (title[strcspn(title, "&<>")]) {
  8807. /* HTML escaping needed */
  8808. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8809. if (esc) {
  8810. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8811. mg_strlcpy(p, title + i, 2);
  8812. if (*p == '&') {
  8813. strcpy(p, "&amp;");
  8814. } else if (*p == '<') {
  8815. strcpy(p, "&lt;");
  8816. } else if (*p == '>') {
  8817. strcpy(p, "&gt;");
  8818. }
  8819. }
  8820. } else {
  8821. title = "";
  8822. }
  8823. }
  8824. sort_direction = ((conn->request_info.query_string != NULL)
  8825. && (conn->request_info.query_string[0] != '\0')
  8826. && (conn->request_info.query_string[1] == 'd'))
  8827. ? 'a'
  8828. : 'd';
  8829. conn->must_close = 1;
  8830. /* Create 200 OK response */
  8831. mg_response_header_start(conn, 200);
  8832. send_static_cache_header(conn);
  8833. send_additional_header(conn);
  8834. mg_response_header_add(conn,
  8835. "Content-Type",
  8836. "text/html; charset=utf-8",
  8837. -1);
  8838. /* Send all headers */
  8839. mg_response_header_send(conn);
  8840. /* Body */
  8841. mg_printf(conn,
  8842. "<!DOCTYPE html>"
  8843. "<html><head><title>Index of %s</title>"
  8844. "<style>th {text-align: left;}</style></head>"
  8845. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8846. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8847. "<th><a href=\"?d%c\">Modified</a></th>"
  8848. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8849. "<tr><td colspan=\"3\"><hr></td></tr>",
  8850. esc ? esc : title,
  8851. esc ? esc : title,
  8852. sort_direction,
  8853. sort_direction,
  8854. sort_direction);
  8855. mg_free(esc);
  8856. /* Print first entry - link to a parent directory */
  8857. mg_printf(conn,
  8858. "<tr><td><a href=\"%s\">%s</a></td>"
  8859. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8860. "..",
  8861. "Parent directory",
  8862. "-",
  8863. "-");
  8864. /* Sort and print directory entries */
  8865. if (data.entries != NULL) {
  8866. mg_sort(data.entries,
  8867. data.num_entries,
  8868. sizeof(data.entries[0]),
  8869. compare_dir_entries,
  8870. (void *)conn->request_info.query_string);
  8871. for (i = 0; i < data.num_entries; i++) {
  8872. print_dir_entry(conn, &data.entries[i]);
  8873. mg_free(data.entries[i].file_name);
  8874. }
  8875. mg_free(data.entries);
  8876. }
  8877. mg_printf(conn, "%s", "</table></pre></body></html>");
  8878. conn->status_code = 200;
  8879. }
  8880. #endif /* NO_FILESYSTEMS */
  8881. /* Send len bytes from the opened file to the client. */
  8882. static void
  8883. send_file_data(struct mg_connection *conn,
  8884. struct mg_file *filep,
  8885. int64_t offset,
  8886. int64_t len,
  8887. int no_buffering)
  8888. {
  8889. char buf[MG_BUF_LEN];
  8890. int to_read, num_read, num_written;
  8891. int64_t size;
  8892. if (!filep || !conn) {
  8893. return;
  8894. }
  8895. /* Sanity check the offset */
  8896. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8897. : (int64_t)(filep->stat.size);
  8898. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8899. if (len > 0 && filep->access.fp != NULL) {
  8900. /* file stored on disk */
  8901. #if defined(__linux__)
  8902. /* sendfile is only available for Linux */
  8903. if ((conn->ssl == 0) && (conn->throttle == 0)
  8904. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8905. "yes"))) {
  8906. off_t sf_offs = (off_t)offset;
  8907. ssize_t sf_sent;
  8908. int sf_file = fileno(filep->access.fp);
  8909. int loop_cnt = 0;
  8910. do {
  8911. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8912. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8913. size_t sf_tosend =
  8914. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8915. sf_sent =
  8916. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8917. if (sf_sent > 0) {
  8918. len -= sf_sent;
  8919. offset += sf_sent;
  8920. } else if (loop_cnt == 0) {
  8921. /* This file can not be sent using sendfile.
  8922. * This might be the case for pseudo-files in the
  8923. * /sys/ and /proc/ file system.
  8924. * Use the regular user mode copy code instead. */
  8925. break;
  8926. } else if (sf_sent == 0) {
  8927. /* No error, but 0 bytes sent. May be EOF? */
  8928. return;
  8929. }
  8930. loop_cnt++;
  8931. } while ((len > 0) && (sf_sent >= 0));
  8932. if (sf_sent > 0) {
  8933. return; /* OK */
  8934. }
  8935. /* sf_sent<0 means error, thus fall back to the classic way */
  8936. /* This is always the case, if sf_file is not a "normal" file,
  8937. * e.g., for sending data from the output of a CGI process. */
  8938. offset = (int64_t)sf_offs;
  8939. }
  8940. #endif
  8941. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8942. mg_cry_internal(conn,
  8943. "%s: fseeko() failed: %s",
  8944. __func__,
  8945. strerror(ERRNO));
  8946. mg_send_http_error(
  8947. conn,
  8948. 500,
  8949. "%s",
  8950. "Error: Unable to access file at requested position.");
  8951. } else {
  8952. while (len > 0) {
  8953. /* Calculate how much to read from the file into the buffer. */
  8954. /* If no_buffering is set, we should not wait until the
  8955. * CGI->Server buffer is filled, but send everything
  8956. * immediately. In theory buffering could be turned off using
  8957. * setbuf(filep->access.fp, NULL);
  8958. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8959. * but in practice this does not work. A "Linux only" solution
  8960. * may be to use select(). The only portable way is to read byte
  8961. * by byte, but this is quite inefficient from a performance
  8962. * point of view. */
  8963. to_read = no_buffering ? 1 : sizeof(buf);
  8964. if ((int64_t)to_read > len) {
  8965. to_read = (int)len;
  8966. }
  8967. /* Read from file, exit the loop on error */
  8968. if ((num_read = pull_inner(filep->access.fp,
  8969. NULL,
  8970. buf,
  8971. to_read,
  8972. /* unused */ 0.0))
  8973. <= 0) {
  8974. break;
  8975. }
  8976. /* Send read bytes to the client, exit the loop on error */
  8977. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8978. != num_read) {
  8979. break;
  8980. }
  8981. /* Both read and were successful, adjust counters */
  8982. len -= num_written;
  8983. }
  8984. }
  8985. }
  8986. }
  8987. static int
  8988. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8989. {
  8990. return sscanf(header,
  8991. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8992. a,
  8993. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8994. // to an integer value, but function will not report
  8995. // conversion errors; consider using 'strtol' instead
  8996. }
  8997. static void
  8998. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8999. {
  9000. if ((filestat != NULL) && (buf != NULL)) {
  9001. mg_snprintf(NULL,
  9002. NULL, /* All calls to construct_etag use 64 byte buffer */
  9003. buf,
  9004. buf_len,
  9005. "\"%lx.%" INT64_FMT "\"",
  9006. (unsigned long)filestat->last_modified,
  9007. filestat->size);
  9008. }
  9009. }
  9010. static void
  9011. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  9012. {
  9013. if (filep != NULL && filep->fp != NULL) {
  9014. #if defined(_WIN32)
  9015. (void)conn; /* Unused. */
  9016. #else
  9017. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  9018. mg_cry_internal(conn,
  9019. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  9020. __func__,
  9021. strerror(ERRNO));
  9022. }
  9023. #endif
  9024. }
  9025. }
  9026. #if defined(USE_ZLIB)
  9027. #include "mod_zlib.inl"
  9028. #endif
  9029. #if !defined(NO_FILESYSTEMS)
  9030. static void
  9031. handle_static_file_request(struct mg_connection *conn,
  9032. const char *path,
  9033. struct mg_file *filep,
  9034. const char *mime_type,
  9035. const char *additional_headers)
  9036. {
  9037. char lm[64], etag[64];
  9038. char range[128]; /* large enough, so there will be no overflow */
  9039. const char *range_hdr;
  9040. int64_t cl, r1, r2;
  9041. struct vec mime_vec;
  9042. int n, truncated;
  9043. char gz_path[UTF8_PATH_MAX];
  9044. const char *encoding = 0;
  9045. int is_head_request;
  9046. #if defined(USE_ZLIB)
  9047. /* Compression is allowed, unless there is a reason not to use
  9048. * compression. If the file is already compressed, too small or a
  9049. * "range" request was made, on the fly compression is not possible. */
  9050. int allow_on_the_fly_compression = 1;
  9051. #endif
  9052. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  9053. return;
  9054. }
  9055. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  9056. if (mime_type == NULL) {
  9057. get_mime_type(conn, path, &mime_vec);
  9058. } else {
  9059. mime_vec.ptr = mime_type;
  9060. mime_vec.len = strlen(mime_type);
  9061. }
  9062. if (filep->stat.size > INT64_MAX) {
  9063. mg_send_http_error(conn,
  9064. 500,
  9065. "Error: File size is too large to send\n%" INT64_FMT,
  9066. filep->stat.size);
  9067. return;
  9068. }
  9069. cl = (int64_t)filep->stat.size;
  9070. conn->status_code = 200;
  9071. range[0] = '\0';
  9072. #if defined(USE_ZLIB)
  9073. /* if this file is in fact a pre-gzipped file, rewrite its filename
  9074. * it's important to rewrite the filename after resolving
  9075. * the mime type from it, to preserve the actual file's type */
  9076. if (!conn->accept_gzip) {
  9077. allow_on_the_fly_compression = 0;
  9078. }
  9079. #endif
  9080. /* Check if there is a range header */
  9081. range_hdr = mg_get_header(conn, "Range");
  9082. /* For gzipped files, add *.gz */
  9083. if (filep->stat.is_gzipped) {
  9084. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9085. if (truncated) {
  9086. mg_send_http_error(conn,
  9087. 500,
  9088. "Error: Path of zipped file too long (%s)",
  9089. path);
  9090. return;
  9091. }
  9092. path = gz_path;
  9093. encoding = "gzip";
  9094. #if defined(USE_ZLIB)
  9095. /* File is already compressed. No "on the fly" compression. */
  9096. allow_on_the_fly_compression = 0;
  9097. #endif
  9098. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  9099. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  9100. struct mg_file_stat file_stat;
  9101. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9102. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  9103. && !file_stat.is_directory) {
  9104. file_stat.is_gzipped = 1;
  9105. filep->stat = file_stat;
  9106. cl = (int64_t)filep->stat.size;
  9107. path = gz_path;
  9108. encoding = "gzip";
  9109. #if defined(USE_ZLIB)
  9110. /* File is already compressed. No "on the fly" compression. */
  9111. allow_on_the_fly_compression = 0;
  9112. #endif
  9113. }
  9114. }
  9115. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9116. mg_send_http_error(conn,
  9117. 500,
  9118. "Error: Cannot open file\nfopen(%s): %s",
  9119. path,
  9120. strerror(ERRNO));
  9121. return;
  9122. }
  9123. fclose_on_exec(&filep->access, conn);
  9124. /* If "Range" request was made: parse header, send only selected part
  9125. * of the file. */
  9126. r1 = r2 = 0;
  9127. if ((range_hdr != NULL)
  9128. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  9129. && (r2 >= 0)) {
  9130. /* actually, range requests don't play well with a pre-gzipped
  9131. * file (since the range is specified in the uncompressed space) */
  9132. if (filep->stat.is_gzipped) {
  9133. mg_send_http_error(
  9134. conn,
  9135. 416, /* 416 = Range Not Satisfiable */
  9136. "%s",
  9137. "Error: Range requests in gzipped files are not supported");
  9138. (void)mg_fclose(
  9139. &filep->access); /* ignore error on read only file */
  9140. return;
  9141. }
  9142. conn->status_code = 206;
  9143. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  9144. mg_snprintf(conn,
  9145. NULL, /* range buffer is big enough */
  9146. range,
  9147. sizeof(range),
  9148. "bytes "
  9149. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  9150. r1,
  9151. r1 + cl - 1,
  9152. filep->stat.size);
  9153. #if defined(USE_ZLIB)
  9154. /* Do not compress ranges. */
  9155. allow_on_the_fly_compression = 0;
  9156. #endif
  9157. }
  9158. /* Do not compress small files. Small files do not benefit from file
  9159. * compression, but there is still some overhead. */
  9160. #if defined(USE_ZLIB)
  9161. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  9162. /* File is below the size limit. */
  9163. allow_on_the_fly_compression = 0;
  9164. }
  9165. #endif
  9166. /* Prepare Etag, and Last-Modified headers. */
  9167. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9168. construct_etag(etag, sizeof(etag), &filep->stat);
  9169. /* Create 2xx (200, 206) response */
  9170. mg_response_header_start(conn, conn->status_code);
  9171. send_static_cache_header(conn);
  9172. send_additional_header(conn);
  9173. send_cors_header(conn);
  9174. mg_response_header_add(conn,
  9175. "Content-Type",
  9176. mime_vec.ptr,
  9177. (int)mime_vec.len);
  9178. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9179. mg_response_header_add(conn, "Etag", etag, -1);
  9180. #if defined(USE_ZLIB)
  9181. /* On the fly compression allowed */
  9182. if (allow_on_the_fly_compression) {
  9183. /* For on the fly compression, we don't know the content size in
  9184. * advance, so we have to use chunked encoding */
  9185. encoding = "gzip";
  9186. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9187. /* HTTP/2 is always using "chunks" (frames) */
  9188. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9189. }
  9190. } else
  9191. #endif
  9192. {
  9193. /* Without on-the-fly compression, we know the content-length
  9194. * and we can use ranges (with on-the-fly compression we cannot).
  9195. * So we send these response headers only in this case. */
  9196. char len[32];
  9197. int trunc = 0;
  9198. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9199. if (!trunc) {
  9200. mg_response_header_add(conn, "Content-Length", len, -1);
  9201. }
  9202. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9203. }
  9204. if (encoding) {
  9205. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9206. }
  9207. if (range[0] != 0) {
  9208. mg_response_header_add(conn, "Content-Range", range, -1);
  9209. }
  9210. /* The code above does not add any header starting with X- to make
  9211. * sure no one of the additional_headers is included twice */
  9212. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9213. mg_response_header_add_lines(conn, additional_headers);
  9214. }
  9215. /* Send all headers */
  9216. mg_response_header_send(conn);
  9217. if (!is_head_request) {
  9218. #if defined(USE_ZLIB)
  9219. if (allow_on_the_fly_compression) {
  9220. /* Compress and send */
  9221. send_compressed_data(conn, filep);
  9222. } else
  9223. #endif
  9224. {
  9225. /* Send file directly */
  9226. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9227. }
  9228. }
  9229. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9230. }
  9231. CIVETWEB_API int
  9232. mg_send_file_body(struct mg_connection *conn, const char *path)
  9233. {
  9234. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9235. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9236. return -1;
  9237. }
  9238. fclose_on_exec(&file.access, conn);
  9239. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9240. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9241. return 0; /* >= 0 for OK */
  9242. }
  9243. #endif /* NO_FILESYSTEMS */
  9244. #if !defined(NO_CACHING)
  9245. /* Return True if we should reply 304 Not Modified. */
  9246. static int
  9247. is_not_modified(const struct mg_connection *conn,
  9248. const struct mg_file_stat *filestat)
  9249. {
  9250. char etag[64];
  9251. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9252. const char *inm = mg_get_header(conn, "If-None-Match");
  9253. construct_etag(etag, sizeof(etag), filestat);
  9254. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9255. || ((ims != NULL)
  9256. && (filestat->last_modified <= parse_date_string(ims)));
  9257. }
  9258. static void
  9259. handle_not_modified_static_file_request(struct mg_connection *conn,
  9260. struct mg_file *filep)
  9261. {
  9262. char lm[64], etag[64];
  9263. if ((conn == NULL) || (filep == NULL)) {
  9264. return;
  9265. }
  9266. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9267. construct_etag(etag, sizeof(etag), &filep->stat);
  9268. /* Create 304 "not modified" response */
  9269. mg_response_header_start(conn, 304);
  9270. send_static_cache_header(conn);
  9271. send_additional_header(conn);
  9272. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9273. mg_response_header_add(conn, "Etag", etag, -1);
  9274. /* Send all headers */
  9275. mg_response_header_send(conn);
  9276. }
  9277. #endif
  9278. #if !defined(NO_FILESYSTEMS)
  9279. CIVETWEB_API void
  9280. mg_send_file(struct mg_connection *conn, const char *path)
  9281. {
  9282. mg_send_mime_file2(conn, path, NULL, NULL);
  9283. }
  9284. CIVETWEB_API void
  9285. mg_send_mime_file(struct mg_connection *conn,
  9286. const char *path,
  9287. const char *mime_type)
  9288. {
  9289. mg_send_mime_file2(conn, path, mime_type, NULL);
  9290. }
  9291. CIVETWEB_API void
  9292. mg_send_mime_file2(struct mg_connection *conn,
  9293. const char *path,
  9294. const char *mime_type,
  9295. const char *additional_headers)
  9296. {
  9297. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9298. if (!conn) {
  9299. /* No conn */
  9300. return;
  9301. }
  9302. if (mg_stat(conn, path, &file.stat)) {
  9303. #if !defined(NO_CACHING)
  9304. if (is_not_modified(conn, &file.stat)) {
  9305. /* Send 304 "Not Modified" - this must not send any body data */
  9306. handle_not_modified_static_file_request(conn, &file);
  9307. } else
  9308. #endif /* NO_CACHING */
  9309. if (file.stat.is_directory) {
  9310. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9311. "yes")) {
  9312. handle_directory_request(conn, path);
  9313. } else {
  9314. mg_send_http_error(conn,
  9315. 403,
  9316. "%s",
  9317. "Error: Directory listing denied");
  9318. }
  9319. } else {
  9320. handle_static_file_request(
  9321. conn, path, &file, mime_type, additional_headers);
  9322. }
  9323. } else {
  9324. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9325. }
  9326. }
  9327. /* For a given PUT path, create all intermediate subdirectories.
  9328. * Return 0 if the path itself is a directory.
  9329. * Return 1 if the path leads to a file.
  9330. * Return -1 for if the path is too long.
  9331. * Return -2 if path can not be created.
  9332. */
  9333. static int
  9334. put_dir(struct mg_connection *conn, const char *path)
  9335. {
  9336. char buf[UTF8_PATH_MAX];
  9337. const char *s, *p;
  9338. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9339. size_t len;
  9340. int res = 1;
  9341. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9342. len = (size_t)(p - path);
  9343. if (len >= sizeof(buf)) {
  9344. /* path too long */
  9345. res = -1;
  9346. break;
  9347. }
  9348. memcpy(buf, path, len);
  9349. buf[len] = '\0';
  9350. /* Try to create intermediate directory */
  9351. DEBUG_TRACE("mkdir(%s)", buf);
  9352. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9353. /* path does not exist and can not be created */
  9354. res = -2;
  9355. break;
  9356. }
  9357. /* Is path itself a directory? */
  9358. if (p[1] == '\0') {
  9359. res = 0;
  9360. }
  9361. }
  9362. return res;
  9363. }
  9364. static void
  9365. remove_bad_file(const struct mg_connection *conn, const char *path)
  9366. {
  9367. int r = mg_remove(conn, path);
  9368. if (r != 0) {
  9369. mg_cry_internal(conn,
  9370. "%s: Cannot remove invalid file %s",
  9371. __func__,
  9372. path);
  9373. }
  9374. }
  9375. CIVETWEB_API long long
  9376. mg_store_body(struct mg_connection *conn, const char *path)
  9377. {
  9378. char buf[MG_BUF_LEN];
  9379. long long len = 0;
  9380. int ret, n;
  9381. struct mg_file fi;
  9382. if (conn->consumed_content != 0) {
  9383. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9384. return -11;
  9385. }
  9386. ret = put_dir(conn, path);
  9387. if (ret < 0) {
  9388. /* -1 for path too long,
  9389. * -2 for path can not be created. */
  9390. return ret;
  9391. }
  9392. if (ret != 1) {
  9393. /* Return 0 means, path itself is a directory. */
  9394. return 0;
  9395. }
  9396. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9397. return -12;
  9398. }
  9399. ret = mg_read(conn, buf, sizeof(buf));
  9400. while (ret > 0) {
  9401. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9402. if (n != ret) {
  9403. (void)mg_fclose(
  9404. &fi.access); /* File is bad and will be removed anyway. */
  9405. remove_bad_file(conn, path);
  9406. return -13;
  9407. }
  9408. len += ret;
  9409. ret = mg_read(conn, buf, sizeof(buf));
  9410. }
  9411. /* File is open for writing. If fclose fails, there was probably an
  9412. * error flushing the buffer to disk, so the file on disk might be
  9413. * broken. Delete it and return an error to the caller. */
  9414. if (mg_fclose(&fi.access) != 0) {
  9415. remove_bad_file(conn, path);
  9416. return -14;
  9417. }
  9418. return len;
  9419. }
  9420. #endif /* NO_FILESYSTEMS */
  9421. /* Parse a buffer:
  9422. * Forward the string pointer till the end of a word, then
  9423. * terminate it and forward till the begin of the next word.
  9424. */
  9425. static int
  9426. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9427. {
  9428. /* Forward until a space is found - use isgraph here */
  9429. /* Extended ASCII characters are also treated as word characters. */
  9430. /* See http://www.cplusplus.com/reference/cctype/ */
  9431. while ((unsigned char)**ppw > 127 || isgraph((unsigned char)**ppw)) {
  9432. (*ppw)++;
  9433. }
  9434. /* Check end of word */
  9435. if (eol) {
  9436. /* must be a end of line */
  9437. if ((**ppw != '\r') && (**ppw != '\n')) {
  9438. return -1;
  9439. }
  9440. } else {
  9441. /* must be a end of a word, but not a line */
  9442. if (**ppw != ' ') {
  9443. return -1;
  9444. }
  9445. }
  9446. /* Terminate and forward to the next word */
  9447. do {
  9448. **ppw = 0;
  9449. (*ppw)++;
  9450. } while (isspace((unsigned char)**ppw));
  9451. /* Check after term */
  9452. if (!eol) {
  9453. /* if it's not the end of line, there must be a next word */
  9454. if (!isgraph((unsigned char)**ppw)) {
  9455. return -1;
  9456. }
  9457. }
  9458. /* ok */
  9459. return 1;
  9460. }
  9461. /* Parse HTTP headers from the given buffer, advance buf pointer
  9462. * to the point where parsing stopped.
  9463. * All parameters must be valid pointers (not NULL).
  9464. * Return <0 on error. */
  9465. static int
  9466. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9467. {
  9468. int i;
  9469. int num_headers = 0;
  9470. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9471. char *dp = *buf;
  9472. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9473. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9474. dp++;
  9475. }
  9476. if (dp == *buf) {
  9477. /* End of headers reached. */
  9478. break;
  9479. }
  9480. /* Drop all spaces after header name before : */
  9481. while (*dp == ' ') {
  9482. *dp = 0;
  9483. dp++;
  9484. }
  9485. if (*dp != ':') {
  9486. /* This is not a valid field. */
  9487. return -1;
  9488. }
  9489. /* End of header key (*dp == ':') */
  9490. /* Truncate here and set the key name */
  9491. *dp = 0;
  9492. hdr[i].name = *buf;
  9493. /* Skip all spaces */
  9494. do {
  9495. dp++;
  9496. } while ((*dp == ' ') || (*dp == '\t'));
  9497. /* The rest of the line is the value */
  9498. hdr[i].value = dp;
  9499. /* Find end of line */
  9500. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9501. dp++;
  9502. };
  9503. /* eliminate \r */
  9504. if (*dp == '\r') {
  9505. *dp = 0;
  9506. dp++;
  9507. if (*dp != '\n') {
  9508. /* This is not a valid line. */
  9509. return -1;
  9510. }
  9511. }
  9512. /* here *dp is either 0 or '\n' */
  9513. /* in any case, we have found a complete header */
  9514. num_headers = i + 1;
  9515. if (*dp) {
  9516. *dp = 0;
  9517. dp++;
  9518. *buf = dp;
  9519. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9520. /* We've had CRLF twice in a row
  9521. * This is the end of the headers */
  9522. break;
  9523. }
  9524. /* continue within the loop, find the next header */
  9525. } else {
  9526. *buf = dp;
  9527. break;
  9528. }
  9529. }
  9530. return num_headers;
  9531. }
  9532. struct mg_http_method_info {
  9533. const char *name;
  9534. int request_has_body;
  9535. int response_has_body;
  9536. int is_safe;
  9537. int is_idempotent;
  9538. int is_cacheable;
  9539. };
  9540. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9541. static const struct mg_http_method_info http_methods[] = {
  9542. /* HTTP (RFC 2616) */
  9543. {"GET", 0, 1, 1, 1, 1},
  9544. {"POST", 1, 1, 0, 0, 0},
  9545. {"PUT", 1, 0, 0, 1, 0},
  9546. {"DELETE", 0, 0, 0, 1, 0},
  9547. {"HEAD", 0, 0, 1, 1, 1},
  9548. {"OPTIONS", 0, 0, 1, 1, 0},
  9549. {"CONNECT", 1, 1, 0, 0, 0},
  9550. /* TRACE method (RFC 2616) is not supported for security reasons */
  9551. /* PATCH method (RFC 5789) */
  9552. {"PATCH", 1, 0, 0, 0, 0},
  9553. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9554. /* WEBDAV (RFC 2518) */
  9555. {"PROPFIND", 0, 1, 1, 1, 0},
  9556. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9557. * Some PROPFIND results MAY be cached, with care,
  9558. * as there is no cache validation mechanism for
  9559. * most properties. This method is both safe and
  9560. * idempotent (see Section 9.1 of [RFC2616]). */
  9561. {"MKCOL", 0, 0, 0, 1, 0},
  9562. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9563. * When MKCOL is invoked without a request body,
  9564. * the newly created collection SHOULD have no
  9565. * members. A MKCOL request message may contain
  9566. * a message body. The precise behavior of a MKCOL
  9567. * request when the body is present is undefined,
  9568. * ... ==> We do not support MKCOL with body data.
  9569. * This method is idempotent, but not safe (see
  9570. * Section 9.1 of [RFC2616]). Responses to this
  9571. * method MUST NOT be cached. */
  9572. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9573. {"LOCK", 1, 1, 0, 0, 0},
  9574. {"UNLOCK", 1, 0, 0, 0, 0},
  9575. {"PROPPATCH", 1, 1, 0, 0, 0},
  9576. {"COPY", 1, 0, 0, 0, 0},
  9577. {"MOVE", 1, 1, 0, 0, 0},
  9578. /* Unsupported WEBDAV Methods: */
  9579. /* + 11 methods from RFC 3253 */
  9580. /* ORDERPATCH (RFC 3648) */
  9581. /* ACL (RFC 3744) */
  9582. /* SEARCH (RFC 5323) */
  9583. /* + MicroSoft extensions
  9584. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9585. /* REPORT method (RFC 3253) */
  9586. {"REPORT", 1, 1, 1, 1, 1},
  9587. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9588. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9589. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9590. * to be useful for REST in case a "GET request with body" is
  9591. * required. */
  9592. {NULL, 0, 0, 0, 0, 0}
  9593. /* end of list */
  9594. };
  9595. /* All method names */
  9596. static char *all_methods = NULL; /* Built by mg_init_library */
  9597. static const struct mg_http_method_info *
  9598. get_http_method_info(const char *method)
  9599. {
  9600. /* Check if the method is known to the server. The list of all known
  9601. * HTTP methods can be found here at
  9602. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9603. */
  9604. const struct mg_http_method_info *m = http_methods;
  9605. while (m->name) {
  9606. if (!strcmp(m->name, method)) {
  9607. return m;
  9608. }
  9609. m++;
  9610. }
  9611. return NULL;
  9612. }
  9613. static int
  9614. is_valid_http_method(const char *method)
  9615. {
  9616. return (get_http_method_info(method) != NULL);
  9617. }
  9618. /* Parse HTTP request, fill in mg_request_info structure.
  9619. * This function modifies the buffer by NUL-terminating
  9620. * HTTP request components, header names and header values.
  9621. * Parameters:
  9622. * buf (in/out): pointer to the HTTP header to parse and split
  9623. * len (in): length of HTTP header buffer
  9624. * re (out): parsed header as mg_request_info
  9625. * buf and ri must be valid pointers (not NULL), len>0.
  9626. * Returns <0 on error. */
  9627. static int
  9628. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9629. {
  9630. int request_length;
  9631. int init_skip = 0;
  9632. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9633. * remote_port */
  9634. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9635. NULL;
  9636. ri->num_headers = 0;
  9637. /* RFC says that all initial whitespaces should be ignored */
  9638. /* This included all leading \r and \n (isspace) */
  9639. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9640. while ((len > 0) && isspace((unsigned char)*buf)) {
  9641. buf++;
  9642. len--;
  9643. init_skip++;
  9644. }
  9645. if (len == 0) {
  9646. /* Incomplete request */
  9647. return 0;
  9648. }
  9649. /* Control characters are not allowed, including zero */
  9650. if (iscntrl((unsigned char)*buf)) {
  9651. return -1;
  9652. }
  9653. /* Find end of HTTP header */
  9654. request_length = get_http_header_len(buf, len);
  9655. if (request_length <= 0) {
  9656. return request_length;
  9657. }
  9658. buf[request_length - 1] = '\0';
  9659. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9660. return -1;
  9661. }
  9662. /* The first word has to be the HTTP method */
  9663. ri->request_method = buf;
  9664. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9665. return -1;
  9666. }
  9667. /* The second word is the URI */
  9668. ri->request_uri = buf;
  9669. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9670. return -1;
  9671. }
  9672. /* Next would be the HTTP version */
  9673. ri->http_version = buf;
  9674. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9675. return -1;
  9676. }
  9677. /* Check for a valid HTTP version key */
  9678. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9679. /* Invalid request */
  9680. return -1;
  9681. }
  9682. ri->http_version += 5;
  9683. /* Check for a valid http method */
  9684. if (!is_valid_http_method(ri->request_method)) {
  9685. return -1;
  9686. }
  9687. /* Parse all HTTP headers */
  9688. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9689. if (ri->num_headers < 0) {
  9690. /* Error while parsing headers */
  9691. return -1;
  9692. }
  9693. return request_length + init_skip;
  9694. }
  9695. static int
  9696. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9697. {
  9698. int response_length;
  9699. int init_skip = 0;
  9700. char *tmp, *tmp2;
  9701. long l;
  9702. /* Initialize elements. */
  9703. ri->http_version = ri->status_text = NULL;
  9704. ri->num_headers = ri->status_code = 0;
  9705. /* RFC says that all initial whitespaces should be ignored */
  9706. /* This included all leading \r and \n (isspace) */
  9707. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9708. while ((len > 0) && isspace((unsigned char)*buf)) {
  9709. buf++;
  9710. len--;
  9711. init_skip++;
  9712. }
  9713. if (len == 0) {
  9714. /* Incomplete request */
  9715. return 0;
  9716. }
  9717. /* Control characters are not allowed, including zero */
  9718. if (iscntrl((unsigned char)*buf)) {
  9719. return -1;
  9720. }
  9721. /* Find end of HTTP header */
  9722. response_length = get_http_header_len(buf, len);
  9723. if (response_length <= 0) {
  9724. return response_length;
  9725. }
  9726. buf[response_length - 1] = '\0';
  9727. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9728. return -1;
  9729. }
  9730. /* The first word is the HTTP version */
  9731. /* Check for a valid HTTP version key */
  9732. if (strncmp(buf, "HTTP/", 5) != 0) {
  9733. /* Invalid request */
  9734. return -1;
  9735. }
  9736. buf += 5;
  9737. if (!isgraph((unsigned char)buf[0])) {
  9738. /* Invalid request */
  9739. return -1;
  9740. }
  9741. ri->http_version = buf;
  9742. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9743. return -1;
  9744. }
  9745. /* The second word is the status as a number */
  9746. tmp = buf;
  9747. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9748. return -1;
  9749. }
  9750. l = strtol(tmp, &tmp2, 10);
  9751. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9752. /* Everything else but a 3 digit code is invalid */
  9753. return -1;
  9754. }
  9755. ri->status_code = (int)l;
  9756. /* The rest of the line is the status text */
  9757. ri->status_text = buf;
  9758. /* Find end of status text */
  9759. /* isgraph or isspace = isprint */
  9760. while (isprint((unsigned char)*buf)) {
  9761. buf++;
  9762. }
  9763. if ((*buf != '\r') && (*buf != '\n')) {
  9764. return -1;
  9765. }
  9766. /* Terminate string and forward buf to next line */
  9767. do {
  9768. *buf = 0;
  9769. buf++;
  9770. } while (isspace((unsigned char)*buf));
  9771. /* Parse all HTTP headers */
  9772. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9773. if (ri->num_headers < 0) {
  9774. /* Error while parsing headers */
  9775. return -1;
  9776. }
  9777. return response_length + init_skip;
  9778. }
  9779. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9780. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9781. * buffer (which marks the end of HTTP request). Buffer buf may already
  9782. * have some data. The length of the data is stored in nread.
  9783. * Upon every read operation, increase nread by the number of bytes read. */
  9784. static int
  9785. read_message(FILE *fp,
  9786. struct mg_connection *conn,
  9787. char *buf,
  9788. int bufsiz,
  9789. int *nread)
  9790. {
  9791. int request_len, n = 0;
  9792. struct timespec last_action_time;
  9793. double request_timeout;
  9794. if (!conn) {
  9795. return 0;
  9796. }
  9797. memset(&last_action_time, 0, sizeof(last_action_time));
  9798. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9799. /* value of request_timeout is in seconds, config in milliseconds */
  9800. request_timeout =
  9801. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9802. } else {
  9803. request_timeout =
  9804. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9805. / 1000.0;
  9806. }
  9807. if (conn->handled_requests > 0) {
  9808. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9809. request_timeout =
  9810. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9811. / 1000.0;
  9812. }
  9813. }
  9814. request_len = get_http_header_len(buf, *nread);
  9815. while (request_len == 0) {
  9816. /* Full request not yet received */
  9817. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9818. /* Server is to be stopped. */
  9819. return -1;
  9820. }
  9821. if (*nread >= bufsiz) {
  9822. /* Request too long */
  9823. return -2;
  9824. }
  9825. n = pull_inner(
  9826. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9827. if (n == -2) {
  9828. /* Receive error */
  9829. return -1;
  9830. }
  9831. /* update clock after every read request */
  9832. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9833. if (n > 0) {
  9834. *nread += n;
  9835. request_len = get_http_header_len(buf, *nread);
  9836. }
  9837. if ((n <= 0) && (request_timeout >= 0)) {
  9838. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9839. > request_timeout) {
  9840. /* Timeout */
  9841. return -3;
  9842. }
  9843. }
  9844. }
  9845. return request_len;
  9846. }
  9847. #if !defined(NO_CGI) || !defined(NO_FILES)
  9848. static int
  9849. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9850. {
  9851. const char *expect;
  9852. char buf[MG_BUF_LEN];
  9853. int success = 0;
  9854. if (!conn) {
  9855. return 0;
  9856. }
  9857. expect = mg_get_header(conn, "Expect");
  9858. DEBUG_ASSERT(fp != NULL);
  9859. if (!fp) {
  9860. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9861. return 0;
  9862. }
  9863. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9864. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9865. */
  9866. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9867. } else {
  9868. if (expect != NULL) {
  9869. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9870. conn->status_code = 100;
  9871. } else {
  9872. conn->status_code = 200;
  9873. }
  9874. DEBUG_ASSERT(conn->consumed_content == 0);
  9875. if (conn->consumed_content != 0) {
  9876. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9877. return 0;
  9878. }
  9879. for (;;) {
  9880. int nread = mg_read(conn, buf, sizeof(buf));
  9881. if (nread <= 0) {
  9882. success = (nread == 0);
  9883. break;
  9884. }
  9885. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9886. break;
  9887. }
  9888. }
  9889. /* Each error code path in this function must send an error */
  9890. if (!success) {
  9891. /* NOTE: Maybe some data has already been sent. */
  9892. /* TODO (low): If some data has been sent, a correct error
  9893. * reply can no longer be sent, so just close the connection */
  9894. mg_send_http_error(conn, 500, "%s", "");
  9895. }
  9896. }
  9897. return success;
  9898. }
  9899. #endif
  9900. #if defined(USE_TIMERS)
  9901. #define TIMER_API static
  9902. #include "timer.inl"
  9903. #endif /* USE_TIMERS */
  9904. #if !defined(NO_CGI)
  9905. /* This structure helps to create an environment for the spawned CGI
  9906. * program.
  9907. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9908. * last element must be NULL.
  9909. * However, on Windows there is a requirement that all these
  9910. * VARIABLE=VALUE\0
  9911. * strings must reside in a contiguous buffer. The end of the buffer is
  9912. * marked by two '\0' characters.
  9913. * We satisfy both worlds: we create an envp array (which is vars), all
  9914. * entries are actually pointers inside buf. */
  9915. struct cgi_environment {
  9916. struct mg_connection *conn;
  9917. /* Data block */
  9918. char *buf; /* Environment buffer */
  9919. size_t buflen; /* Space available in buf */
  9920. size_t bufused; /* Space taken in buf */
  9921. /* Index block */
  9922. char **var; /* char **envp */
  9923. size_t varlen; /* Number of variables available in var */
  9924. size_t varused; /* Number of variables stored in var */
  9925. };
  9926. static void addenv(struct cgi_environment *env,
  9927. PRINTF_FORMAT_STRING(const char *fmt),
  9928. ...) PRINTF_ARGS(2, 3);
  9929. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9930. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9931. static void
  9932. addenv(struct cgi_environment *env, const char *fmt, ...)
  9933. {
  9934. size_t i, n, space;
  9935. int truncated = 0;
  9936. char *added;
  9937. va_list ap;
  9938. if ((env->varlen - env->varused) < 2) {
  9939. mg_cry_internal(env->conn,
  9940. "%s: Cannot register CGI variable [%s]",
  9941. __func__,
  9942. fmt);
  9943. return;
  9944. }
  9945. /* Calculate how much space is left in the buffer */
  9946. space = (env->buflen - env->bufused);
  9947. do {
  9948. /* Space for "\0\0" is always needed. */
  9949. if (space <= 2) {
  9950. /* Allocate new buffer */
  9951. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9952. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9953. if (!added) {
  9954. /* Out of memory */
  9955. mg_cry_internal(
  9956. env->conn,
  9957. "%s: Cannot allocate memory for CGI variable [%s]",
  9958. __func__,
  9959. fmt);
  9960. return;
  9961. }
  9962. /* Retarget pointers */
  9963. env->buf = added;
  9964. env->buflen = n;
  9965. for (i = 0, n = 0; i < env->varused; i++) {
  9966. env->var[i] = added + n;
  9967. n += strlen(added + n) + 1;
  9968. }
  9969. space = (env->buflen - env->bufused);
  9970. }
  9971. /* Make a pointer to the free space int the buffer */
  9972. added = env->buf + env->bufused;
  9973. /* Copy VARIABLE=VALUE\0 string into the free space */
  9974. va_start(ap, fmt);
  9975. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9976. va_end(ap);
  9977. /* Do not add truncated strings to the environment */
  9978. if (truncated) {
  9979. /* Reallocate the buffer */
  9980. space = 0;
  9981. }
  9982. } while (truncated);
  9983. /* Calculate number of bytes added to the environment */
  9984. n = strlen(added) + 1;
  9985. env->bufused += n;
  9986. /* Append a pointer to the added string into the envp array */
  9987. env->var[env->varused] = added;
  9988. env->varused++;
  9989. }
  9990. /* Return 0 on success, non-zero if an error occurs. */
  9991. static int
  9992. prepare_cgi_environment(struct mg_connection *conn,
  9993. const char *prog,
  9994. struct cgi_environment *env,
  9995. int cgi_config_idx)
  9996. {
  9997. const char *s;
  9998. struct vec var_vec;
  9999. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  10000. int i, truncated, uri_len;
  10001. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  10002. return -1;
  10003. }
  10004. env->conn = conn;
  10005. env->buflen = CGI_ENVIRONMENT_SIZE;
  10006. env->bufused = 0;
  10007. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  10008. if (env->buf == NULL) {
  10009. mg_cry_internal(conn,
  10010. "%s: Not enough memory for environmental buffer",
  10011. __func__);
  10012. return -1;
  10013. }
  10014. env->varlen = MAX_CGI_ENVIR_VARS;
  10015. env->varused = 0;
  10016. env->var =
  10017. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  10018. if (env->var == NULL) {
  10019. mg_cry_internal(conn,
  10020. "%s: Not enough memory for environmental variables",
  10021. __func__);
  10022. mg_free(env->buf);
  10023. return -1;
  10024. }
  10025. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  10026. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10027. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10028. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  10029. addenv(env,
  10030. "FALLBACK_DOCUMENT_ROOT=%s",
  10031. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  10032. }
  10033. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  10034. /* Prepare the environment block */
  10035. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  10036. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  10037. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  10038. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  10039. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10040. addenv(env, "REMOTE_ADDR=%s", src_addr);
  10041. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  10042. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  10043. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  10044. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  10045. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  10046. /* SCRIPT_NAME */
  10047. uri_len = (int)strlen(conn->request_info.local_uri);
  10048. if (conn->path_info == NULL) {
  10049. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  10050. /* URI: /path_to_script/script.cgi */
  10051. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  10052. } else {
  10053. /* URI: /path_to_script/ ... using index.cgi */
  10054. const char *index_file = strrchr(prog, '/');
  10055. if (index_file) {
  10056. addenv(env,
  10057. "SCRIPT_NAME=%s%s",
  10058. conn->request_info.local_uri,
  10059. index_file + 1);
  10060. }
  10061. }
  10062. } else {
  10063. /* URI: /path_to_script/script.cgi/path_info */
  10064. addenv(env,
  10065. "SCRIPT_NAME=%.*s",
  10066. uri_len - (int)strlen(conn->path_info),
  10067. conn->request_info.local_uri);
  10068. }
  10069. addenv(env, "SCRIPT_FILENAME=%s", prog);
  10070. if (conn->path_info == NULL) {
  10071. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10072. } else {
  10073. addenv(env,
  10074. "PATH_TRANSLATED=%s%s",
  10075. conn->dom_ctx->config[DOCUMENT_ROOT],
  10076. conn->path_info);
  10077. }
  10078. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  10079. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  10080. addenv(env, "CONTENT_TYPE=%s", s);
  10081. }
  10082. if (conn->request_info.query_string != NULL) {
  10083. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  10084. }
  10085. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  10086. addenv(env, "CONTENT_LENGTH=%s", s);
  10087. }
  10088. if ((s = getenv("PATH")) != NULL) {
  10089. addenv(env, "PATH=%s", s);
  10090. }
  10091. if (conn->path_info != NULL) {
  10092. addenv(env, "PATH_INFO=%s", conn->path_info);
  10093. }
  10094. if (conn->status_code > 0) {
  10095. /* CGI error handler should show the status code */
  10096. addenv(env, "STATUS=%d", conn->status_code);
  10097. }
  10098. #if defined(_WIN32)
  10099. if ((s = getenv("COMSPEC")) != NULL) {
  10100. addenv(env, "COMSPEC=%s", s);
  10101. }
  10102. if ((s = getenv("SYSTEMROOT")) != NULL) {
  10103. addenv(env, "SYSTEMROOT=%s", s);
  10104. }
  10105. if ((s = getenv("SystemDrive")) != NULL) {
  10106. addenv(env, "SystemDrive=%s", s);
  10107. }
  10108. if ((s = getenv("ProgramFiles")) != NULL) {
  10109. addenv(env, "ProgramFiles=%s", s);
  10110. }
  10111. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  10112. addenv(env, "ProgramFiles(x86)=%s", s);
  10113. }
  10114. #else
  10115. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  10116. addenv(env, "LD_LIBRARY_PATH=%s", s);
  10117. }
  10118. #endif /* _WIN32 */
  10119. if ((s = getenv("PERLLIB")) != NULL) {
  10120. addenv(env, "PERLLIB=%s", s);
  10121. }
  10122. if (conn->request_info.remote_user != NULL) {
  10123. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  10124. addenv(env, "%s", "AUTH_TYPE=Digest");
  10125. }
  10126. /* Add all headers as HTTP_* variables */
  10127. for (i = 0; i < conn->request_info.num_headers; i++) {
  10128. (void)mg_snprintf(conn,
  10129. &truncated,
  10130. http_var_name,
  10131. sizeof(http_var_name),
  10132. "HTTP_%s",
  10133. conn->request_info.http_headers[i].name);
  10134. if (truncated) {
  10135. mg_cry_internal(conn,
  10136. "%s: HTTP header variable too long [%s]",
  10137. __func__,
  10138. conn->request_info.http_headers[i].name);
  10139. continue;
  10140. }
  10141. /* Convert variable name into uppercase, and change - to _ */
  10142. for (p = http_var_name; *p != '\0'; p++) {
  10143. if (*p == '-') {
  10144. *p = '_';
  10145. }
  10146. *p = (char)toupper((unsigned char)*p);
  10147. }
  10148. addenv(env,
  10149. "%s=%s",
  10150. http_var_name,
  10151. conn->request_info.http_headers[i].value);
  10152. }
  10153. /* Add user-specified variables */
  10154. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  10155. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  10156. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  10157. }
  10158. env->var[env->varused] = NULL;
  10159. env->buf[env->bufused] = '\0';
  10160. return 0;
  10161. }
  10162. /* Data for CGI process control: PID and number of references */
  10163. struct process_control_data {
  10164. pid_t pid;
  10165. ptrdiff_t references;
  10166. };
  10167. static int
  10168. abort_cgi_process(void *data)
  10169. {
  10170. /* Waitpid checks for child status and won't work for a pid that does
  10171. * not identify a child of the current process. Thus, if the pid is
  10172. * reused, we will not affect a different process. */
  10173. struct process_control_data *proc = (struct process_control_data *)data;
  10174. int status = 0;
  10175. ptrdiff_t refs;
  10176. pid_t ret_pid;
  10177. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  10178. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  10179. /* Stop child process */
  10180. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  10181. kill(proc->pid, SIGABRT);
  10182. /* Wait until process is terminated (don't leave zombies) */
  10183. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  10184. ;
  10185. } else {
  10186. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10187. }
  10188. /* Dec reference counter */
  10189. refs = mg_atomic_dec(&proc->references);
  10190. if (refs == 0) {
  10191. /* no more references - free data */
  10192. mg_free(data);
  10193. }
  10194. return 0;
  10195. }
  10196. /* Local (static) function assumes all arguments are valid. */
  10197. static void
  10198. handle_cgi_request(struct mg_connection *conn,
  10199. const char *prog,
  10200. int cgi_config_idx)
  10201. {
  10202. char *buf;
  10203. size_t buflen;
  10204. int headers_len, data_len, i, truncated;
  10205. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10206. const char *status, *status_text;
  10207. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10208. struct mg_request_info ri;
  10209. struct cgi_environment blk;
  10210. FILE *in = NULL, *out = NULL, *err = NULL;
  10211. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10212. pid_t pid = (pid_t)-1;
  10213. struct process_control_data *proc = NULL;
  10214. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  10215. int no_buffering = 0;
  10216. #if defined(USE_TIMERS)
  10217. double cgi_timeout;
  10218. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  10219. /* Get timeout in seconds */
  10220. cgi_timeout =
  10221. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  10222. } else {
  10223. cgi_timeout =
  10224. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10225. }
  10226. #endif
  10227. if (cfg_buffering != NULL) {
  10228. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10229. no_buffering = 1;
  10230. }
  10231. }
  10232. buf = NULL;
  10233. buflen = conn->phys_ctx->max_request_size;
  10234. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10235. if (i != 0) {
  10236. blk.buf = NULL;
  10237. blk.var = NULL;
  10238. goto done;
  10239. }
  10240. /* CGI must be executed in its own directory. 'dir' must point to the
  10241. * directory containing executable program, 'p' must point to the
  10242. * executable program name relative to 'dir'. */
  10243. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10244. if (truncated) {
  10245. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10246. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10247. goto done;
  10248. }
  10249. if ((p = strrchr(dir, '/')) != NULL) {
  10250. *p++ = '\0';
  10251. } else {
  10252. dir[0] = '.';
  10253. dir[1] = '\0';
  10254. p = (char *)prog;
  10255. }
  10256. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10257. status = strerror(ERRNO);
  10258. mg_cry_internal(
  10259. conn,
  10260. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10261. prog,
  10262. status);
  10263. mg_send_http_error(conn,
  10264. 500,
  10265. "Error: Cannot create CGI pipe: %s",
  10266. status);
  10267. goto done;
  10268. }
  10269. proc = (struct process_control_data *)
  10270. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10271. if (proc == NULL) {
  10272. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10273. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10274. goto done;
  10275. }
  10276. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10277. pid = spawn_process(
  10278. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10279. if (pid == (pid_t)-1) {
  10280. status = strerror(ERRNO);
  10281. mg_cry_internal(
  10282. conn,
  10283. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10284. prog,
  10285. status);
  10286. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10287. mg_free(proc);
  10288. proc = NULL;
  10289. goto done;
  10290. }
  10291. /* Store data in shared process_control_data */
  10292. proc->pid = pid;
  10293. proc->references = 1;
  10294. #if defined(USE_TIMERS)
  10295. if (cgi_timeout > 0.0) {
  10296. proc->references = 2;
  10297. // Start a timer for CGI
  10298. timer_add(conn->phys_ctx,
  10299. cgi_timeout /* in seconds */,
  10300. 0.0,
  10301. 1,
  10302. abort_cgi_process,
  10303. (void *)proc,
  10304. NULL);
  10305. }
  10306. #endif
  10307. /* Parent closes only one side of the pipes.
  10308. * If we don't mark them as closed, close() attempt before
  10309. * return from this function throws an exception on Windows.
  10310. * Windows does not like when closed descriptor is closed again. */
  10311. (void)close(fdin[0]);
  10312. (void)close(fdout[1]);
  10313. (void)close(fderr[1]);
  10314. fdin[0] = fdout[1] = fderr[1] = -1;
  10315. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10316. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10317. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10318. status = strerror(ERRNO);
  10319. mg_cry_internal(conn,
  10320. "Error: CGI program \"%s\": Can not open fd: %s",
  10321. prog,
  10322. status);
  10323. mg_send_http_error(conn,
  10324. 500,
  10325. "Error: CGI can not open fd\nfdopen: %s",
  10326. status);
  10327. goto done;
  10328. }
  10329. setbuf(in, NULL);
  10330. setbuf(out, NULL);
  10331. setbuf(err, NULL);
  10332. fout.access.fp = out;
  10333. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10334. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10335. conn->content_len);
  10336. /* This is a POST/PUT request, or another request with body data. */
  10337. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10338. /* Error sending the body data */
  10339. mg_cry_internal(
  10340. conn,
  10341. "Error: CGI program \"%s\": Forward body data failed",
  10342. prog);
  10343. goto done;
  10344. }
  10345. }
  10346. /* Close so child gets an EOF. */
  10347. fclose(in);
  10348. in = NULL;
  10349. fdin[1] = -1;
  10350. /* Now read CGI reply into a buffer. We need to set correct
  10351. * status code, thus we need to see all HTTP headers first.
  10352. * Do not send anything back to client, until we buffer in all
  10353. * HTTP headers. */
  10354. data_len = 0;
  10355. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10356. if (buf == NULL) {
  10357. mg_send_http_error(conn,
  10358. 500,
  10359. "Error: Not enough memory for CGI buffer (%u bytes)",
  10360. (unsigned int)buflen);
  10361. mg_cry_internal(
  10362. conn,
  10363. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10364. "bytes)",
  10365. prog,
  10366. (unsigned int)buflen);
  10367. goto done;
  10368. }
  10369. DEBUG_TRACE("CGI: %s", "wait for response");
  10370. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10371. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10372. if (headers_len <= 0) {
  10373. /* Could not parse the CGI response. Check if some error message on
  10374. * stderr. */
  10375. i = pull_all(err, conn, buf, (int)buflen);
  10376. if (i > 0) {
  10377. /* CGI program explicitly sent an error */
  10378. /* Write the error message to the internal log */
  10379. mg_cry_internal(conn,
  10380. "Error: CGI program \"%s\" sent error "
  10381. "message: [%.*s]",
  10382. prog,
  10383. i,
  10384. buf);
  10385. /* Don't send the error message back to the client */
  10386. mg_send_http_error(conn,
  10387. 500,
  10388. "Error: CGI program \"%s\" failed.",
  10389. prog);
  10390. } else {
  10391. /* CGI program did not explicitly send an error, but a broken
  10392. * respon header */
  10393. mg_cry_internal(conn,
  10394. "Error: CGI program sent malformed or too big "
  10395. "(>%u bytes) HTTP headers: [%.*s]",
  10396. (unsigned)buflen,
  10397. data_len,
  10398. buf);
  10399. mg_send_http_error(conn,
  10400. 500,
  10401. "Error: CGI program sent malformed or too big "
  10402. "(>%u bytes) HTTP headers: [%.*s]",
  10403. (unsigned)buflen,
  10404. data_len,
  10405. buf);
  10406. }
  10407. /* in both cases, abort processing CGI */
  10408. goto done;
  10409. }
  10410. pbuf = buf;
  10411. buf[headers_len - 1] = '\0';
  10412. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10413. /* Make up and send the status line */
  10414. status_text = "OK";
  10415. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10416. != NULL) {
  10417. conn->status_code = atoi(status);
  10418. status_text = status;
  10419. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10420. status_text++;
  10421. }
  10422. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10423. != NULL) {
  10424. conn->status_code = 307;
  10425. } else {
  10426. conn->status_code = 200;
  10427. }
  10428. if (!should_keep_alive(conn)) {
  10429. conn->must_close = 1;
  10430. }
  10431. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10432. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10433. /* Send headers */
  10434. for (i = 0; i < ri.num_headers; i++) {
  10435. DEBUG_TRACE("CGI header: %s: %s",
  10436. ri.http_headers[i].name,
  10437. ri.http_headers[i].value);
  10438. mg_printf(conn,
  10439. "%s: %s\r\n",
  10440. ri.http_headers[i].name,
  10441. ri.http_headers[i].value);
  10442. }
  10443. mg_write(conn, "\r\n", 2);
  10444. /* Send chunk of data that may have been read after the headers */
  10445. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10446. /* Read the rest of CGI output and send to the client */
  10447. DEBUG_TRACE("CGI: %s", "forward all data");
  10448. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10449. DEBUG_TRACE("CGI: %s", "all data sent");
  10450. done:
  10451. mg_free(blk.var);
  10452. mg_free(blk.buf);
  10453. if (pid != (pid_t)-1) {
  10454. abort_cgi_process((void *)proc);
  10455. }
  10456. if (fdin[0] != -1) {
  10457. close(fdin[0]);
  10458. }
  10459. if (fdout[1] != -1) {
  10460. close(fdout[1]);
  10461. }
  10462. if (fderr[1] != -1) {
  10463. close(fderr[1]);
  10464. }
  10465. if (in != NULL) {
  10466. fclose(in);
  10467. } else if (fdin[1] != -1) {
  10468. close(fdin[1]);
  10469. }
  10470. if (out != NULL) {
  10471. fclose(out);
  10472. } else if (fdout[0] != -1) {
  10473. close(fdout[0]);
  10474. }
  10475. if (err != NULL) {
  10476. fclose(err);
  10477. } else if (fderr[0] != -1) {
  10478. close(fderr[0]);
  10479. }
  10480. mg_free(buf);
  10481. }
  10482. #endif /* !NO_CGI */
  10483. #if !defined(NO_FILES)
  10484. static void
  10485. dav_mkcol(struct mg_connection *conn, const char *path)
  10486. {
  10487. int rc, body_len;
  10488. struct de de;
  10489. if (conn == NULL) {
  10490. return;
  10491. }
  10492. /* TODO (mid): Check the mg_send_http_error situations in this function
  10493. */
  10494. memset(&de.file, 0, sizeof(de.file));
  10495. if (!mg_stat(conn, path, &de.file)) {
  10496. mg_cry_internal(conn,
  10497. "%s: mg_stat(%s) failed: %s",
  10498. __func__,
  10499. path,
  10500. strerror(ERRNO));
  10501. }
  10502. if (de.file.last_modified) {
  10503. /* TODO (mid): This check does not seem to make any sense ! */
  10504. /* TODO (mid): Add a webdav unit test first, before changing
  10505. * anything here. */
  10506. mg_send_http_error(
  10507. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10508. return;
  10509. }
  10510. body_len = conn->data_len - conn->request_len;
  10511. if (body_len > 0) {
  10512. mg_send_http_error(
  10513. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10514. return;
  10515. }
  10516. rc = mg_mkdir(conn, path, 0755);
  10517. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10518. if (rc == 0) {
  10519. /* Create 201 "Created" response */
  10520. mg_response_header_start(conn, 201);
  10521. send_static_cache_header(conn);
  10522. send_additional_header(conn);
  10523. mg_response_header_add(conn, "Content-Length", "0", -1);
  10524. /* Send all headers - there is no body */
  10525. mg_response_header_send(conn);
  10526. } else {
  10527. int http_status = 500;
  10528. switch (errno) {
  10529. case EEXIST:
  10530. http_status = 405;
  10531. break;
  10532. case EACCES:
  10533. http_status = 403;
  10534. break;
  10535. case ENOENT:
  10536. http_status = 409;
  10537. break;
  10538. }
  10539. mg_send_http_error(conn,
  10540. http_status,
  10541. "Error processing %s: %s",
  10542. path,
  10543. strerror(ERRNO));
  10544. }
  10545. }
  10546. /* Forward decrlaration */
  10547. static int get_uri_type(const char *uri);
  10548. static const char *
  10549. get_rel_url_at_current_server(const char *uri,
  10550. const struct mg_connection *conn);
  10551. static void
  10552. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10553. {
  10554. const char *overwrite_hdr;
  10555. const char *destination_hdr;
  10556. const char *root;
  10557. int rc, dest_uri_type;
  10558. int http_status = 400;
  10559. int do_overwrite = 0;
  10560. int destination_ok = 0;
  10561. char dest_path[UTF8_PATH_MAX];
  10562. struct mg_file_stat ignored;
  10563. if (conn == NULL) {
  10564. return;
  10565. }
  10566. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10567. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10568. destination_hdr = mg_get_header(conn, "Destination");
  10569. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10570. do_overwrite = 1;
  10571. }
  10572. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10573. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10574. return;
  10575. }
  10576. if (root != NULL) {
  10577. char *local_dest = NULL;
  10578. dest_uri_type = get_uri_type(destination_hdr);
  10579. if (dest_uri_type == 2) {
  10580. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10581. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10582. const char *h =
  10583. get_rel_url_at_current_server(destination_hdr, conn);
  10584. if (h) {
  10585. size_t len = strlen(h);
  10586. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10587. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10588. }
  10589. }
  10590. if (local_dest != NULL) {
  10591. remove_dot_segments(local_dest);
  10592. if (local_dest[0] == '/') {
  10593. int trunc_check = 0;
  10594. mg_snprintf(conn,
  10595. &trunc_check,
  10596. dest_path,
  10597. sizeof(dest_path),
  10598. "%s/%s",
  10599. root,
  10600. local_dest);
  10601. if (trunc_check == 0) {
  10602. destination_ok = 1;
  10603. }
  10604. }
  10605. mg_free(local_dest);
  10606. }
  10607. }
  10608. if (!destination_ok) {
  10609. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10610. return;
  10611. }
  10612. /* Check now if this file exists */
  10613. if (mg_stat(conn, dest_path, &ignored)) {
  10614. /* File exists */
  10615. if (do_overwrite) {
  10616. /* Overwrite allowed: delete the file first */
  10617. if (0 != remove(dest_path)) {
  10618. /* No overwrite: return error */
  10619. mg_send_http_error(conn,
  10620. 403,
  10621. "Cannot overwrite file: %s",
  10622. dest_path);
  10623. return;
  10624. }
  10625. } else {
  10626. /* No overwrite: return error */
  10627. mg_send_http_error(conn,
  10628. 412,
  10629. "Destination already exists: %s",
  10630. dest_path);
  10631. return;
  10632. }
  10633. }
  10634. /* Copy / Move / Rename operation. */
  10635. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10636. #if defined(_WIN32)
  10637. {
  10638. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10639. wchar_t wSource[UTF16_PATH_MAX];
  10640. wchar_t wDest[UTF16_PATH_MAX];
  10641. BOOL ok;
  10642. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10643. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10644. if (do_copy) {
  10645. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10646. } else {
  10647. ok = MoveFileExW(wSource,
  10648. wDest,
  10649. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10650. }
  10651. if (ok) {
  10652. rc = 0;
  10653. } else {
  10654. DWORD lastErr = GetLastError();
  10655. if (lastErr == ERROR_ALREADY_EXISTS) {
  10656. mg_send_http_error(conn,
  10657. 412,
  10658. "Destination already exists: %s",
  10659. dest_path);
  10660. return;
  10661. }
  10662. rc = -1;
  10663. http_status = 400;
  10664. }
  10665. }
  10666. #else
  10667. {
  10668. /* Linux uses already UTF-8, we don't need to convert file names. */
  10669. if (do_copy) {
  10670. /* TODO: COPY for Linux. */
  10671. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10672. return;
  10673. }
  10674. rc = rename(path, dest_path);
  10675. if (rc) {
  10676. switch (errno) {
  10677. case EEXIST:
  10678. http_status = 412;
  10679. break;
  10680. case EACCES:
  10681. http_status = 403;
  10682. break;
  10683. case ENOENT:
  10684. http_status = 409;
  10685. break;
  10686. }
  10687. }
  10688. }
  10689. #endif
  10690. if (rc == 0) {
  10691. /* Create 204 "No Content" response */
  10692. mg_response_header_start(conn, 204);
  10693. mg_response_header_add(conn, "Content-Length", "0", -1);
  10694. /* Send all headers - there is no body */
  10695. mg_response_header_send(conn);
  10696. } else {
  10697. mg_send_http_error(conn, http_status, "Operation failed");
  10698. }
  10699. }
  10700. static void
  10701. put_file(struct mg_connection *conn, const char *path)
  10702. {
  10703. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10704. const char *range;
  10705. int64_t r1, r2;
  10706. int rc;
  10707. if (conn == NULL) {
  10708. return;
  10709. }
  10710. DEBUG_TRACE("store %s", path);
  10711. if (mg_stat(conn, path, &file.stat)) {
  10712. /* File already exists */
  10713. conn->status_code = 200;
  10714. if (file.stat.is_directory) {
  10715. /* This is an already existing directory,
  10716. * so there is nothing to do for the server. */
  10717. rc = 0;
  10718. } else {
  10719. /* File exists and is not a directory. */
  10720. /* Can it be replaced? */
  10721. /* Check if the server may write this file */
  10722. if (access(path, W_OK) == 0) {
  10723. /* Access granted */
  10724. rc = 1;
  10725. } else {
  10726. mg_send_http_error(
  10727. conn,
  10728. 403,
  10729. "Error: Put not possible\nReplacing %s is not allowed",
  10730. path);
  10731. return;
  10732. }
  10733. }
  10734. } else {
  10735. /* File should be created */
  10736. conn->status_code = 201;
  10737. rc = put_dir(conn, path);
  10738. }
  10739. if (rc == 0) {
  10740. /* put_dir returns 0 if path is a directory */
  10741. /* Create response */
  10742. mg_response_header_start(conn, conn->status_code);
  10743. send_no_cache_header(conn);
  10744. send_additional_header(conn);
  10745. mg_response_header_add(conn, "Content-Length", "0", -1);
  10746. /* Send all headers - there is no body */
  10747. mg_response_header_send(conn);
  10748. /* Request to create a directory has been fulfilled successfully.
  10749. * No need to put a file. */
  10750. return;
  10751. }
  10752. if (rc == -1) {
  10753. /* put_dir returns -1 if the path is too long */
  10754. mg_send_http_error(conn,
  10755. 414,
  10756. "Error: Path too long\nput_dir(%s): %s",
  10757. path,
  10758. strerror(ERRNO));
  10759. return;
  10760. }
  10761. if (rc == -2) {
  10762. /* put_dir returns -2 if the directory can not be created */
  10763. mg_send_http_error(conn,
  10764. 500,
  10765. "Error: Can not create directory\nput_dir(%s): %s",
  10766. path,
  10767. strerror(ERRNO));
  10768. return;
  10769. }
  10770. /* A file should be created or overwritten. */
  10771. /* Currently CivetWeb does not need read+write access. */
  10772. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10773. || file.access.fp == NULL) {
  10774. (void)mg_fclose(&file.access);
  10775. mg_send_http_error(conn,
  10776. 500,
  10777. "Error: Can not create file\nfopen(%s): %s",
  10778. path,
  10779. strerror(ERRNO));
  10780. return;
  10781. }
  10782. fclose_on_exec(&file.access, conn);
  10783. range = mg_get_header(conn, "Content-Range");
  10784. r1 = r2 = 0;
  10785. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10786. conn->status_code = 206; /* Partial content */
  10787. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10788. mg_send_http_error(conn,
  10789. 500,
  10790. "Error: Internal error processing file %s",
  10791. path);
  10792. return;
  10793. }
  10794. }
  10795. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10796. /* forward_body_data failed.
  10797. * The error code has already been sent to the client,
  10798. * and conn->status_code is already set. */
  10799. (void)mg_fclose(&file.access);
  10800. return;
  10801. }
  10802. if (mg_fclose(&file.access) != 0) {
  10803. /* fclose failed. This might have different reasons, but a likely
  10804. * one is "no space on disk", http 507. */
  10805. conn->status_code = 507;
  10806. }
  10807. /* Create response (status_code has been set before) */
  10808. mg_response_header_start(conn, conn->status_code);
  10809. send_no_cache_header(conn);
  10810. send_additional_header(conn);
  10811. mg_response_header_add(conn, "Content-Length", "0", -1);
  10812. /* Send all headers - there is no body */
  10813. mg_response_header_send(conn);
  10814. }
  10815. static void
  10816. delete_file(struct mg_connection *conn, const char *path)
  10817. {
  10818. struct de de;
  10819. memset(&de.file, 0, sizeof(de.file));
  10820. if (!mg_stat(conn, path, &de.file)) {
  10821. /* mg_stat returns 0 if the file does not exist */
  10822. mg_send_http_error(conn,
  10823. 404,
  10824. "Error: Cannot delete file\nFile %s not found",
  10825. path);
  10826. return;
  10827. }
  10828. DEBUG_TRACE("delete %s", path);
  10829. if (de.file.is_directory) {
  10830. if (remove_directory(conn, path)) {
  10831. /* Delete is successful: Return 204 without content. */
  10832. mg_send_http_error(conn, 204, "%s", "");
  10833. } else {
  10834. /* Delete is not successful: Return 500 (Server error). */
  10835. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10836. }
  10837. return;
  10838. }
  10839. /* This is an existing file (not a directory).
  10840. * Check if write permission is granted. */
  10841. if (access(path, W_OK) != 0) {
  10842. /* File is read only */
  10843. mg_send_http_error(
  10844. conn,
  10845. 403,
  10846. "Error: Delete not possible\nDeleting %s is not allowed",
  10847. path);
  10848. return;
  10849. }
  10850. /* Try to delete it. */
  10851. if (mg_remove(conn, path) == 0) {
  10852. /* Delete was successful: Return 204 without content. */
  10853. mg_response_header_start(conn, 204);
  10854. send_no_cache_header(conn);
  10855. send_additional_header(conn);
  10856. mg_response_header_add(conn, "Content-Length", "0", -1);
  10857. mg_response_header_send(conn);
  10858. } else {
  10859. /* Delete not successful (file locked). */
  10860. mg_send_http_error(conn,
  10861. 423,
  10862. "Error: Cannot delete file\nremove(%s): %s",
  10863. path,
  10864. strerror(ERRNO));
  10865. }
  10866. }
  10867. #endif /* !NO_FILES */
  10868. #if !defined(NO_FILESYSTEMS)
  10869. static void
  10870. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10871. static void
  10872. do_ssi_include(struct mg_connection *conn,
  10873. const char *ssi,
  10874. char *tag,
  10875. int include_level)
  10876. {
  10877. char file_name[MG_BUF_LEN], path[512], *p;
  10878. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10879. size_t len;
  10880. int truncated = 0;
  10881. if (conn == NULL) {
  10882. return;
  10883. }
  10884. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10885. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10886. * always < MG_BUF_LEN. */
  10887. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10888. /* File name is relative to the webserver root */
  10889. file_name[511] = 0;
  10890. (void)mg_snprintf(conn,
  10891. &truncated,
  10892. path,
  10893. sizeof(path),
  10894. "%s/%s",
  10895. conn->dom_ctx->config[DOCUMENT_ROOT],
  10896. file_name);
  10897. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10898. /* File name is relative to the webserver working directory
  10899. * or it is absolute system path */
  10900. file_name[511] = 0;
  10901. (void)
  10902. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10903. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10904. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10905. /* File name is relative to the current document */
  10906. file_name[511] = 0;
  10907. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10908. if (!truncated) {
  10909. if ((p = strrchr(path, '/')) != NULL) {
  10910. p[1] = '\0';
  10911. }
  10912. len = strlen(path);
  10913. (void)mg_snprintf(conn,
  10914. &truncated,
  10915. path + len,
  10916. sizeof(path) - len,
  10917. "%s",
  10918. file_name);
  10919. }
  10920. } else {
  10921. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10922. return;
  10923. }
  10924. if (truncated) {
  10925. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10926. return;
  10927. }
  10928. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10929. mg_cry_internal(conn,
  10930. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10931. tag,
  10932. path,
  10933. strerror(ERRNO));
  10934. } else {
  10935. fclose_on_exec(&file.access, conn);
  10936. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10937. > 0) {
  10938. send_ssi_file(conn, path, &file, include_level + 1);
  10939. } else {
  10940. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10941. }
  10942. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10943. }
  10944. }
  10945. #if !defined(NO_POPEN)
  10946. static void
  10947. do_ssi_exec(struct mg_connection *conn, char *tag)
  10948. {
  10949. char cmd[1024] = "";
  10950. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10951. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10952. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10953. } else {
  10954. cmd[1023] = 0;
  10955. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10956. mg_cry_internal(conn,
  10957. "Cannot SSI #exec: [%s]: %s",
  10958. cmd,
  10959. strerror(ERRNO));
  10960. } else {
  10961. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10962. pclose(file.access.fp);
  10963. }
  10964. }
  10965. }
  10966. #endif /* !NO_POPEN */
  10967. static int
  10968. mg_fgetc(struct mg_file *filep)
  10969. {
  10970. if (filep == NULL) {
  10971. return EOF;
  10972. }
  10973. if (filep->access.fp != NULL) {
  10974. return fgetc(filep->access.fp);
  10975. } else {
  10976. return EOF;
  10977. }
  10978. }
  10979. static void
  10980. send_ssi_file(struct mg_connection *conn,
  10981. const char *path,
  10982. struct mg_file *filep,
  10983. int include_level)
  10984. {
  10985. char buf[MG_BUF_LEN];
  10986. int ch, len, in_tag, in_ssi_tag;
  10987. if (include_level > 10) {
  10988. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10989. return;
  10990. }
  10991. in_tag = in_ssi_tag = len = 0;
  10992. /* Read file, byte by byte, and look for SSI include tags */
  10993. while ((ch = mg_fgetc(filep)) != EOF) {
  10994. if (in_tag) {
  10995. /* We are in a tag, either SSI tag or html tag */
  10996. if (ch == '>') {
  10997. /* Tag is closing */
  10998. buf[len++] = '>';
  10999. if (in_ssi_tag) {
  11000. /* Handle SSI tag */
  11001. buf[len] = 0;
  11002. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  11003. do_ssi_include(conn, path, buf + 12, include_level + 1);
  11004. #if !defined(NO_POPEN)
  11005. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  11006. do_ssi_exec(conn, buf + 9);
  11007. #endif /* !NO_POPEN */
  11008. } else {
  11009. mg_cry_internal(conn,
  11010. "%s: unknown SSI "
  11011. "command: \"%s\"",
  11012. path,
  11013. buf);
  11014. }
  11015. len = 0;
  11016. in_ssi_tag = in_tag = 0;
  11017. } else {
  11018. /* Not an SSI tag */
  11019. /* Flush buffer */
  11020. (void)mg_write(conn, buf, (size_t)len);
  11021. len = 0;
  11022. in_tag = 0;
  11023. }
  11024. } else {
  11025. /* Tag is still open */
  11026. buf[len++] = (char)(ch & 0xff);
  11027. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  11028. /* All SSI tags start with <!--# */
  11029. in_ssi_tag = 1;
  11030. }
  11031. if ((len + 2) > (int)sizeof(buf)) {
  11032. /* Tag to long for buffer */
  11033. mg_cry_internal(conn, "%s: tag is too large", path);
  11034. return;
  11035. }
  11036. }
  11037. } else {
  11038. /* We are not in a tag yet. */
  11039. if (ch == '<') {
  11040. /* Tag is opening */
  11041. in_tag = 1;
  11042. if (len > 0) {
  11043. /* Flush current buffer.
  11044. * Buffer is filled with "len" bytes. */
  11045. (void)mg_write(conn, buf, (size_t)len);
  11046. }
  11047. /* Store the < */
  11048. len = 1;
  11049. buf[0] = '<';
  11050. } else {
  11051. /* No Tag */
  11052. /* Add data to buffer */
  11053. buf[len++] = (char)(ch & 0xff);
  11054. /* Flush if buffer is full */
  11055. if (len == (int)sizeof(buf)) {
  11056. mg_write(conn, buf, (size_t)len);
  11057. len = 0;
  11058. }
  11059. }
  11060. }
  11061. }
  11062. /* Send the rest of buffered data */
  11063. if (len > 0) {
  11064. mg_write(conn, buf, (size_t)len);
  11065. }
  11066. }
  11067. static void
  11068. handle_ssi_file_request(struct mg_connection *conn,
  11069. const char *path,
  11070. struct mg_file *filep)
  11071. {
  11072. char date[64];
  11073. time_t curtime = time(NULL);
  11074. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  11075. return;
  11076. }
  11077. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  11078. /* File exists (precondition for calling this function),
  11079. * but can not be opened by the server. */
  11080. mg_send_http_error(conn,
  11081. 500,
  11082. "Error: Cannot read file\nfopen(%s): %s",
  11083. path,
  11084. strerror(ERRNO));
  11085. } else {
  11086. /* Set "must_close" for HTTP/1.x, since we do not know the
  11087. * content length */
  11088. conn->must_close = 1;
  11089. gmt_time_string(date, sizeof(date), &curtime);
  11090. fclose_on_exec(&filep->access, conn);
  11091. /* 200 OK response */
  11092. mg_response_header_start(conn, 200);
  11093. send_no_cache_header(conn);
  11094. send_additional_header(conn);
  11095. send_cors_header(conn);
  11096. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11097. mg_response_header_send(conn);
  11098. /* Header sent, now send body */
  11099. send_ssi_file(conn, path, filep, 0);
  11100. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  11101. }
  11102. }
  11103. #endif /* NO_FILESYSTEMS */
  11104. #if !defined(NO_FILES)
  11105. static void
  11106. send_options(struct mg_connection *conn)
  11107. {
  11108. if (!conn || !all_methods) {
  11109. return;
  11110. }
  11111. /* We do not set a "Cache-Control" header here, but leave the default.
  11112. * Since browsers do not send an OPTIONS request, we can not test the
  11113. * effect anyway. */
  11114. mg_response_header_start(conn, 200);
  11115. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11116. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  11117. /* Use the same as before */
  11118. mg_response_header_add(conn, "Allow", all_methods, -1);
  11119. mg_response_header_add(conn, "DAV", "1", -1);
  11120. } else {
  11121. /* TODO: Check this later for HTTP/2 */
  11122. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  11123. }
  11124. send_additional_header(conn);
  11125. mg_response_header_send(conn);
  11126. }
  11127. /* Writes PROPFIND properties for a collection element */
  11128. static int
  11129. print_props(struct mg_connection *conn,
  11130. const char *uri,
  11131. const char *name,
  11132. struct mg_file_stat *filep)
  11133. {
  11134. size_t i;
  11135. char mtime[64];
  11136. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11137. char *link_concat;
  11138. size_t link_concat_len;
  11139. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  11140. return 0;
  11141. }
  11142. link_concat_len = strlen(uri) + strlen(name) + 1;
  11143. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  11144. if (!link_concat) {
  11145. return 0;
  11146. }
  11147. strcpy(link_concat, uri);
  11148. strcat(link_concat, name);
  11149. /* Get full link used in request */
  11150. mg_construct_local_link(
  11151. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  11152. /*
  11153. OutputDebugStringA("print_props:\n uri: ");
  11154. OutputDebugStringA(uri);
  11155. OutputDebugStringA("\n name: ");
  11156. OutputDebugStringA(name);
  11157. OutputDebugStringA("\n link: ");
  11158. OutputDebugStringA(link_buf);
  11159. OutputDebugStringA("\n");
  11160. */
  11161. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  11162. mg_printf(conn,
  11163. "<d:response>"
  11164. "<d:href>%s</d:href>"
  11165. "<d:propstat>"
  11166. "<d:prop>"
  11167. "<d:resourcetype>%s</d:resourcetype>"
  11168. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  11169. "<d:getlastmodified>%s</d:getlastmodified>"
  11170. "<d:lockdiscovery>",
  11171. link_buf,
  11172. filep->is_directory ? "<d:collection/>" : "",
  11173. filep->size,
  11174. mtime);
  11175. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11176. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11177. if (!strcmp(dav_lock[i].path, link_buf)) {
  11178. mg_printf(conn,
  11179. "<d:activelock>"
  11180. "<d:locktype><d:write/></d:locktype>"
  11181. "<d:lockscope><d:exclusive/></d:lockscope>"
  11182. "<d:depth>0</d:depth>"
  11183. "<d:owner>%s</d:owner>"
  11184. "<d:timeout>Second-%u</d:timeout>"
  11185. "<d:locktoken>"
  11186. "<d:href>%s</d:href>"
  11187. "</d:locktoken>"
  11188. "</d:activelock>\n",
  11189. dav_lock[i].user,
  11190. (unsigned)LOCK_DURATION_S,
  11191. dav_lock[i].token);
  11192. }
  11193. }
  11194. mg_printf(conn,
  11195. "</d:lockdiscovery>"
  11196. "</d:prop>"
  11197. "<d:status>HTTP/1.1 200 OK</d:status>"
  11198. "</d:propstat>"
  11199. "</d:response>\n");
  11200. mg_free(link_concat);
  11201. return 1;
  11202. }
  11203. static int
  11204. print_dav_dir_entry(struct de *de, void *data)
  11205. {
  11206. struct mg_connection *conn = (struct mg_connection *)data;
  11207. if (!de || !conn
  11208. || !print_props(
  11209. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  11210. /* stop scan */
  11211. return 1;
  11212. }
  11213. return 0;
  11214. }
  11215. static void
  11216. handle_propfind(struct mg_connection *conn,
  11217. const char *path,
  11218. struct mg_file_stat *filep)
  11219. {
  11220. const char *depth = mg_get_header(conn, "Depth");
  11221. if (!conn || !path || !filep || !conn->dom_ctx) {
  11222. return;
  11223. }
  11224. /* return 207 "Multi-Status" */
  11225. conn->must_close = 1;
  11226. mg_response_header_start(conn, 207);
  11227. send_static_cache_header(conn);
  11228. send_additional_header(conn);
  11229. mg_response_header_add(conn,
  11230. "Content-Type",
  11231. "application/xml; charset=utf-8",
  11232. -1);
  11233. mg_response_header_send(conn);
  11234. /* Content */
  11235. mg_printf(conn,
  11236. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11237. "<d:multistatus xmlns:d='DAV:'>\n");
  11238. /* Print properties for the requested resource itself */
  11239. print_props(conn, conn->request_info.local_uri, "", filep);
  11240. /* If it is a directory, print directory entries too if Depth is not 0
  11241. */
  11242. if (filep->is_directory
  11243. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11244. "yes")
  11245. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11246. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11247. }
  11248. mg_printf(conn, "%s\n", "</d:multistatus>");
  11249. }
  11250. static void
  11251. dav_lock_file(struct mg_connection *conn, const char *path)
  11252. {
  11253. /* internal function - therefore conn is assumed to be valid */
  11254. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11255. uint64_t new_locktime;
  11256. int lock_index = -1;
  11257. int i;
  11258. uint64_t LOCK_DURATION_NS =
  11259. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11260. struct twebdav_lock *dav_lock = NULL;
  11261. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11262. || !conn->phys_ctx) {
  11263. return;
  11264. }
  11265. dav_lock = conn->phys_ctx->webdav_lock;
  11266. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11267. /* const char *refresh = mg_get_header(conn, "If"); */
  11268. /* Link refresh should have an "If" header:
  11269. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11270. * But it seems Windows Explorer does not send them.
  11271. */
  11272. mg_lock_context(conn->phys_ctx);
  11273. new_locktime = mg_get_current_time_ns();
  11274. /* Find a slot for a lock */
  11275. while (lock_index < 0) {
  11276. /* find existing lock */
  11277. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11278. if (!strcmp(dav_lock[i].path, link_buf)) {
  11279. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11280. /* locked by the same user */
  11281. dav_lock[i].locktime = new_locktime;
  11282. lock_index = i;
  11283. break;
  11284. } else {
  11285. /* already locked by someone else */
  11286. if (new_locktime
  11287. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11288. /* Lock expired */
  11289. dav_lock[i].path[0] = 0;
  11290. } else {
  11291. /* Lock still valid */
  11292. mg_unlock_context(conn->phys_ctx);
  11293. mg_send_http_error(conn, 423, "%s", "Already locked");
  11294. return;
  11295. }
  11296. }
  11297. }
  11298. }
  11299. /* create new lock token */
  11300. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11301. if (dav_lock[i].path[0] == 0) {
  11302. char s[32];
  11303. dav_lock[i].locktime = mg_get_current_time_ns();
  11304. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11305. mg_md5(dav_lock[i].token,
  11306. link_buf,
  11307. "\x01",
  11308. s,
  11309. "\x01",
  11310. conn->request_info.remote_user,
  11311. NULL);
  11312. mg_strlcpy(dav_lock[i].path,
  11313. link_buf,
  11314. sizeof(dav_lock[i].path));
  11315. mg_strlcpy(dav_lock[i].user,
  11316. conn->request_info.remote_user,
  11317. sizeof(dav_lock[i].user));
  11318. lock_index = i;
  11319. break;
  11320. }
  11321. }
  11322. if (lock_index < 0) {
  11323. /* too many locks. Find oldest lock */
  11324. uint64_t oldest_locktime = dav_lock[0].locktime;
  11325. lock_index = 0;
  11326. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11327. if (dav_lock[i].locktime < oldest_locktime) {
  11328. oldest_locktime = dav_lock[i].locktime;
  11329. lock_index = i;
  11330. }
  11331. }
  11332. /* invalidate oldest lock */
  11333. dav_lock[lock_index].path[0] = 0;
  11334. }
  11335. }
  11336. mg_unlock_context(conn->phys_ctx);
  11337. /* return 200 "OK" */
  11338. conn->must_close = 1;
  11339. mg_response_header_start(conn, 200);
  11340. send_static_cache_header(conn);
  11341. send_additional_header(conn);
  11342. mg_response_header_add(conn,
  11343. "Content-Type",
  11344. "application/xml; charset=utf-8",
  11345. -1);
  11346. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11347. mg_response_header_send(conn);
  11348. /* Content */
  11349. mg_printf(conn,
  11350. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11351. "<d:prop xmlns:d=\"DAV:\">\n"
  11352. " <d:lockdiscovery>\n"
  11353. " <d:activelock>\n"
  11354. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11355. " <d:locktype><d:write/></d:locktype>\n"
  11356. " <d:owner>\n"
  11357. " <d:href>%s</d:href>\n"
  11358. " </d:owner>\n"
  11359. " <d:timeout>Second-%u</d:timeout>\n"
  11360. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11361. " <d:lockroot>\n"
  11362. " <d:href>%s</d:href>\n"
  11363. " </d:lockroot>\n"
  11364. " </d:activelock>\n"
  11365. " </d:lockdiscovery>\n"
  11366. " </d:prop>\n",
  11367. dav_lock[lock_index].user,
  11368. (LOCK_DURATION_S),
  11369. dav_lock[lock_index].token,
  11370. dav_lock[lock_index].path);
  11371. }
  11372. static void
  11373. dav_unlock_file(struct mg_connection *conn, const char *path)
  11374. {
  11375. /* internal function - therefore conn is assumed to be valid */
  11376. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11377. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11378. int lock_index;
  11379. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11380. return;
  11381. }
  11382. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11383. mg_lock_context(conn->phys_ctx);
  11384. /* find existing lock */
  11385. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11386. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11387. /* Success: return 204 "No Content" */
  11388. mg_unlock_context(conn->phys_ctx);
  11389. conn->must_close = 1;
  11390. mg_response_header_start(conn, 204);
  11391. mg_response_header_send(conn);
  11392. return;
  11393. }
  11394. }
  11395. mg_unlock_context(conn->phys_ctx);
  11396. /* Error: Cannot unlock a resource that is not locked */
  11397. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11398. }
  11399. static void
  11400. dav_proppatch(struct mg_connection *conn, const char *path)
  11401. {
  11402. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11403. if (!conn || !path || !conn->dom_ctx) {
  11404. return;
  11405. }
  11406. /* return 207 "Multi-Status" */
  11407. conn->must_close = 1;
  11408. mg_response_header_start(conn, 207);
  11409. send_static_cache_header(conn);
  11410. send_additional_header(conn);
  11411. mg_response_header_add(conn,
  11412. "Content-Type",
  11413. "application/xml; charset=utf-8",
  11414. -1);
  11415. mg_response_header_send(conn);
  11416. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11417. /* Content */
  11418. mg_printf(conn,
  11419. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11420. "<d:multistatus xmlns:d='DAV:'>\n"
  11421. "<d:response>\n<d:href>%s</d:href>\n",
  11422. link_buf);
  11423. mg_printf(conn,
  11424. "<d:propstat><d:status>HTTP/1.1 403 "
  11425. "Forbidden</d:status></d:propstat>\n");
  11426. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11427. }
  11428. #endif
  11429. CIVETWEB_API void
  11430. mg_lock_connection(struct mg_connection *conn)
  11431. {
  11432. if (conn) {
  11433. (void)pthread_mutex_lock(&conn->mutex);
  11434. }
  11435. }
  11436. CIVETWEB_API void
  11437. mg_unlock_connection(struct mg_connection *conn)
  11438. {
  11439. if (conn) {
  11440. (void)pthread_mutex_unlock(&conn->mutex);
  11441. }
  11442. }
  11443. CIVETWEB_API void
  11444. mg_lock_context(struct mg_context *ctx)
  11445. {
  11446. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11447. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11448. }
  11449. }
  11450. CIVETWEB_API void
  11451. mg_unlock_context(struct mg_context *ctx)
  11452. {
  11453. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11454. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11455. }
  11456. }
  11457. #if defined(USE_LUA)
  11458. #include "mod_lua.inl"
  11459. #endif /* USE_LUA */
  11460. #if defined(USE_DUKTAPE)
  11461. #include "mod_duktape.inl"
  11462. #endif /* USE_DUKTAPE */
  11463. #if defined(USE_WEBSOCKET)
  11464. #if !defined(NO_SSL_DL)
  11465. #if !defined(OPENSSL_API_3_0)
  11466. #define SHA_API static
  11467. #include "sha1.inl"
  11468. #endif
  11469. #endif
  11470. static int
  11471. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11472. {
  11473. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11474. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11475. size_t dst_len = sizeof(b64_sha);
  11476. #if !defined(OPENSSL_API_3_0)
  11477. SHA_CTX sha_ctx;
  11478. #endif
  11479. int truncated;
  11480. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11481. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11482. if (truncated) {
  11483. conn->must_close = 1;
  11484. return 0;
  11485. }
  11486. DEBUG_TRACE("%s", "Send websocket handshake");
  11487. #if defined(OPENSSL_API_3_0)
  11488. EVP_Digest((unsigned char *)buf,
  11489. (uint32_t)strlen(buf),
  11490. (unsigned char *)sha,
  11491. NULL,
  11492. EVP_get_digestbyname("sha1"),
  11493. NULL);
  11494. #else
  11495. SHA1_Init(&sha_ctx);
  11496. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11497. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11498. #endif
  11499. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11500. mg_printf(conn,
  11501. "HTTP/1.1 101 Switching Protocols\r\n"
  11502. "Upgrade: websocket\r\n"
  11503. "Connection: Upgrade\r\n"
  11504. "Sec-WebSocket-Accept: %s\r\n",
  11505. b64_sha);
  11506. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11507. // Send negotiated compression extension parameters
  11508. websocket_deflate_response(conn);
  11509. #endif
  11510. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11511. mg_printf(conn,
  11512. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11513. conn->request_info.acceptedWebSocketSubprotocol);
  11514. } else {
  11515. mg_printf(conn, "%s", "\r\n");
  11516. }
  11517. return 1;
  11518. }
  11519. #if !defined(MG_MAX_UNANSWERED_PING)
  11520. /* Configuration of the maximum number of websocket PINGs that might
  11521. * stay unanswered before the connection is considered broken.
  11522. * Note: The name of this define may still change (until it is
  11523. * defined as a compile parameter in a documentation).
  11524. */
  11525. #define MG_MAX_UNANSWERED_PING (5)
  11526. #endif
  11527. static void
  11528. read_websocket(struct mg_connection *conn,
  11529. mg_websocket_data_handler ws_data_handler,
  11530. void *callback_data)
  11531. {
  11532. /* Pointer to the beginning of the portion of the incoming websocket
  11533. * message queue.
  11534. * The original websocket upgrade request is never removed, so the queue
  11535. * begins after it. */
  11536. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11537. int n, error, exit_by_callback;
  11538. int ret;
  11539. /* body_len is the length of the entire queue in bytes
  11540. * len is the length of the current message
  11541. * data_len is the length of the current message's data payload
  11542. * header_len is the length of the current message's header */
  11543. size_t i, len, mask_len = 0, header_len, body_len;
  11544. uint64_t data_len = 0;
  11545. /* "The masking key is a 32-bit value chosen at random by the client."
  11546. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11547. */
  11548. unsigned char mask[4];
  11549. /* data points to the place where the message is stored when passed to
  11550. * the websocket_data callback. This is either mem on the stack, or a
  11551. * dynamically allocated buffer if it is too large. */
  11552. unsigned char mem[4096];
  11553. unsigned char mop; /* mask flag and opcode */
  11554. /* Variables used for connection monitoring */
  11555. double timeout = -1.0;
  11556. int enable_ping_pong = 0;
  11557. int ping_count = 0;
  11558. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11559. enable_ping_pong =
  11560. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11561. "yes");
  11562. }
  11563. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11564. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11565. }
  11566. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11567. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11568. }
  11569. if (timeout <= 0.0) {
  11570. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11571. }
  11572. /* Enter data processing loop */
  11573. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11574. conn->request_info.remote_addr,
  11575. conn->request_info.remote_port);
  11576. conn->in_websocket_handling = 1;
  11577. mg_set_thread_name("wsock");
  11578. /* Loop continuously, reading messages from the socket, invoking the
  11579. * callback, and waiting repeatedly until an error occurs. */
  11580. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11581. && (!conn->must_close)) {
  11582. header_len = 0;
  11583. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11584. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11585. len = buf[1] & 127;
  11586. mask_len = (buf[1] & 128) ? 4 : 0;
  11587. if ((len < 126) && (body_len >= mask_len)) {
  11588. /* inline 7-bit length field */
  11589. data_len = len;
  11590. header_len = 2 + mask_len;
  11591. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11592. /* 16-bit length field */
  11593. header_len = 4 + mask_len;
  11594. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11595. } else if (body_len >= (10 + mask_len)) {
  11596. /* 64-bit length field */
  11597. uint32_t l1, l2;
  11598. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11599. memcpy(&l2, &buf[6], 4);
  11600. header_len = 10 + mask_len;
  11601. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11602. if (data_len > (uint64_t)0x7FFF0000ul) {
  11603. /* no can do */
  11604. mg_cry_internal(
  11605. conn,
  11606. "%s",
  11607. "websocket out of memory; closing connection");
  11608. break;
  11609. }
  11610. }
  11611. }
  11612. if ((header_len > 0) && (body_len >= header_len)) {
  11613. /* Allocate space to hold websocket payload */
  11614. unsigned char *data = mem;
  11615. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11616. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11617. conn->phys_ctx);
  11618. if (data == NULL) {
  11619. /* Allocation failed, exit the loop and then close the
  11620. * connection */
  11621. mg_cry_internal(
  11622. conn,
  11623. "%s",
  11624. "websocket out of memory; closing connection");
  11625. break;
  11626. }
  11627. }
  11628. /* Copy the mask before we shift the queue and destroy it */
  11629. if (mask_len > 0) {
  11630. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11631. } else {
  11632. memset(mask, 0, sizeof(mask));
  11633. }
  11634. /* Read frame payload from the first message in the queue into
  11635. * data and advance the queue by moving the memory in place. */
  11636. DEBUG_ASSERT(body_len >= header_len);
  11637. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11638. mop = buf[0]; /* current mask and opcode */
  11639. /* Overflow case */
  11640. len = body_len - header_len;
  11641. memcpy(data, buf + header_len, len);
  11642. error = 0;
  11643. while ((uint64_t)len < data_len) {
  11644. n = pull_inner(NULL,
  11645. conn,
  11646. (char *)(data + len),
  11647. (int)(data_len - len),
  11648. timeout);
  11649. if (n <= -2) {
  11650. error = 1;
  11651. break;
  11652. } else if (n > 0) {
  11653. len += (size_t)n;
  11654. } else {
  11655. /* Timeout: should retry */
  11656. /* TODO: retry condition */
  11657. }
  11658. }
  11659. if (error) {
  11660. mg_cry_internal(
  11661. conn,
  11662. "%s",
  11663. "Websocket pull failed; closing connection");
  11664. if (data != mem) {
  11665. mg_free(data);
  11666. }
  11667. break;
  11668. }
  11669. conn->data_len = conn->request_len;
  11670. } else {
  11671. mop = buf[0]; /* current mask and opcode, overwritten by
  11672. * memmove() */
  11673. /* Length of the message being read at the front of the
  11674. * queue. Cast to 31 bit is OK, since we limited
  11675. * data_len before. */
  11676. len = (size_t)data_len + header_len;
  11677. /* Copy the data payload into the data pointer for the
  11678. * callback. Cast to 31 bit is OK, since we
  11679. * limited data_len */
  11680. memcpy(data, buf + header_len, (size_t)data_len);
  11681. /* Move the queue forward len bytes */
  11682. memmove(buf, buf + len, body_len - len);
  11683. /* Mark the queue as advanced */
  11684. conn->data_len -= (int)len;
  11685. }
  11686. /* Apply mask if necessary */
  11687. if (mask_len > 0) {
  11688. for (i = 0; i < (size_t)data_len; i++) {
  11689. data[i] ^= mask[i & 3];
  11690. }
  11691. }
  11692. exit_by_callback = 0;
  11693. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11694. /* filter PONG messages */
  11695. DEBUG_TRACE("PONG from %s:%u",
  11696. conn->request_info.remote_addr,
  11697. conn->request_info.remote_port);
  11698. /* No unanwered PINGs left */
  11699. ping_count = 0;
  11700. } else if (enable_ping_pong
  11701. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11702. /* reply PING messages */
  11703. DEBUG_TRACE("Reply PING from %s:%u",
  11704. conn->request_info.remote_addr,
  11705. conn->request_info.remote_port);
  11706. ret = mg_websocket_write(conn,
  11707. MG_WEBSOCKET_OPCODE_PONG,
  11708. (char *)data,
  11709. (size_t)data_len);
  11710. if (ret <= 0) {
  11711. /* Error: send failed */
  11712. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11713. break;
  11714. }
  11715. } else {
  11716. /* Exit the loop if callback signals to exit (server side),
  11717. * or "connection close" opcode received (client side). */
  11718. if (ws_data_handler != NULL) {
  11719. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11720. if (mop & 0x40) {
  11721. /* Inflate the data received if bit RSV1 is set. */
  11722. if (!conn->websocket_deflate_initialized) {
  11723. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11724. exit_by_callback = 1;
  11725. }
  11726. if (!exit_by_callback) {
  11727. size_t inflate_buf_size_old = 0;
  11728. size_t inflate_buf_size =
  11729. data_len
  11730. * 4; // Initial guess of the inflated message
  11731. // size. We double the memory when needed.
  11732. Bytef *inflated = NULL;
  11733. Bytef *new_mem = NULL;
  11734. conn->websocket_inflate_state.avail_in =
  11735. (uInt)(data_len + 4);
  11736. conn->websocket_inflate_state.next_in = data;
  11737. // Add trailing 0x00 0x00 0xff 0xff bytes
  11738. data[data_len] = '\x00';
  11739. data[data_len + 1] = '\x00';
  11740. data[data_len + 2] = '\xff';
  11741. data[data_len + 3] = '\xff';
  11742. do {
  11743. if (inflate_buf_size_old == 0) {
  11744. new_mem =
  11745. (Bytef *)mg_calloc(inflate_buf_size,
  11746. sizeof(Bytef));
  11747. } else {
  11748. inflate_buf_size *= 2;
  11749. new_mem =
  11750. (Bytef *)mg_realloc(inflated,
  11751. inflate_buf_size);
  11752. }
  11753. if (new_mem == NULL) {
  11754. mg_cry_internal(
  11755. conn,
  11756. "Out of memory: Cannot allocate "
  11757. "inflate buffer of %lu bytes",
  11758. (unsigned long)inflate_buf_size);
  11759. exit_by_callback = 1;
  11760. break;
  11761. }
  11762. inflated = new_mem;
  11763. conn->websocket_inflate_state.avail_out =
  11764. (uInt)(inflate_buf_size
  11765. - inflate_buf_size_old);
  11766. conn->websocket_inflate_state.next_out =
  11767. inflated + inflate_buf_size_old;
  11768. ret = inflate(&conn->websocket_inflate_state,
  11769. Z_SYNC_FLUSH);
  11770. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11771. || ret == Z_MEM_ERROR) {
  11772. mg_cry_internal(
  11773. conn,
  11774. "ZLIB inflate error: %i %s",
  11775. ret,
  11776. (conn->websocket_inflate_state.msg
  11777. ? conn->websocket_inflate_state.msg
  11778. : "<no error message>"));
  11779. exit_by_callback = 1;
  11780. break;
  11781. }
  11782. inflate_buf_size_old = inflate_buf_size;
  11783. } while (conn->websocket_inflate_state.avail_out
  11784. == 0);
  11785. inflate_buf_size -=
  11786. conn->websocket_inflate_state.avail_out;
  11787. if (!ws_data_handler(conn,
  11788. mop,
  11789. (char *)inflated,
  11790. inflate_buf_size,
  11791. callback_data)) {
  11792. exit_by_callback = 1;
  11793. }
  11794. mg_free(inflated);
  11795. }
  11796. } else
  11797. #endif
  11798. if (!ws_data_handler(conn,
  11799. mop,
  11800. (char *)data,
  11801. (size_t)data_len,
  11802. callback_data)) {
  11803. exit_by_callback = 1;
  11804. }
  11805. }
  11806. }
  11807. /* It a buffer has been allocated, free it again */
  11808. if (data != mem) {
  11809. mg_free(data);
  11810. }
  11811. if (exit_by_callback) {
  11812. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11813. conn->request_info.remote_addr,
  11814. conn->request_info.remote_port);
  11815. break;
  11816. }
  11817. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11818. /* Opcode == 8, connection close */
  11819. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11820. conn->request_info.remote_addr,
  11821. conn->request_info.remote_port);
  11822. break;
  11823. }
  11824. /* Not breaking the loop, process next websocket frame. */
  11825. } else {
  11826. /* Read from the socket into the next available location in the
  11827. * message queue. */
  11828. n = pull_inner(NULL,
  11829. conn,
  11830. conn->buf + conn->data_len,
  11831. conn->buf_size - conn->data_len,
  11832. timeout);
  11833. if (n <= -2) {
  11834. /* Error, no bytes read */
  11835. DEBUG_TRACE("PULL from %s:%u failed",
  11836. conn->request_info.remote_addr,
  11837. conn->request_info.remote_port);
  11838. break;
  11839. }
  11840. if (n > 0) {
  11841. conn->data_len += n;
  11842. /* Reset open PING count */
  11843. ping_count = 0;
  11844. } else {
  11845. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11846. && (!conn->must_close)) {
  11847. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11848. /* Stop sending PING */
  11849. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11850. "- closing connection",
  11851. ping_count,
  11852. conn->request_info.remote_addr,
  11853. conn->request_info.remote_port);
  11854. break;
  11855. }
  11856. if (enable_ping_pong) {
  11857. /* Send Websocket PING message */
  11858. DEBUG_TRACE("PING to %s:%u",
  11859. conn->request_info.remote_addr,
  11860. conn->request_info.remote_port);
  11861. ret = mg_websocket_write(conn,
  11862. MG_WEBSOCKET_OPCODE_PING,
  11863. NULL,
  11864. 0);
  11865. if (ret <= 0) {
  11866. /* Error: send failed */
  11867. DEBUG_TRACE("Send PING failed (%i)", ret);
  11868. break;
  11869. }
  11870. ping_count++;
  11871. }
  11872. }
  11873. /* Timeout: should retry */
  11874. /* TODO: get timeout def */
  11875. }
  11876. }
  11877. }
  11878. /* Leave data processing loop */
  11879. mg_set_thread_name("worker");
  11880. conn->in_websocket_handling = 0;
  11881. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11882. conn->request_info.remote_addr,
  11883. conn->request_info.remote_port);
  11884. }
  11885. static int
  11886. mg_websocket_write_exec(struct mg_connection *conn,
  11887. int opcode,
  11888. const char *data,
  11889. size_t dataLen,
  11890. uint32_t masking_key)
  11891. {
  11892. unsigned char header[14];
  11893. size_t headerLen;
  11894. int retval;
  11895. #if defined(GCC_DIAGNOSTIC)
  11896. /* Disable spurious conversion warning for GCC */
  11897. #pragma GCC diagnostic push
  11898. #pragma GCC diagnostic ignored "-Wconversion"
  11899. #endif
  11900. /* Note that POSIX/Winsock's send() is threadsafe
  11901. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11902. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11903. * push(), although that is only a problem if the packet is large or
  11904. * outgoing buffer is full). */
  11905. /* TODO: Check if this lock should be moved to user land.
  11906. * Currently the server sets this lock for websockets, but
  11907. * not for any other connection. It must be set for every
  11908. * conn read/written by more than one thread, no matter if
  11909. * it is a websocket or regular connection. */
  11910. (void)mg_lock_connection(conn);
  11911. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11912. size_t deflated_size = 0;
  11913. Bytef *deflated = 0;
  11914. // Deflate websocket messages over 100kb
  11915. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11916. if (use_deflate) {
  11917. if (!conn->websocket_deflate_initialized) {
  11918. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11919. return 0;
  11920. }
  11921. // Deflating the message
  11922. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11923. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11924. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11925. deflated_size = (size_t)compressBound((uLong)dataLen);
  11926. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11927. if (deflated == NULL) {
  11928. mg_cry_internal(
  11929. conn,
  11930. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11931. (unsigned long)deflated_size);
  11932. mg_unlock_connection(conn);
  11933. return -1;
  11934. }
  11935. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11936. conn->websocket_deflate_state.next_out = deflated;
  11937. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11938. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11939. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11940. } else
  11941. #endif
  11942. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11943. #if defined(GCC_DIAGNOSTIC)
  11944. #pragma GCC diagnostic pop
  11945. #endif
  11946. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11947. if (dataLen < 126) {
  11948. /* inline 7-bit length field */
  11949. header[1] = (unsigned char)dataLen;
  11950. headerLen = 2;
  11951. } else if (dataLen <= 0xFFFF) {
  11952. /* 16-bit length field */
  11953. uint16_t len = htons((uint16_t)dataLen);
  11954. header[1] = 126;
  11955. memcpy(header + 2, &len, 2);
  11956. headerLen = 4;
  11957. } else {
  11958. /* 64-bit length field */
  11959. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11960. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11961. header[1] = 127;
  11962. memcpy(header + 2, &len1, 4);
  11963. memcpy(header + 6, &len2, 4);
  11964. headerLen = 10;
  11965. }
  11966. if (masking_key) {
  11967. /* add mask */
  11968. header[1] |= 0x80;
  11969. memcpy(header + headerLen, &masking_key, 4);
  11970. headerLen += 4;
  11971. }
  11972. retval = mg_write(conn, header, headerLen);
  11973. if (retval != (int)headerLen) {
  11974. /* Did not send complete header */
  11975. retval = -1;
  11976. } else {
  11977. if (dataLen > 0) {
  11978. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11979. if (use_deflate) {
  11980. retval = mg_write(conn, deflated, dataLen);
  11981. mg_free(deflated);
  11982. } else
  11983. #endif
  11984. retval = mg_write(conn, data, dataLen);
  11985. }
  11986. /* if dataLen == 0, the header length (2) is returned */
  11987. }
  11988. /* TODO: Remove this unlock as well, when lock is removed. */
  11989. mg_unlock_connection(conn);
  11990. return retval;
  11991. }
  11992. CIVETWEB_API int
  11993. mg_websocket_write(struct mg_connection *conn,
  11994. int opcode,
  11995. const char *data,
  11996. size_t dataLen)
  11997. {
  11998. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11999. }
  12000. static void
  12001. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  12002. {
  12003. size_t i = 0;
  12004. i = 0;
  12005. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  12006. /* Convert in 32 bit words, if data is 4 byte aligned */
  12007. while (i < (in_len - 3)) {
  12008. *(uint32_t *)(void *)(out + i) =
  12009. *(uint32_t *)(void *)(in + i) ^ masking_key;
  12010. i += 4;
  12011. }
  12012. }
  12013. if (i != in_len) {
  12014. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  12015. while (i < in_len) {
  12016. *(uint8_t *)(void *)(out + i) =
  12017. *(uint8_t *)(void *)(in + i)
  12018. ^ *(((uint8_t *)&masking_key) + (i % 4));
  12019. i++;
  12020. }
  12021. }
  12022. }
  12023. CIVETWEB_API int
  12024. mg_websocket_client_write(struct mg_connection *conn,
  12025. int opcode,
  12026. const char *data,
  12027. size_t dataLen)
  12028. {
  12029. int retval = -1;
  12030. char *masked_data =
  12031. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  12032. uint32_t masking_key = 0;
  12033. if (masked_data == NULL) {
  12034. /* Return -1 in an error case */
  12035. mg_cry_internal(conn,
  12036. "%s",
  12037. "Cannot allocate buffer for masked websocket response: "
  12038. "Out of memory");
  12039. return -1;
  12040. }
  12041. do {
  12042. /* Get a masking key - but not 0 */
  12043. masking_key = (uint32_t)get_random();
  12044. } while (masking_key == 0);
  12045. mask_data(data, dataLen, masking_key, masked_data);
  12046. retval = mg_websocket_write_exec(
  12047. conn, opcode, masked_data, dataLen, masking_key);
  12048. mg_free(masked_data);
  12049. return retval;
  12050. }
  12051. static void
  12052. handle_websocket_request(struct mg_connection *conn,
  12053. const char *path,
  12054. int is_callback_resource,
  12055. struct mg_websocket_subprotocols *subprotocols,
  12056. mg_websocket_connect_handler ws_connect_handler,
  12057. mg_websocket_ready_handler ws_ready_handler,
  12058. mg_websocket_data_handler ws_data_handler,
  12059. mg_websocket_close_handler ws_close_handler,
  12060. void *cbData)
  12061. {
  12062. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  12063. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  12064. ptrdiff_t lua_websock = 0;
  12065. #if !defined(USE_LUA)
  12066. (void)path;
  12067. #endif
  12068. /* Step 1: Check websocket protocol version. */
  12069. /* Step 1.1: Check Sec-WebSocket-Key. */
  12070. if (!websock_key) {
  12071. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  12072. * requires a Sec-WebSocket-Key header.
  12073. */
  12074. /* It could be the hixie draft version
  12075. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  12076. */
  12077. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  12078. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  12079. char key3[8];
  12080. if ((key1 != NULL) && (key2 != NULL)) {
  12081. /* This version uses 8 byte body data in a GET request */
  12082. conn->content_len = 8;
  12083. if (8 == mg_read(conn, key3, 8)) {
  12084. /* This is the hixie version */
  12085. mg_send_http_error(conn,
  12086. 426,
  12087. "%s",
  12088. "Protocol upgrade to RFC 6455 required");
  12089. return;
  12090. }
  12091. }
  12092. /* This is an unknown version */
  12093. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  12094. return;
  12095. }
  12096. /* Step 1.2: Check websocket protocol version. */
  12097. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  12098. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  12099. /* Reject wrong versions */
  12100. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  12101. return;
  12102. }
  12103. /* Step 1.3: Could check for "Host", but we do not really need this
  12104. * value for anything, so just ignore it. */
  12105. /* Step 2: If a callback is responsible, call it. */
  12106. if (is_callback_resource) {
  12107. /* Step 2.1 check and select subprotocol */
  12108. const char *protocols[64]; // max 64 headers
  12109. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  12110. "Sec-WebSocket-Protocol",
  12111. protocols,
  12112. 64);
  12113. if ((nbSubprotocolHeader > 0) && subprotocols) {
  12114. int headerNo, idx;
  12115. size_t len;
  12116. const char *sep, *curSubProtocol,
  12117. *acceptedWebSocketSubprotocol = NULL;
  12118. /* look for matching subprotocol */
  12119. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  12120. /* There might be multiple headers ... */
  12121. const char *protocol = protocols[headerNo];
  12122. curSubProtocol = protocol;
  12123. /* ... and in every header there might be a , separated list */
  12124. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  12125. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  12126. curSubProtocol++;
  12127. sep = strchr(curSubProtocol, ',');
  12128. if (sep) {
  12129. len = (size_t)(sep - curSubProtocol);
  12130. } else {
  12131. len = strlen(curSubProtocol);
  12132. }
  12133. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  12134. // COMPARE: curSubProtocol ==
  12135. // subprotocols->subprotocols[idx]
  12136. if ((strlen(subprotocols->subprotocols[idx]) == len)
  12137. && (strncmp(curSubProtocol,
  12138. subprotocols->subprotocols[idx],
  12139. len)
  12140. == 0)) {
  12141. acceptedWebSocketSubprotocol =
  12142. subprotocols->subprotocols[idx];
  12143. break;
  12144. }
  12145. }
  12146. curSubProtocol += len;
  12147. }
  12148. }
  12149. conn->request_info.acceptedWebSocketSubprotocol =
  12150. acceptedWebSocketSubprotocol;
  12151. }
  12152. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12153. websocket_deflate_negotiate(conn);
  12154. #endif
  12155. if ((ws_connect_handler != NULL)
  12156. && (ws_connect_handler(conn, cbData) != 0)) {
  12157. /* C callback has returned non-zero, do not proceed with
  12158. * handshake.
  12159. */
  12160. /* Note that C callbacks are no longer called when Lua is
  12161. * responsible, so C can no longer filter callbacks for Lua. */
  12162. return;
  12163. }
  12164. }
  12165. #if defined(USE_LUA)
  12166. /* Step 3: No callback. Check if Lua is responsible. */
  12167. else {
  12168. /* Step 3.1: Check if Lua is responsible. */
  12169. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  12170. lua_websock = match_prefix_strlen(
  12171. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  12172. }
  12173. if (lua_websock > 0) {
  12174. /* Step 3.2: Lua is responsible: call it. */
  12175. conn->lua_websocket_state = lua_websocket_new(path, conn);
  12176. if (!conn->lua_websocket_state) {
  12177. /* Lua rejected the new client */
  12178. return;
  12179. }
  12180. }
  12181. }
  12182. #endif
  12183. /* Step 4: Check if there is a responsible websocket handler. */
  12184. if (!is_callback_resource && !lua_websock) {
  12185. /* There is no callback, and Lua is not responsible either. */
  12186. /* Reply with a 404 Not Found. We are still at a standard
  12187. * HTTP request here, before the websocket handshake, so
  12188. * we can still send standard HTTP error replies. */
  12189. mg_send_http_error(conn, 404, "%s", "Not found");
  12190. return;
  12191. }
  12192. /* Step 5: The websocket connection has been accepted */
  12193. if (!send_websocket_handshake(conn, websock_key)) {
  12194. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  12195. return;
  12196. }
  12197. /* Step 6: Call the ready handler */
  12198. if (is_callback_resource) {
  12199. if (ws_ready_handler != NULL) {
  12200. ws_ready_handler(conn, cbData);
  12201. }
  12202. #if defined(USE_LUA)
  12203. } else if (lua_websock) {
  12204. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  12205. /* the ready handler returned false */
  12206. return;
  12207. }
  12208. #endif
  12209. }
  12210. /* Step 7: Enter the read loop */
  12211. if (is_callback_resource) {
  12212. read_websocket(conn, ws_data_handler, cbData);
  12213. #if defined(USE_LUA)
  12214. } else if (lua_websock) {
  12215. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  12216. #endif
  12217. }
  12218. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12219. /* Step 8: Close the deflate & inflate buffers */
  12220. if (conn->websocket_deflate_initialized) {
  12221. deflateEnd(&conn->websocket_deflate_state);
  12222. inflateEnd(&conn->websocket_inflate_state);
  12223. }
  12224. #endif
  12225. /* Step 9: Call the close handler */
  12226. if (ws_close_handler) {
  12227. ws_close_handler(conn, cbData);
  12228. }
  12229. }
  12230. #endif /* !USE_WEBSOCKET */
  12231. /* Is upgrade request:
  12232. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12233. * 1 = upgrade to websocket
  12234. * 2 = upgrade to HTTP/2
  12235. * -1 = upgrade to unknown protocol
  12236. */
  12237. static int
  12238. should_switch_to_protocol(const struct mg_connection *conn)
  12239. {
  12240. const char *connection_headers[8];
  12241. const char *upgrade_to;
  12242. int connection_header_count, i, should_upgrade;
  12243. /* A websocket protocol has the following HTTP headers:
  12244. *
  12245. * Connection: Upgrade
  12246. * Upgrade: Websocket
  12247. *
  12248. * It seems some clients use multiple headers:
  12249. * see https://github.com/civetweb/civetweb/issues/1083
  12250. */
  12251. connection_header_count = get_req_headers(&conn->request_info,
  12252. "Connection",
  12253. connection_headers,
  12254. 8);
  12255. should_upgrade = 0;
  12256. for (i = 0; i < connection_header_count; i++) {
  12257. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12258. should_upgrade = 1;
  12259. }
  12260. }
  12261. if (!should_upgrade) {
  12262. return PROTOCOL_TYPE_HTTP1;
  12263. }
  12264. upgrade_to = mg_get_header(conn, "Upgrade");
  12265. if (upgrade_to == NULL) {
  12266. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12267. return -1;
  12268. }
  12269. /* Upgrade to ... */
  12270. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12271. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12272. * "Sec-WebSocket-Version" are also required.
  12273. * Don't check them here, since even an unsupported websocket protocol
  12274. * request still IS a websocket request (in contrast to a standard HTTP
  12275. * request). It will fail later in handle_websocket_request.
  12276. */
  12277. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12278. }
  12279. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12280. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12281. }
  12282. /* Upgrade to another protocol */
  12283. return -1;
  12284. }
  12285. static int
  12286. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12287. {
  12288. int n;
  12289. unsigned int a, b, c, d, slash;
  12290. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12291. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12292. // integer value, but function will not report conversion
  12293. // errors; consider using 'strtol' instead
  12294. slash = 32;
  12295. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12296. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12297. // an integer value, but function will not report conversion
  12298. // errors; consider using 'strtol' instead
  12299. n = 0;
  12300. }
  12301. }
  12302. if ((n > 0) && ((size_t)n == vec->len)) {
  12303. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12304. /* IPv4 format */
  12305. if (sa->sa.sa_family == AF_INET) {
  12306. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12307. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12308. | ((uint32_t)c << 8) | (uint32_t)d;
  12309. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12310. return (ip & mask) == net;
  12311. }
  12312. return 0;
  12313. }
  12314. }
  12315. #if defined(USE_IPV6)
  12316. else {
  12317. char ad[50];
  12318. const char *p;
  12319. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12320. slash = 128;
  12321. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12322. n = 0;
  12323. }
  12324. }
  12325. if ((n <= 0) && no_strict) {
  12326. /* no square brackets? */
  12327. p = strchr(vec->ptr, '/');
  12328. if (p && (p < (vec->ptr + vec->len))) {
  12329. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12330. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12331. n += (int)(p - vec->ptr);
  12332. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12333. } else {
  12334. n = 0;
  12335. }
  12336. } else if (vec->len < sizeof(ad)) {
  12337. n = (int)vec->len;
  12338. slash = 128;
  12339. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12340. }
  12341. }
  12342. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12343. p = ad;
  12344. c = 0;
  12345. /* zone indexes are unsupported, at least two colons are needed */
  12346. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12347. if (*(p++) == ':') {
  12348. c++;
  12349. }
  12350. }
  12351. if ((*p == '\0') && (c >= 2)) {
  12352. struct sockaddr_in6 sin6;
  12353. unsigned int i;
  12354. /* for strict validation, an actual IPv6 argument is needed */
  12355. if (sa->sa.sa_family != AF_INET6) {
  12356. return 0;
  12357. }
  12358. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12359. /* IPv6 format */
  12360. for (i = 0; i < 16; i++) {
  12361. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12362. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12363. uint8_t mask = 0;
  12364. if (8 * i + 8 < slash) {
  12365. mask = 0xFFu;
  12366. } else if (8 * i < slash) {
  12367. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12368. }
  12369. if ((ip & mask) != net) {
  12370. return 0;
  12371. }
  12372. }
  12373. return 1;
  12374. }
  12375. }
  12376. }
  12377. }
  12378. #else
  12379. (void)no_strict;
  12380. #endif
  12381. /* malformed */
  12382. return -1;
  12383. }
  12384. static int
  12385. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12386. {
  12387. int throttle = 0;
  12388. struct vec vec, val;
  12389. char mult;
  12390. double v;
  12391. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12392. mult = ',';
  12393. if ((val.ptr == NULL)
  12394. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12395. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12396. // to an integer value, but function will not report
  12397. // conversion errors; consider using 'strtol' instead
  12398. || (v < 0)
  12399. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12400. && (mult != ','))) {
  12401. continue;
  12402. }
  12403. v *= (lowercase(&mult) == 'k')
  12404. ? 1024
  12405. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12406. if (vec.len == 1 && vec.ptr[0] == '*') {
  12407. throttle = (int)v;
  12408. } else {
  12409. int matched = parse_match_net(&vec, rsa, 0);
  12410. if (matched >= 0) {
  12411. /* a valid IP subnet */
  12412. if (matched) {
  12413. throttle = (int)v;
  12414. }
  12415. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12416. throttle = (int)v;
  12417. }
  12418. }
  12419. }
  12420. return throttle;
  12421. }
  12422. /* The mg_upload function is superseded by mg_handle_form_request. */
  12423. #include "handle_form.inl"
  12424. static int
  12425. get_first_ssl_listener_index(const struct mg_context *ctx)
  12426. {
  12427. unsigned int i;
  12428. int idx = -1;
  12429. if (ctx) {
  12430. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12431. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12432. }
  12433. }
  12434. return idx;
  12435. }
  12436. /* Return host (without port) */
  12437. static void
  12438. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12439. {
  12440. const char *host_header =
  12441. get_header(ri->http_headers, ri->num_headers, "Host");
  12442. host->ptr = NULL;
  12443. host->len = 0;
  12444. if (host_header != NULL) {
  12445. const char *pos;
  12446. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12447. * is found. */
  12448. if (*host_header == '[') {
  12449. pos = strchr(host_header, ']');
  12450. if (!pos) {
  12451. /* Malformed hostname starts with '[', but no ']' found */
  12452. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12453. return;
  12454. }
  12455. /* terminate after ']' */
  12456. host->ptr = host_header;
  12457. host->len = (size_t)(pos + 1 - host_header);
  12458. } else {
  12459. /* Otherwise, a ':' separates hostname and port number */
  12460. pos = strchr(host_header, ':');
  12461. if (pos != NULL) {
  12462. host->len = (size_t)(pos - host_header);
  12463. } else {
  12464. host->len = strlen(host_header);
  12465. }
  12466. host->ptr = host_header;
  12467. }
  12468. }
  12469. }
  12470. static int
  12471. switch_domain_context(struct mg_connection *conn)
  12472. {
  12473. struct vec host;
  12474. get_host_from_request_info(&host, &conn->request_info);
  12475. if (host.ptr) {
  12476. if (conn->ssl) {
  12477. /* This is a HTTPS connection, maybe we have a hostname
  12478. * from SNI (set in ssl_servername_callback). */
  12479. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12480. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12481. /* We are not using the default domain */
  12482. if ((strlen(sslhost) != host.len)
  12483. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12484. /* Mismatch between SNI domain and HTTP domain */
  12485. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12486. sslhost,
  12487. (int)host.len,
  12488. host.ptr);
  12489. return 0;
  12490. }
  12491. }
  12492. } else {
  12493. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12494. while (dom) {
  12495. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12496. size_t domNameLen = strlen(domName);
  12497. if ((domNameLen == host.len)
  12498. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12499. /* Found matching domain */
  12500. DEBUG_TRACE("HTTP domain %s found",
  12501. dom->config[AUTHENTICATION_DOMAIN]);
  12502. /* TODO: Check if this is a HTTP or HTTPS domain */
  12503. conn->dom_ctx = dom;
  12504. break;
  12505. }
  12506. mg_lock_context(conn->phys_ctx);
  12507. dom = dom->next;
  12508. mg_unlock_context(conn->phys_ctx);
  12509. }
  12510. }
  12511. DEBUG_TRACE("HTTP%s Host: %.*s",
  12512. conn->ssl ? "S" : "",
  12513. (int)host.len,
  12514. host.ptr);
  12515. } else {
  12516. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12517. return 1;
  12518. }
  12519. return 1;
  12520. }
  12521. static void
  12522. redirect_to_https_port(struct mg_connection *conn, int port)
  12523. {
  12524. char target_url[MG_BUF_LEN];
  12525. int truncated = 0;
  12526. const char *expect_proto =
  12527. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12528. /* Use "308 Permanent Redirect" */
  12529. int redirect_code = 308;
  12530. /* In any case, close the current connection */
  12531. conn->must_close = 1;
  12532. /* Send host, port, uri and (if it exists) ?query_string */
  12533. if (mg_construct_local_link(
  12534. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12535. < 0) {
  12536. truncated = 1;
  12537. } else if (conn->request_info.query_string != NULL) {
  12538. size_t slen1 = strlen(target_url);
  12539. size_t slen2 = strlen(conn->request_info.query_string);
  12540. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12541. target_url[slen1] = '?';
  12542. memcpy(target_url + slen1 + 1,
  12543. conn->request_info.query_string,
  12544. slen2);
  12545. target_url[slen1 + slen2 + 1] = 0;
  12546. } else {
  12547. truncated = 1;
  12548. }
  12549. }
  12550. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12551. * is used as buffer size) */
  12552. if (truncated) {
  12553. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12554. return;
  12555. }
  12556. /* Use redirect helper function */
  12557. mg_send_http_redirect(conn, target_url, redirect_code);
  12558. }
  12559. static void
  12560. mg_set_handler_type(struct mg_context *phys_ctx,
  12561. struct mg_domain_context *dom_ctx,
  12562. const char *uri,
  12563. int handler_type,
  12564. int is_delete_request,
  12565. mg_request_handler handler,
  12566. struct mg_websocket_subprotocols *subprotocols,
  12567. mg_websocket_connect_handler connect_handler,
  12568. mg_websocket_ready_handler ready_handler,
  12569. mg_websocket_data_handler data_handler,
  12570. mg_websocket_close_handler close_handler,
  12571. mg_authorization_handler auth_handler,
  12572. void *cbdata)
  12573. {
  12574. struct mg_handler_info *tmp_rh, **lastref;
  12575. size_t urilen = strlen(uri);
  12576. if (handler_type == WEBSOCKET_HANDLER) {
  12577. DEBUG_ASSERT(handler == NULL);
  12578. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12579. || ready_handler != NULL || data_handler != NULL
  12580. || close_handler != NULL);
  12581. DEBUG_ASSERT(auth_handler == NULL);
  12582. if (handler != NULL) {
  12583. return;
  12584. }
  12585. if (!is_delete_request && (connect_handler == NULL)
  12586. && (ready_handler == NULL) && (data_handler == NULL)
  12587. && (close_handler == NULL)) {
  12588. return;
  12589. }
  12590. if (auth_handler != NULL) {
  12591. return;
  12592. }
  12593. } else if (handler_type == REQUEST_HANDLER) {
  12594. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12595. && data_handler == NULL && close_handler == NULL);
  12596. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12597. DEBUG_ASSERT(auth_handler == NULL);
  12598. if ((connect_handler != NULL) || (ready_handler != NULL)
  12599. || (data_handler != NULL) || (close_handler != NULL)) {
  12600. return;
  12601. }
  12602. if (!is_delete_request && (handler == NULL)) {
  12603. return;
  12604. }
  12605. if (auth_handler != NULL) {
  12606. return;
  12607. }
  12608. } else if (handler_type == AUTH_HANDLER) {
  12609. DEBUG_ASSERT(handler == NULL);
  12610. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12611. && data_handler == NULL && close_handler == NULL);
  12612. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12613. if (handler != NULL) {
  12614. return;
  12615. }
  12616. if ((connect_handler != NULL) || (ready_handler != NULL)
  12617. || (data_handler != NULL) || (close_handler != NULL)) {
  12618. return;
  12619. }
  12620. if (!is_delete_request && (auth_handler == NULL)) {
  12621. return;
  12622. }
  12623. } else {
  12624. /* Unknown handler type. */
  12625. return;
  12626. }
  12627. if (!phys_ctx || !dom_ctx) {
  12628. /* no context available */
  12629. return;
  12630. }
  12631. mg_lock_context(phys_ctx);
  12632. /* first try to find an existing handler */
  12633. do {
  12634. lastref = &(dom_ctx->handlers);
  12635. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12636. tmp_rh = tmp_rh->next) {
  12637. if (tmp_rh->handler_type == handler_type
  12638. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12639. if (!is_delete_request) {
  12640. /* update existing handler */
  12641. if (handler_type == REQUEST_HANDLER) {
  12642. /* Wait for end of use before updating */
  12643. if (tmp_rh->refcount) {
  12644. mg_unlock_context(phys_ctx);
  12645. mg_sleep(1);
  12646. mg_lock_context(phys_ctx);
  12647. /* tmp_rh might have been freed, search again. */
  12648. break;
  12649. }
  12650. /* Ok, the handler is no more use -> Update it */
  12651. tmp_rh->handler = handler;
  12652. } else if (handler_type == WEBSOCKET_HANDLER) {
  12653. tmp_rh->subprotocols = subprotocols;
  12654. tmp_rh->connect_handler = connect_handler;
  12655. tmp_rh->ready_handler = ready_handler;
  12656. tmp_rh->data_handler = data_handler;
  12657. tmp_rh->close_handler = close_handler;
  12658. } else { /* AUTH_HANDLER */
  12659. tmp_rh->auth_handler = auth_handler;
  12660. }
  12661. tmp_rh->cbdata = cbdata;
  12662. } else {
  12663. /* remove existing handler */
  12664. if (handler_type == REQUEST_HANDLER) {
  12665. /* Wait for end of use before removing */
  12666. if (tmp_rh->refcount) {
  12667. tmp_rh->removing = 1;
  12668. mg_unlock_context(phys_ctx);
  12669. mg_sleep(1);
  12670. mg_lock_context(phys_ctx);
  12671. /* tmp_rh might have been freed, search again. */
  12672. break;
  12673. }
  12674. /* Ok, the handler is no more used */
  12675. }
  12676. *lastref = tmp_rh->next;
  12677. mg_free(tmp_rh->uri);
  12678. mg_free(tmp_rh);
  12679. }
  12680. mg_unlock_context(phys_ctx);
  12681. return;
  12682. }
  12683. lastref = &(tmp_rh->next);
  12684. }
  12685. } while (tmp_rh != NULL);
  12686. if (is_delete_request) {
  12687. /* no handler to set, this was a remove request to a non-existing
  12688. * handler */
  12689. mg_unlock_context(phys_ctx);
  12690. return;
  12691. }
  12692. tmp_rh =
  12693. (struct mg_handler_info *)mg_calloc_ctx(1,
  12694. sizeof(struct mg_handler_info),
  12695. phys_ctx);
  12696. if (tmp_rh == NULL) {
  12697. mg_unlock_context(phys_ctx);
  12698. mg_cry_ctx_internal(phys_ctx,
  12699. "%s",
  12700. "Cannot create new request handler struct, OOM");
  12701. return;
  12702. }
  12703. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12704. if (!tmp_rh->uri) {
  12705. mg_unlock_context(phys_ctx);
  12706. mg_free(tmp_rh);
  12707. mg_cry_ctx_internal(phys_ctx,
  12708. "%s",
  12709. "Cannot create new request handler struct, OOM");
  12710. return;
  12711. }
  12712. tmp_rh->uri_len = urilen;
  12713. if (handler_type == REQUEST_HANDLER) {
  12714. tmp_rh->refcount = 0;
  12715. tmp_rh->removing = 0;
  12716. tmp_rh->handler = handler;
  12717. } else if (handler_type == WEBSOCKET_HANDLER) {
  12718. tmp_rh->subprotocols = subprotocols;
  12719. tmp_rh->connect_handler = connect_handler;
  12720. tmp_rh->ready_handler = ready_handler;
  12721. tmp_rh->data_handler = data_handler;
  12722. tmp_rh->close_handler = close_handler;
  12723. } else { /* AUTH_HANDLER */
  12724. tmp_rh->auth_handler = auth_handler;
  12725. }
  12726. tmp_rh->cbdata = cbdata;
  12727. tmp_rh->handler_type = handler_type;
  12728. tmp_rh->next = NULL;
  12729. *lastref = tmp_rh;
  12730. mg_unlock_context(phys_ctx);
  12731. }
  12732. CIVETWEB_API void
  12733. mg_set_request_handler(struct mg_context *ctx,
  12734. const char *uri,
  12735. mg_request_handler handler,
  12736. void *cbdata)
  12737. {
  12738. mg_set_handler_type(ctx,
  12739. &(ctx->dd),
  12740. uri,
  12741. REQUEST_HANDLER,
  12742. handler == NULL,
  12743. handler,
  12744. NULL,
  12745. NULL,
  12746. NULL,
  12747. NULL,
  12748. NULL,
  12749. NULL,
  12750. cbdata);
  12751. }
  12752. CIVETWEB_API void
  12753. mg_set_websocket_handler(struct mg_context *ctx,
  12754. const char *uri,
  12755. mg_websocket_connect_handler connect_handler,
  12756. mg_websocket_ready_handler ready_handler,
  12757. mg_websocket_data_handler data_handler,
  12758. mg_websocket_close_handler close_handler,
  12759. void *cbdata)
  12760. {
  12761. mg_set_websocket_handler_with_subprotocols(ctx,
  12762. uri,
  12763. NULL,
  12764. connect_handler,
  12765. ready_handler,
  12766. data_handler,
  12767. close_handler,
  12768. cbdata);
  12769. }
  12770. CIVETWEB_API void
  12771. mg_set_websocket_handler_with_subprotocols(
  12772. struct mg_context *ctx,
  12773. const char *uri,
  12774. struct mg_websocket_subprotocols *subprotocols,
  12775. mg_websocket_connect_handler connect_handler,
  12776. mg_websocket_ready_handler ready_handler,
  12777. mg_websocket_data_handler data_handler,
  12778. mg_websocket_close_handler close_handler,
  12779. void *cbdata)
  12780. {
  12781. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12782. && (data_handler == NULL)
  12783. && (close_handler == NULL);
  12784. mg_set_handler_type(ctx,
  12785. &(ctx->dd),
  12786. uri,
  12787. WEBSOCKET_HANDLER,
  12788. is_delete_request,
  12789. NULL,
  12790. subprotocols,
  12791. connect_handler,
  12792. ready_handler,
  12793. data_handler,
  12794. close_handler,
  12795. NULL,
  12796. cbdata);
  12797. }
  12798. CIVETWEB_API void
  12799. mg_set_auth_handler(struct mg_context *ctx,
  12800. const char *uri,
  12801. mg_authorization_handler handler,
  12802. void *cbdata)
  12803. {
  12804. mg_set_handler_type(ctx,
  12805. &(ctx->dd),
  12806. uri,
  12807. AUTH_HANDLER,
  12808. handler == NULL,
  12809. NULL,
  12810. NULL,
  12811. NULL,
  12812. NULL,
  12813. NULL,
  12814. NULL,
  12815. handler,
  12816. cbdata);
  12817. }
  12818. static int
  12819. get_request_handler(struct mg_connection *conn,
  12820. int handler_type,
  12821. mg_request_handler *handler,
  12822. struct mg_websocket_subprotocols **subprotocols,
  12823. mg_websocket_connect_handler *connect_handler,
  12824. mg_websocket_ready_handler *ready_handler,
  12825. mg_websocket_data_handler *data_handler,
  12826. mg_websocket_close_handler *close_handler,
  12827. mg_authorization_handler *auth_handler,
  12828. void **cbdata,
  12829. struct mg_handler_info **handler_info)
  12830. {
  12831. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12832. if (request_info) {
  12833. const char *uri = request_info->local_uri;
  12834. size_t urilen = strlen(uri);
  12835. struct mg_handler_info *tmp_rh;
  12836. int step, matched;
  12837. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12838. return 0;
  12839. }
  12840. mg_lock_context(conn->phys_ctx);
  12841. for (step = 0; step < 3; step++) {
  12842. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12843. tmp_rh = tmp_rh->next) {
  12844. if (tmp_rh->handler_type != handler_type) {
  12845. continue;
  12846. }
  12847. if (step == 0) {
  12848. /* first try for an exact match */
  12849. matched = (tmp_rh->uri_len == urilen)
  12850. && (strcmp(tmp_rh->uri, uri) == 0);
  12851. } else if (step == 1) {
  12852. /* next try for a partial match, we will accept
  12853. uri/something */
  12854. matched =
  12855. (tmp_rh->uri_len < urilen)
  12856. && (uri[tmp_rh->uri_len] == '/')
  12857. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12858. } else {
  12859. /* finally try for pattern match */
  12860. matched =
  12861. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12862. }
  12863. if (matched) {
  12864. if (handler_type == WEBSOCKET_HANDLER) {
  12865. *subprotocols = tmp_rh->subprotocols;
  12866. *connect_handler = tmp_rh->connect_handler;
  12867. *ready_handler = tmp_rh->ready_handler;
  12868. *data_handler = tmp_rh->data_handler;
  12869. *close_handler = tmp_rh->close_handler;
  12870. } else if (handler_type == REQUEST_HANDLER) {
  12871. if (tmp_rh->removing) {
  12872. /* Treat as none found */
  12873. step = 2;
  12874. break;
  12875. }
  12876. *handler = tmp_rh->handler;
  12877. /* Acquire handler and give it back */
  12878. tmp_rh->refcount++;
  12879. *handler_info = tmp_rh;
  12880. } else { /* AUTH_HANDLER */
  12881. *auth_handler = tmp_rh->auth_handler;
  12882. }
  12883. *cbdata = tmp_rh->cbdata;
  12884. mg_unlock_context(conn->phys_ctx);
  12885. return 1;
  12886. }
  12887. }
  12888. }
  12889. mg_unlock_context(conn->phys_ctx);
  12890. }
  12891. return 0; /* none found */
  12892. }
  12893. /* Check if the script file is in a path, allowed for script files.
  12894. * This can be used if uploading files is possible not only for the server
  12895. * admin, and the upload mechanism does not check the file extension.
  12896. */
  12897. static int
  12898. is_in_script_path(const struct mg_connection *conn, const char *path)
  12899. {
  12900. /* TODO (Feature): Add config value for allowed script path.
  12901. * Default: All allowed. */
  12902. (void)conn;
  12903. (void)path;
  12904. return 1;
  12905. }
  12906. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12907. static int
  12908. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12909. int bits,
  12910. char *data,
  12911. size_t len,
  12912. void *cbdata)
  12913. {
  12914. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12915. if (pcallbacks->websocket_data) {
  12916. return pcallbacks->websocket_data(conn, bits, data, len);
  12917. }
  12918. /* No handler set - assume "OK" */
  12919. return 1;
  12920. }
  12921. static void
  12922. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12923. void *cbdata)
  12924. {
  12925. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12926. if (pcallbacks->connection_close) {
  12927. pcallbacks->connection_close(conn);
  12928. }
  12929. }
  12930. #endif
  12931. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12932. */
  12933. static void
  12934. release_handler_ref(struct mg_connection *conn,
  12935. struct mg_handler_info *handler_info)
  12936. {
  12937. if (handler_info != NULL) {
  12938. /* Use context lock for ref counter */
  12939. mg_lock_context(conn->phys_ctx);
  12940. handler_info->refcount--;
  12941. mg_unlock_context(conn->phys_ctx);
  12942. }
  12943. }
  12944. /* This is the heart of the Civetweb's logic.
  12945. * This function is called when the request is read, parsed and validated,
  12946. * and Civetweb must decide what action to take: serve a file, or
  12947. * a directory, or call embedded function, etcetera. */
  12948. static void
  12949. handle_request(struct mg_connection *conn)
  12950. {
  12951. struct mg_request_info *ri = &conn->request_info;
  12952. char path[UTF8_PATH_MAX];
  12953. int uri_len, ssl_index;
  12954. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12955. is_put_or_delete_request = 0, is_callback_resource = 0,
  12956. is_template_text_file = 0, is_webdav_request = 0;
  12957. int i;
  12958. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12959. mg_request_handler callback_handler = NULL;
  12960. struct mg_handler_info *handler_info = NULL;
  12961. struct mg_websocket_subprotocols *subprotocols;
  12962. mg_websocket_connect_handler ws_connect_handler = NULL;
  12963. mg_websocket_ready_handler ws_ready_handler = NULL;
  12964. mg_websocket_data_handler ws_data_handler = NULL;
  12965. mg_websocket_close_handler ws_close_handler = NULL;
  12966. void *callback_data = NULL;
  12967. mg_authorization_handler auth_handler = NULL;
  12968. void *auth_callback_data = NULL;
  12969. int handler_type;
  12970. time_t curtime = time(NULL);
  12971. char date[64];
  12972. char *tmp;
  12973. path[0] = 0;
  12974. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12975. conn->request_state = 0;
  12976. /* 1. get the request url */
  12977. /* 1.1. split into url and query string */
  12978. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12979. != NULL) {
  12980. *((char *)conn->request_info.query_string++) = '\0';
  12981. }
  12982. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12983. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12984. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12985. if (ssl_index >= 0) {
  12986. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12987. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12988. redirect_to_https_port(conn, port);
  12989. } else {
  12990. /* A http to https forward port has been specified,
  12991. * but no https port to forward to. */
  12992. mg_send_http_error(conn,
  12993. 503,
  12994. "%s",
  12995. "Error: SSL forward not configured properly");
  12996. mg_cry_internal(conn,
  12997. "%s",
  12998. "Can not redirect to SSL, no SSL port available");
  12999. }
  13000. return;
  13001. }
  13002. uri_len = (int)strlen(ri->local_uri);
  13003. /* 1.3. decode url (if config says so) */
  13004. if (should_decode_url(conn)) {
  13005. url_decode_in_place((char *)ri->local_uri);
  13006. }
  13007. /* URL decode the query-string only if explicitly set in the configuration
  13008. */
  13009. if (conn->request_info.query_string) {
  13010. if (should_decode_query_string(conn)) {
  13011. url_decode_in_place((char *)conn->request_info.query_string);
  13012. }
  13013. }
  13014. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  13015. * possible. The fact that we cleaned the URI is stored in that the
  13016. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  13017. * ri->local_uri_raw still points to memory allocated in
  13018. * worker_thread_run(). ri->local_uri is private to the request so we
  13019. * don't have to use preallocated memory here. */
  13020. tmp = mg_strdup(ri->local_uri_raw);
  13021. if (!tmp) {
  13022. /* Out of memory. We cannot do anything reasonable here. */
  13023. return;
  13024. }
  13025. remove_dot_segments(tmp);
  13026. ri->local_uri = tmp;
  13027. /* step 1. completed, the url is known now */
  13028. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  13029. /* 2. if this ip has limited speed, set it for this connection */
  13030. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  13031. &conn->client.rsa,
  13032. ri->local_uri);
  13033. /* 3. call a "handle everything" callback, if registered */
  13034. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  13035. /* Note that since V1.7 the "begin_request" function is called
  13036. * before an authorization check. If an authorization check is
  13037. * required, use a request_handler instead. */
  13038. i = conn->phys_ctx->callbacks.begin_request(conn);
  13039. if (i > 0) {
  13040. /* callback already processed the request. Store the
  13041. return value as a status code for the access log. */
  13042. conn->status_code = i;
  13043. if (!conn->must_close) {
  13044. discard_unread_request_data(conn);
  13045. }
  13046. DEBUG_TRACE("%s", "begin_request handled request");
  13047. return;
  13048. } else if (i == 0) {
  13049. /* civetweb should process the request */
  13050. } else {
  13051. /* unspecified - may change with the next version */
  13052. DEBUG_TRACE("%s", "done (undocumented behavior)");
  13053. return;
  13054. }
  13055. }
  13056. /* request not yet handled by a handler or redirect, so the request
  13057. * is processed here */
  13058. /* 4. Check for CORS preflight requests and handle them (if configured).
  13059. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  13060. */
  13061. if (!strcmp(ri->request_method, "OPTIONS")) {
  13062. /* Send a response to CORS preflights only if
  13063. * access_control_allow_methods is not NULL and not an empty string.
  13064. * In this case, scripts can still handle CORS. */
  13065. const char *cors_meth_cfg =
  13066. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  13067. const char *cors_orig_cfg =
  13068. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  13069. const char *cors_origin =
  13070. get_header(ri->http_headers, ri->num_headers, "Origin");
  13071. const char *cors_acrm = get_header(ri->http_headers,
  13072. ri->num_headers,
  13073. "Access-Control-Request-Method");
  13074. int cors_replace_asterisk_with_origin = mg_strcasecmp(conn->dom_ctx->config[REPLACE_ASTERISK_WITH_ORIGIN], "yes");
  13075. /* Todo: check if cors_origin is in cors_orig_cfg.
  13076. * Or, let the client check this. */
  13077. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  13078. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  13079. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  13080. /* This is a valid CORS preflight, and the server is configured
  13081. * to handle it automatically. */
  13082. const char *cors_acrh =
  13083. get_header(ri->http_headers,
  13084. ri->num_headers,
  13085. "Access-Control-Request-Headers");
  13086. const char *cors_cred_cfg =
  13087. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  13088. const char *cors_exphdr_cfg =
  13089. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  13090. gmt_time_string(date, sizeof(date), &curtime);
  13091. mg_printf(conn,
  13092. "HTTP/1.1 200 OK\r\n"
  13093. "Date: %s\r\n"
  13094. "Access-Control-Allow-Origin: %s\r\n"
  13095. "Access-Control-Allow-Methods: %s\r\n"
  13096. "Content-Length: 0\r\n"
  13097. "Connection: %s\r\n",
  13098. date,
  13099. (cors_replace_asterisk_with_origin == 0 && cors_orig_cfg[0] == '*') ? cors_origin : cors_orig_cfg,
  13100. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  13101. suggest_connection_header(conn));
  13102. if (cors_cred_cfg && *cors_cred_cfg) {
  13103. mg_printf(conn,
  13104. "Access-Control-Allow-Credentials: %s\r\n",
  13105. cors_cred_cfg);
  13106. }
  13107. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  13108. mg_printf(conn,
  13109. "Access-Control-Expose-Headers: %s\r\n",
  13110. cors_exphdr_cfg);
  13111. }
  13112. if (cors_acrh || (cors_cred_cfg && *cors_cred_cfg)) {
  13113. /* CORS request is asking for additional headers */
  13114. const char *cors_hdr_cfg =
  13115. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  13116. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  13117. /* Allow only if access_control_allow_headers is
  13118. * not NULL and not an empty string. If this
  13119. * configuration is set to *, allow everything.
  13120. * Otherwise this configuration must be a list
  13121. * of allowed HTTP header names. */
  13122. mg_printf(conn,
  13123. "Access-Control-Allow-Headers: %s\r\n",
  13124. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  13125. : cors_hdr_cfg));
  13126. }
  13127. }
  13128. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  13129. mg_printf(conn, "\r\n");
  13130. DEBUG_TRACE("%s", "OPTIONS done");
  13131. return;
  13132. }
  13133. }
  13134. /* 5. interpret the url to find out how the request must be handled
  13135. */
  13136. /* 5.1. first test, if the request targets the regular http(s)://
  13137. * protocol namespace or the websocket ws(s):// protocol namespace.
  13138. */
  13139. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  13140. #if defined(USE_WEBSOCKET)
  13141. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  13142. #else
  13143. handler_type = REQUEST_HANDLER;
  13144. #endif /* defined(USE_WEBSOCKET) */
  13145. if (is_websocket_request) {
  13146. HTTP1_only;
  13147. }
  13148. /* 5.2. check if the request will be handled by a callback */
  13149. if (get_request_handler(conn,
  13150. handler_type,
  13151. &callback_handler,
  13152. &subprotocols,
  13153. &ws_connect_handler,
  13154. &ws_ready_handler,
  13155. &ws_data_handler,
  13156. &ws_close_handler,
  13157. NULL,
  13158. &callback_data,
  13159. &handler_info)) {
  13160. /* 5.2.1. A callback will handle this request. All requests
  13161. * handled by a callback have to be considered as requests
  13162. * to a script resource. */
  13163. is_callback_resource = 1;
  13164. is_script_resource = 1;
  13165. is_put_or_delete_request = is_put_or_delete_method(conn);
  13166. /* Never handle a C callback according to File WebDav rules,
  13167. * even if it is a webdav method */
  13168. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  13169. } else {
  13170. no_callback_resource:
  13171. /* 5.2.2. No callback is responsible for this request. The URI
  13172. * addresses a file based resource (static content or Lua/cgi
  13173. * scripts in the file system). */
  13174. is_callback_resource = 0;
  13175. interpret_uri(conn,
  13176. path,
  13177. sizeof(path),
  13178. &file.stat,
  13179. &is_found,
  13180. &is_script_resource,
  13181. &is_websocket_request,
  13182. &is_put_or_delete_request,
  13183. &is_webdav_request,
  13184. &is_template_text_file);
  13185. }
  13186. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  13187. if (is_webdav_request) {
  13188. /* TODO: Do we need a config option? */
  13189. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  13190. if (webdav_enable[0] != 'y') {
  13191. mg_send_http_error(conn,
  13192. 405,
  13193. "%s method not allowed",
  13194. conn->request_info.request_method);
  13195. DEBUG_TRACE("%s", "webdav rejected");
  13196. return;
  13197. }
  13198. }
  13199. /* 6. authorization check */
  13200. /* 6.1. a custom authorization handler is installed */
  13201. if (get_request_handler(conn,
  13202. AUTH_HANDLER,
  13203. NULL,
  13204. NULL,
  13205. NULL,
  13206. NULL,
  13207. NULL,
  13208. NULL,
  13209. &auth_handler,
  13210. &auth_callback_data,
  13211. NULL)) {
  13212. if (!auth_handler(conn, auth_callback_data)) {
  13213. /* Callback handler will not be used anymore. Release it */
  13214. release_handler_ref(conn, handler_info);
  13215. DEBUG_TRACE("%s", "auth handler rejected request");
  13216. return;
  13217. }
  13218. } else if (is_put_or_delete_request && !is_script_resource
  13219. && !is_callback_resource) {
  13220. HTTP1_only;
  13221. /* 6.2. this request is a PUT/DELETE to a real file */
  13222. /* 6.2.1. thus, the server must have real files */
  13223. #if defined(NO_FILES)
  13224. if (1) {
  13225. #else
  13226. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  13227. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  13228. #endif
  13229. /* This code path will not be called for request handlers */
  13230. DEBUG_ASSERT(handler_info == NULL);
  13231. /* This server does not have any real files, thus the
  13232. * PUT/DELETE methods are not valid. */
  13233. mg_send_http_error(conn,
  13234. 405,
  13235. "%s method not allowed",
  13236. conn->request_info.request_method);
  13237. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  13238. return;
  13239. }
  13240. #if !defined(NO_FILES)
  13241. /* 6.2.2. Check if put authorization for static files is
  13242. * available.
  13243. */
  13244. if (!is_authorized_for_put(conn)) {
  13245. send_authorization_request(conn, NULL);
  13246. DEBUG_TRACE("%s", "file write needs authorization");
  13247. return;
  13248. }
  13249. #endif
  13250. } else {
  13251. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13252. * or it is a PUT or DELETE request to a resource that does not
  13253. * correspond to a file. Check authorization. */
  13254. if (!check_authorization(conn, path)) {
  13255. send_authorization_request(conn, NULL);
  13256. /* Callback handler will not be used anymore. Release it */
  13257. release_handler_ref(conn, handler_info);
  13258. DEBUG_TRACE("%s", "access authorization required");
  13259. return;
  13260. }
  13261. }
  13262. /* request is authorized or does not need authorization */
  13263. /* 7. check if there are request handlers for this uri */
  13264. if (is_callback_resource) {
  13265. HTTP1_only;
  13266. if (!is_websocket_request) {
  13267. i = callback_handler(conn, callback_data);
  13268. /* Callback handler will not be used anymore. Release it */
  13269. release_handler_ref(conn, handler_info);
  13270. if (i > 0) {
  13271. /* Do nothing, callback has served the request. Store
  13272. * then return value as status code for the log and discard
  13273. * all data from the client not used by the callback. */
  13274. conn->status_code = i;
  13275. if (!conn->must_close) {
  13276. discard_unread_request_data(conn);
  13277. }
  13278. } else {
  13279. /* The handler did NOT handle the request. */
  13280. /* Some proper reactions would be:
  13281. * a) close the connections without sending anything
  13282. * b) send a 404 not found
  13283. * c) try if there is a file matching the URI
  13284. * It would be possible to do a, b or c in the callback
  13285. * implementation, and return 1 - we cannot do anything
  13286. * here, that is not possible in the callback.
  13287. *
  13288. * TODO: What would be the best reaction here?
  13289. * (Note: The reaction may change, if there is a better
  13290. * idea.)
  13291. */
  13292. /* For the moment, use option c: We look for a proper file,
  13293. * but since a file request is not always a script resource,
  13294. * the authorization check might be different. */
  13295. callback_handler = NULL;
  13296. /* Here we are at a dead end:
  13297. * According to URI matching, a callback should be
  13298. * responsible for handling the request,
  13299. * we called it, but the callback declared itself
  13300. * not responsible.
  13301. * We use a goto here, to get out of this dead end,
  13302. * and continue with the default handling.
  13303. * A goto here is simpler and better to understand
  13304. * than some curious loop. */
  13305. goto no_callback_resource;
  13306. }
  13307. } else {
  13308. #if defined(USE_WEBSOCKET)
  13309. handle_websocket_request(conn,
  13310. path,
  13311. is_callback_resource,
  13312. subprotocols,
  13313. ws_connect_handler,
  13314. ws_ready_handler,
  13315. ws_data_handler,
  13316. ws_close_handler,
  13317. callback_data);
  13318. #endif
  13319. }
  13320. DEBUG_TRACE("%s", "websocket handling done");
  13321. return;
  13322. }
  13323. /* 8. handle websocket requests */
  13324. #if defined(USE_WEBSOCKET)
  13325. if (is_websocket_request) {
  13326. HTTP1_only;
  13327. if (is_script_resource) {
  13328. if (is_in_script_path(conn, path)) {
  13329. /* Websocket Lua script */
  13330. handle_websocket_request(conn,
  13331. path,
  13332. 0 /* Lua Script */,
  13333. NULL,
  13334. NULL,
  13335. NULL,
  13336. NULL,
  13337. NULL,
  13338. conn->phys_ctx->user_data);
  13339. } else {
  13340. /* Script was in an illegal path */
  13341. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13342. }
  13343. } else {
  13344. mg_send_http_error(conn, 404, "%s", "Not found");
  13345. }
  13346. DEBUG_TRACE("%s", "websocket script done");
  13347. return;
  13348. } else
  13349. #endif
  13350. #if defined(NO_FILES)
  13351. /* 9a. In case the server uses only callbacks, this uri is
  13352. * unknown.
  13353. * Then, all request handling ends here. */
  13354. mg_send_http_error(conn, 404, "%s", "Not Found");
  13355. #else
  13356. /* 9b. This request is either for a static file or resource handled
  13357. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13358. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13359. mg_send_http_error(conn, 404, "%s", "Not Found");
  13360. DEBUG_TRACE("%s", "no document root available");
  13361. return;
  13362. }
  13363. /* 10. Request is handled by a script */
  13364. if (is_script_resource) {
  13365. HTTP1_only;
  13366. handle_file_based_request(conn, path, &file);
  13367. DEBUG_TRACE("%s", "script handling done");
  13368. return;
  13369. }
  13370. /* Request was not handled by a callback or script. It will be
  13371. * handled by a server internal method. */
  13372. /* 11. Handle put/delete/mkcol requests */
  13373. if (is_put_or_delete_request) {
  13374. HTTP1_only;
  13375. /* 11.1. PUT method */
  13376. if (!strcmp(ri->request_method, "PUT")) {
  13377. put_file(conn, path);
  13378. DEBUG_TRACE("handling %s request to %s done",
  13379. ri->request_method,
  13380. path);
  13381. return;
  13382. }
  13383. /* 11.2. DELETE method */
  13384. if (!strcmp(ri->request_method, "DELETE")) {
  13385. delete_file(conn, path);
  13386. DEBUG_TRACE("handling %s request to %s done",
  13387. ri->request_method,
  13388. path);
  13389. return;
  13390. }
  13391. /* 11.3. MKCOL method */
  13392. if (!strcmp(ri->request_method, "MKCOL")) {
  13393. dav_mkcol(conn, path);
  13394. DEBUG_TRACE("handling %s request to %s done",
  13395. ri->request_method,
  13396. path);
  13397. return;
  13398. }
  13399. /* 11.4. MOVE method */
  13400. if (!strcmp(ri->request_method, "MOVE")) {
  13401. dav_move_file(conn, path, 0);
  13402. DEBUG_TRACE("handling %s request to %s done",
  13403. ri->request_method,
  13404. path);
  13405. return;
  13406. }
  13407. if (!strcmp(ri->request_method, "COPY")) {
  13408. dav_move_file(conn, path, 1);
  13409. DEBUG_TRACE("handling %s request to %s done",
  13410. ri->request_method,
  13411. path);
  13412. return;
  13413. }
  13414. /* 11.5. LOCK method */
  13415. if (!strcmp(ri->request_method, "LOCK")) {
  13416. dav_lock_file(conn, path);
  13417. DEBUG_TRACE("handling %s request to %s done",
  13418. ri->request_method,
  13419. path);
  13420. return;
  13421. }
  13422. /* 11.6. UNLOCK method */
  13423. if (!strcmp(ri->request_method, "UNLOCK")) {
  13424. dav_unlock_file(conn, path);
  13425. DEBUG_TRACE("handling %s request to %s done",
  13426. ri->request_method,
  13427. path);
  13428. return;
  13429. }
  13430. /* 11.7. PROPPATCH method */
  13431. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13432. dav_proppatch(conn, path);
  13433. DEBUG_TRACE("handling %s request to %s done",
  13434. ri->request_method,
  13435. path);
  13436. return;
  13437. }
  13438. /* 11.8. Other methods, e.g.: PATCH
  13439. * This method is not supported for static resources,
  13440. * only for scripts (Lua, CGI) and callbacks. */
  13441. mg_send_http_error(conn,
  13442. 405,
  13443. "%s method not allowed",
  13444. conn->request_info.request_method);
  13445. DEBUG_TRACE("method %s on %s is not supported",
  13446. ri->request_method,
  13447. path);
  13448. return;
  13449. }
  13450. /* 11. File does not exist, or it was configured that it should be
  13451. * hidden */
  13452. if (!is_found || (must_hide_file(conn, path))) {
  13453. mg_send_http_error(conn, 404, "%s", "Not found");
  13454. DEBUG_TRACE("handling %s request to %s: file not found",
  13455. ri->request_method,
  13456. path);
  13457. return;
  13458. }
  13459. /* 12. Directory uris should end with a slash */
  13460. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13461. && (ri->local_uri[uri_len - 1] != '/')) {
  13462. /* Path + server root */
  13463. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13464. char *new_path;
  13465. if (ri->query_string) {
  13466. buflen += strlen(ri->query_string);
  13467. }
  13468. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13469. if (!new_path) {
  13470. mg_send_http_error(conn, 500, "out or memory");
  13471. } else {
  13472. mg_get_request_link(conn, new_path, buflen - 1);
  13473. strcat(new_path, "/");
  13474. if (ri->query_string) {
  13475. /* Append ? and query string */
  13476. strcat(new_path, "?");
  13477. strcat(new_path, ri->query_string);
  13478. }
  13479. mg_send_http_redirect(conn, new_path, 301);
  13480. mg_free(new_path);
  13481. }
  13482. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13483. ri->request_method,
  13484. path);
  13485. return;
  13486. }
  13487. /* 13. Handle other methods than GET/HEAD */
  13488. /* 13.1. Handle PROPFIND */
  13489. if (!strcmp(ri->request_method, "PROPFIND")) {
  13490. handle_propfind(conn, path, &file.stat);
  13491. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13492. return;
  13493. }
  13494. /* 13.2. Handle OPTIONS for files */
  13495. if (!strcmp(ri->request_method, "OPTIONS")) {
  13496. /* This standard handler is only used for real files.
  13497. * Scripts should support the OPTIONS method themselves, to allow a
  13498. * maximum flexibility.
  13499. * Lua and CGI scripts may fully support CORS this way (including
  13500. * preflights). */
  13501. send_options(conn);
  13502. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13503. return;
  13504. }
  13505. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13506. if ((0 != strcmp(ri->request_method, "GET"))
  13507. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13508. mg_send_http_error(conn,
  13509. 405,
  13510. "%s method not allowed",
  13511. conn->request_info.request_method);
  13512. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13513. return;
  13514. }
  13515. /* 14. directories */
  13516. if (file.stat.is_directory) {
  13517. /* Substitute files have already been handled above. */
  13518. /* Here we can either generate and send a directory listing,
  13519. * or send an "access denied" error. */
  13520. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13521. "yes")) {
  13522. handle_directory_request(conn, path);
  13523. } else {
  13524. mg_send_http_error(conn,
  13525. 403,
  13526. "%s",
  13527. "Error: Directory listing denied");
  13528. }
  13529. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13530. return;
  13531. }
  13532. /* 15. Files with search/replace patterns: LSP and SSI */
  13533. if (is_template_text_file) {
  13534. HTTP1_only;
  13535. handle_file_based_request(conn, path, &file);
  13536. DEBUG_TRACE("handling %s request to %s done (template)",
  13537. ri->request_method,
  13538. path);
  13539. return;
  13540. }
  13541. /* 16. Static file - maybe cached */
  13542. #if !defined(NO_CACHING)
  13543. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13544. /* Send 304 "Not Modified" - this must not send any body data */
  13545. handle_not_modified_static_file_request(conn, &file);
  13546. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13547. ri->request_method,
  13548. path);
  13549. return;
  13550. }
  13551. #endif /* !NO_CACHING */
  13552. /* 17. Static file - not cached */
  13553. handle_static_file_request(conn, path, &file, NULL, NULL);
  13554. DEBUG_TRACE("handling %s request to %s done (static)",
  13555. ri->request_method,
  13556. path);
  13557. #endif /* !defined(NO_FILES) */
  13558. }
  13559. #if !defined(NO_FILESYSTEMS)
  13560. static void
  13561. handle_file_based_request(struct mg_connection *conn,
  13562. const char *path,
  13563. struct mg_file *file)
  13564. {
  13565. #if !defined(NO_CGI)
  13566. int cgi_config_idx, inc, max;
  13567. #endif
  13568. if (!conn || !conn->dom_ctx) {
  13569. return;
  13570. }
  13571. #if defined(USE_LUA)
  13572. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13573. path)
  13574. > 0) {
  13575. if (is_in_script_path(conn, path)) {
  13576. /* Lua server page: an SSI like page containing mostly plain
  13577. * html code plus some tags with server generated contents. */
  13578. handle_lsp_request(conn, path, file, NULL);
  13579. } else {
  13580. /* Script was in an illegal path */
  13581. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13582. }
  13583. return;
  13584. }
  13585. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13586. > 0) {
  13587. if (is_in_script_path(conn, path)) {
  13588. /* Lua in-server module script: a CGI like script used to
  13589. * generate the entire reply. */
  13590. mg_exec_lua_script(conn, path, NULL);
  13591. } else {
  13592. /* Script was in an illegal path */
  13593. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13594. }
  13595. return;
  13596. }
  13597. #endif
  13598. #if defined(USE_DUKTAPE)
  13599. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13600. path)
  13601. > 0) {
  13602. if (is_in_script_path(conn, path)) {
  13603. /* Call duktape to generate the page */
  13604. mg_exec_duktape_script(conn, path);
  13605. } else {
  13606. /* Script was in an illegal path */
  13607. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13608. }
  13609. return;
  13610. }
  13611. #endif
  13612. #if !defined(NO_CGI)
  13613. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13614. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13615. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13616. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13617. if (match_prefix_strlen(
  13618. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13619. path)
  13620. > 0) {
  13621. if (is_in_script_path(conn, path)) {
  13622. /* CGI scripts may support all HTTP methods */
  13623. handle_cgi_request(conn, path, cgi_config_idx);
  13624. } else {
  13625. /* Script was in an illegal path */
  13626. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13627. }
  13628. return;
  13629. }
  13630. }
  13631. }
  13632. #endif /* !NO_CGI */
  13633. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13634. if (is_in_script_path(conn, path)) {
  13635. handle_ssi_file_request(conn, path, file);
  13636. } else {
  13637. /* Script was in an illegal path */
  13638. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13639. }
  13640. return;
  13641. }
  13642. #if !defined(NO_CACHING)
  13643. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13644. /* Send 304 "Not Modified" - this must not send any body data */
  13645. handle_not_modified_static_file_request(conn, file);
  13646. return;
  13647. }
  13648. #endif /* !NO_CACHING */
  13649. handle_static_file_request(conn, path, file, NULL, NULL);
  13650. }
  13651. #endif /* NO_FILESYSTEMS */
  13652. static void
  13653. close_all_listening_sockets(struct mg_context *ctx)
  13654. {
  13655. unsigned int i;
  13656. if (!ctx) {
  13657. return;
  13658. }
  13659. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13660. closesocket(ctx->listening_sockets[i].sock);
  13661. #if defined(USE_X_DOM_SOCKET)
  13662. /* For unix domain sockets, the socket name represents a file that has
  13663. * to be deleted. */
  13664. /* See
  13665. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13666. */
  13667. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13668. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13669. IGNORE_UNUSED_RESULT(
  13670. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13671. }
  13672. #endif
  13673. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13674. }
  13675. mg_free(ctx->listening_sockets);
  13676. ctx->listening_sockets = NULL;
  13677. mg_free(ctx->listening_socket_fds);
  13678. ctx->listening_socket_fds = NULL;
  13679. }
  13680. /* Valid listening port specification is: [ip_address:]port[s]
  13681. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13682. * Examples for IPv6: [::]:80, [::1]:80,
  13683. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13684. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13685. * In order to bind to both, IPv4 and IPv6, you can either add
  13686. * both ports using 8080,[::]:8080, or the short form +8080.
  13687. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13688. * one only accepting IPv4 the other only IPv6. +8080 creates
  13689. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13690. * environment, they might work differently, or might not work
  13691. * at all - it must be tested what options work best in the
  13692. * relevant network environment.
  13693. */
  13694. static int
  13695. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13696. {
  13697. unsigned int a, b, c, d;
  13698. unsigned port;
  13699. unsigned long portUL;
  13700. int len;
  13701. const char *cb;
  13702. char *endptr;
  13703. #if defined(USE_IPV6)
  13704. char buf[100] = {0};
  13705. #endif
  13706. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13707. * Also, all-zeroes in the socket address means binding to all addresses
  13708. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13709. memset(so, 0, sizeof(*so));
  13710. so->lsa.sin.sin_family = AF_INET;
  13711. *ip_version = 0;
  13712. /* Initialize len as invalid. */
  13713. port = 0;
  13714. len = 0;
  13715. /* Test for different ways to format this string */
  13716. if (sscanf(vec->ptr,
  13717. "%u.%u.%u.%u:%u%n",
  13718. &a,
  13719. &b,
  13720. &c,
  13721. &d,
  13722. &port,
  13723. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13724. // to an integer value, but function will not report
  13725. // conversion errors; consider using 'strtol' instead
  13726. == 5) {
  13727. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13728. so->lsa.sin.sin_addr.s_addr =
  13729. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13730. so->lsa.sin.sin_port = htons((uint16_t)port);
  13731. *ip_version = 4;
  13732. #if defined(USE_IPV6)
  13733. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13734. && ((size_t)len <= vec->len)
  13735. && mg_inet_pton(
  13736. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13737. /* IPv6 address, examples: see above */
  13738. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13739. */
  13740. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13741. *ip_version = 6;
  13742. #endif
  13743. } else if ((vec->ptr[0] == '+')
  13744. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13745. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13746. // string to an integer value, but function will not
  13747. // report conversion errors; consider using 'strtol'
  13748. // instead
  13749. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13750. /* Add 1 to len for the + character we skipped before */
  13751. len++;
  13752. #if defined(USE_IPV6)
  13753. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13754. so->lsa.sin6.sin6_family = AF_INET6;
  13755. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13756. *ip_version = 4 + 6;
  13757. #else
  13758. /* Bind to IPv4 only, since IPv6 is not built in. */
  13759. so->lsa.sin.sin_port = htons((uint16_t)port);
  13760. *ip_version = 4;
  13761. #endif
  13762. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13763. && (vec->ptr != endptr)) {
  13764. len = (int)(endptr - vec->ptr);
  13765. port = (uint16_t)portUL;
  13766. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13767. so->lsa.sin.sin_port = htons((uint16_t)port);
  13768. *ip_version = 4;
  13769. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13770. /* String could be a hostname. This check algorithm
  13771. * will only work for RFC 952 compliant hostnames,
  13772. * starting with a letter, containing only letters,
  13773. * digits and hyphen ('-'). Newer specs may allow
  13774. * more, but this is not guaranteed here, since it
  13775. * may interfere with rules for port option lists. */
  13776. /* According to RFC 1035, hostnames are restricted to 255 characters
  13777. * in total (63 between two dots). */
  13778. char hostname[256];
  13779. size_t hostnlen = (size_t)(cb - vec->ptr);
  13780. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13781. /* This would be invalid in any case */
  13782. *ip_version = 0;
  13783. return 0;
  13784. }
  13785. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13786. if (mg_inet_pton(
  13787. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13788. if (sscanf(cb + 1, "%u%n", &port, &len)
  13789. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13790. // string to an integer value, but function will not
  13791. // report conversion errors; consider using 'strtol'
  13792. // instead
  13793. *ip_version = 4;
  13794. so->lsa.sin.sin_port = htons((uint16_t)port);
  13795. len += (int)(hostnlen + 1);
  13796. } else {
  13797. len = 0;
  13798. }
  13799. #if defined(USE_IPV6)
  13800. } else if (mg_inet_pton(AF_INET6,
  13801. hostname,
  13802. &so->lsa.sin6,
  13803. sizeof(so->lsa.sin6),
  13804. 1)) {
  13805. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13806. *ip_version = 6;
  13807. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13808. len += (int)(hostnlen + 1);
  13809. } else {
  13810. len = 0;
  13811. }
  13812. #endif
  13813. } else {
  13814. len = 0;
  13815. }
  13816. #if defined(USE_X_DOM_SOCKET)
  13817. } else if (vec->ptr[0] == 'x') {
  13818. /* unix (linux) domain socket */
  13819. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13820. len = vec->len;
  13821. so->lsa.sun.sun_family = AF_UNIX;
  13822. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13823. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13824. port = 0;
  13825. *ip_version = 99;
  13826. } else {
  13827. /* String too long */
  13828. len = 0;
  13829. }
  13830. #endif
  13831. } else {
  13832. /* Parsing failure. */
  13833. len = 0;
  13834. }
  13835. /* sscanf and the option splitting code ensure the following condition
  13836. * Make sure the port is valid and vector ends with the port, 'o', 's', or
  13837. * 'r' */
  13838. if ((len > 0) && (is_valid_port(port))) {
  13839. int bad_suffix = 0;
  13840. size_t i;
  13841. /* Parse any suffix character(s) after the port number */
  13842. for (i = len; i < vec->len; i++) {
  13843. unsigned char *opt = NULL;
  13844. switch (vec->ptr[i]) {
  13845. case 'o':
  13846. opt = &so->is_optional;
  13847. break;
  13848. case 'r':
  13849. opt = &so->ssl_redir;
  13850. break;
  13851. case 's':
  13852. opt = &so->is_ssl;
  13853. break;
  13854. default: /* empty */
  13855. break;
  13856. }
  13857. if ((opt) && (*opt == 0))
  13858. *opt = 1;
  13859. else {
  13860. bad_suffix = 1;
  13861. break;
  13862. }
  13863. }
  13864. if ((bad_suffix == 0) && ((so->is_ssl == 0) || (so->ssl_redir == 0))) {
  13865. return 1;
  13866. }
  13867. }
  13868. /* Reset ip_version to 0 if there is an error */
  13869. *ip_version = 0;
  13870. return 0;
  13871. }
  13872. /* Is there any SSL port in use? */
  13873. static int
  13874. is_ssl_port_used(const char *ports)
  13875. {
  13876. if (ports) {
  13877. /* There are several different allowed syntax variants:
  13878. * - "80" for a single port using every network interface
  13879. * - "localhost:80" for a single port using only localhost
  13880. * - "80,localhost:8080" for two ports, one bound to localhost
  13881. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13882. * to IPv4 localhost, one to IPv6 localhost
  13883. * - "+80" use port 80 for IPv4 and IPv6
  13884. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13885. * for both: IPv4 and IPv4
  13886. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13887. * additionally port 8080 bound to localhost connections
  13888. *
  13889. * If we just look for 's' anywhere in the string, "localhost:80"
  13890. * will be detected as SSL (false positive).
  13891. * Looking for 's' after a digit may cause false positives in
  13892. * "my24service:8080".
  13893. * Looking from 's' backward if there are only ':' and numbers
  13894. * before will not work for "24service:8080" (non SSL, port 8080)
  13895. * or "24s" (SSL, port 24).
  13896. *
  13897. * Remark: Initially hostnames were not allowed to start with a
  13898. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13899. * Section 2.1).
  13900. *
  13901. * To get this correct, the entire string must be parsed as a whole,
  13902. * reading it as a list element for element and parsing with an
  13903. * algorithm equivalent to parse_port_string.
  13904. *
  13905. * In fact, we use local interface names here, not arbitrary
  13906. * hostnames, so in most cases the only name will be "localhost".
  13907. *
  13908. * So, for now, we use this simple algorithm, that may still return
  13909. * a false positive in bizarre cases.
  13910. */
  13911. int i;
  13912. int portslen = (int)strlen(ports);
  13913. char prevIsNumber = 0;
  13914. for (i = 0; i < portslen; i++) {
  13915. if (prevIsNumber) {
  13916. int suffixCharIdx = (ports[i] == 'o')
  13917. ? (i + 1)
  13918. : i; /* allow "os" and "or" suffixes */
  13919. if (ports[suffixCharIdx] == 's'
  13920. || ports[suffixCharIdx] == 'r') {
  13921. return 1;
  13922. }
  13923. }
  13924. if (ports[i] >= '0' && ports[i] <= '9') {
  13925. prevIsNumber = 1;
  13926. } else {
  13927. prevIsNumber = 0;
  13928. }
  13929. }
  13930. }
  13931. return 0;
  13932. }
  13933. static int
  13934. set_ports_option(struct mg_context *phys_ctx)
  13935. {
  13936. const char *list;
  13937. int on = 1;
  13938. #if defined(USE_IPV6)
  13939. int off = 0;
  13940. #endif
  13941. struct vec vec;
  13942. struct socket so, *ptr;
  13943. struct mg_pollfd *pfd;
  13944. union usa usa;
  13945. socklen_t len;
  13946. int ip_version;
  13947. int portsTotal = 0;
  13948. int portsOk = 0;
  13949. const char *opt_txt;
  13950. long opt_listen_backlog;
  13951. if (!phys_ctx) {
  13952. return 0;
  13953. }
  13954. memset(&so, 0, sizeof(so));
  13955. memset(&usa, 0, sizeof(usa));
  13956. len = sizeof(usa);
  13957. list = phys_ctx->dd.config[LISTENING_PORTS];
  13958. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13959. portsTotal++;
  13960. if (!parse_port_string(&vec, &so, &ip_version)) {
  13961. mg_cry_ctx_internal(
  13962. phys_ctx,
  13963. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13964. (int)vec.len,
  13965. vec.ptr,
  13966. portsTotal,
  13967. "[IP_ADDRESS:]PORT[s|r]");
  13968. continue;
  13969. }
  13970. #if !defined(NO_SSL)
  13971. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13972. mg_cry_ctx_internal(phys_ctx,
  13973. "Cannot add SSL socket (entry %i)",
  13974. portsTotal);
  13975. continue;
  13976. }
  13977. #endif
  13978. /* Create socket. */
  13979. /* For a list of protocol numbers (e.g., TCP==6) see:
  13980. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13981. */
  13982. if ((so.sock =
  13983. socket(so.lsa.sa.sa_family,
  13984. SOCK_STREAM,
  13985. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13986. == INVALID_SOCKET) {
  13987. mg_cry_ctx_internal(phys_ctx,
  13988. "cannot create socket (entry %i)",
  13989. portsTotal);
  13990. if (so.is_optional) {
  13991. portsOk++; /* it's okay if we couldn't create a socket,
  13992. this port is optional anyway */
  13993. }
  13994. continue;
  13995. }
  13996. #if defined(_WIN32)
  13997. /* Windows SO_REUSEADDR lets many procs binds to a
  13998. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13999. * if someone already has the socket -- DTL */
  14000. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  14001. * Windows might need a few seconds before
  14002. * the same port can be used again in the
  14003. * same process, so a short Sleep may be
  14004. * required between mg_stop and mg_start.
  14005. */
  14006. if (setsockopt(so.sock,
  14007. SOL_SOCKET,
  14008. SO_EXCLUSIVEADDRUSE,
  14009. (SOCK_OPT_TYPE)&on,
  14010. sizeof(on))
  14011. != 0) {
  14012. /* Set reuse option, but don't abort on errors. */
  14013. mg_cry_ctx_internal(
  14014. phys_ctx,
  14015. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  14016. portsTotal);
  14017. }
  14018. #else
  14019. if (setsockopt(so.sock,
  14020. SOL_SOCKET,
  14021. SO_REUSEADDR,
  14022. (SOCK_OPT_TYPE)&on,
  14023. sizeof(on))
  14024. != 0) {
  14025. /* Set reuse option, but don't abort on errors. */
  14026. mg_cry_ctx_internal(
  14027. phys_ctx,
  14028. "cannot set socket option SO_REUSEADDR (entry %i)",
  14029. portsTotal);
  14030. }
  14031. #endif
  14032. #if defined(USE_X_DOM_SOCKET)
  14033. if (ip_version == 99) {
  14034. /* Unix domain socket */
  14035. } else
  14036. #endif
  14037. if (ip_version > 4) {
  14038. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  14039. #if defined(USE_IPV6)
  14040. if (ip_version > 6) {
  14041. if (so.lsa.sa.sa_family == AF_INET6
  14042. && setsockopt(so.sock,
  14043. IPPROTO_IPV6,
  14044. IPV6_V6ONLY,
  14045. (void *)&off,
  14046. sizeof(off))
  14047. != 0) {
  14048. /* Set IPv6 only option, but don't abort on errors. */
  14049. mg_cry_ctx_internal(phys_ctx,
  14050. "cannot set socket option "
  14051. "IPV6_V6ONLY=off (entry %i)",
  14052. portsTotal);
  14053. }
  14054. } else {
  14055. if (so.lsa.sa.sa_family == AF_INET6
  14056. && setsockopt(so.sock,
  14057. IPPROTO_IPV6,
  14058. IPV6_V6ONLY,
  14059. (void *)&on,
  14060. sizeof(on))
  14061. != 0) {
  14062. /* Set IPv6 only option, but don't abort on errors. */
  14063. mg_cry_ctx_internal(phys_ctx,
  14064. "cannot set socket option "
  14065. "IPV6_V6ONLY=on (entry %i)",
  14066. portsTotal);
  14067. }
  14068. }
  14069. #else
  14070. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  14071. closesocket(so.sock);
  14072. if (so.is_optional) {
  14073. portsOk++; /* it's okay if we couldn't set the socket option,
  14074. this port is optional anyway */
  14075. }
  14076. so.sock = INVALID_SOCKET;
  14077. continue;
  14078. #endif
  14079. }
  14080. if (so.lsa.sa.sa_family == AF_INET) {
  14081. len = sizeof(so.lsa.sin);
  14082. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14083. mg_cry_ctx_internal(phys_ctx,
  14084. "cannot bind to %.*s: %d (%s)",
  14085. (int)vec.len,
  14086. vec.ptr,
  14087. (int)ERRNO,
  14088. strerror(errno));
  14089. closesocket(so.sock);
  14090. so.sock = INVALID_SOCKET;
  14091. if (so.is_optional) {
  14092. portsOk++; /* it's okay if we couldn't bind, this port is
  14093. optional anyway */
  14094. }
  14095. continue;
  14096. }
  14097. }
  14098. #if defined(USE_IPV6)
  14099. else if (so.lsa.sa.sa_family == AF_INET6) {
  14100. len = sizeof(so.lsa.sin6);
  14101. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14102. mg_cry_ctx_internal(phys_ctx,
  14103. "cannot bind to IPv6 %.*s: %d (%s)",
  14104. (int)vec.len,
  14105. vec.ptr,
  14106. (int)ERRNO,
  14107. strerror(errno));
  14108. closesocket(so.sock);
  14109. so.sock = INVALID_SOCKET;
  14110. if (so.is_optional) {
  14111. portsOk++; /* it's okay if we couldn't bind, this port is
  14112. optional anyway */
  14113. }
  14114. continue;
  14115. }
  14116. }
  14117. #endif
  14118. #if defined(USE_X_DOM_SOCKET)
  14119. else if (so.lsa.sa.sa_family == AF_UNIX) {
  14120. len = sizeof(so.lsa.sun);
  14121. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14122. mg_cry_ctx_internal(phys_ctx,
  14123. "cannot bind to unix socket %s: %d (%s)",
  14124. so.lsa.sun.sun_path,
  14125. (int)ERRNO,
  14126. strerror(errno));
  14127. closesocket(so.sock);
  14128. so.sock = INVALID_SOCKET;
  14129. if (so.is_optional) {
  14130. portsOk++; /* it's okay if we couldn't bind, this port is
  14131. optional anyway */
  14132. }
  14133. continue;
  14134. }
  14135. }
  14136. #endif
  14137. else {
  14138. mg_cry_ctx_internal(
  14139. phys_ctx,
  14140. "cannot bind: address family not supported (entry %i)",
  14141. portsTotal);
  14142. closesocket(so.sock);
  14143. so.sock = INVALID_SOCKET;
  14144. continue;
  14145. }
  14146. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  14147. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  14148. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  14149. mg_cry_ctx_internal(phys_ctx,
  14150. "%s value \"%s\" is invalid",
  14151. config_options[LISTEN_BACKLOG_SIZE].name,
  14152. opt_txt);
  14153. closesocket(so.sock);
  14154. so.sock = INVALID_SOCKET;
  14155. continue;
  14156. }
  14157. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  14158. mg_cry_ctx_internal(phys_ctx,
  14159. "cannot listen to %.*s: %d (%s)",
  14160. (int)vec.len,
  14161. vec.ptr,
  14162. (int)ERRNO,
  14163. strerror(errno));
  14164. closesocket(so.sock);
  14165. so.sock = INVALID_SOCKET;
  14166. continue;
  14167. }
  14168. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  14169. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  14170. int err = (int)ERRNO;
  14171. mg_cry_ctx_internal(phys_ctx,
  14172. "call to getsockname failed %.*s: %d (%s)",
  14173. (int)vec.len,
  14174. vec.ptr,
  14175. err,
  14176. strerror(errno));
  14177. closesocket(so.sock);
  14178. so.sock = INVALID_SOCKET;
  14179. continue;
  14180. }
  14181. /* Update lsa port in case of random free ports */
  14182. #if defined(USE_IPV6)
  14183. if (so.lsa.sa.sa_family == AF_INET6) {
  14184. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  14185. } else
  14186. #endif
  14187. {
  14188. so.lsa.sin.sin_port = usa.sin.sin_port;
  14189. }
  14190. if ((ptr = (struct socket *)
  14191. mg_realloc_ctx(phys_ctx->listening_sockets,
  14192. (phys_ctx->num_listening_sockets + 1)
  14193. * sizeof(phys_ctx->listening_sockets[0]),
  14194. phys_ctx))
  14195. == NULL) {
  14196. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14197. closesocket(so.sock);
  14198. so.sock = INVALID_SOCKET;
  14199. continue;
  14200. }
  14201. /* The +2 below includes the original +1 (for the socket we're about to
  14202. * add), plus another +1 for the thread_shutdown_notification_socket
  14203. * that we'll also want to poll() on so that mg_stop() can return
  14204. * quickly
  14205. */
  14206. if ((pfd = (struct mg_pollfd *)
  14207. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  14208. (phys_ctx->num_listening_sockets + 2)
  14209. * sizeof(phys_ctx->listening_socket_fds[0]),
  14210. phys_ctx))
  14211. == NULL) {
  14212. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14213. closesocket(so.sock);
  14214. so.sock = INVALID_SOCKET;
  14215. mg_free(ptr);
  14216. continue;
  14217. }
  14218. set_close_on_exec(so.sock, NULL, phys_ctx);
  14219. phys_ctx->listening_sockets = ptr;
  14220. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  14221. phys_ctx->listening_socket_fds = pfd;
  14222. phys_ctx->num_listening_sockets++;
  14223. portsOk++;
  14224. }
  14225. if (portsOk != portsTotal) {
  14226. close_all_listening_sockets(phys_ctx);
  14227. portsOk = 0;
  14228. }
  14229. return portsOk;
  14230. }
  14231. static const char *
  14232. header_val(const struct mg_connection *conn, const char *header)
  14233. {
  14234. const char *header_value;
  14235. if ((header_value = mg_get_header(conn, header)) == NULL) {
  14236. return "-";
  14237. } else {
  14238. return header_value;
  14239. }
  14240. }
  14241. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  14242. #include "external_log_access.inl"
  14243. #elif !defined(NO_FILESYSTEMS)
  14244. static void
  14245. log_access(const struct mg_connection *conn)
  14246. {
  14247. const struct mg_request_info *ri;
  14248. struct mg_file fi;
  14249. char date[64], src_addr[IP_ADDR_STR_LEN];
  14250. #if defined(REENTRANT_TIME)
  14251. struct tm _tm;
  14252. struct tm *tm = &_tm;
  14253. #else
  14254. struct tm *tm;
  14255. #endif
  14256. const char *referer;
  14257. const char *user_agent;
  14258. char log_buf[4096];
  14259. if (!conn || !conn->dom_ctx) {
  14260. return;
  14261. }
  14262. /* Set log message to "empty" */
  14263. log_buf[0] = 0;
  14264. #if defined(USE_LUA)
  14265. if (conn->phys_ctx->lua_bg_log_available) {
  14266. int ret;
  14267. struct mg_context *ctx = conn->phys_ctx;
  14268. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14269. pthread_mutex_lock(&ctx->lua_bg_mutex);
  14270. /* call "log()" in Lua */
  14271. lua_getglobal(lstate, "log");
  14272. prepare_lua_request_info_inner(conn, lstate);
  14273. push_lua_response_log_data(conn, lstate);
  14274. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  14275. if (ret == 0) {
  14276. int t = lua_type(lstate, -1);
  14277. if (t == LUA_TBOOLEAN) {
  14278. if (lua_toboolean(lstate, -1) == 0) {
  14279. /* log() returned false: do not log */
  14280. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14281. return;
  14282. }
  14283. /* log returned true: continue logging */
  14284. } else if (t == LUA_TSTRING) {
  14285. size_t len;
  14286. const char *txt = lua_tolstring(lstate, -1, &len);
  14287. if ((len == 0) || (*txt == 0)) {
  14288. /* log() returned empty string: do not log */
  14289. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14290. return;
  14291. }
  14292. /* Copy test from Lua into log_buf */
  14293. if (len >= sizeof(log_buf)) {
  14294. len = sizeof(log_buf) - 1;
  14295. }
  14296. memcpy(log_buf, txt, len);
  14297. log_buf[len] = 0;
  14298. }
  14299. } else {
  14300. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14301. }
  14302. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14303. }
  14304. #endif
  14305. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14306. if (mg_fopen(conn,
  14307. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14308. MG_FOPEN_MODE_APPEND,
  14309. &fi)
  14310. == 0) {
  14311. fi.access.fp = NULL;
  14312. }
  14313. } else {
  14314. fi.access.fp = NULL;
  14315. }
  14316. /* Log is written to a file and/or a callback. If both are not set,
  14317. * executing the rest of the function is pointless. */
  14318. if ((fi.access.fp == NULL)
  14319. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14320. return;
  14321. }
  14322. /* If we did not get a log message from Lua, create it here. */
  14323. if (!log_buf[0]) {
  14324. #if defined(REENTRANT_TIME)
  14325. localtime_r(&conn->conn_birth_time, tm);
  14326. #else
  14327. tm = localtime(&conn->conn_birth_time);
  14328. #endif
  14329. if (tm != NULL) {
  14330. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14331. } else {
  14332. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14333. }
  14334. ri = &conn->request_info;
  14335. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14336. referer = header_val(conn, "Referer");
  14337. user_agent = header_val(conn, "User-Agent");
  14338. mg_snprintf(conn,
  14339. NULL, /* Ignore truncation in access log */
  14340. log_buf,
  14341. sizeof(log_buf),
  14342. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14343. " %s %s",
  14344. src_addr,
  14345. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14346. date,
  14347. ri->request_method ? ri->request_method : "-",
  14348. ri->request_uri ? ri->request_uri : "-",
  14349. ri->query_string ? "?" : "",
  14350. ri->query_string ? ri->query_string : "",
  14351. ri->http_version,
  14352. conn->status_code,
  14353. conn->num_bytes_sent,
  14354. referer,
  14355. user_agent);
  14356. }
  14357. /* Here we have a log message in log_buf. Call the callback */
  14358. if (conn->phys_ctx->callbacks.log_access) {
  14359. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14360. /* do not log if callback returns non-zero */
  14361. if (fi.access.fp) {
  14362. mg_fclose(&fi.access);
  14363. }
  14364. return;
  14365. }
  14366. }
  14367. /* Store in file */
  14368. if (fi.access.fp) {
  14369. int ok = 1;
  14370. flockfile(fi.access.fp);
  14371. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14372. ok = 0;
  14373. }
  14374. if (fflush(fi.access.fp) != 0) {
  14375. ok = 0;
  14376. }
  14377. funlockfile(fi.access.fp);
  14378. if (mg_fclose(&fi.access) != 0) {
  14379. ok = 0;
  14380. }
  14381. if (!ok) {
  14382. mg_cry_internal(conn,
  14383. "Error writing log file %s",
  14384. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14385. }
  14386. }
  14387. }
  14388. #else
  14389. #error "Either enable filesystems or provide a custom log_access implementation"
  14390. #endif /* Externally provided function */
  14391. /* Verify given socket address against the ACL.
  14392. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14393. */
  14394. static int
  14395. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14396. {
  14397. int allowed, flag, matched;
  14398. struct vec vec;
  14399. if (phys_ctx) {
  14400. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14401. /* If any ACL is set, deny by default */
  14402. allowed = (list == NULL) ? '+' : '-';
  14403. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14404. flag = vec.ptr[0];
  14405. matched = -1;
  14406. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14407. vec.ptr++;
  14408. vec.len--;
  14409. matched = parse_match_net(&vec, sa, 1);
  14410. }
  14411. if (matched < 0) {
  14412. mg_cry_ctx_internal(phys_ctx,
  14413. "%s: subnet must be [+|-]IP-addr[/x]",
  14414. __func__);
  14415. return -1;
  14416. }
  14417. if (matched) {
  14418. allowed = flag;
  14419. }
  14420. }
  14421. return allowed == '+';
  14422. }
  14423. return -1;
  14424. }
  14425. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14426. static int
  14427. set_uid_option(struct mg_context *phys_ctx)
  14428. {
  14429. int success = 0;
  14430. if (phys_ctx) {
  14431. /* We are currently running as curr_uid. */
  14432. const uid_t curr_uid = getuid();
  14433. /* If set, we want to run as run_as_user. */
  14434. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14435. const struct passwd *to_pw = NULL;
  14436. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14437. /* run_as_user does not exist on the system. We can't proceed
  14438. * further. */
  14439. mg_cry_ctx_internal(phys_ctx,
  14440. "%s: unknown user [%s]",
  14441. __func__,
  14442. run_as_user);
  14443. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14444. /* There was either no request to change user, or we're already
  14445. * running as run_as_user. Nothing else to do.
  14446. */
  14447. success = 1;
  14448. } else {
  14449. /* Valid change request. */
  14450. if (setgid(to_pw->pw_gid) == -1) {
  14451. mg_cry_ctx_internal(phys_ctx,
  14452. "%s: setgid(%s): %s",
  14453. __func__,
  14454. run_as_user,
  14455. strerror(errno));
  14456. } else if (setgroups(0, NULL) == -1) {
  14457. mg_cry_ctx_internal(phys_ctx,
  14458. "%s: setgroups(): %s",
  14459. __func__,
  14460. strerror(errno));
  14461. } else if (setuid(to_pw->pw_uid) == -1) {
  14462. mg_cry_ctx_internal(phys_ctx,
  14463. "%s: setuid(%s): %s",
  14464. __func__,
  14465. run_as_user,
  14466. strerror(errno));
  14467. } else {
  14468. success = 1;
  14469. }
  14470. }
  14471. }
  14472. return success;
  14473. }
  14474. #endif /* !_WIN32 */
  14475. static void
  14476. tls_dtor(void *key)
  14477. {
  14478. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14479. /* key == pthread_getspecific(sTlsKey); */
  14480. if (tls) {
  14481. if (tls->is_master == 2) {
  14482. tls->is_master = -3; /* Mark memory as dead */
  14483. mg_free(tls);
  14484. }
  14485. }
  14486. pthread_setspecific(sTlsKey, NULL);
  14487. }
  14488. #if defined(USE_MBEDTLS)
  14489. /* Check if SSL is required.
  14490. * If so, set up ctx->ssl_ctx pointer. */
  14491. static int
  14492. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14493. {
  14494. if (!phys_ctx) {
  14495. return 0;
  14496. }
  14497. if (!dom_ctx) {
  14498. dom_ctx = &(phys_ctx->dd);
  14499. }
  14500. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14501. /* No SSL port is set. No need to setup SSL. */
  14502. return 1;
  14503. }
  14504. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14505. if (dom_ctx->ssl_ctx == NULL) {
  14506. fprintf(stderr, "ssl_ctx malloc failed\n");
  14507. return 0;
  14508. }
  14509. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14510. == 0
  14511. ? 1
  14512. : 0;
  14513. }
  14514. #elif defined(USE_GNUTLS)
  14515. /* Check if SSL is required.
  14516. * If so, set up ctx->ssl_ctx pointer. */
  14517. static int
  14518. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14519. {
  14520. if (!phys_ctx) {
  14521. return 0;
  14522. }
  14523. if (!dom_ctx) {
  14524. dom_ctx = &(phys_ctx->dd);
  14525. }
  14526. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14527. /* No SSL port is set. No need to setup SSL. */
  14528. return 1;
  14529. }
  14530. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14531. if (dom_ctx->ssl_ctx == NULL) {
  14532. fprintf(stderr, "ssl_ctx malloc failed\n");
  14533. return 0;
  14534. }
  14535. return gtls_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14536. == 0
  14537. ? 1
  14538. : 0;
  14539. }
  14540. #elif !defined(NO_SSL)
  14541. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14542. struct mg_domain_context *dom_ctx,
  14543. const char *pem,
  14544. const char *chain);
  14545. static const char *ssl_error(void);
  14546. static int
  14547. refresh_trust(struct mg_connection *conn)
  14548. {
  14549. struct stat cert_buf;
  14550. int64_t t = 0;
  14551. const char *pem;
  14552. const char *chain;
  14553. int should_verify_peer;
  14554. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14555. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14556. * refresh_trust still can not work. */
  14557. return 0;
  14558. }
  14559. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14560. if (chain == NULL) {
  14561. /* pem is not NULL here */
  14562. chain = pem;
  14563. }
  14564. if (*chain == 0) {
  14565. chain = NULL;
  14566. }
  14567. if (stat(pem, &cert_buf) != -1) {
  14568. t = (int64_t)cert_buf.st_mtime;
  14569. }
  14570. mg_lock_context(conn->phys_ctx);
  14571. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14572. conn->dom_ctx->ssl_cert_last_mtime = t;
  14573. should_verify_peer = 0;
  14574. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14575. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14576. == 0) {
  14577. should_verify_peer = 1;
  14578. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14579. "optional")
  14580. == 0) {
  14581. should_verify_peer = 1;
  14582. }
  14583. }
  14584. if (should_verify_peer) {
  14585. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14586. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14587. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14588. ca_file,
  14589. ca_path)
  14590. != 1) {
  14591. mg_unlock_context(conn->phys_ctx);
  14592. mg_cry_ctx_internal(
  14593. conn->phys_ctx,
  14594. "SSL_CTX_load_verify_locations error: %s "
  14595. "ssl_verify_peer requires setting "
  14596. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14597. "present in "
  14598. "the .conf file?",
  14599. ssl_error());
  14600. return 0;
  14601. }
  14602. }
  14603. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14604. mg_unlock_context(conn->phys_ctx);
  14605. return 0;
  14606. }
  14607. }
  14608. mg_unlock_context(conn->phys_ctx);
  14609. return 1;
  14610. }
  14611. #if defined(OPENSSL_API_1_1)
  14612. #else
  14613. static pthread_mutex_t *ssl_mutexes;
  14614. #endif /* OPENSSL_API_1_1 */
  14615. static int
  14616. sslize(struct mg_connection *conn,
  14617. int (*func)(SSL *),
  14618. const struct mg_client_options *client_options)
  14619. {
  14620. int ret, err;
  14621. int short_trust;
  14622. unsigned timeout = 1024;
  14623. unsigned i;
  14624. if (!conn) {
  14625. return 0;
  14626. }
  14627. short_trust =
  14628. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14629. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14630. if (short_trust) {
  14631. int trust_ret = refresh_trust(conn);
  14632. if (!trust_ret) {
  14633. return trust_ret;
  14634. }
  14635. }
  14636. mg_lock_context(conn->phys_ctx);
  14637. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14638. mg_unlock_context(conn->phys_ctx);
  14639. if (conn->ssl == NULL) {
  14640. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14641. OPENSSL_REMOVE_THREAD_STATE();
  14642. return 0;
  14643. }
  14644. SSL_set_app_data(conn->ssl, (char *)conn);
  14645. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14646. if (ret != 1) {
  14647. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14648. SSL_free(conn->ssl);
  14649. conn->ssl = NULL;
  14650. OPENSSL_REMOVE_THREAD_STATE();
  14651. return 0;
  14652. }
  14653. if (client_options) {
  14654. if (client_options->host_name) {
  14655. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14656. }
  14657. }
  14658. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14659. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14660. /* NOTE: The loop below acts as a back-off, so we can end
  14661. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14662. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14663. if (to >= 0) {
  14664. timeout = (unsigned)to;
  14665. }
  14666. }
  14667. /* SSL functions may fail and require to be called again:
  14668. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14669. * Here "func" could be SSL_connect or SSL_accept. */
  14670. for (i = 0; i <= timeout; i += 50) {
  14671. ERR_clear_error();
  14672. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14673. ret = func(conn->ssl);
  14674. if (ret != 1) {
  14675. err = SSL_get_error(conn->ssl, ret);
  14676. if ((err == SSL_ERROR_WANT_CONNECT)
  14677. || (err == SSL_ERROR_WANT_ACCEPT)
  14678. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14679. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14680. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14681. /* Don't wait if the server is going to be stopped. */
  14682. break;
  14683. }
  14684. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14685. /* Simply retry the function call. */
  14686. mg_sleep(50);
  14687. } else {
  14688. /* Need to retry the function call "later".
  14689. * See https://linux.die.net/man/3/ssl_get_error
  14690. * This is typical for non-blocking sockets. */
  14691. struct mg_pollfd pfd[2];
  14692. int pollres;
  14693. unsigned int num_sock = 1;
  14694. pfd[0].fd = conn->client.sock;
  14695. pfd[0].events = ((err == SSL_ERROR_WANT_CONNECT)
  14696. || (err == SSL_ERROR_WANT_WRITE))
  14697. ? POLLOUT
  14698. : POLLIN;
  14699. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14700. pfd[num_sock].fd =
  14701. conn->phys_ctx->thread_shutdown_notification_socket;
  14702. pfd[num_sock].events = POLLIN;
  14703. num_sock++;
  14704. }
  14705. pollres = mg_poll(pfd,
  14706. num_sock,
  14707. 50,
  14708. &(conn->phys_ctx->stop_flag));
  14709. if (pollres < 0) {
  14710. /* Break if error occurred (-1)
  14711. * or server shutdown (-2) */
  14712. break;
  14713. }
  14714. }
  14715. } else if (err == SSL_ERROR_SYSCALL) {
  14716. /* This is an IO error. Look at errno. */
  14717. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14718. break;
  14719. } else {
  14720. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14721. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14722. break;
  14723. }
  14724. } else {
  14725. /* success */
  14726. break;
  14727. }
  14728. }
  14729. ERR_clear_error();
  14730. if (ret != 1) {
  14731. SSL_free(conn->ssl);
  14732. conn->ssl = NULL;
  14733. OPENSSL_REMOVE_THREAD_STATE();
  14734. return 0;
  14735. }
  14736. return 1;
  14737. }
  14738. /* Return OpenSSL error message (from CRYPTO lib) */
  14739. static const char *
  14740. ssl_error(void)
  14741. {
  14742. unsigned long err;
  14743. err = ERR_get_error();
  14744. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14745. }
  14746. static int
  14747. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14748. {
  14749. int i;
  14750. const char hexdigit[] = "0123456789abcdef";
  14751. if ((memlen <= 0) || (buflen <= 0)) {
  14752. return 0;
  14753. }
  14754. if (buflen < (3 * memlen)) {
  14755. return 0;
  14756. }
  14757. for (i = 0; i < memlen; i++) {
  14758. if (i > 0) {
  14759. buf[3 * i - 1] = ' ';
  14760. }
  14761. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14762. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14763. }
  14764. buf[3 * memlen - 1] = 0;
  14765. return 1;
  14766. }
  14767. static int
  14768. ssl_get_client_cert_info(const struct mg_connection *conn,
  14769. struct mg_client_cert *client_cert)
  14770. {
  14771. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14772. if (cert) {
  14773. char str_buf[1024];
  14774. unsigned char buf[256];
  14775. char *str_serial = NULL;
  14776. unsigned int ulen;
  14777. int ilen;
  14778. unsigned char *tmp_buf;
  14779. unsigned char *tmp_p;
  14780. /* Handle to algorithm used for fingerprint */
  14781. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14782. /* Get Subject and issuer */
  14783. X509_NAME *subj = X509_get_subject_name(cert);
  14784. X509_NAME *iss = X509_get_issuer_name(cert);
  14785. /* Get serial number */
  14786. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14787. /* Translate serial number to a hex string */
  14788. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14789. if (serial_bn) {
  14790. str_serial = BN_bn2hex(serial_bn);
  14791. BN_free(serial_bn);
  14792. }
  14793. client_cert->serial =
  14794. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14795. /* Translate subject and issuer to a string */
  14796. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14797. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14798. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14799. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14800. /* Calculate SHA1 fingerprint and store as a hex string */
  14801. ulen = 0;
  14802. /* ASN1_digest is deprecated. Do the calculation manually,
  14803. * using EVP_Digest. */
  14804. ilen = i2d_X509(cert, NULL);
  14805. tmp_buf = (ilen > 0)
  14806. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14807. conn->phys_ctx)
  14808. : NULL;
  14809. if (tmp_buf) {
  14810. tmp_p = tmp_buf;
  14811. (void)i2d_X509(cert, &tmp_p);
  14812. if (!EVP_Digest(
  14813. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14814. ulen = 0;
  14815. }
  14816. mg_free(tmp_buf);
  14817. }
  14818. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14819. *str_buf = 0;
  14820. }
  14821. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14822. client_cert->peer_cert = (void *)cert;
  14823. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14824. * see https://linux.die.net/man/3/bn_bn2hex */
  14825. OPENSSL_free(str_serial);
  14826. return 1;
  14827. }
  14828. return 0;
  14829. }
  14830. #if defined(OPENSSL_API_1_1)
  14831. #else
  14832. static void
  14833. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14834. {
  14835. (void)line;
  14836. (void)file;
  14837. if (mode & 1) {
  14838. /* 1 is CRYPTO_LOCK */
  14839. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14840. } else {
  14841. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14842. }
  14843. }
  14844. #endif /* OPENSSL_API_1_1 */
  14845. #if !defined(NO_SSL_DL)
  14846. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14847. static void *
  14848. load_tls_dll(char *ebuf,
  14849. size_t ebuf_len,
  14850. const char *dll_name,
  14851. struct ssl_func *sw,
  14852. int *feature_missing)
  14853. {
  14854. union {
  14855. void *p;
  14856. void (*fp)(void);
  14857. } u;
  14858. void *dll_handle;
  14859. struct ssl_func *fp;
  14860. int ok;
  14861. int truncated = 0;
  14862. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14863. mg_snprintf(NULL,
  14864. NULL, /* No truncation check for ebuf */
  14865. ebuf,
  14866. ebuf_len,
  14867. "%s: cannot load %s",
  14868. __func__,
  14869. dll_name);
  14870. return NULL;
  14871. }
  14872. ok = 1;
  14873. for (fp = sw; fp->name != NULL; fp++) {
  14874. #if defined(_WIN32)
  14875. /* GetProcAddress() returns pointer to function */
  14876. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14877. #else
  14878. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14879. * pointers to function pointers. We need to use a union to make a
  14880. * cast. */
  14881. u.p = dlsym(dll_handle, fp->name);
  14882. #endif /* _WIN32 */
  14883. /* Set pointer (might be NULL) */
  14884. fp->ptr = u.fp;
  14885. if (u.fp == NULL) {
  14886. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14887. if (feature_missing) {
  14888. feature_missing[fp->required]++;
  14889. }
  14890. if (fp->required == TLS_Mandatory) {
  14891. /* Mandatory function is missing */
  14892. if (ok) {
  14893. /* This is the first missing function.
  14894. * Create a new error message. */
  14895. mg_snprintf(NULL,
  14896. &truncated,
  14897. ebuf,
  14898. ebuf_len,
  14899. "%s: %s: cannot find %s",
  14900. __func__,
  14901. dll_name,
  14902. fp->name);
  14903. ok = 0;
  14904. } else {
  14905. /* This is yet anothermissing function.
  14906. * Append existing error message. */
  14907. size_t cur_len = strlen(ebuf);
  14908. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14909. mg_snprintf(NULL,
  14910. &truncated,
  14911. ebuf + cur_len,
  14912. ebuf_len - cur_len - 3,
  14913. ", %s",
  14914. fp->name);
  14915. if (truncated) {
  14916. /* If truncated, add "..." */
  14917. strcat(ebuf, "...");
  14918. }
  14919. }
  14920. }
  14921. }
  14922. }
  14923. }
  14924. if (!ok) {
  14925. (void)dlclose(dll_handle);
  14926. return NULL;
  14927. }
  14928. return dll_handle;
  14929. }
  14930. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14931. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14932. #endif /* NO_SSL_DL */
  14933. #if defined(SSL_ALREADY_INITIALIZED)
  14934. static volatile ptrdiff_t cryptolib_users =
  14935. 1; /* Reference counter for crypto library. */
  14936. #else
  14937. static volatile ptrdiff_t cryptolib_users =
  14938. 0; /* Reference counter for crypto library. */
  14939. #endif
  14940. static int
  14941. initialize_openssl(char *ebuf, size_t ebuf_len)
  14942. {
  14943. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14944. int i, num_locks;
  14945. size_t size;
  14946. #endif
  14947. if (ebuf_len > 0) {
  14948. ebuf[0] = 0;
  14949. }
  14950. #if !defined(NO_SSL_DL)
  14951. if (!cryptolib_dll_handle) {
  14952. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14953. cryptolib_dll_handle = load_tls_dll(
  14954. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14955. if (!cryptolib_dll_handle) {
  14956. mg_snprintf(NULL,
  14957. NULL, /* No truncation check for ebuf */
  14958. ebuf,
  14959. ebuf_len,
  14960. "%s: error loading library %s",
  14961. __func__,
  14962. CRYPTO_LIB);
  14963. DEBUG_TRACE("%s", ebuf);
  14964. return 0;
  14965. }
  14966. }
  14967. #endif /* NO_SSL_DL */
  14968. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14969. return 1;
  14970. }
  14971. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14972. /* Initialize locking callbacks, needed for thread safety.
  14973. * http://www.openssl.org/support/faq.html#PROG1
  14974. */
  14975. num_locks = CRYPTO_num_locks();
  14976. if (num_locks < 0) {
  14977. num_locks = 0;
  14978. }
  14979. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14980. /* allocate mutex array, if required */
  14981. if (num_locks == 0) {
  14982. /* No mutex array required */
  14983. ssl_mutexes = NULL;
  14984. } else {
  14985. /* Mutex array required - allocate it */
  14986. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14987. /* Check OOM */
  14988. if (ssl_mutexes == NULL) {
  14989. mg_snprintf(NULL,
  14990. NULL, /* No truncation check for ebuf */
  14991. ebuf,
  14992. ebuf_len,
  14993. "%s: cannot allocate mutexes: %s",
  14994. __func__,
  14995. ssl_error());
  14996. DEBUG_TRACE("%s", ebuf);
  14997. return 0;
  14998. }
  14999. /* initialize mutex array */
  15000. for (i = 0; i < num_locks; i++) {
  15001. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  15002. mg_snprintf(NULL,
  15003. NULL, /* No truncation check for ebuf */
  15004. ebuf,
  15005. ebuf_len,
  15006. "%s: error initializing mutex %i of %i",
  15007. __func__,
  15008. i,
  15009. num_locks);
  15010. DEBUG_TRACE("%s", ebuf);
  15011. mg_free(ssl_mutexes);
  15012. return 0;
  15013. }
  15014. }
  15015. }
  15016. CRYPTO_set_locking_callback(&ssl_locking_callback);
  15017. CRYPTO_set_id_callback(&mg_current_thread_id);
  15018. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15019. #if !defined(NO_SSL_DL)
  15020. if (!ssllib_dll_handle) {
  15021. ssllib_dll_handle =
  15022. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  15023. if (!ssllib_dll_handle) {
  15024. #if !defined(OPENSSL_API_1_1)
  15025. mg_free(ssl_mutexes);
  15026. #endif
  15027. DEBUG_TRACE("%s", ebuf);
  15028. return 0;
  15029. }
  15030. }
  15031. #endif /* NO_SSL_DL */
  15032. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15033. && !defined(NO_SSL_DL)
  15034. /* Initialize SSL library */
  15035. OPENSSL_init_ssl(0, NULL);
  15036. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  15037. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  15038. NULL);
  15039. #else
  15040. /* Initialize SSL library */
  15041. SSL_library_init();
  15042. SSL_load_error_strings();
  15043. #endif
  15044. return 1;
  15045. }
  15046. static int
  15047. ssl_use_pem_file(struct mg_context *phys_ctx,
  15048. struct mg_domain_context *dom_ctx,
  15049. const char *pem,
  15050. const char *chain)
  15051. {
  15052. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15053. mg_cry_ctx_internal(phys_ctx,
  15054. "%s: cannot open certificate file %s: %s",
  15055. __func__,
  15056. pem,
  15057. ssl_error());
  15058. return 0;
  15059. }
  15060. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  15061. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15062. mg_cry_ctx_internal(phys_ctx,
  15063. "%s: cannot open private key file %s: %s",
  15064. __func__,
  15065. pem,
  15066. ssl_error());
  15067. return 0;
  15068. }
  15069. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  15070. mg_cry_ctx_internal(phys_ctx,
  15071. "%s: certificate and private key do not match: %s",
  15072. __func__,
  15073. pem);
  15074. return 0;
  15075. }
  15076. /* In contrast to OpenSSL, wolfSSL does not support certificate
  15077. * chain files that contain private keys and certificates in
  15078. * SSL_CTX_use_certificate_chain_file.
  15079. * The CivetWeb-Server used pem-Files that contained both information.
  15080. * In order to make wolfSSL work, it is split in two files.
  15081. * One file that contains key and certificate used by the server and
  15082. * an optional chain file for the ssl stack.
  15083. */
  15084. if (chain) {
  15085. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  15086. mg_cry_ctx_internal(phys_ctx,
  15087. "%s: cannot use certificate chain file %s: %s",
  15088. __func__,
  15089. chain,
  15090. ssl_error());
  15091. return 0;
  15092. }
  15093. }
  15094. return 1;
  15095. }
  15096. #if defined(OPENSSL_API_1_1)
  15097. static unsigned long
  15098. ssl_get_protocol(int version_id)
  15099. {
  15100. long unsigned ret = (long unsigned)SSL_OP_ALL;
  15101. if (version_id > 0)
  15102. ret |= SSL_OP_NO_SSLv2;
  15103. if (version_id > 1)
  15104. ret |= SSL_OP_NO_SSLv3;
  15105. if (version_id > 2)
  15106. ret |= SSL_OP_NO_TLSv1;
  15107. if (version_id > 3)
  15108. ret |= SSL_OP_NO_TLSv1_1;
  15109. if (version_id > 4)
  15110. ret |= SSL_OP_NO_TLSv1_2;
  15111. #if defined(SSL_OP_NO_TLSv1_3)
  15112. if (version_id > 5)
  15113. ret |= SSL_OP_NO_TLSv1_3;
  15114. #endif
  15115. return ret;
  15116. }
  15117. #else
  15118. static long
  15119. ssl_get_protocol(int version_id)
  15120. {
  15121. unsigned long ret = (unsigned long)SSL_OP_ALL;
  15122. if (version_id > 0)
  15123. ret |= SSL_OP_NO_SSLv2;
  15124. if (version_id > 1)
  15125. ret |= SSL_OP_NO_SSLv3;
  15126. if (version_id > 2)
  15127. ret |= SSL_OP_NO_TLSv1;
  15128. if (version_id > 3)
  15129. ret |= SSL_OP_NO_TLSv1_1;
  15130. if (version_id > 4)
  15131. ret |= SSL_OP_NO_TLSv1_2;
  15132. #if defined(SSL_OP_NO_TLSv1_3)
  15133. if (version_id > 5)
  15134. ret |= SSL_OP_NO_TLSv1_3;
  15135. #endif
  15136. return (long)ret;
  15137. }
  15138. #endif /* OPENSSL_API_1_1 */
  15139. /* SSL callback documentation:
  15140. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  15141. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  15142. * https://linux.die.net/man/3/ssl_set_info_callback */
  15143. /* Note: There is no "const" for the first argument in the documentation
  15144. * examples, however some (maybe most, but not all) headers of OpenSSL
  15145. * versions / OpenSSL compatibility layers have it. Having a different
  15146. * definition will cause a warning in C and an error in C++. Use "const SSL
  15147. * *", while automatic conversion from "SSL *" works for all compilers,
  15148. * but not other way around */
  15149. static void
  15150. ssl_info_callback(const SSL *ssl, int what, int ret)
  15151. {
  15152. (void)ret;
  15153. if (what & SSL_CB_HANDSHAKE_START) {
  15154. SSL_get_app_data(ssl);
  15155. }
  15156. if (what & SSL_CB_HANDSHAKE_DONE) {
  15157. /* TODO: check for openSSL 1.1 */
  15158. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  15159. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  15160. }
  15161. }
  15162. static int
  15163. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  15164. {
  15165. #if defined(GCC_DIAGNOSTIC)
  15166. #pragma GCC diagnostic push
  15167. #pragma GCC diagnostic ignored "-Wcast-align"
  15168. #endif /* defined(GCC_DIAGNOSTIC) */
  15169. /* We used an aligned pointer in SSL_set_app_data */
  15170. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  15171. #if defined(GCC_DIAGNOSTIC)
  15172. #pragma GCC diagnostic pop
  15173. #endif /* defined(GCC_DIAGNOSTIC) */
  15174. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15175. (void)ad;
  15176. (void)arg;
  15177. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15178. DEBUG_ASSERT(0);
  15179. return SSL_TLSEXT_ERR_NOACK;
  15180. }
  15181. conn->dom_ctx = &(conn->phys_ctx->dd);
  15182. /* Old clients (Win XP) will not support SNI. Then, there
  15183. * is no server name available in the request - we can
  15184. * only work with the default certificate.
  15185. * Multiple HTTPS hosts on one IP+port are only possible
  15186. * with a certificate containing all alternative names.
  15187. */
  15188. if ((servername == NULL) || (*servername == 0)) {
  15189. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  15190. mg_lock_context(conn->phys_ctx);
  15191. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15192. mg_unlock_context(conn->phys_ctx);
  15193. return SSL_TLSEXT_ERR_NOACK;
  15194. }
  15195. DEBUG_TRACE("TLS connection to host %s", servername);
  15196. while (conn->dom_ctx) {
  15197. if (!mg_strcasecmp(servername,
  15198. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  15199. /* Found matching domain */
  15200. DEBUG_TRACE("TLS domain %s found",
  15201. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  15202. break;
  15203. }
  15204. mg_lock_context(conn->phys_ctx);
  15205. conn->dom_ctx = conn->dom_ctx->next;
  15206. mg_unlock_context(conn->phys_ctx);
  15207. }
  15208. if (conn->dom_ctx == NULL) {
  15209. /* Default domain */
  15210. DEBUG_TRACE("TLS default domain %s used",
  15211. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  15212. conn->dom_ctx = &(conn->phys_ctx->dd);
  15213. }
  15214. mg_lock_context(conn->phys_ctx);
  15215. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15216. mg_unlock_context(conn->phys_ctx);
  15217. return SSL_TLSEXT_ERR_OK;
  15218. }
  15219. #if defined(USE_ALPN)
  15220. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  15221. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  15222. alpn_proto_list + 3 + 8,
  15223. NULL};
  15224. #if defined(USE_HTTP2)
  15225. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  15226. alpn_proto_list + 3,
  15227. alpn_proto_list + 3 + 8,
  15228. NULL};
  15229. #endif
  15230. static int
  15231. alpn_select_cb(SSL *ssl,
  15232. const unsigned char **out,
  15233. unsigned char *outlen,
  15234. const unsigned char *in,
  15235. unsigned int inlen,
  15236. void *arg)
  15237. {
  15238. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15239. unsigned int i, j, enable_http2 = 0;
  15240. const char **alpn_proto_order = alpn_proto_order_http1;
  15241. struct mg_workerTLS *tls =
  15242. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  15243. (void)ssl;
  15244. if (tls == NULL) {
  15245. /* Need to store protocol in Thread Local Storage */
  15246. /* If there is no Thread Local Storage, don't use ALPN */
  15247. return SSL_TLSEXT_ERR_NOACK;
  15248. }
  15249. #if defined(USE_HTTP2)
  15250. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  15251. if (enable_http2) {
  15252. alpn_proto_order = alpn_proto_order_http2;
  15253. }
  15254. #endif
  15255. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  15256. /* check all accepted protocols in this order */
  15257. const char *alpn_proto = alpn_proto_order[j];
  15258. /* search input for matching protocol */
  15259. for (i = 0; i < inlen; i++) {
  15260. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  15261. *out = in + i + 1;
  15262. *outlen = in[i];
  15263. tls->alpn_proto = alpn_proto;
  15264. return SSL_TLSEXT_ERR_OK;
  15265. }
  15266. }
  15267. }
  15268. /* Nothing found */
  15269. return SSL_TLSEXT_ERR_NOACK;
  15270. }
  15271. static int
  15272. next_protos_advertised_cb(SSL *ssl,
  15273. const unsigned char **data,
  15274. unsigned int *len,
  15275. void *arg)
  15276. {
  15277. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15278. *data = (const unsigned char *)alpn_proto_list;
  15279. *len = (unsigned int)strlen((const char *)data);
  15280. (void)ssl;
  15281. (void)dom_ctx;
  15282. return SSL_TLSEXT_ERR_OK;
  15283. }
  15284. static int
  15285. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15286. {
  15287. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  15288. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  15289. (const unsigned char *)alpn_proto_list,
  15290. alpn_len);
  15291. if (ret != 0) {
  15292. mg_cry_ctx_internal(phys_ctx,
  15293. "SSL_CTX_set_alpn_protos error: %s",
  15294. ssl_error());
  15295. }
  15296. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  15297. alpn_select_cb,
  15298. (void *)dom_ctx);
  15299. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  15300. next_protos_advertised_cb,
  15301. (void *)dom_ctx);
  15302. return ret;
  15303. }
  15304. #endif
  15305. /* Setup SSL CTX as required by CivetWeb */
  15306. static int
  15307. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  15308. struct mg_domain_context *dom_ctx,
  15309. const char *pem,
  15310. const char *chain)
  15311. {
  15312. int callback_ret;
  15313. int should_verify_peer;
  15314. int peer_certificate_optional;
  15315. const char *ca_path;
  15316. const char *ca_file;
  15317. int use_default_verify_paths;
  15318. int verify_depth;
  15319. struct timespec now_mt;
  15320. md5_byte_t ssl_context_id[16];
  15321. md5_state_t md5state;
  15322. int protocol_ver;
  15323. int ssl_cache_timeout;
  15324. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15325. && !defined(NO_SSL_DL)
  15326. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15327. mg_cry_ctx_internal(phys_ctx,
  15328. "SSL_CTX_new (server) error: %s",
  15329. ssl_error());
  15330. return 0;
  15331. }
  15332. #else
  15333. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15334. mg_cry_ctx_internal(phys_ctx,
  15335. "SSL_CTX_new (server) error: %s",
  15336. ssl_error());
  15337. return 0;
  15338. }
  15339. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15340. #if defined(SSL_OP_NO_TLSv1_3)
  15341. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15342. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15343. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15344. | SSL_OP_NO_TLSv1_3);
  15345. #else
  15346. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15347. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15348. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15349. #endif
  15350. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15351. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15352. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15353. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15354. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15355. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15356. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15357. #if defined(SSL_OP_NO_RENEGOTIATION)
  15358. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15359. #endif
  15360. #if !defined(NO_SSL_DL)
  15361. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15362. #endif /* NO_SSL_DL */
  15363. /* In SSL documentation examples callback defined without const
  15364. * specifier 'void (*)(SSL *, int, int)' See:
  15365. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15366. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15367. * But in the source code const SSL is used:
  15368. * 'void (*)(const SSL *, int, int)' See:
  15369. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15370. * Problem about wrong documentation described, but not resolved:
  15371. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15372. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15373. * But when compiled with modern C++ compiler, correct const should be
  15374. * provided
  15375. */
  15376. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15377. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15378. ssl_servername_callback);
  15379. /* If a callback has been specified, call it. */
  15380. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15381. ? 0
  15382. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15383. phys_ctx->user_data));
  15384. /* If callback returns 0, civetweb sets up the SSL certificate.
  15385. * If it returns 1, civetweb assumes the callback already did this.
  15386. * If it returns -1, initializing ssl fails. */
  15387. if (callback_ret < 0) {
  15388. mg_cry_ctx_internal(phys_ctx,
  15389. "SSL callback returned error: %i",
  15390. callback_ret);
  15391. return 0;
  15392. }
  15393. if (callback_ret > 0) {
  15394. /* Callback did everything. */
  15395. return 1;
  15396. }
  15397. /* If a domain callback has been specified, call it. */
  15398. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15399. ? 0
  15400. : (phys_ctx->callbacks.init_ssl_domain(
  15401. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15402. dom_ctx->ssl_ctx,
  15403. phys_ctx->user_data));
  15404. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15405. * If it returns 1, civetweb assumes the callback already did this.
  15406. * If it returns -1, initializing ssl fails. */
  15407. if (callback_ret < 0) {
  15408. mg_cry_ctx_internal(phys_ctx,
  15409. "Domain SSL callback returned error: %i",
  15410. callback_ret);
  15411. return 0;
  15412. }
  15413. if (callback_ret > 0) {
  15414. /* Domain callback did everything. */
  15415. return 1;
  15416. }
  15417. /* Use some combination of start time, domain and port as a SSL
  15418. * context ID. This should be unique on the current machine. */
  15419. md5_init(&md5state);
  15420. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15421. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15422. md5_append(&md5state,
  15423. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15424. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15425. md5_append(&md5state,
  15426. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15427. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15428. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15429. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15430. md5_finish(&md5state, ssl_context_id);
  15431. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15432. (unsigned char *)ssl_context_id,
  15433. sizeof(ssl_context_id));
  15434. if (pem != NULL) {
  15435. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15436. return 0;
  15437. }
  15438. }
  15439. /* Should we support client certificates? */
  15440. /* Default is "no". */
  15441. should_verify_peer = 0;
  15442. peer_certificate_optional = 0;
  15443. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15444. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15445. /* Yes, they are mandatory */
  15446. should_verify_peer = 1;
  15447. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15448. "optional")
  15449. == 0) {
  15450. /* Yes, they are optional */
  15451. should_verify_peer = 1;
  15452. peer_certificate_optional = 1;
  15453. }
  15454. }
  15455. use_default_verify_paths =
  15456. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15457. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15458. == 0);
  15459. if (should_verify_peer) {
  15460. ca_path = dom_ctx->config[SSL_CA_PATH];
  15461. ca_file = dom_ctx->config[SSL_CA_FILE];
  15462. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15463. != 1) {
  15464. mg_cry_ctx_internal(phys_ctx,
  15465. "SSL_CTX_load_verify_locations error: %s "
  15466. "ssl_verify_peer requires setting "
  15467. "either ssl_ca_path or ssl_ca_file. "
  15468. "Is any of them present in the "
  15469. ".conf file?",
  15470. ssl_error());
  15471. return 0;
  15472. }
  15473. if (peer_certificate_optional) {
  15474. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15475. } else {
  15476. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15477. SSL_VERIFY_PEER
  15478. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15479. NULL);
  15480. }
  15481. if (use_default_verify_paths
  15482. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15483. mg_cry_ctx_internal(phys_ctx,
  15484. "SSL_CTX_set_default_verify_paths error: %s",
  15485. ssl_error());
  15486. return 0;
  15487. }
  15488. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15489. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15490. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15491. }
  15492. }
  15493. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15494. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15495. dom_ctx->config[SSL_CIPHER_LIST])
  15496. != 1) {
  15497. mg_cry_ctx_internal(phys_ctx,
  15498. "SSL_CTX_set_cipher_list error: %s",
  15499. ssl_error());
  15500. }
  15501. }
  15502. /* SSL session caching */
  15503. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15504. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15505. : 0);
  15506. if (ssl_cache_timeout > 0) {
  15507. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15508. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15509. * default */
  15510. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15511. }
  15512. #if defined(USE_ALPN)
  15513. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15514. #if !defined(NO_SSL_DL)
  15515. if (!tls_feature_missing[TLS_ALPN])
  15516. #endif
  15517. {
  15518. init_alpn(phys_ctx, dom_ctx);
  15519. }
  15520. #endif
  15521. return 1;
  15522. }
  15523. /* Check if SSL is required.
  15524. * If so, dynamically load SSL library
  15525. * and set up ctx->ssl_ctx pointer. */
  15526. static int
  15527. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15528. {
  15529. void *ssl_ctx = 0;
  15530. int callback_ret;
  15531. const char *pem;
  15532. const char *chain;
  15533. char ebuf[128];
  15534. if (!phys_ctx) {
  15535. return 0;
  15536. }
  15537. if (!dom_ctx) {
  15538. dom_ctx = &(phys_ctx->dd);
  15539. }
  15540. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15541. /* No SSL port is set. No need to setup SSL. */
  15542. return 1;
  15543. }
  15544. /* Check for external SSL_CTX */
  15545. callback_ret =
  15546. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15547. ? 0
  15548. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15549. phys_ctx->user_data));
  15550. if (callback_ret < 0) {
  15551. /* Callback exists and returns <0: Initializing failed. */
  15552. mg_cry_ctx_internal(phys_ctx,
  15553. "external_ssl_ctx callback returned error: %i",
  15554. callback_ret);
  15555. return 0;
  15556. } else if (callback_ret > 0) {
  15557. /* Callback exists and returns >0: Initializing complete,
  15558. * civetweb should not modify the SSL context. */
  15559. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15560. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15561. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15562. return 0;
  15563. }
  15564. return 1;
  15565. }
  15566. /* If the callback does not exist or return 0, civetweb must initialize
  15567. * the SSL context. Handle "domain" callback next. */
  15568. /* Check for external domain SSL_CTX callback. */
  15569. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15570. ? 0
  15571. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15572. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15573. &ssl_ctx,
  15574. phys_ctx->user_data));
  15575. if (callback_ret < 0) {
  15576. /* Callback < 0: Error. Abort init. */
  15577. mg_cry_ctx_internal(
  15578. phys_ctx,
  15579. "external_ssl_ctx_domain callback returned error: %i",
  15580. callback_ret);
  15581. return 0;
  15582. } else if (callback_ret > 0) {
  15583. /* Callback > 0: Consider init done. */
  15584. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15585. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15586. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15587. return 0;
  15588. }
  15589. return 1;
  15590. }
  15591. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15592. * 0, CivetWeb should continue initializing SSL */
  15593. /* If PEM file is not specified and the init_ssl callbacks
  15594. * are not specified, setup will fail. */
  15595. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15596. && (phys_ctx->callbacks.init_ssl == NULL)
  15597. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15598. /* No certificate and no init_ssl callbacks:
  15599. * Essential data to set up TLS is missing.
  15600. */
  15601. mg_cry_ctx_internal(phys_ctx,
  15602. "Initializing SSL failed: -%s is not set",
  15603. config_options[SSL_CERTIFICATE].name);
  15604. return 0;
  15605. }
  15606. /* If a certificate chain is configured, use it. */
  15607. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15608. if (chain == NULL) {
  15609. /* Default: certificate chain in PEM file */
  15610. chain = pem;
  15611. }
  15612. if ((chain != NULL) && (*chain == 0)) {
  15613. /* If the chain is an empty string, don't use it. */
  15614. chain = NULL;
  15615. }
  15616. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15617. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15618. return 0;
  15619. }
  15620. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15621. }
  15622. static void
  15623. uninitialize_openssl(void)
  15624. {
  15625. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15626. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15627. /* Shutdown according to
  15628. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15629. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15630. */
  15631. CONF_modules_unload(1);
  15632. #else
  15633. int i;
  15634. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15635. /* Shutdown according to
  15636. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15637. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15638. */
  15639. CRYPTO_set_locking_callback(NULL);
  15640. CRYPTO_set_id_callback(NULL);
  15641. ENGINE_cleanup();
  15642. CONF_modules_unload(1);
  15643. ERR_free_strings();
  15644. EVP_cleanup();
  15645. CRYPTO_cleanup_all_ex_data();
  15646. OPENSSL_REMOVE_THREAD_STATE();
  15647. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15648. pthread_mutex_destroy(&ssl_mutexes[i]);
  15649. }
  15650. mg_free(ssl_mutexes);
  15651. ssl_mutexes = NULL;
  15652. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15653. }
  15654. }
  15655. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) */
  15656. #if !defined(NO_FILESYSTEMS)
  15657. static int
  15658. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15659. {
  15660. if (phys_ctx) {
  15661. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15662. const char *path;
  15663. struct mg_connection fc;
  15664. if (!dom_ctx) {
  15665. dom_ctx = &(phys_ctx->dd);
  15666. }
  15667. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15668. if ((path != NULL)
  15669. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15670. mg_cry_ctx_internal(phys_ctx,
  15671. "Cannot open %s: %s",
  15672. path,
  15673. strerror(ERRNO));
  15674. return 0;
  15675. }
  15676. return 1;
  15677. }
  15678. return 0;
  15679. }
  15680. #endif /* NO_FILESYSTEMS */
  15681. static int
  15682. set_acl_option(struct mg_context *phys_ctx)
  15683. {
  15684. union usa sa;
  15685. memset(&sa, 0, sizeof(sa));
  15686. #if defined(USE_IPV6)
  15687. sa.sin6.sin6_family = AF_INET6;
  15688. #else
  15689. sa.sin.sin_family = AF_INET;
  15690. #endif
  15691. return check_acl(phys_ctx, &sa) != -1;
  15692. }
  15693. static void
  15694. reset_per_request_attributes(struct mg_connection *conn)
  15695. {
  15696. if (!conn) {
  15697. return;
  15698. }
  15699. conn->num_bytes_sent = conn->consumed_content = 0;
  15700. conn->path_info = NULL;
  15701. conn->status_code = -1;
  15702. conn->content_len = -1;
  15703. conn->is_chunked = 0;
  15704. conn->must_close = 0;
  15705. conn->request_len = 0;
  15706. conn->request_state = 0;
  15707. conn->throttle = 0;
  15708. conn->accept_gzip = 0;
  15709. conn->response_info.content_length = conn->request_info.content_length = -1;
  15710. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15711. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15712. conn->response_info.status_text = NULL;
  15713. conn->response_info.status_code = 0;
  15714. conn->request_info.remote_user = NULL;
  15715. conn->request_info.request_method = NULL;
  15716. conn->request_info.request_uri = NULL;
  15717. /* Free cleaned local URI (if any) */
  15718. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15719. mg_free((void *)conn->request_info.local_uri);
  15720. conn->request_info.local_uri = NULL;
  15721. }
  15722. conn->request_info.local_uri = NULL;
  15723. #if defined(USE_SERVER_STATS)
  15724. conn->processing_time = 0;
  15725. #endif
  15726. }
  15727. static int
  15728. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15729. {
  15730. if ((so->lsa.sa.sa_family == AF_INET)
  15731. || (so->lsa.sa.sa_family == AF_INET6)) {
  15732. /* Only for TCP sockets */
  15733. if (setsockopt(so->sock,
  15734. IPPROTO_TCP,
  15735. TCP_NODELAY,
  15736. (SOCK_OPT_TYPE)&nodelay_on,
  15737. sizeof(nodelay_on))
  15738. != 0) {
  15739. /* Error */
  15740. return 1;
  15741. }
  15742. }
  15743. /* OK */
  15744. return 0;
  15745. }
  15746. #if !defined(__ZEPHYR__)
  15747. static void
  15748. close_socket_gracefully(struct mg_connection *conn)
  15749. {
  15750. #if defined(_WIN32)
  15751. char buf[MG_BUF_LEN];
  15752. int n;
  15753. #endif
  15754. struct linger linger;
  15755. int error_code = 0;
  15756. int linger_timeout = -2;
  15757. socklen_t opt_len = sizeof(error_code);
  15758. if (!conn) {
  15759. return;
  15760. }
  15761. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15762. * "Note that enabling a nonzero timeout on a nonblocking socket
  15763. * is not recommended.", so set it to blocking now */
  15764. set_blocking_mode(conn->client.sock);
  15765. /* Send FIN to the client */
  15766. shutdown(conn->client.sock, SHUTDOWN_WR);
  15767. #if defined(_WIN32)
  15768. /* Read and discard pending incoming data. If we do not do that and
  15769. * close
  15770. * the socket, the data in the send buffer may be discarded. This
  15771. * behaviour is seen on Windows, when client keeps sending data
  15772. * when server decides to close the connection; then when client
  15773. * does recv() it gets no data back. */
  15774. do {
  15775. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15776. } while (n > 0);
  15777. #endif
  15778. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15779. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15780. }
  15781. /* Set linger option according to configuration */
  15782. if (linger_timeout >= 0) {
  15783. /* Set linger option to avoid socket hanging out after close. This
  15784. * prevent ephemeral port exhaust problem under high QPS. */
  15785. linger.l_onoff = 1;
  15786. #if defined(_MSC_VER)
  15787. #pragma warning(push)
  15788. #pragma warning(disable : 4244)
  15789. #endif
  15790. #if defined(GCC_DIAGNOSTIC)
  15791. #pragma GCC diagnostic push
  15792. #pragma GCC diagnostic ignored "-Wconversion"
  15793. #endif
  15794. /* Data type of linger structure elements may differ,
  15795. * so we don't know what cast we need here.
  15796. * Disable type conversion warnings. */
  15797. linger.l_linger = (linger_timeout + 999) / 1000;
  15798. #if defined(GCC_DIAGNOSTIC)
  15799. #pragma GCC diagnostic pop
  15800. #endif
  15801. #if defined(_MSC_VER)
  15802. #pragma warning(pop)
  15803. #endif
  15804. } else {
  15805. linger.l_onoff = 0;
  15806. linger.l_linger = 0;
  15807. }
  15808. if (linger_timeout < -1) {
  15809. /* Default: don't configure any linger */
  15810. } else if (getsockopt(conn->client.sock,
  15811. SOL_SOCKET,
  15812. SO_ERROR,
  15813. #if defined(_WIN32) /* WinSock uses different data type here */
  15814. (char *)&error_code,
  15815. #else
  15816. &error_code,
  15817. #endif
  15818. &opt_len)
  15819. != 0) {
  15820. /* Cannot determine if socket is already closed. This should
  15821. * not occur and never did in a test. Log an error message
  15822. * and continue. */
  15823. mg_cry_internal(conn,
  15824. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15825. __func__,
  15826. strerror(ERRNO));
  15827. #if defined(_WIN32)
  15828. } else if (error_code == WSAECONNRESET) {
  15829. #else
  15830. } else if (error_code == ECONNRESET) {
  15831. #endif
  15832. /* Socket already closed by client/peer, close socket without linger
  15833. */
  15834. } else {
  15835. /* Set linger timeout */
  15836. if (setsockopt(conn->client.sock,
  15837. SOL_SOCKET,
  15838. SO_LINGER,
  15839. (char *)&linger,
  15840. sizeof(linger))
  15841. != 0) {
  15842. mg_cry_internal(
  15843. conn,
  15844. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15845. __func__,
  15846. linger.l_onoff,
  15847. linger.l_linger,
  15848. strerror(ERRNO));
  15849. }
  15850. }
  15851. /* Now we know that our FIN is ACK-ed, safe to close */
  15852. closesocket(conn->client.sock);
  15853. conn->client.sock = INVALID_SOCKET;
  15854. }
  15855. #endif
  15856. static void
  15857. close_connection(struct mg_connection *conn)
  15858. {
  15859. #if defined(USE_SERVER_STATS)
  15860. conn->conn_state = 6; /* to close */
  15861. #endif
  15862. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15863. if (conn->lua_websocket_state) {
  15864. lua_websocket_close(conn, conn->lua_websocket_state);
  15865. conn->lua_websocket_state = NULL;
  15866. }
  15867. #endif
  15868. mg_lock_connection(conn);
  15869. /* Set close flag, so keep-alive loops will stop */
  15870. conn->must_close = 1;
  15871. /* call the connection_close callback if assigned */
  15872. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15873. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15874. conn->phys_ctx->callbacks.connection_close(conn);
  15875. }
  15876. }
  15877. /* Reset user data, after close callback is called.
  15878. * Do not reuse it. If the user needs a destructor,
  15879. * it must be done in the connection_close callback. */
  15880. mg_set_user_connection_data(conn, NULL);
  15881. #if defined(USE_SERVER_STATS)
  15882. conn->conn_state = 7; /* closing */
  15883. #endif
  15884. #if defined(USE_MBEDTLS)
  15885. if (conn->ssl != NULL) {
  15886. mbed_ssl_close(conn->ssl);
  15887. conn->ssl = NULL;
  15888. }
  15889. #elif defined(USE_GNUTLS)
  15890. if (conn->ssl != NULL) {
  15891. gtls_ssl_close(conn->ssl);
  15892. conn->ssl = NULL;
  15893. }
  15894. #elif !defined(NO_SSL)
  15895. if (conn->ssl != NULL) {
  15896. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15897. */
  15898. SSL_shutdown(conn->ssl);
  15899. SSL_free(conn->ssl);
  15900. OPENSSL_REMOVE_THREAD_STATE();
  15901. conn->ssl = NULL;
  15902. }
  15903. #endif
  15904. if (conn->client.sock != INVALID_SOCKET) {
  15905. #if defined(__ZEPHYR__)
  15906. closesocket(conn->client.sock);
  15907. #else
  15908. close_socket_gracefully(conn);
  15909. #endif
  15910. conn->client.sock = INVALID_SOCKET;
  15911. }
  15912. /* call the connection_closed callback if assigned */
  15913. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15914. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15915. conn->phys_ctx->callbacks.connection_closed(conn);
  15916. }
  15917. }
  15918. mg_unlock_connection(conn);
  15919. #if defined(USE_SERVER_STATS)
  15920. conn->conn_state = 8; /* closed */
  15921. #endif
  15922. }
  15923. CIVETWEB_API void
  15924. mg_close_connection(struct mg_connection *conn)
  15925. {
  15926. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15927. return;
  15928. }
  15929. #if defined(USE_WEBSOCKET)
  15930. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15931. if (conn->in_websocket_handling) {
  15932. /* Set close flag, so the server thread can exit. */
  15933. conn->must_close = 1;
  15934. return;
  15935. }
  15936. }
  15937. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15938. unsigned int i;
  15939. /* client context: loops must end */
  15940. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15941. conn->must_close = 1;
  15942. /* We need to get the client thread out of the select/recv call
  15943. * here. */
  15944. /* Since we use a sleep quantum of some seconds to check for recv
  15945. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15946. /* join worker thread */
  15947. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15948. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15949. }
  15950. }
  15951. #endif /* defined(USE_WEBSOCKET) */
  15952. close_connection(conn);
  15953. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  15954. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  15955. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15956. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15957. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15958. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15959. }
  15960. #endif
  15961. #if defined(USE_WEBSOCKET)
  15962. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15963. mg_free(conn->phys_ctx->worker_threadids);
  15964. (void)pthread_mutex_destroy(&conn->mutex);
  15965. mg_free(conn);
  15966. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15967. (void)pthread_mutex_destroy(&conn->mutex);
  15968. mg_free(conn);
  15969. }
  15970. #else
  15971. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15972. (void)pthread_mutex_destroy(&conn->mutex);
  15973. mg_free(conn);
  15974. }
  15975. #endif /* defined(USE_WEBSOCKET) */
  15976. }
  15977. static struct mg_connection *
  15978. mg_connect_client_impl(const struct mg_client_options *client_options,
  15979. int use_ssl,
  15980. struct mg_init_data *init,
  15981. struct mg_error_data *error)
  15982. {
  15983. struct mg_connection *conn = NULL;
  15984. SOCKET sock;
  15985. union usa sa;
  15986. struct sockaddr *psa;
  15987. socklen_t len;
  15988. unsigned max_req_size =
  15989. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15990. /* Size of structures, aligned to 8 bytes */
  15991. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15992. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15993. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15994. (void)init; /* TODO: Implement required options */
  15995. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15996. if (error != NULL) {
  15997. error->code = MG_ERROR_DATA_CODE_OK;
  15998. error->code_sub = 0;
  15999. if (error->text_buffer_size > 0) {
  16000. error->text[0] = 0;
  16001. }
  16002. }
  16003. if (conn == NULL) {
  16004. if (error != NULL) {
  16005. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  16006. error->code_sub = (unsigned)alloc_size;
  16007. mg_snprintf(NULL,
  16008. NULL, /* No truncation check for ebuf */
  16009. error->text,
  16010. error->text_buffer_size,
  16011. "calloc(): %s",
  16012. strerror(ERRNO));
  16013. }
  16014. return NULL;
  16015. }
  16016. #if defined(GCC_DIAGNOSTIC)
  16017. #pragma GCC diagnostic push
  16018. #pragma GCC diagnostic ignored "-Wcast-align"
  16019. #endif /* defined(GCC_DIAGNOSTIC) */
  16020. /* conn_size is aligned to 8 bytes */
  16021. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  16022. #if defined(GCC_DIAGNOSTIC)
  16023. #pragma GCC diagnostic pop
  16024. #endif /* defined(GCC_DIAGNOSTIC) */
  16025. conn->buf = (((char *)conn) + conn_size + ctx_size);
  16026. conn->buf_size = (int)max_req_size;
  16027. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  16028. conn->dom_ctx = &(conn->phys_ctx->dd);
  16029. if (!connect_socket(conn->phys_ctx,
  16030. client_options->host,
  16031. client_options->port,
  16032. use_ssl,
  16033. error,
  16034. &sock,
  16035. &sa)) {
  16036. /* "error" will be set by connect_socket. */
  16037. /* free all memory and return NULL; */
  16038. mg_free(conn);
  16039. return NULL;
  16040. }
  16041. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16042. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16043. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  16044. && !defined(NO_SSL_DL)
  16045. if (use_ssl
  16046. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  16047. == NULL) {
  16048. if (error != NULL) {
  16049. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16050. mg_snprintf(NULL,
  16051. NULL, /* No truncation check for ebuf */
  16052. error->text,
  16053. error->text_buffer_size,
  16054. "SSL_CTX_new error: %s",
  16055. ssl_error());
  16056. }
  16057. closesocket(sock);
  16058. mg_free(conn);
  16059. return NULL;
  16060. }
  16061. #else
  16062. if (use_ssl
  16063. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  16064. == NULL) {
  16065. if (error != NULL) {
  16066. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16067. mg_snprintf(NULL,
  16068. NULL, /* No truncation check for ebuf */
  16069. error->text,
  16070. error->text_buffer_size,
  16071. "SSL_CTX_new error: %s",
  16072. ssl_error());
  16073. }
  16074. closesocket(sock);
  16075. mg_free(conn);
  16076. return NULL;
  16077. }
  16078. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  16079. #endif /* NO_SSL */
  16080. #if defined(USE_IPV6)
  16081. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  16082. : sizeof(conn->client.rsa.sin6);
  16083. psa = (sa.sa.sa_family == AF_INET)
  16084. ? (struct sockaddr *)&(conn->client.rsa.sin)
  16085. : (struct sockaddr *)&(conn->client.rsa.sin6);
  16086. #else
  16087. len = sizeof(conn->client.rsa.sin);
  16088. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  16089. #endif
  16090. conn->client.sock = sock;
  16091. conn->client.lsa = sa;
  16092. if (getsockname(sock, psa, &len) != 0) {
  16093. mg_cry_internal(conn,
  16094. "%s: getsockname() failed: %s",
  16095. __func__,
  16096. strerror(ERRNO));
  16097. }
  16098. conn->client.is_ssl = use_ssl ? 1 : 0;
  16099. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16100. if (error != NULL) {
  16101. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  16102. error->code_sub = (unsigned)ERRNO;
  16103. mg_snprintf(NULL,
  16104. NULL, /* No truncation check for ebuf */
  16105. error->text,
  16106. error->text_buffer_size,
  16107. "Can not create mutex");
  16108. }
  16109. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16110. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16111. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16112. #endif
  16113. closesocket(sock);
  16114. mg_free(conn);
  16115. return NULL;
  16116. }
  16117. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16118. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16119. if (use_ssl) {
  16120. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  16121. * SSL_CTX_set_verify call is needed to switch off server
  16122. * certificate checking, which is off by default in OpenSSL and
  16123. * on in yaSSL. */
  16124. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  16125. * SSL_VERIFY_PEER, verify_ssl_server); */
  16126. if (client_options->client_cert) {
  16127. if (!ssl_use_pem_file(conn->phys_ctx,
  16128. conn->dom_ctx,
  16129. client_options->client_cert,
  16130. NULL)) {
  16131. if (error != NULL) {
  16132. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  16133. mg_snprintf(NULL,
  16134. NULL, /* No truncation check for ebuf */
  16135. error->text,
  16136. error->text_buffer_size,
  16137. "Can not use SSL client certificate");
  16138. }
  16139. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16140. closesocket(sock);
  16141. mg_free(conn);
  16142. return NULL;
  16143. }
  16144. }
  16145. if (client_options->server_cert) {
  16146. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  16147. client_options->server_cert,
  16148. NULL)
  16149. != 1) {
  16150. if (error != NULL) {
  16151. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  16152. mg_snprintf(NULL,
  16153. NULL, /* No truncation check for ebuf */
  16154. error->text,
  16155. error->text_buffer_size,
  16156. "SSL_CTX_load_verify_locations error: %s",
  16157. ssl_error());
  16158. }
  16159. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16160. closesocket(sock);
  16161. mg_free(conn);
  16162. return NULL;
  16163. }
  16164. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  16165. } else {
  16166. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  16167. }
  16168. if (!sslize(conn, SSL_connect, client_options)) {
  16169. if (error != NULL) {
  16170. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  16171. mg_snprintf(NULL,
  16172. NULL, /* No truncation check for ebuf */
  16173. error->text,
  16174. error->text_buffer_size,
  16175. "SSL connection error");
  16176. }
  16177. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16178. closesocket(sock);
  16179. mg_free(conn);
  16180. return NULL;
  16181. }
  16182. }
  16183. #endif
  16184. return conn;
  16185. }
  16186. CIVETWEB_API struct mg_connection *
  16187. mg_connect_client_secure(const struct mg_client_options *client_options,
  16188. char *error_buffer,
  16189. size_t error_buffer_size)
  16190. {
  16191. struct mg_init_data init;
  16192. struct mg_error_data error;
  16193. memset(&init, 0, sizeof(init));
  16194. memset(&error, 0, sizeof(error));
  16195. error.text_buffer_size = error_buffer_size;
  16196. error.text = error_buffer;
  16197. return mg_connect_client_impl(client_options, 1, &init, &error);
  16198. }
  16199. CIVETWEB_API struct mg_connection *
  16200. mg_connect_client(const char *host,
  16201. int port,
  16202. int use_ssl,
  16203. char *error_buffer,
  16204. size_t error_buffer_size)
  16205. {
  16206. struct mg_client_options opts;
  16207. struct mg_init_data init;
  16208. struct mg_error_data error;
  16209. memset(&init, 0, sizeof(init));
  16210. memset(&error, 0, sizeof(error));
  16211. error.text_buffer_size = error_buffer_size;
  16212. error.text = error_buffer;
  16213. memset(&opts, 0, sizeof(opts));
  16214. opts.host = host;
  16215. opts.port = port;
  16216. if (use_ssl) {
  16217. opts.host_name = host;
  16218. }
  16219. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  16220. }
  16221. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16222. CIVETWEB_API struct mg_connection *
  16223. mg_connect_client2(const char *host,
  16224. const char *protocol,
  16225. int port,
  16226. const char *path,
  16227. struct mg_init_data *init,
  16228. struct mg_error_data *error)
  16229. {
  16230. (void)path;
  16231. int is_ssl, is_ws;
  16232. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  16233. if (error != NULL) {
  16234. error->code = MG_ERROR_DATA_CODE_OK;
  16235. error->code_sub = 0;
  16236. if (error->text_buffer_size > 0) {
  16237. *error->text = 0;
  16238. }
  16239. }
  16240. if ((host == NULL) || (protocol == NULL)) {
  16241. if (error != NULL) {
  16242. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16243. mg_snprintf(NULL,
  16244. NULL, /* No truncation check for error buffers */
  16245. error->text,
  16246. error->text_buffer_size,
  16247. "%s",
  16248. "Invalid parameters");
  16249. }
  16250. return NULL;
  16251. }
  16252. /* check all known protocols */
  16253. if (!mg_strcasecmp(protocol, "http")) {
  16254. is_ssl = 0;
  16255. is_ws = 0;
  16256. } else if (!mg_strcasecmp(protocol, "https")) {
  16257. is_ssl = 1;
  16258. is_ws = 0;
  16259. #if defined(USE_WEBSOCKET)
  16260. } else if (!mg_strcasecmp(protocol, "ws")) {
  16261. is_ssl = 0;
  16262. is_ws = 1;
  16263. } else if (!mg_strcasecmp(protocol, "wss")) {
  16264. is_ssl = 1;
  16265. is_ws = 1;
  16266. #endif
  16267. } else {
  16268. if (error != NULL) {
  16269. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16270. mg_snprintf(NULL,
  16271. NULL, /* No truncation check for error buffers */
  16272. error->text,
  16273. error->text_buffer_size,
  16274. "Protocol %s not supported",
  16275. protocol);
  16276. }
  16277. return NULL;
  16278. }
  16279. /* TODO: The current implementation here just calls the old
  16280. * implementations, without using any new options. This is just a first
  16281. * step to test the new interfaces. */
  16282. #if defined(USE_WEBSOCKET)
  16283. if (is_ws) {
  16284. /* TODO: implement all options */
  16285. return mg_connect_websocket_client(
  16286. host,
  16287. port,
  16288. is_ssl,
  16289. ((error != NULL) ? error->text : NULL),
  16290. ((error != NULL) ? error->text_buffer_size : 0),
  16291. (path ? path : ""),
  16292. NULL /* TODO: origin */,
  16293. experimental_websocket_client_data_wrapper,
  16294. experimental_websocket_client_close_wrapper,
  16295. (void *)init->callbacks);
  16296. }
  16297. #else
  16298. (void)is_ws;
  16299. #endif
  16300. /* TODO: all additional options */
  16301. struct mg_client_options opts;
  16302. memset(&opts, 0, sizeof(opts));
  16303. opts.host = host;
  16304. opts.port = port;
  16305. return mg_connect_client_impl(&opts, is_ssl, init, error);
  16306. }
  16307. #endif
  16308. static const struct {
  16309. const char *proto;
  16310. size_t proto_len;
  16311. unsigned default_port;
  16312. } abs_uri_protocols[] = {{"http://", 7, 80},
  16313. {"https://", 8, 443},
  16314. {"ws://", 5, 80},
  16315. {"wss://", 6, 443},
  16316. {NULL, 0, 0}};
  16317. /* Check if the uri is valid.
  16318. * return 0 for invalid uri,
  16319. * return 1 for *,
  16320. * return 2 for relative uri,
  16321. * return 3 for absolute uri without port,
  16322. * return 4 for absolute uri with port */
  16323. static int
  16324. get_uri_type(const char *uri)
  16325. {
  16326. int i;
  16327. const char *hostend, *portbegin;
  16328. char *portend;
  16329. unsigned long port;
  16330. /* According to the HTTP standard
  16331. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  16332. * URI can be an asterisk (*) or should start with slash (relative uri),
  16333. * or it should start with the protocol (absolute uri). */
  16334. if ((uri[0] == '*') && (uri[1] == '\0')) {
  16335. /* asterisk */
  16336. return 1;
  16337. }
  16338. /* Valid URIs according to RFC 3986
  16339. * (https://www.ietf.org/rfc/rfc3986.txt)
  16340. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16341. * and unreserved characters A-Z a-z 0-9 and -._~
  16342. * and % encoded symbols.
  16343. */
  16344. for (i = 0; uri[i] != 0; i++) {
  16345. if ((unsigned char)uri[i] < 33) {
  16346. /* control characters and spaces are invalid */
  16347. return 0;
  16348. }
  16349. /* Allow everything else here (See #894) */
  16350. }
  16351. /* A relative uri starts with a / character */
  16352. if (uri[0] == '/') {
  16353. /* relative uri */
  16354. return 2;
  16355. }
  16356. /* It could be an absolute uri: */
  16357. /* This function only checks if the uri is valid, not if it is
  16358. * addressing the current server. So civetweb can also be used
  16359. * as a proxy server. */
  16360. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16361. if (mg_strncasecmp(uri,
  16362. abs_uri_protocols[i].proto,
  16363. abs_uri_protocols[i].proto_len)
  16364. == 0) {
  16365. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16366. if (!hostend) {
  16367. return 0;
  16368. }
  16369. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16370. if (!portbegin) {
  16371. return 3;
  16372. }
  16373. port = strtoul(portbegin + 1, &portend, 10);
  16374. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16375. return 0;
  16376. }
  16377. return 4;
  16378. }
  16379. }
  16380. return 0;
  16381. }
  16382. /* Return NULL or the relative uri at the current server */
  16383. static const char *
  16384. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16385. {
  16386. const char *server_domain;
  16387. size_t server_domain_len;
  16388. size_t request_domain_len = 0;
  16389. unsigned long port = 0;
  16390. int i, auth_domain_check_enabled;
  16391. const char *hostbegin = NULL;
  16392. const char *hostend = NULL;
  16393. const char *portbegin;
  16394. char *portend;
  16395. auth_domain_check_enabled =
  16396. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16397. /* DNS is case insensitive, so use case insensitive string compare here
  16398. */
  16399. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16400. if (mg_strncasecmp(uri,
  16401. abs_uri_protocols[i].proto,
  16402. abs_uri_protocols[i].proto_len)
  16403. == 0) {
  16404. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16405. hostend = strchr(hostbegin, '/');
  16406. if (!hostend) {
  16407. return 0;
  16408. }
  16409. portbegin = strchr(hostbegin, ':');
  16410. if ((!portbegin) || (portbegin > hostend)) {
  16411. port = abs_uri_protocols[i].default_port;
  16412. request_domain_len = (size_t)(hostend - hostbegin);
  16413. } else {
  16414. port = strtoul(portbegin + 1, &portend, 10);
  16415. if ((portend != hostend) || (port <= 0)
  16416. || !is_valid_port(port)) {
  16417. return 0;
  16418. }
  16419. request_domain_len = (size_t)(portbegin - hostbegin);
  16420. }
  16421. /* protocol found, port set */
  16422. break;
  16423. }
  16424. }
  16425. if (!port) {
  16426. /* port remains 0 if the protocol is not found */
  16427. return 0;
  16428. }
  16429. /* Check if the request is directed to a different server. */
  16430. /* First check if the port is the same. */
  16431. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16432. /* Request is directed to a different port */
  16433. return 0;
  16434. }
  16435. /* Finally check if the server corresponds to the authentication
  16436. * domain of the server (the server domain).
  16437. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16438. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16439. * but do not allow substrings (like
  16440. * http://notmydomain.com/path/file.ext
  16441. * or http://mydomain.com.fake/path/file.ext).
  16442. */
  16443. if (auth_domain_check_enabled) {
  16444. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16445. server_domain_len = strlen(server_domain);
  16446. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16447. return 0;
  16448. }
  16449. if ((request_domain_len == server_domain_len)
  16450. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16451. /* Request is directed to this server - full name match. */
  16452. } else {
  16453. if (request_domain_len < (server_domain_len + 2)) {
  16454. /* Request is directed to another server: The server name
  16455. * is longer than the request name.
  16456. * Drop this case here to avoid overflows in the
  16457. * following checks. */
  16458. return 0;
  16459. }
  16460. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16461. /* Request is directed to another server: It could be a
  16462. * substring
  16463. * like notmyserver.com */
  16464. return 0;
  16465. }
  16466. if (0
  16467. != memcmp(server_domain,
  16468. hostbegin + request_domain_len - server_domain_len,
  16469. server_domain_len)) {
  16470. /* Request is directed to another server:
  16471. * The server name is different. */
  16472. return 0;
  16473. }
  16474. }
  16475. }
  16476. return hostend;
  16477. }
  16478. static int
  16479. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16480. {
  16481. if (ebuf_len > 0) {
  16482. ebuf[0] = '\0';
  16483. }
  16484. *err = 0;
  16485. reset_per_request_attributes(conn);
  16486. if (!conn) {
  16487. mg_snprintf(conn,
  16488. NULL, /* No truncation check for ebuf */
  16489. ebuf,
  16490. ebuf_len,
  16491. "%s",
  16492. "Internal error");
  16493. *err = 500;
  16494. return 0;
  16495. }
  16496. /* Set the time the request was received. This value should be used for
  16497. * timeouts. */
  16498. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16499. conn->request_len =
  16500. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16501. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16502. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16503. mg_snprintf(conn,
  16504. NULL, /* No truncation check for ebuf */
  16505. ebuf,
  16506. ebuf_len,
  16507. "%s",
  16508. "Invalid message size");
  16509. *err = 500;
  16510. return 0;
  16511. }
  16512. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16513. mg_snprintf(conn,
  16514. NULL, /* No truncation check for ebuf */
  16515. ebuf,
  16516. ebuf_len,
  16517. "%s",
  16518. "Message too large");
  16519. *err = 413;
  16520. return 0;
  16521. }
  16522. if (conn->request_len <= 0) {
  16523. if (conn->data_len > 0) {
  16524. mg_snprintf(conn,
  16525. NULL, /* No truncation check for ebuf */
  16526. ebuf,
  16527. ebuf_len,
  16528. "%s",
  16529. conn->request_len == -3 ? "Request timeout"
  16530. : "Malformed message");
  16531. *err = 400;
  16532. } else {
  16533. /* Server did not recv anything -> just close the connection */
  16534. conn->must_close = 1;
  16535. mg_snprintf(conn,
  16536. NULL, /* No truncation check for ebuf */
  16537. ebuf,
  16538. ebuf_len,
  16539. "%s",
  16540. "No data received");
  16541. *err = 0;
  16542. }
  16543. return 0;
  16544. }
  16545. return 1;
  16546. }
  16547. static int
  16548. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16549. {
  16550. const char *cl;
  16551. conn->connection_type =
  16552. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16553. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16554. return 0;
  16555. }
  16556. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16557. <= 0) {
  16558. mg_snprintf(conn,
  16559. NULL, /* No truncation check for ebuf */
  16560. ebuf,
  16561. ebuf_len,
  16562. "%s",
  16563. "Bad request");
  16564. *err = 400;
  16565. return 0;
  16566. }
  16567. /* Message is a valid request */
  16568. if (!switch_domain_context(conn)) {
  16569. mg_snprintf(conn,
  16570. NULL, /* No truncation check for ebuf */
  16571. ebuf,
  16572. ebuf_len,
  16573. "%s",
  16574. "Bad request: Host mismatch");
  16575. *err = 400;
  16576. return 0;
  16577. }
  16578. #if USE_ZLIB
  16579. if (((cl = get_header(conn->request_info.http_headers,
  16580. conn->request_info.num_headers,
  16581. "Accept-Encoding"))
  16582. != NULL)
  16583. && strstr(cl, "gzip")) {
  16584. conn->accept_gzip = 1;
  16585. }
  16586. #endif
  16587. if (((cl = get_header(conn->request_info.http_headers,
  16588. conn->request_info.num_headers,
  16589. "Transfer-Encoding"))
  16590. != NULL)
  16591. && mg_strcasecmp(cl, "identity")) {
  16592. if (mg_strcasecmp(cl, "chunked")) {
  16593. mg_snprintf(conn,
  16594. NULL, /* No truncation check for ebuf */
  16595. ebuf,
  16596. ebuf_len,
  16597. "%s",
  16598. "Bad request");
  16599. *err = 400;
  16600. return 0;
  16601. }
  16602. conn->is_chunked = 1;
  16603. conn->content_len = 0; /* not yet read */
  16604. } else if ((cl = get_header(conn->request_info.http_headers,
  16605. conn->request_info.num_headers,
  16606. "Content-Length"))
  16607. != NULL) {
  16608. /* Request has content length set */
  16609. char *endptr = NULL;
  16610. conn->content_len = strtoll(cl, &endptr, 10);
  16611. if ((endptr == cl) || (conn->content_len < 0)) {
  16612. mg_snprintf(conn,
  16613. NULL, /* No truncation check for ebuf */
  16614. ebuf,
  16615. ebuf_len,
  16616. "%s",
  16617. "Bad request");
  16618. *err = 411;
  16619. return 0;
  16620. }
  16621. /* Publish the content length back to the request info. */
  16622. conn->request_info.content_length = conn->content_len;
  16623. } else {
  16624. /* There is no exception, see RFC7230. */
  16625. conn->content_len = 0;
  16626. }
  16627. return 1;
  16628. }
  16629. /* conn is assumed to be valid in this internal function */
  16630. static int
  16631. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16632. {
  16633. const char *cl;
  16634. conn->connection_type =
  16635. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16636. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16637. return 0;
  16638. }
  16639. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16640. <= 0) {
  16641. mg_snprintf(conn,
  16642. NULL, /* No truncation check for ebuf */
  16643. ebuf,
  16644. ebuf_len,
  16645. "%s",
  16646. "Bad response");
  16647. *err = 400;
  16648. return 0;
  16649. }
  16650. /* Message is a valid response */
  16651. if (((cl = get_header(conn->response_info.http_headers,
  16652. conn->response_info.num_headers,
  16653. "Transfer-Encoding"))
  16654. != NULL)
  16655. && mg_strcasecmp(cl, "identity")) {
  16656. if (mg_strcasecmp(cl, "chunked")) {
  16657. mg_snprintf(conn,
  16658. NULL, /* No truncation check for ebuf */
  16659. ebuf,
  16660. ebuf_len,
  16661. "%s",
  16662. "Bad request");
  16663. *err = 400;
  16664. return 0;
  16665. }
  16666. conn->is_chunked = 1;
  16667. conn->content_len = 0; /* not yet read */
  16668. } else if ((cl = get_header(conn->response_info.http_headers,
  16669. conn->response_info.num_headers,
  16670. "Content-Length"))
  16671. != NULL) {
  16672. char *endptr = NULL;
  16673. conn->content_len = strtoll(cl, &endptr, 10);
  16674. if ((endptr == cl) || (conn->content_len < 0)) {
  16675. mg_snprintf(conn,
  16676. NULL, /* No truncation check for ebuf */
  16677. ebuf,
  16678. ebuf_len,
  16679. "%s",
  16680. "Bad request");
  16681. *err = 411;
  16682. return 0;
  16683. }
  16684. /* Publish the content length back to the response info. */
  16685. conn->response_info.content_length = conn->content_len;
  16686. /* TODO: check if it is still used in response_info */
  16687. conn->request_info.content_length = conn->content_len;
  16688. /* TODO: we should also consider HEAD method */
  16689. if (conn->response_info.status_code == 304) {
  16690. conn->content_len = 0;
  16691. }
  16692. } else {
  16693. /* TODO: we should also consider HEAD method */
  16694. if (((conn->response_info.status_code >= 100)
  16695. && (conn->response_info.status_code <= 199))
  16696. || (conn->response_info.status_code == 204)
  16697. || (conn->response_info.status_code == 304)) {
  16698. conn->content_len = 0;
  16699. } else {
  16700. conn->content_len = -1; /* unknown content length */
  16701. }
  16702. }
  16703. return 1;
  16704. }
  16705. CIVETWEB_API int
  16706. mg_get_response(struct mg_connection *conn,
  16707. char *ebuf,
  16708. size_t ebuf_len,
  16709. int timeout)
  16710. {
  16711. int err, ret;
  16712. char txt[32]; /* will not overflow */
  16713. char *save_timeout;
  16714. char *new_timeout;
  16715. if (ebuf_len > 0) {
  16716. ebuf[0] = '\0';
  16717. }
  16718. if (!conn) {
  16719. mg_snprintf(conn,
  16720. NULL, /* No truncation check for ebuf */
  16721. ebuf,
  16722. ebuf_len,
  16723. "%s",
  16724. "Parameter error");
  16725. return -1;
  16726. }
  16727. /* Reset the previous responses */
  16728. conn->data_len = 0;
  16729. /* Implementation of API function for HTTP clients */
  16730. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16731. if (timeout >= 0) {
  16732. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16733. new_timeout = txt;
  16734. } else {
  16735. new_timeout = NULL;
  16736. }
  16737. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16738. ret = get_response(conn, ebuf, ebuf_len, &err);
  16739. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16740. /* TODO: here, the URI is the http response code */
  16741. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16742. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16743. /* TODO (mid): Define proper return values - maybe return length?
  16744. * For the first test use <0 for error and >0 for OK */
  16745. return (ret == 0) ? -1 : +1;
  16746. }
  16747. CIVETWEB_API struct mg_connection *
  16748. mg_download(const char *host,
  16749. int port,
  16750. int use_ssl,
  16751. char *ebuf,
  16752. size_t ebuf_len,
  16753. const char *fmt,
  16754. ...)
  16755. {
  16756. struct mg_connection *conn;
  16757. va_list ap;
  16758. int i;
  16759. int reqerr;
  16760. if (ebuf_len > 0) {
  16761. ebuf[0] = '\0';
  16762. }
  16763. va_start(ap, fmt);
  16764. /* open a connection */
  16765. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16766. if (conn != NULL) {
  16767. i = mg_vprintf(conn, fmt, ap);
  16768. if (i <= 0) {
  16769. mg_snprintf(conn,
  16770. NULL, /* No truncation check for ebuf */
  16771. ebuf,
  16772. ebuf_len,
  16773. "%s",
  16774. "Error sending request");
  16775. } else {
  16776. /* make sure the buffer is clear */
  16777. conn->data_len = 0;
  16778. get_response(conn, ebuf, ebuf_len, &reqerr);
  16779. /* TODO: here, the URI is the http response code */
  16780. conn->request_info.local_uri = conn->request_info.request_uri;
  16781. }
  16782. }
  16783. /* if an error occurred, close the connection */
  16784. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16785. mg_close_connection(conn);
  16786. conn = NULL;
  16787. }
  16788. va_end(ap);
  16789. return conn;
  16790. }
  16791. struct websocket_client_thread_data {
  16792. struct mg_connection *conn;
  16793. mg_websocket_data_handler data_handler;
  16794. mg_websocket_close_handler close_handler;
  16795. void *callback_data;
  16796. };
  16797. #if defined(USE_WEBSOCKET)
  16798. #if defined(_WIN32)
  16799. static unsigned __stdcall websocket_client_thread(void *data)
  16800. #else
  16801. static void *
  16802. websocket_client_thread(void *data)
  16803. #endif
  16804. {
  16805. struct websocket_client_thread_data *cdata =
  16806. (struct websocket_client_thread_data *)data;
  16807. void *user_thread_ptr = NULL;
  16808. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16809. struct sigaction sa;
  16810. /* Ignore SIGPIPE */
  16811. memset(&sa, 0, sizeof(sa));
  16812. sa.sa_handler = SIG_IGN;
  16813. sigaction(SIGPIPE, &sa, NULL);
  16814. #endif
  16815. mg_set_thread_name("ws-clnt");
  16816. if (cdata->conn->phys_ctx) {
  16817. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16818. /* 3 indicates a websocket client thread */
  16819. /* TODO: check if conn->phys_ctx can be set */
  16820. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16821. cdata->conn->phys_ctx, 3);
  16822. }
  16823. }
  16824. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16825. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16826. if (cdata->close_handler != NULL) {
  16827. cdata->close_handler(cdata->conn, cdata->callback_data);
  16828. }
  16829. /* The websocket_client context has only this thread. If it runs out,
  16830. set the stop_flag to 2 (= "stopped"). */
  16831. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16832. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16833. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16834. 3,
  16835. user_thread_ptr);
  16836. }
  16837. mg_free((void *)cdata);
  16838. #if defined(_WIN32)
  16839. return 0;
  16840. #else
  16841. return NULL;
  16842. #endif
  16843. }
  16844. #endif
  16845. #if defined(USE_WEBSOCKET)
  16846. static void
  16847. generate_websocket_magic(char *magic25)
  16848. {
  16849. uint64_t rnd;
  16850. unsigned char buffer[2 * sizeof(rnd)];
  16851. rnd = get_random();
  16852. memcpy(buffer, &rnd, sizeof(rnd));
  16853. rnd = get_random();
  16854. memcpy(buffer + sizeof(rnd), &rnd, sizeof(rnd));
  16855. size_t dst_len = 24 + 1;
  16856. mg_base64_encode(buffer, sizeof(buffer), magic25, &dst_len);
  16857. }
  16858. #endif
  16859. static struct mg_connection *
  16860. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16861. int use_ssl,
  16862. char *error_buffer,
  16863. size_t error_buffer_size,
  16864. const char *path,
  16865. const char *origin,
  16866. const char *extensions,
  16867. mg_websocket_data_handler data_func,
  16868. mg_websocket_close_handler close_func,
  16869. void *user_data)
  16870. {
  16871. struct mg_connection *conn = NULL;
  16872. #if defined(USE_WEBSOCKET)
  16873. struct websocket_client_thread_data *thread_data;
  16874. char magic[32];
  16875. generate_websocket_magic(magic);
  16876. const char *host = client_options->host;
  16877. int i;
  16878. struct mg_init_data init;
  16879. struct mg_error_data error;
  16880. memset(&init, 0, sizeof(init));
  16881. memset(&error, 0, sizeof(error));
  16882. error.text_buffer_size = error_buffer_size;
  16883. error.text = error_buffer;
  16884. #if defined(__clang__)
  16885. #pragma clang diagnostic push
  16886. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16887. #endif
  16888. /* Establish the client connection and request upgrade */
  16889. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16890. /* Connection object will be null if something goes wrong */
  16891. if (conn == NULL) {
  16892. /* error_buffer should be already filled ... */
  16893. if (!error_buffer[0]) {
  16894. /* ... if not add an error message */
  16895. mg_snprintf(conn,
  16896. NULL, /* No truncation check for ebuf */
  16897. error_buffer,
  16898. error_buffer_size,
  16899. "Unexpected error");
  16900. }
  16901. return NULL;
  16902. }
  16903. if (origin != NULL) {
  16904. if (extensions != NULL) {
  16905. i = mg_printf(conn,
  16906. "GET %s HTTP/1.1\r\n"
  16907. "Host: %s\r\n"
  16908. "Upgrade: websocket\r\n"
  16909. "Connection: Upgrade\r\n"
  16910. "Sec-WebSocket-Key: %s\r\n"
  16911. "Sec-WebSocket-Version: 13\r\n"
  16912. "Sec-WebSocket-Extensions: %s\r\n"
  16913. "Origin: %s\r\n"
  16914. "\r\n",
  16915. path,
  16916. host,
  16917. magic,
  16918. extensions,
  16919. origin);
  16920. } else {
  16921. i = mg_printf(conn,
  16922. "GET %s HTTP/1.1\r\n"
  16923. "Host: %s\r\n"
  16924. "Upgrade: websocket\r\n"
  16925. "Connection: Upgrade\r\n"
  16926. "Sec-WebSocket-Key: %s\r\n"
  16927. "Sec-WebSocket-Version: 13\r\n"
  16928. "Origin: %s\r\n"
  16929. "\r\n",
  16930. path,
  16931. host,
  16932. magic,
  16933. origin);
  16934. }
  16935. } else {
  16936. if (extensions != NULL) {
  16937. i = mg_printf(conn,
  16938. "GET %s HTTP/1.1\r\n"
  16939. "Host: %s\r\n"
  16940. "Upgrade: websocket\r\n"
  16941. "Connection: Upgrade\r\n"
  16942. "Sec-WebSocket-Key: %s\r\n"
  16943. "Sec-WebSocket-Version: 13\r\n"
  16944. "Sec-WebSocket-Extensions: %s\r\n"
  16945. "\r\n",
  16946. path,
  16947. host,
  16948. magic,
  16949. extensions);
  16950. } else {
  16951. i = mg_printf(conn,
  16952. "GET %s HTTP/1.1\r\n"
  16953. "Host: %s\r\n"
  16954. "Upgrade: websocket\r\n"
  16955. "Connection: Upgrade\r\n"
  16956. "Sec-WebSocket-Key: %s\r\n"
  16957. "Sec-WebSocket-Version: 13\r\n"
  16958. "\r\n",
  16959. path,
  16960. host,
  16961. magic);
  16962. }
  16963. }
  16964. if (i <= 0) {
  16965. mg_snprintf(conn,
  16966. NULL, /* No truncation check for ebuf */
  16967. error_buffer,
  16968. error_buffer_size,
  16969. "%s",
  16970. "Error sending request");
  16971. mg_close_connection(conn);
  16972. return NULL;
  16973. }
  16974. conn->data_len = 0;
  16975. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16976. mg_close_connection(conn);
  16977. return NULL;
  16978. }
  16979. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16980. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16981. #if defined(__clang__)
  16982. #pragma clang diagnostic pop
  16983. #endif
  16984. if (conn->response_info.status_code != 101) {
  16985. /* We sent an "upgrade" request. For a correct websocket
  16986. * protocol handshake, we expect a "101 Continue" response.
  16987. * Otherwise it is a protocol violation. Maybe the HTTP
  16988. * Server does not know websockets. */
  16989. if (!*error_buffer) {
  16990. /* set an error, if not yet set */
  16991. mg_snprintf(conn,
  16992. NULL, /* No truncation check for ebuf */
  16993. error_buffer,
  16994. error_buffer_size,
  16995. "Unexpected server reply");
  16996. }
  16997. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16998. mg_close_connection(conn);
  16999. return NULL;
  17000. }
  17001. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  17002. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  17003. if (!thread_data) {
  17004. DEBUG_TRACE("%s\r\n", "Out of memory");
  17005. mg_close_connection(conn);
  17006. return NULL;
  17007. }
  17008. thread_data->conn = conn;
  17009. thread_data->data_handler = data_func;
  17010. thread_data->close_handler = close_func;
  17011. thread_data->callback_data = user_data;
  17012. conn->phys_ctx->worker_threadids =
  17013. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  17014. if (!conn->phys_ctx->worker_threadids) {
  17015. DEBUG_TRACE("%s\r\n", "Out of memory");
  17016. mg_free(thread_data);
  17017. mg_close_connection(conn);
  17018. return NULL;
  17019. }
  17020. /* Now upgrade to ws/wss client context */
  17021. conn->phys_ctx->user_data = user_data;
  17022. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  17023. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  17024. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  17025. /* Start a thread to read the websocket client connection
  17026. * This thread will automatically stop when mg_disconnect is
  17027. * called on the client connection */
  17028. if (mg_start_thread_with_id(websocket_client_thread,
  17029. thread_data,
  17030. conn->phys_ctx->worker_threadids)
  17031. != 0) {
  17032. conn->phys_ctx->spawned_worker_threads = 0;
  17033. mg_free(thread_data);
  17034. mg_close_connection(conn);
  17035. conn = NULL;
  17036. DEBUG_TRACE("%s",
  17037. "Websocket client connect thread could not be started\r\n");
  17038. }
  17039. #else
  17040. /* Appease "unused parameter" warnings */
  17041. (void)client_options;
  17042. (void)use_ssl;
  17043. (void)error_buffer;
  17044. (void)error_buffer_size;
  17045. (void)path;
  17046. (void)origin;
  17047. (void)extensions;
  17048. (void)user_data;
  17049. (void)data_func;
  17050. (void)close_func;
  17051. #endif
  17052. return conn;
  17053. }
  17054. CIVETWEB_API struct mg_connection *
  17055. mg_connect_websocket_client(const char *host,
  17056. int port,
  17057. int use_ssl,
  17058. char *error_buffer,
  17059. size_t error_buffer_size,
  17060. const char *path,
  17061. const char *origin,
  17062. mg_websocket_data_handler data_func,
  17063. mg_websocket_close_handler close_func,
  17064. void *user_data)
  17065. {
  17066. struct mg_client_options client_options;
  17067. memset(&client_options, 0, sizeof(client_options));
  17068. client_options.host = host;
  17069. client_options.port = port;
  17070. if (use_ssl) {
  17071. client_options.host_name = host;
  17072. }
  17073. return mg_connect_websocket_client_impl(&client_options,
  17074. use_ssl,
  17075. error_buffer,
  17076. error_buffer_size,
  17077. path,
  17078. origin,
  17079. NULL,
  17080. data_func,
  17081. close_func,
  17082. user_data);
  17083. }
  17084. CIVETWEB_API struct mg_connection *
  17085. mg_connect_websocket_client_secure(
  17086. const struct mg_client_options *client_options,
  17087. char *error_buffer,
  17088. size_t error_buffer_size,
  17089. const char *path,
  17090. const char *origin,
  17091. mg_websocket_data_handler data_func,
  17092. mg_websocket_close_handler close_func,
  17093. void *user_data)
  17094. {
  17095. if (!client_options) {
  17096. return NULL;
  17097. }
  17098. return mg_connect_websocket_client_impl(client_options,
  17099. 1,
  17100. error_buffer,
  17101. error_buffer_size,
  17102. path,
  17103. origin,
  17104. NULL,
  17105. data_func,
  17106. close_func,
  17107. user_data);
  17108. }
  17109. CIVETWEB_API struct mg_connection *
  17110. mg_connect_websocket_client_extensions(const char *host,
  17111. int port,
  17112. int use_ssl,
  17113. char *error_buffer,
  17114. size_t error_buffer_size,
  17115. const char *path,
  17116. const char *origin,
  17117. const char *extensions,
  17118. mg_websocket_data_handler data_func,
  17119. mg_websocket_close_handler close_func,
  17120. void *user_data)
  17121. {
  17122. struct mg_client_options client_options;
  17123. memset(&client_options, 0, sizeof(client_options));
  17124. client_options.host = host;
  17125. client_options.port = port;
  17126. return mg_connect_websocket_client_impl(&client_options,
  17127. use_ssl,
  17128. error_buffer,
  17129. error_buffer_size,
  17130. path,
  17131. origin,
  17132. extensions,
  17133. data_func,
  17134. close_func,
  17135. user_data);
  17136. }
  17137. CIVETWEB_API struct mg_connection *
  17138. mg_connect_websocket_client_secure_extensions(
  17139. const struct mg_client_options *client_options,
  17140. char *error_buffer,
  17141. size_t error_buffer_size,
  17142. const char *path,
  17143. const char *origin,
  17144. const char *extensions,
  17145. mg_websocket_data_handler data_func,
  17146. mg_websocket_close_handler close_func,
  17147. void *user_data)
  17148. {
  17149. if (!client_options) {
  17150. return NULL;
  17151. }
  17152. return mg_connect_websocket_client_impl(client_options,
  17153. 1,
  17154. error_buffer,
  17155. error_buffer_size,
  17156. path,
  17157. origin,
  17158. extensions,
  17159. data_func,
  17160. close_func,
  17161. user_data);
  17162. }
  17163. /* Prepare connection data structure */
  17164. static void
  17165. init_connection(struct mg_connection *conn)
  17166. {
  17167. /* Is keep alive allowed by the server */
  17168. int keep_alive_enabled =
  17169. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  17170. if (!keep_alive_enabled) {
  17171. conn->must_close = 1;
  17172. }
  17173. /* Important: on new connection, reset the receiving buffer. Credit
  17174. * goes to crule42. */
  17175. conn->data_len = 0;
  17176. conn->handled_requests = 0;
  17177. conn->connection_type = CONNECTION_TYPE_INVALID;
  17178. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  17179. mg_set_user_connection_data(conn, NULL);
  17180. #if defined(USE_SERVER_STATS)
  17181. conn->conn_state = 2; /* init */
  17182. #endif
  17183. /* call the init_connection callback if assigned */
  17184. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  17185. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  17186. void *conn_data = NULL;
  17187. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  17188. mg_set_user_connection_data(conn, conn_data);
  17189. }
  17190. }
  17191. }
  17192. /* Process a connection - may handle multiple requests
  17193. * using the same connection.
  17194. * Must be called with a valid connection (conn and
  17195. * conn->phys_ctx must be valid).
  17196. */
  17197. static void
  17198. process_new_connection(struct mg_connection *conn)
  17199. {
  17200. struct mg_request_info *ri = &conn->request_info;
  17201. int keep_alive, discard_len;
  17202. char ebuf[100];
  17203. const char *hostend;
  17204. int reqerr, uri_type;
  17205. #if defined(USE_SERVER_STATS)
  17206. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  17207. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  17208. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  17209. #endif
  17210. DEBUG_TRACE("Start processing connection from %s",
  17211. conn->request_info.remote_addr);
  17212. /* Loop over multiple requests sent using the same connection
  17213. * (while "keep alive"). */
  17214. do {
  17215. DEBUG_TRACE("calling get_request (%i times for this connection)",
  17216. conn->handled_requests + 1);
  17217. #if defined(USE_SERVER_STATS)
  17218. conn->conn_state = 3; /* ready */
  17219. #endif
  17220. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  17221. /* The request sent by the client could not be understood by
  17222. * the server, or it was incomplete or a timeout. Send an
  17223. * error message and close the connection. */
  17224. if (reqerr > 0) {
  17225. DEBUG_ASSERT(ebuf[0] != '\0');
  17226. mg_send_http_error(conn, reqerr, "%s", ebuf);
  17227. }
  17228. } else if (strcmp(ri->http_version, "1.0")
  17229. && strcmp(ri->http_version, "1.1")) {
  17230. /* HTTP/2 is not allowed here */
  17231. mg_snprintf(conn,
  17232. NULL, /* No truncation check for ebuf */
  17233. ebuf,
  17234. sizeof(ebuf),
  17235. "Bad HTTP version: [%s]",
  17236. ri->http_version);
  17237. mg_send_http_error(conn, 505, "%s", ebuf);
  17238. }
  17239. if (ebuf[0] == '\0') {
  17240. uri_type = get_uri_type(conn->request_info.request_uri);
  17241. switch (uri_type) {
  17242. case 1:
  17243. /* Asterisk */
  17244. conn->request_info.local_uri_raw = 0;
  17245. /* TODO: Deal with '*'. */
  17246. break;
  17247. case 2:
  17248. /* relative uri */
  17249. conn->request_info.local_uri_raw =
  17250. conn->request_info.request_uri;
  17251. break;
  17252. case 3:
  17253. case 4:
  17254. /* absolute uri (with/without port) */
  17255. hostend = get_rel_url_at_current_server(
  17256. conn->request_info.request_uri, conn);
  17257. if (hostend) {
  17258. conn->request_info.local_uri_raw = hostend;
  17259. } else {
  17260. conn->request_info.local_uri_raw = NULL;
  17261. }
  17262. break;
  17263. default:
  17264. mg_snprintf(conn,
  17265. NULL, /* No truncation check for ebuf */
  17266. ebuf,
  17267. sizeof(ebuf),
  17268. "Invalid URI");
  17269. mg_send_http_error(conn, 400, "%s", ebuf);
  17270. conn->request_info.local_uri_raw = NULL;
  17271. break;
  17272. }
  17273. conn->request_info.local_uri =
  17274. (char *)conn->request_info.local_uri_raw;
  17275. }
  17276. if (ebuf[0] != '\0') {
  17277. conn->protocol_type = -1;
  17278. } else {
  17279. /* HTTP/1 allows protocol upgrade */
  17280. conn->protocol_type = should_switch_to_protocol(conn);
  17281. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  17282. /* This will occur, if a HTTP/1.1 request should be upgraded
  17283. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  17284. * Since most (all?) major browsers only support HTTP/2 using
  17285. * ALPN, this is hard to test and very low priority.
  17286. * Deactivate it (at least for now).
  17287. */
  17288. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17289. }
  17290. }
  17291. DEBUG_TRACE("http: %s, error: %s",
  17292. (ri->http_version ? ri->http_version : "none"),
  17293. (ebuf[0] ? ebuf : "none"));
  17294. if (ebuf[0] == '\0') {
  17295. if (conn->request_info.local_uri) {
  17296. /* handle request to local server */
  17297. handle_request_stat_log(conn);
  17298. } else {
  17299. /* TODO: handle non-local request (PROXY) */
  17300. conn->must_close = 1;
  17301. }
  17302. } else {
  17303. conn->must_close = 1;
  17304. }
  17305. /* Response complete. Free header buffer */
  17306. free_buffered_response_header_list(conn);
  17307. if (ri->remote_user != NULL) {
  17308. mg_free((void *)ri->remote_user);
  17309. /* Important! When having connections with and without auth
  17310. * would cause double free and then crash */
  17311. ri->remote_user = NULL;
  17312. }
  17313. /* NOTE(lsm): order is important here. should_keep_alive() call
  17314. * is using parsed request, which will be invalid after
  17315. * memmove's below.
  17316. * Therefore, memorize should_keep_alive() result now for later
  17317. * use in loop exit condition. */
  17318. /* Enable it only if this request is completely discardable. */
  17319. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  17320. && should_keep_alive(conn) && (conn->content_len >= 0)
  17321. && (conn->request_len > 0)
  17322. && ((conn->is_chunked == 4)
  17323. || (!conn->is_chunked
  17324. && ((conn->consumed_content == conn->content_len)
  17325. || ((conn->request_len + conn->content_len)
  17326. <= conn->data_len))))
  17327. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  17328. if (keep_alive) {
  17329. /* Discard all buffered data for this request */
  17330. discard_len =
  17331. ((conn->request_len + conn->content_len) < conn->data_len)
  17332. ? (int)(conn->request_len + conn->content_len)
  17333. : conn->data_len;
  17334. conn->data_len -= discard_len;
  17335. if (conn->data_len > 0) {
  17336. DEBUG_TRACE("discard_len = %d", discard_len);
  17337. memmove(conn->buf,
  17338. conn->buf + discard_len,
  17339. (size_t)conn->data_len);
  17340. }
  17341. }
  17342. DEBUG_ASSERT(conn->data_len >= 0);
  17343. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  17344. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  17345. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  17346. (long int)conn->data_len,
  17347. (long int)conn->buf_size);
  17348. break;
  17349. }
  17350. conn->handled_requests++;
  17351. } while (keep_alive);
  17352. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  17353. conn->request_info.remote_addr,
  17354. difftime(time(NULL), conn->conn_birth_time));
  17355. close_connection(conn);
  17356. #if defined(USE_SERVER_STATS)
  17357. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17358. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17359. #endif
  17360. }
  17361. static int
  17362. mg_start_worker_thread(struct mg_context *ctx,
  17363. int only_if_no_idle_threads); /* forward declaration */
  17364. #if defined(ALTERNATIVE_QUEUE)
  17365. static void
  17366. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17367. {
  17368. unsigned int i;
  17369. (void)mg_start_worker_thread(
  17370. ctx, 1); /* will start a worker-thread only if there aren't currently
  17371. any idle worker-threads */
  17372. while (!ctx->stop_flag) {
  17373. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17374. /* find a free worker slot and signal it */
  17375. if (ctx->client_socks[i].in_use == 2) {
  17376. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17377. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17378. ctx->client_socks[i] = *sp;
  17379. ctx->client_socks[i].in_use = 1;
  17380. /* socket has been moved to the consumer */
  17381. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17382. (void)event_signal(ctx->client_wait_events[i]);
  17383. return;
  17384. }
  17385. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17386. }
  17387. }
  17388. /* queue is full */
  17389. mg_sleep(1);
  17390. }
  17391. /* must consume */
  17392. set_blocking_mode(sp->sock);
  17393. closesocket(sp->sock);
  17394. }
  17395. static int
  17396. consume_socket(struct mg_context *ctx,
  17397. struct socket *sp,
  17398. int thread_index,
  17399. int counter_was_preincremented)
  17400. {
  17401. DEBUG_TRACE("%s", "going idle");
  17402. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17403. if (counter_was_preincremented
  17404. == 0) { /* first call only: the master-thread pre-incremented this
  17405. before he spawned us */
  17406. ctx->idle_worker_thread_count++;
  17407. }
  17408. ctx->client_socks[thread_index].in_use = 2;
  17409. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17410. event_wait(ctx->client_wait_events[thread_index]);
  17411. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17412. *sp = ctx->client_socks[thread_index];
  17413. if (ctx->stop_flag) {
  17414. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17415. if (sp->in_use == 1) {
  17416. /* must consume */
  17417. set_blocking_mode(sp->sock);
  17418. closesocket(sp->sock);
  17419. }
  17420. return 0;
  17421. }
  17422. ctx->idle_worker_thread_count--;
  17423. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17424. if (sp->in_use == 1) {
  17425. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17426. return 1;
  17427. }
  17428. /* must not reach here */
  17429. DEBUG_ASSERT(0);
  17430. return 0;
  17431. }
  17432. #else /* ALTERNATIVE_QUEUE */
  17433. /* Worker threads take accepted socket from the queue */
  17434. static int
  17435. consume_socket(struct mg_context *ctx,
  17436. struct socket *sp,
  17437. int thread_index,
  17438. int counter_was_preincremented)
  17439. {
  17440. (void)thread_index;
  17441. DEBUG_TRACE("%s", "going idle");
  17442. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17443. if (counter_was_preincremented
  17444. == 0) { /* first call only: the master-thread pre-incremented this
  17445. before he spawned us */
  17446. ctx->idle_worker_thread_count++;
  17447. }
  17448. /* If the queue is empty, wait. We're idle at this point. */
  17449. while ((ctx->sq_head == ctx->sq_tail)
  17450. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17451. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17452. }
  17453. /* If we're stopping, sq_head may be equal to sq_tail. */
  17454. if (ctx->sq_head > ctx->sq_tail) {
  17455. /* Copy socket from the queue and increment tail */
  17456. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17457. ctx->sq_tail++;
  17458. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17459. /* Wrap pointers if needed */
  17460. while (ctx->sq_tail > ctx->sq_size) {
  17461. ctx->sq_tail -= ctx->sq_size;
  17462. ctx->sq_head -= ctx->sq_size;
  17463. }
  17464. }
  17465. (void)pthread_cond_signal(&ctx->sq_empty);
  17466. ctx->idle_worker_thread_count--;
  17467. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17468. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17469. }
  17470. /* Master thread adds accepted socket to a queue */
  17471. static void
  17472. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17473. {
  17474. int queue_filled;
  17475. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17476. queue_filled = ctx->sq_head - ctx->sq_tail;
  17477. /* If the queue is full, wait */
  17478. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17479. && (queue_filled >= ctx->sq_size)) {
  17480. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17481. #if defined(USE_SERVER_STATS)
  17482. if (queue_filled > ctx->sq_max_fill) {
  17483. ctx->sq_max_fill = queue_filled;
  17484. }
  17485. #endif
  17486. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17487. ctx->sq_blocked = 0; /* Not blocked now */
  17488. queue_filled = ctx->sq_head - ctx->sq_tail;
  17489. }
  17490. if (queue_filled < ctx->sq_size) {
  17491. /* Copy socket to the queue and increment head */
  17492. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17493. ctx->sq_head++;
  17494. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17495. }
  17496. queue_filled = ctx->sq_head - ctx->sq_tail;
  17497. #if defined(USE_SERVER_STATS)
  17498. if (queue_filled > ctx->sq_max_fill) {
  17499. ctx->sq_max_fill = queue_filled;
  17500. }
  17501. #endif
  17502. (void)pthread_cond_signal(&ctx->sq_full);
  17503. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17504. (void)mg_start_worker_thread(
  17505. ctx, 1); /* will start a worker-thread only if there aren't currently
  17506. any idle worker-threads */
  17507. }
  17508. #endif /* ALTERNATIVE_QUEUE */
  17509. static void
  17510. worker_thread_run(struct mg_connection *conn)
  17511. {
  17512. struct mg_context *ctx = conn->phys_ctx;
  17513. int thread_index;
  17514. struct mg_workerTLS tls;
  17515. int first_call_to_consume_socket = 1;
  17516. mg_set_thread_name("worker");
  17517. tls.is_master = 0;
  17518. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17519. #if defined(_WIN32)
  17520. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17521. #endif
  17522. /* Initialize thread local storage before calling any callback */
  17523. pthread_setspecific(sTlsKey, &tls);
  17524. /* Check if there is a user callback */
  17525. if (ctx->callbacks.init_thread) {
  17526. /* call init_thread for a worker thread (type 1), and store the
  17527. * return value */
  17528. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17529. } else {
  17530. /* No callback: set user pointer to NULL */
  17531. tls.user_ptr = NULL;
  17532. }
  17533. /* Connection structure has been pre-allocated */
  17534. thread_index = (int)(conn - ctx->worker_connections);
  17535. if ((thread_index < 0)
  17536. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17537. mg_cry_ctx_internal(ctx,
  17538. "Internal error: Invalid worker index %i",
  17539. thread_index);
  17540. return;
  17541. }
  17542. /* Request buffers are not pre-allocated. They are private to the
  17543. * request and do not contain any state information that might be
  17544. * of interest to anyone observing a server status. */
  17545. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17546. if (conn->buf == NULL) {
  17547. mg_cry_ctx_internal(
  17548. ctx,
  17549. "Out of memory: Cannot allocate buffer for worker %i",
  17550. thread_index);
  17551. return;
  17552. }
  17553. conn->buf_size = (int)ctx->max_request_size;
  17554. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17555. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17556. conn->request_info.user_data = ctx->user_data;
  17557. /* Allocate a mutex for this connection to allow communication both
  17558. * within the request handler and from elsewhere in the application
  17559. */
  17560. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17561. mg_free(conn->buf);
  17562. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17563. return;
  17564. }
  17565. #if defined(USE_SERVER_STATS)
  17566. conn->conn_state = 1; /* not consumed */
  17567. #endif
  17568. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17569. * signal sq_empty condvar to wake up the master waiting in
  17570. * produce_socket() */
  17571. while (consume_socket(
  17572. ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17573. first_call_to_consume_socket = 0;
  17574. /* New connections must start with new protocol negotiation */
  17575. tls.alpn_proto = NULL;
  17576. #if defined(USE_SERVER_STATS)
  17577. conn->conn_close_time = 0;
  17578. #endif
  17579. conn->conn_birth_time = time(NULL);
  17580. /* Fill in IP, port info early so even if SSL setup below fails,
  17581. * error handler would have the corresponding info.
  17582. * Thanks to Johannes Winkelmann for the patch.
  17583. */
  17584. conn->request_info.remote_port =
  17585. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17586. conn->request_info.server_port =
  17587. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17588. sockaddr_to_string(conn->request_info.remote_addr,
  17589. sizeof(conn->request_info.remote_addr),
  17590. &conn->client.rsa);
  17591. DEBUG_TRACE("Incoming %sconnection from %s",
  17592. (conn->client.is_ssl ? "SSL " : ""),
  17593. conn->request_info.remote_addr);
  17594. conn->request_info.is_ssl = conn->client.is_ssl;
  17595. if (conn->client.is_ssl) {
  17596. #if defined(USE_MBEDTLS)
  17597. /* HTTPS connection */
  17598. if (mbed_ssl_accept(&(conn->ssl),
  17599. conn->dom_ctx->ssl_ctx,
  17600. (int *)&(conn->client.sock),
  17601. conn->phys_ctx)
  17602. == 0) {
  17603. /* conn->dom_ctx is set in get_request */
  17604. /* process HTTPS connection */
  17605. init_connection(conn);
  17606. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17607. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17608. process_new_connection(conn);
  17609. } else {
  17610. /* make sure the connection is cleaned up on SSL failure */
  17611. close_connection(conn);
  17612. }
  17613. #elif defined(USE_GNUTLS)
  17614. /* HTTPS connection */
  17615. if (gtls_ssl_accept(&(conn->ssl),
  17616. conn->dom_ctx->ssl_ctx,
  17617. conn->client.sock,
  17618. conn->phys_ctx)
  17619. == 0) {
  17620. /* conn->dom_ctx is set in get_request */
  17621. /* process HTTPS connection */
  17622. init_connection(conn);
  17623. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17624. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17625. process_new_connection(conn);
  17626. } else {
  17627. /* make sure the connection is cleaned up on SSL failure */
  17628. close_connection(conn);
  17629. }
  17630. #elif !defined(NO_SSL)
  17631. /* HTTPS connection */
  17632. if (sslize(conn, SSL_accept, NULL)) {
  17633. /* conn->dom_ctx is set in get_request */
  17634. /* Get SSL client certificate information (if set) */
  17635. struct mg_client_cert client_cert;
  17636. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17637. conn->request_info.client_cert = &client_cert;
  17638. }
  17639. /* process HTTPS connection */
  17640. #if defined(USE_HTTP2)
  17641. if ((tls.alpn_proto != NULL)
  17642. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17643. /* process HTTPS/2 connection */
  17644. init_connection(conn);
  17645. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17646. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17647. conn->content_len =
  17648. -1; /* content length is not predefined */
  17649. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17650. process_new_http2_connection(conn);
  17651. } else
  17652. #endif
  17653. {
  17654. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17655. init_connection(conn);
  17656. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17657. /* Start with HTTP, WS will be an "upgrade" request later */
  17658. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17659. process_new_connection(conn);
  17660. }
  17661. /* Free client certificate info */
  17662. if (conn->request_info.client_cert) {
  17663. mg_free((void *)(conn->request_info.client_cert->subject));
  17664. mg_free((void *)(conn->request_info.client_cert->issuer));
  17665. mg_free((void *)(conn->request_info.client_cert->serial));
  17666. mg_free((void *)(conn->request_info.client_cert->finger));
  17667. /* Free certificate memory */
  17668. X509_free(
  17669. (X509 *)conn->request_info.client_cert->peer_cert);
  17670. conn->request_info.client_cert->peer_cert = 0;
  17671. conn->request_info.client_cert->subject = 0;
  17672. conn->request_info.client_cert->issuer = 0;
  17673. conn->request_info.client_cert->serial = 0;
  17674. conn->request_info.client_cert->finger = 0;
  17675. conn->request_info.client_cert = 0;
  17676. }
  17677. } else {
  17678. /* make sure the connection is cleaned up on SSL failure */
  17679. close_connection(conn);
  17680. }
  17681. #endif
  17682. } else {
  17683. /* process HTTP connection */
  17684. init_connection(conn);
  17685. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17686. /* Start with HTTP, WS will be an "upgrade" request later */
  17687. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17688. process_new_connection(conn);
  17689. }
  17690. DEBUG_TRACE("%s", "Connection closed");
  17691. #if defined(USE_SERVER_STATS)
  17692. conn->conn_close_time = time(NULL);
  17693. #endif
  17694. }
  17695. /* Call exit thread user callback */
  17696. if (ctx->callbacks.exit_thread) {
  17697. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17698. }
  17699. /* delete thread local storage objects */
  17700. pthread_setspecific(sTlsKey, NULL);
  17701. #if defined(_WIN32)
  17702. CloseHandle(tls.pthread_cond_helper_mutex);
  17703. #endif
  17704. pthread_mutex_destroy(&conn->mutex);
  17705. /* Free the request buffer. */
  17706. conn->buf_size = 0;
  17707. mg_free(conn->buf);
  17708. conn->buf = NULL;
  17709. /* Free cleaned URI (if any) */
  17710. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17711. mg_free((void *)conn->request_info.local_uri);
  17712. conn->request_info.local_uri = NULL;
  17713. }
  17714. #if defined(USE_SERVER_STATS)
  17715. conn->conn_state = 9; /* done */
  17716. #endif
  17717. DEBUG_TRACE("%s", "exiting");
  17718. }
  17719. /* Threads have different return types on Windows and Unix. */
  17720. #if defined(_WIN32)
  17721. static unsigned __stdcall worker_thread(void *thread_func_param)
  17722. {
  17723. worker_thread_run((struct mg_connection *)thread_func_param);
  17724. return 0;
  17725. }
  17726. #else
  17727. static void *
  17728. worker_thread(void *thread_func_param)
  17729. {
  17730. #if !defined(__ZEPHYR__)
  17731. struct sigaction sa;
  17732. /* Ignore SIGPIPE */
  17733. memset(&sa, 0, sizeof(sa));
  17734. sa.sa_handler = SIG_IGN;
  17735. sigaction(SIGPIPE, &sa, NULL);
  17736. #endif
  17737. worker_thread_run((struct mg_connection *)thread_func_param);
  17738. return NULL;
  17739. }
  17740. #endif /* _WIN32 */
  17741. /* This is an internal function, thus all arguments are expected to be
  17742. * valid - a NULL check is not required. */
  17743. static void
  17744. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17745. {
  17746. struct socket so;
  17747. char src_addr[IP_ADDR_STR_LEN];
  17748. socklen_t len = sizeof(so.rsa);
  17749. #if !defined(__ZEPHYR__)
  17750. int on = 1;
  17751. #endif
  17752. memset(&so, 0, sizeof(so));
  17753. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17754. == INVALID_SOCKET) {
  17755. } else if (check_acl(ctx, &so.rsa) != 1) {
  17756. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17757. mg_cry_ctx_internal(ctx,
  17758. "%s: %s is not allowed to connect",
  17759. __func__,
  17760. src_addr);
  17761. closesocket(so.sock);
  17762. } else {
  17763. /* Put so socket structure into the queue */
  17764. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17765. set_close_on_exec(so.sock, NULL, ctx);
  17766. so.is_ssl = listener->is_ssl;
  17767. so.ssl_redir = listener->ssl_redir;
  17768. so.is_optional = listener->is_optional;
  17769. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17770. mg_cry_ctx_internal(ctx,
  17771. "%s: getsockname() failed: %s",
  17772. __func__,
  17773. strerror(ERRNO));
  17774. }
  17775. #if !defined(__ZEPHYR__)
  17776. if ((so.lsa.sa.sa_family == AF_INET)
  17777. || (so.lsa.sa.sa_family == AF_INET6)) {
  17778. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17779. * This is needed because if HTTP-level keep-alive
  17780. * is enabled, and client resets the connection, server won't get
  17781. * TCP FIN or RST and will keep the connection open forever. With
  17782. * TCP keep-alive, next keep-alive handshake will figure out that
  17783. * the client is down and will close the server end.
  17784. * Thanks to Igor Klopov who suggested the patch. */
  17785. if (setsockopt(so.sock,
  17786. SOL_SOCKET,
  17787. SO_KEEPALIVE,
  17788. (SOCK_OPT_TYPE)&on,
  17789. sizeof(on))
  17790. != 0) {
  17791. mg_cry_ctx_internal(
  17792. ctx,
  17793. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17794. __func__,
  17795. strerror(ERRNO));
  17796. }
  17797. }
  17798. #endif
  17799. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17800. * to effectively fill up the underlying IP packet payload and
  17801. * reduce the overhead of sending lots of small buffers. However
  17802. * this hurts the server's throughput (ie. operations per second)
  17803. * when HTTP 1.1 persistent connections are used and the responses
  17804. * are relatively small (eg. less than 1400 bytes).
  17805. */
  17806. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17807. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17808. if (set_tcp_nodelay(&so, 1) != 0) {
  17809. mg_cry_ctx_internal(
  17810. ctx,
  17811. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17812. __func__,
  17813. strerror(ERRNO));
  17814. }
  17815. }
  17816. /* The "non blocking" property should already be
  17817. * inherited from the parent socket. Set it for
  17818. * non-compliant socket implementations. */
  17819. set_non_blocking_mode(so.sock);
  17820. so.in_use = 0;
  17821. produce_socket(ctx, &so);
  17822. }
  17823. }
  17824. static void
  17825. master_thread_run(struct mg_context *ctx)
  17826. {
  17827. struct mg_workerTLS tls;
  17828. struct mg_pollfd *pfd;
  17829. unsigned int i;
  17830. unsigned int workerthreadcount;
  17831. if (!ctx || !ctx->listening_socket_fds) {
  17832. return;
  17833. }
  17834. mg_set_thread_name("master");
  17835. /* Increase priority of the master thread */
  17836. #if defined(_WIN32)
  17837. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17838. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17839. int min_prio = sched_get_priority_min(SCHED_RR);
  17840. int max_prio = sched_get_priority_max(SCHED_RR);
  17841. if ((min_prio >= 0) && (max_prio >= 0)
  17842. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17843. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17844. struct sched_param sched_param = {0};
  17845. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17846. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17847. }
  17848. #endif
  17849. /* Initialize thread local storage */
  17850. #if defined(_WIN32)
  17851. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17852. #endif
  17853. tls.is_master = 1;
  17854. pthread_setspecific(sTlsKey, &tls);
  17855. if (ctx->callbacks.init_thread) {
  17856. /* Callback for the master thread (type 0) */
  17857. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17858. } else {
  17859. tls.user_ptr = NULL;
  17860. }
  17861. /* Lua background script "start" event */
  17862. #if defined(USE_LUA)
  17863. if (ctx->lua_background_state) {
  17864. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17865. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17866. /* call "start()" in Lua */
  17867. lua_getglobal(lstate, "start");
  17868. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17869. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17870. if (ret != 0) {
  17871. struct mg_connection fc;
  17872. lua_cry(fake_connection(&fc, ctx),
  17873. ret,
  17874. lstate,
  17875. "lua_background_script",
  17876. "start");
  17877. }
  17878. } else {
  17879. lua_pop(lstate, 1);
  17880. }
  17881. /* determine if there is a "log()" function in Lua background script */
  17882. lua_getglobal(lstate, "log");
  17883. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17884. ctx->lua_bg_log_available = 1;
  17885. }
  17886. lua_pop(lstate, 1);
  17887. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17888. }
  17889. #endif
  17890. /* Server starts *now* */
  17891. ctx->start_time = time(NULL);
  17892. /* Server accept loop */
  17893. pfd = ctx->listening_socket_fds;
  17894. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17895. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17896. pfd[i].fd = ctx->listening_sockets[i].sock;
  17897. pfd[i].events = POLLIN;
  17898. }
  17899. /* We listen on this socket just so that mg_stop() can cause mg_poll()
  17900. * to return ASAP. Don't worry, we did allocate an extra slot at the end
  17901. * of listening_socket_fds[] just to hold this
  17902. */
  17903. pfd[ctx->num_listening_sockets].fd =
  17904. ctx->thread_shutdown_notification_socket;
  17905. pfd[ctx->num_listening_sockets].events = POLLIN;
  17906. if (mg_poll(pfd,
  17907. ctx->num_listening_sockets
  17908. + 1, // +1 for the thread_shutdown_notification_socket
  17909. SOCKET_TIMEOUT_QUANTUM,
  17910. &(ctx->stop_flag))
  17911. > 0) {
  17912. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17913. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17914. * successful poll, and POLLIN is defined as
  17915. * (POLLRDNORM | POLLRDBAND)
  17916. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17917. * pfd[i].revents == POLLIN. */
  17918. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17919. && (pfd[i].revents & POLLIN)) {
  17920. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17921. }
  17922. }
  17923. }
  17924. }
  17925. /* Here stop_flag is 1 - Initiate shutdown. */
  17926. DEBUG_TRACE("%s", "stopping workers");
  17927. /* Stop signal received: somebody called mg_stop. Quit. */
  17928. close_all_listening_sockets(ctx);
  17929. /* Wakeup workers that are waiting for connections to handle. */
  17930. #if defined(ALTERNATIVE_QUEUE)
  17931. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17932. event_signal(ctx->client_wait_events[i]);
  17933. }
  17934. #else
  17935. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17936. pthread_cond_broadcast(&ctx->sq_full);
  17937. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17938. #endif
  17939. /* Join all worker threads to avoid leaking threads. */
  17940. workerthreadcount = ctx->spawned_worker_threads;
  17941. for (i = 0; i < workerthreadcount; i++) {
  17942. if (ctx->worker_threadids[i] != 0) {
  17943. mg_join_thread(ctx->worker_threadids[i]);
  17944. }
  17945. }
  17946. #if defined(USE_LUA)
  17947. /* Free Lua state of lua background task */
  17948. if (ctx->lua_background_state) {
  17949. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17950. ctx->lua_bg_log_available = 0;
  17951. /* call "stop()" in Lua */
  17952. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17953. lua_getglobal(lstate, "stop");
  17954. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17955. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17956. if (ret != 0) {
  17957. struct mg_connection fc;
  17958. lua_cry(fake_connection(&fc, ctx),
  17959. ret,
  17960. lstate,
  17961. "lua_background_script",
  17962. "stop");
  17963. }
  17964. }
  17965. DEBUG_TRACE("Close Lua background state %p", lstate);
  17966. lua_close(lstate);
  17967. ctx->lua_background_state = 0;
  17968. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17969. }
  17970. #endif
  17971. DEBUG_TRACE("%s", "exiting");
  17972. /* call exit thread callback */
  17973. if (ctx->callbacks.exit_thread) {
  17974. /* Callback for the master thread (type 0) */
  17975. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17976. }
  17977. #if defined(_WIN32)
  17978. CloseHandle(tls.pthread_cond_helper_mutex);
  17979. #endif
  17980. pthread_setspecific(sTlsKey, NULL);
  17981. /* Signal mg_stop() that we're done.
  17982. * WARNING: This must be the very last thing this
  17983. * thread does, as ctx becomes invalid after this line. */
  17984. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17985. }
  17986. /* Threads have different return types on Windows and Unix. */
  17987. #if defined(_WIN32)
  17988. static unsigned __stdcall master_thread(void *thread_func_param)
  17989. {
  17990. master_thread_run((struct mg_context *)thread_func_param);
  17991. return 0;
  17992. }
  17993. #else
  17994. static void *
  17995. master_thread(void *thread_func_param)
  17996. {
  17997. #if !defined(__ZEPHYR__)
  17998. struct sigaction sa;
  17999. /* Ignore SIGPIPE */
  18000. memset(&sa, 0, sizeof(sa));
  18001. sa.sa_handler = SIG_IGN;
  18002. sigaction(SIGPIPE, &sa, NULL);
  18003. #endif
  18004. master_thread_run((struct mg_context *)thread_func_param);
  18005. return NULL;
  18006. }
  18007. #endif /* _WIN32 */
  18008. static void
  18009. free_context(struct mg_context *ctx)
  18010. {
  18011. int i;
  18012. struct mg_handler_info *tmp_rh;
  18013. if (ctx == NULL) {
  18014. return;
  18015. }
  18016. /* Call user callback */
  18017. if (ctx->callbacks.exit_context) {
  18018. ctx->callbacks.exit_context(ctx);
  18019. }
  18020. /* All threads exited, no sync is needed. Destroy thread mutex and
  18021. * condvars
  18022. */
  18023. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  18024. #if defined(ALTERNATIVE_QUEUE)
  18025. mg_free(ctx->client_socks);
  18026. if (ctx->client_wait_events != NULL) {
  18027. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  18028. event_destroy(ctx->client_wait_events[i]);
  18029. }
  18030. mg_free(ctx->client_wait_events);
  18031. }
  18032. #else
  18033. (void)pthread_cond_destroy(&ctx->sq_empty);
  18034. (void)pthread_cond_destroy(&ctx->sq_full);
  18035. mg_free(ctx->squeue);
  18036. #endif
  18037. /* Destroy other context global data structures mutex */
  18038. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  18039. #if defined(USE_LUA)
  18040. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  18041. #endif
  18042. /* Deallocate shutdown-triggering socket-pair */
  18043. if (ctx->user_shutdown_notification_socket >= 0) {
  18044. closesocket(ctx->user_shutdown_notification_socket);
  18045. }
  18046. if (ctx->thread_shutdown_notification_socket >= 0) {
  18047. closesocket(ctx->thread_shutdown_notification_socket);
  18048. }
  18049. /* Deallocate config parameters */
  18050. for (i = 0; i < NUM_OPTIONS; i++) {
  18051. if (ctx->dd.config[i] != NULL) {
  18052. #if defined(_MSC_VER)
  18053. #pragma warning(suppress : 6001)
  18054. #endif
  18055. mg_free(ctx->dd.config[i]);
  18056. }
  18057. }
  18058. /* Deallocate request handlers */
  18059. while (ctx->dd.handlers) {
  18060. tmp_rh = ctx->dd.handlers;
  18061. ctx->dd.handlers = tmp_rh->next;
  18062. mg_free(tmp_rh->uri);
  18063. mg_free(tmp_rh);
  18064. }
  18065. #if defined(USE_MBEDTLS)
  18066. if (ctx->dd.ssl_ctx != NULL) {
  18067. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  18068. mg_free(ctx->dd.ssl_ctx);
  18069. ctx->dd.ssl_ctx = NULL;
  18070. }
  18071. #elif defined(USE_GNUTLS)
  18072. if (ctx->dd.ssl_ctx != NULL) {
  18073. gtls_sslctx_uninit(ctx->dd.ssl_ctx);
  18074. mg_free(ctx->dd.ssl_ctx);
  18075. ctx->dd.ssl_ctx = NULL;
  18076. }
  18077. #elif !defined(NO_SSL)
  18078. /* Deallocate SSL context */
  18079. if (ctx->dd.ssl_ctx != NULL) {
  18080. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  18081. int callback_ret =
  18082. (ctx->callbacks.external_ssl_ctx == NULL)
  18083. ? 0
  18084. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  18085. if (callback_ret == 0) {
  18086. SSL_CTX_free(ctx->dd.ssl_ctx);
  18087. }
  18088. /* else: ignore error and omit SSL_CTX_free in case
  18089. * callback_ret is 1 */
  18090. }
  18091. #endif /* !NO_SSL */
  18092. /* Deallocate worker thread ID array */
  18093. mg_free(ctx->worker_threadids);
  18094. /* Deallocate worker thread ID array */
  18095. mg_free(ctx->worker_connections);
  18096. /* deallocate system name string */
  18097. mg_free(ctx->systemName);
  18098. /* Deallocate context itself */
  18099. mg_free(ctx);
  18100. }
  18101. CIVETWEB_API void
  18102. mg_stop(struct mg_context *ctx)
  18103. {
  18104. pthread_t mt;
  18105. if (!ctx) {
  18106. return;
  18107. }
  18108. /* We don't use a lock here. Calling mg_stop with the same ctx from
  18109. * two threads is not allowed. */
  18110. mt = ctx->masterthreadid;
  18111. if (mt == 0) {
  18112. return;
  18113. }
  18114. ctx->masterthreadid = 0;
  18115. /* Set stop flag, so all threads know they have to exit. */
  18116. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  18117. /* Closing this socket will cause mg_poll() in all the I/O threads to return
  18118. * immediately */
  18119. closesocket(ctx->user_shutdown_notification_socket);
  18120. ctx->user_shutdown_notification_socket =
  18121. -1; /* to avoid calling closesocket() again in free_context() */
  18122. /* Join timer thread */
  18123. #if defined(USE_TIMERS)
  18124. timers_exit(ctx);
  18125. #endif
  18126. /* Wait until everything has stopped. */
  18127. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  18128. (void)mg_sleep(10);
  18129. }
  18130. /* Wait to stop master thread */
  18131. mg_join_thread(mt);
  18132. /* Close remaining Lua states */
  18133. #if defined(USE_LUA)
  18134. lua_ctx_exit(ctx);
  18135. #endif
  18136. /* Free memory */
  18137. free_context(ctx);
  18138. }
  18139. static void
  18140. get_system_name(char **sysName)
  18141. {
  18142. #if defined(_WIN32)
  18143. char name[128];
  18144. DWORD dwVersion = 0;
  18145. DWORD dwMajorVersion = 0;
  18146. DWORD dwMinorVersion = 0;
  18147. DWORD dwBuild = 0;
  18148. BOOL wowRet, isWoW = FALSE;
  18149. #if defined(_MSC_VER)
  18150. #pragma warning(push)
  18151. /* GetVersion was declared deprecated */
  18152. #pragma warning(disable : 4996)
  18153. #endif
  18154. dwVersion = GetVersion();
  18155. #if defined(_MSC_VER)
  18156. #pragma warning(pop)
  18157. #endif
  18158. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18159. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18160. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  18161. (void)dwBuild;
  18162. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  18163. sprintf(name,
  18164. "Windows %u.%u%s",
  18165. (unsigned)dwMajorVersion,
  18166. (unsigned)dwMinorVersion,
  18167. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  18168. *sysName = mg_strdup(name);
  18169. #elif defined(__rtems__)
  18170. *sysName = mg_strdup("RTEMS");
  18171. #elif defined(__ZEPHYR__)
  18172. *sysName = mg_strdup("Zephyr OS");
  18173. #else
  18174. struct utsname name;
  18175. memset(&name, 0, sizeof(name));
  18176. uname(&name);
  18177. *sysName = mg_strdup(name.sysname);
  18178. #endif
  18179. }
  18180. static void
  18181. legacy_init(const char **options)
  18182. {
  18183. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  18184. if (options) {
  18185. const char **run_options = options;
  18186. const char *optname = config_options[LISTENING_PORTS].name;
  18187. /* Try to find the "listening_ports" option */
  18188. while (*run_options) {
  18189. if (!strcmp(*run_options, optname)) {
  18190. ports_option = run_options[1];
  18191. }
  18192. run_options += 2;
  18193. }
  18194. }
  18195. if (is_ssl_port_used(ports_option)) {
  18196. /* Initialize with SSL support */
  18197. mg_init_library(MG_FEATURES_TLS);
  18198. } else {
  18199. /* Initialize without SSL support */
  18200. mg_init_library(MG_FEATURES_DEFAULT);
  18201. }
  18202. }
  18203. /* we'll assume it's only Windows that doesn't have socketpair() available */
  18204. #if !defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  18205. #define HAVE_SOCKETPAIR 1
  18206. #endif
  18207. static int
  18208. mg_socketpair(int *sockA, int *sockB)
  18209. {
  18210. int temp[2] = {-1, -1};
  18211. int asock = -1;
  18212. /** Default to unallocated */
  18213. *sockA = -1;
  18214. *sockB = -1;
  18215. #if defined(HAVE_SOCKETPAIR)
  18216. int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, temp);
  18217. if (ret == 0) {
  18218. *sockA = temp[0];
  18219. *sockB = temp[1];
  18220. set_close_on_exec(*sockA, NULL, NULL);
  18221. set_close_on_exec(*sockB, NULL, NULL);
  18222. }
  18223. (void)asock; /* not used */
  18224. return ret;
  18225. #else
  18226. /** No socketpair() call is available, so we'll have to roll our own
  18227. * implementation */
  18228. asock = socket(PF_INET, SOCK_STREAM, 0);
  18229. if (asock >= 0) {
  18230. struct sockaddr_in addr;
  18231. struct sockaddr *pa = (struct sockaddr *)&addr;
  18232. socklen_t addrLen = sizeof(addr);
  18233. memset(&addr, 0, sizeof(addr));
  18234. addr.sin_family = AF_INET;
  18235. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18236. addr.sin_port = 0;
  18237. if ((bind(asock, pa, sizeof(addr)) == 0)
  18238. && (getsockname(asock, pa, &addrLen) == 0)
  18239. && (listen(asock, 1) == 0)) {
  18240. temp[0] = socket(PF_INET, SOCK_STREAM, 0);
  18241. if ((temp[0] >= 0) && (connect(temp[0], pa, sizeof(addr)) == 0)) {
  18242. temp[1] = accept(asock, pa, &addrLen);
  18243. if (temp[1] >= 0) {
  18244. closesocket(asock);
  18245. *sockA = temp[0];
  18246. *sockB = temp[1];
  18247. set_close_on_exec(*sockA, NULL, NULL);
  18248. set_close_on_exec(*sockB, NULL, NULL);
  18249. return 0; /* success! */
  18250. }
  18251. }
  18252. }
  18253. }
  18254. /* Cleanup */
  18255. if (asock >= 0)
  18256. closesocket(asock);
  18257. if (temp[0] >= 0)
  18258. closesocket(temp[0]);
  18259. if (temp[1] >= 0)
  18260. closesocket(temp[1]);
  18261. return -1; /* fail! */
  18262. #endif
  18263. }
  18264. static int
  18265. mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads)
  18266. {
  18267. const unsigned int i = ctx->spawned_worker_threads;
  18268. if (i >= ctx->cfg_max_worker_threads) {
  18269. return -1; /* Oops, we hit our worker-thread limit! No more worker
  18270. threads, ever! */
  18271. }
  18272. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18273. #if defined(ALTERNATIVE_QUEUE)
  18274. if ((only_if_no_idle_threads) && (ctx->idle_worker_thread_count > 0)) {
  18275. #else
  18276. if ((only_if_no_idle_threads)
  18277. && (ctx->idle_worker_thread_count
  18278. > (unsigned)(ctx->sq_head - ctx->sq_tail))) {
  18279. #endif
  18280. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18281. return -2; /* There are idle threads available, so no need to spawn a
  18282. new worker thread now */
  18283. }
  18284. ctx->idle_worker_thread_count++; /* we do this here to avoid a race
  18285. condition while the thread is starting
  18286. up */
  18287. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18288. ctx->worker_connections[i].phys_ctx = ctx;
  18289. int ret = mg_start_thread_with_id(worker_thread,
  18290. &ctx->worker_connections[i],
  18291. &ctx->worker_threadids[i]);
  18292. if (ret == 0) {
  18293. ctx->spawned_worker_threads++; /* note that we've filled another slot in
  18294. the table */
  18295. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  18296. } else {
  18297. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18298. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  18299. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18300. }
  18301. return ret;
  18302. }
  18303. CIVETWEB_API struct mg_context *
  18304. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  18305. {
  18306. struct mg_context *ctx;
  18307. const char *name, *value, *default_value;
  18308. int idx, ok, prespawnthreadcount, workerthreadcount;
  18309. unsigned int i;
  18310. int itmp;
  18311. void (*exit_callback)(const struct mg_context *ctx) = 0;
  18312. const char **options =
  18313. ((init != NULL) ? (init->configuration_options) : (NULL));
  18314. struct mg_workerTLS tls;
  18315. if (error != NULL) {
  18316. error->code = MG_ERROR_DATA_CODE_OK;
  18317. error->code_sub = 0;
  18318. if (error->text_buffer_size > 0) {
  18319. *error->text = 0;
  18320. }
  18321. }
  18322. if (mg_init_library_called == 0) {
  18323. /* Legacy INIT, if mg_start is called without mg_init_library.
  18324. * Note: This will cause a memory leak when unloading the library.
  18325. */
  18326. legacy_init(options);
  18327. }
  18328. if (mg_init_library_called == 0) {
  18329. if (error != NULL) {
  18330. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  18331. mg_snprintf(NULL,
  18332. NULL, /* No truncation check for error buffers */
  18333. error->text,
  18334. error->text_buffer_size,
  18335. "%s",
  18336. "Library uninitialized");
  18337. }
  18338. return NULL;
  18339. }
  18340. /* Allocate context and initialize reasonable general case defaults. */
  18341. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  18342. if (ctx == NULL) {
  18343. if (error != NULL) {
  18344. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18345. error->code_sub = (unsigned)sizeof(*ctx);
  18346. mg_snprintf(NULL,
  18347. NULL, /* No truncation check for error buffers */
  18348. error->text,
  18349. error->text_buffer_size,
  18350. "%s",
  18351. "Out of memory");
  18352. }
  18353. return NULL;
  18354. }
  18355. /* Random number generator will initialize at the first call */
  18356. ctx->dd.auth_nonce_mask =
  18357. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  18358. /* Save started thread index to reuse in other external API calls
  18359. * For the sake of thread synchronization all non-civetweb threads
  18360. * can be considered as single external thread */
  18361. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  18362. tls.is_master = -1; /* Thread calling mg_start */
  18363. tls.thread_idx = ctx->starter_thread_idx;
  18364. #if defined(_WIN32)
  18365. tls.pthread_cond_helper_mutex = NULL;
  18366. #endif
  18367. pthread_setspecific(sTlsKey, &tls);
  18368. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  18369. #if !defined(ALTERNATIVE_QUEUE)
  18370. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  18371. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  18372. ctx->sq_blocked = 0;
  18373. #endif
  18374. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  18375. #if defined(USE_LUA)
  18376. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  18377. #endif
  18378. /** mg_stop() will close the user_shutdown_notification_socket, and that
  18379. * will cause poll() to return immediately in the master-thread, so that
  18380. * mg_stop() can also return immediately.
  18381. */
  18382. ok &= (0
  18383. == mg_socketpair(&ctx->user_shutdown_notification_socket,
  18384. &ctx->thread_shutdown_notification_socket));
  18385. if (!ok) {
  18386. unsigned error_id = (unsigned)ERRNO;
  18387. const char *err_msg =
  18388. "Cannot initialize thread synchronization objects";
  18389. /* Fatal error - abort start. However, this situation should never
  18390. * occur in practice. */
  18391. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18392. if (error != NULL) {
  18393. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18394. error->code_sub = error_id;
  18395. mg_snprintf(NULL,
  18396. NULL, /* No truncation check for error buffers */
  18397. error->text,
  18398. error->text_buffer_size,
  18399. "%s",
  18400. err_msg);
  18401. }
  18402. mg_free(ctx);
  18403. pthread_setspecific(sTlsKey, NULL);
  18404. return NULL;
  18405. }
  18406. if ((init != NULL) && (init->callbacks != NULL)) {
  18407. /* Set all callbacks except exit_context. */
  18408. ctx->callbacks = *init->callbacks;
  18409. exit_callback = init->callbacks->exit_context;
  18410. /* The exit callback is activated once the context is successfully
  18411. * created. It should not be called, if an incomplete context object
  18412. * is deleted during a failed initialization. */
  18413. ctx->callbacks.exit_context = 0;
  18414. }
  18415. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  18416. ctx->dd.handlers = NULL;
  18417. ctx->dd.next = NULL;
  18418. #if defined(USE_LUA)
  18419. lua_ctx_init(ctx);
  18420. #endif
  18421. /* Store options */
  18422. while (options && (name = *options++) != NULL) {
  18423. idx = get_option_index(name);
  18424. if (idx == -1) {
  18425. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18426. if (error != NULL) {
  18427. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18428. error->code_sub = (unsigned)-1;
  18429. mg_snprintf(NULL,
  18430. NULL, /* No truncation check for error buffers */
  18431. error->text,
  18432. error->text_buffer_size,
  18433. "Invalid configuration option: %s",
  18434. name);
  18435. }
  18436. free_context(ctx);
  18437. pthread_setspecific(sTlsKey, NULL);
  18438. return NULL;
  18439. } else if ((value = *options++) == NULL) {
  18440. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18441. if (error != NULL) {
  18442. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18443. error->code_sub = (unsigned)idx;
  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. name);
  18450. }
  18451. free_context(ctx);
  18452. pthread_setspecific(sTlsKey, NULL);
  18453. return NULL;
  18454. }
  18455. if (ctx->dd.config[idx] != NULL) {
  18456. /* A duplicate configuration option is not an error - the last
  18457. * option value will be used. */
  18458. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18459. mg_free(ctx->dd.config[idx]);
  18460. }
  18461. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  18462. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18463. }
  18464. /* Set default value if needed */
  18465. for (i = 0; config_options[i].name != NULL; i++) {
  18466. default_value = config_options[i].default_value;
  18467. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  18468. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  18469. }
  18470. }
  18471. /* Request size option */
  18472. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  18473. if (itmp < 1024) {
  18474. mg_cry_ctx_internal(ctx,
  18475. "%s too small",
  18476. config_options[MAX_REQUEST_SIZE].name);
  18477. if (error != NULL) {
  18478. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18479. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  18480. mg_snprintf(NULL,
  18481. NULL, /* No truncation check for error buffers */
  18482. error->text,
  18483. error->text_buffer_size,
  18484. "Invalid configuration option value: %s",
  18485. config_options[MAX_REQUEST_SIZE].name);
  18486. }
  18487. free_context(ctx);
  18488. pthread_setspecific(sTlsKey, NULL);
  18489. return NULL;
  18490. }
  18491. ctx->max_request_size = (unsigned)itmp;
  18492. /* Queue length */
  18493. #if !defined(ALTERNATIVE_QUEUE)
  18494. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  18495. if (itmp < 1) {
  18496. mg_cry_ctx_internal(ctx,
  18497. "%s too small",
  18498. config_options[CONNECTION_QUEUE_SIZE].name);
  18499. if (error != NULL) {
  18500. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18501. error->code_sub = CONNECTION_QUEUE_SIZE;
  18502. mg_snprintf(NULL,
  18503. NULL, /* No truncation check for error buffers */
  18504. error->text,
  18505. error->text_buffer_size,
  18506. "Invalid configuration option value: %s",
  18507. config_options[CONNECTION_QUEUE_SIZE].name);
  18508. }
  18509. free_context(ctx);
  18510. pthread_setspecific(sTlsKey, NULL);
  18511. return NULL;
  18512. }
  18513. ctx->squeue =
  18514. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  18515. if (ctx->squeue == NULL) {
  18516. mg_cry_ctx_internal(ctx,
  18517. "Out of memory: Cannot allocate %s",
  18518. config_options[CONNECTION_QUEUE_SIZE].name);
  18519. if (error != NULL) {
  18520. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18521. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  18522. mg_snprintf(NULL,
  18523. NULL, /* No truncation check for error buffers */
  18524. error->text,
  18525. error->text_buffer_size,
  18526. "Out of memory: Cannot allocate %s",
  18527. config_options[CONNECTION_QUEUE_SIZE].name);
  18528. }
  18529. free_context(ctx);
  18530. pthread_setspecific(sTlsKey, NULL);
  18531. return NULL;
  18532. }
  18533. ctx->sq_size = itmp;
  18534. #endif
  18535. /* Worker thread count option */
  18536. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18537. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18538. if ((prespawnthreadcount < 0)
  18539. || (prespawnthreadcount > workerthreadcount)) {
  18540. prespawnthreadcount =
  18541. workerthreadcount; /* can't prespawn more than all of them! */
  18542. }
  18543. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18544. if (workerthreadcount <= 0) {
  18545. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18546. } else {
  18547. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18548. }
  18549. if (error != NULL) {
  18550. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18551. error->code_sub = NUM_THREADS;
  18552. mg_snprintf(NULL,
  18553. NULL, /* No truncation check for error buffers */
  18554. error->text,
  18555. error->text_buffer_size,
  18556. "Invalid configuration option value: %s",
  18557. config_options[NUM_THREADS].name);
  18558. }
  18559. free_context(ctx);
  18560. pthread_setspecific(sTlsKey, NULL);
  18561. return NULL;
  18562. }
  18563. /* Document root */
  18564. #if defined(NO_FILES)
  18565. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18566. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18567. if (error != NULL) {
  18568. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18569. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18570. mg_snprintf(NULL,
  18571. NULL, /* No truncation check for error buffers */
  18572. error->text,
  18573. error->text_buffer_size,
  18574. "Invalid configuration option value: %s",
  18575. config_options[DOCUMENT_ROOT].name);
  18576. }
  18577. free_context(ctx);
  18578. pthread_setspecific(sTlsKey, NULL);
  18579. return NULL;
  18580. }
  18581. #endif
  18582. get_system_name(&ctx->systemName);
  18583. #if defined(USE_LUA)
  18584. /* If a Lua background script has been configured, start it. */
  18585. ctx->lua_bg_log_available = 0;
  18586. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18587. char ebuf[256];
  18588. struct vec opt_vec;
  18589. struct vec eq_vec;
  18590. const char *sparams;
  18591. memset(ebuf, 0, sizeof(ebuf));
  18592. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18593. /* Create a Lua state, load all standard libraries and the mg table */
  18594. lua_State *state = mg_lua_context_script_prepare(
  18595. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18596. if (!state) {
  18597. mg_cry_ctx_internal(ctx,
  18598. "lua_background_script load error: %s",
  18599. ebuf);
  18600. if (error != NULL) {
  18601. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18602. mg_snprintf(NULL,
  18603. NULL, /* No truncation check for error buffers */
  18604. error->text,
  18605. error->text_buffer_size,
  18606. "Error in script %s: %s",
  18607. config_options[LUA_BACKGROUND_SCRIPT].name,
  18608. ebuf);
  18609. }
  18610. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18611. free_context(ctx);
  18612. pthread_setspecific(sTlsKey, NULL);
  18613. return NULL;
  18614. }
  18615. /* Add a table with parameters into mg.params */
  18616. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18617. if (sparams && sparams[0]) {
  18618. lua_getglobal(state, "mg");
  18619. lua_pushstring(state, "params");
  18620. lua_newtable(state);
  18621. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18622. != NULL) {
  18623. reg_llstring(
  18624. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18625. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18626. break;
  18627. }
  18628. lua_rawset(state, -3);
  18629. lua_pop(state, 1);
  18630. }
  18631. /* Call script */
  18632. state = mg_lua_context_script_run(state,
  18633. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18634. ctx,
  18635. ebuf,
  18636. sizeof(ebuf));
  18637. if (!state) {
  18638. mg_cry_ctx_internal(ctx,
  18639. "lua_background_script start error: %s",
  18640. ebuf);
  18641. if (error != NULL) {
  18642. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18643. mg_snprintf(NULL,
  18644. NULL, /* No truncation check for error buffers */
  18645. error->text,
  18646. error->text_buffer_size,
  18647. "Error in script %s: %s",
  18648. config_options[DOCUMENT_ROOT].name,
  18649. ebuf);
  18650. }
  18651. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18652. free_context(ctx);
  18653. pthread_setspecific(sTlsKey, NULL);
  18654. return NULL;
  18655. }
  18656. /* state remains valid */
  18657. ctx->lua_background_state = (void *)state;
  18658. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18659. } else {
  18660. ctx->lua_background_state = 0;
  18661. }
  18662. #endif
  18663. /* Step by step initialization of ctx - depending on build options */
  18664. #if !defined(NO_FILESYSTEMS)
  18665. if (!set_gpass_option(ctx, NULL)) {
  18666. const char *err_msg = "Invalid global password file";
  18667. /* Fatal error - abort start. */
  18668. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18669. if (error != NULL) {
  18670. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18671. mg_snprintf(NULL,
  18672. NULL, /* No truncation check for error buffers */
  18673. error->text,
  18674. error->text_buffer_size,
  18675. "%s",
  18676. err_msg);
  18677. }
  18678. free_context(ctx);
  18679. pthread_setspecific(sTlsKey, NULL);
  18680. return NULL;
  18681. }
  18682. #endif
  18683. #if defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  18684. if (!mg_sslctx_init(ctx, NULL)) {
  18685. const char *err_msg = "Error initializing SSL context";
  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_TLS_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. #elif !defined(NO_SSL)
  18702. if (!init_ssl_ctx(ctx, NULL)) {
  18703. const char *err_msg = "Error initializing SSL context";
  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_TLS_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_ports_option(ctx)) {
  18721. const char *err_msg = "Failed to setup server ports";
  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_PORTS_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. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18738. if (!set_uid_option(ctx)) {
  18739. const char *err_msg = "Failed to run as configured user";
  18740. /* Fatal error - abort start. */
  18741. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18742. if (error != NULL) {
  18743. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18744. mg_snprintf(NULL,
  18745. NULL, /* No truncation check for error buffers */
  18746. error->text,
  18747. error->text_buffer_size,
  18748. "%s",
  18749. err_msg);
  18750. }
  18751. free_context(ctx);
  18752. pthread_setspecific(sTlsKey, NULL);
  18753. return NULL;
  18754. }
  18755. #endif
  18756. if (!set_acl_option(ctx)) {
  18757. const char *err_msg = "Failed to setup access control list";
  18758. /* Fatal error - abort start. */
  18759. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18760. if (error != NULL) {
  18761. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18762. mg_snprintf(NULL,
  18763. NULL, /* No truncation check for error buffers */
  18764. error->text,
  18765. error->text_buffer_size,
  18766. "%s",
  18767. err_msg);
  18768. }
  18769. free_context(ctx);
  18770. pthread_setspecific(sTlsKey, NULL);
  18771. return NULL;
  18772. }
  18773. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18774. ctx->worker_threadids =
  18775. (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18776. sizeof(pthread_t),
  18777. ctx);
  18778. if (ctx->worker_threadids == NULL) {
  18779. const char *err_msg = "Not enough memory for worker thread ID array";
  18780. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18781. if (error != NULL) {
  18782. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18783. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18784. * (unsigned)sizeof(pthread_t);
  18785. mg_snprintf(NULL,
  18786. NULL, /* No truncation check for error buffers */
  18787. error->text,
  18788. error->text_buffer_size,
  18789. "%s",
  18790. err_msg);
  18791. }
  18792. free_context(ctx);
  18793. pthread_setspecific(sTlsKey, NULL);
  18794. return NULL;
  18795. }
  18796. ctx->worker_connections =
  18797. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18798. sizeof(struct mg_connection),
  18799. ctx);
  18800. if (ctx->worker_connections == NULL) {
  18801. const char *err_msg =
  18802. "Not enough memory for worker thread connection array";
  18803. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18804. if (error != NULL) {
  18805. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18806. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18807. * (unsigned)sizeof(struct mg_connection);
  18808. mg_snprintf(NULL,
  18809. NULL, /* No truncation check for error buffers */
  18810. error->text,
  18811. error->text_buffer_size,
  18812. "%s",
  18813. err_msg);
  18814. }
  18815. free_context(ctx);
  18816. pthread_setspecific(sTlsKey, NULL);
  18817. return NULL;
  18818. }
  18819. #if defined(ALTERNATIVE_QUEUE)
  18820. ctx->client_wait_events =
  18821. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18822. sizeof(ctx->client_wait_events[0]),
  18823. ctx);
  18824. if (ctx->client_wait_events == NULL) {
  18825. const char *err_msg = "Not enough memory for worker event array";
  18826. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18827. mg_free(ctx->worker_threadids);
  18828. if (error != NULL) {
  18829. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18830. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18831. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18832. mg_snprintf(NULL,
  18833. NULL, /* No truncation check for error buffers */
  18834. error->text,
  18835. error->text_buffer_size,
  18836. "%s",
  18837. err_msg);
  18838. }
  18839. free_context(ctx);
  18840. pthread_setspecific(sTlsKey, NULL);
  18841. return NULL;
  18842. }
  18843. ctx->client_socks =
  18844. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18845. sizeof(ctx->client_socks[0]),
  18846. ctx);
  18847. if (ctx->client_socks == NULL) {
  18848. const char *err_msg = "Not enough memory for worker socket array";
  18849. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18850. mg_free(ctx->client_wait_events);
  18851. mg_free(ctx->worker_threadids);
  18852. if (error != NULL) {
  18853. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18854. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18855. * (unsigned)sizeof(ctx->client_socks[0]);
  18856. mg_snprintf(NULL,
  18857. NULL, /* No truncation check for error buffers */
  18858. error->text,
  18859. error->text_buffer_size,
  18860. "%s",
  18861. err_msg);
  18862. }
  18863. free_context(ctx);
  18864. pthread_setspecific(sTlsKey, NULL);
  18865. return NULL;
  18866. }
  18867. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18868. ctx->client_wait_events[i] = event_create();
  18869. if (ctx->client_wait_events[i] == 0) {
  18870. const char *err_msg = "Error creating worker event %i";
  18871. mg_cry_ctx_internal(ctx, err_msg, i);
  18872. while (i > 0) {
  18873. i--;
  18874. event_destroy(ctx->client_wait_events[i]);
  18875. }
  18876. mg_free(ctx->client_socks);
  18877. mg_free(ctx->client_wait_events);
  18878. mg_free(ctx->worker_threadids);
  18879. if (error != NULL) {
  18880. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18881. error->code_sub = (unsigned)ERRNO;
  18882. mg_snprintf(NULL,
  18883. NULL, /* No truncation check for error buffers */
  18884. error->text,
  18885. error->text_buffer_size,
  18886. err_msg,
  18887. i);
  18888. }
  18889. free_context(ctx);
  18890. pthread_setspecific(sTlsKey, NULL);
  18891. return NULL;
  18892. }
  18893. }
  18894. #endif
  18895. #if defined(USE_TIMERS)
  18896. if (timers_init(ctx) != 0) {
  18897. const char *err_msg = "Error creating timers";
  18898. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18899. if (error != NULL) {
  18900. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18901. error->code_sub = (unsigned)ERRNO;
  18902. mg_snprintf(NULL,
  18903. NULL, /* No truncation check for error buffers */
  18904. error->text,
  18905. error->text_buffer_size,
  18906. "%s",
  18907. err_msg);
  18908. }
  18909. free_context(ctx);
  18910. pthread_setspecific(sTlsKey, NULL);
  18911. return NULL;
  18912. }
  18913. #endif
  18914. /* Context has been created - init user libraries */
  18915. if (ctx->callbacks.init_context) {
  18916. ctx->callbacks.init_context(ctx);
  18917. }
  18918. /* From now, the context is successfully created.
  18919. * When it is destroyed, the exit callback should be called. */
  18920. ctx->callbacks.exit_context = exit_callback;
  18921. ctx->context_type = CONTEXT_SERVER; /* server context */
  18922. /* Start worker threads */
  18923. for (i = 0; (int)i < prespawnthreadcount; i++) {
  18924. /* worker_thread sets up the other fields */
  18925. if (mg_start_worker_thread(ctx, 0) != 0) {
  18926. long error_no = (long)ERRNO;
  18927. /* thread was not created */
  18928. if (ctx->spawned_worker_threads > 0) {
  18929. /* If the second, third, ... thread cannot be created, set a
  18930. * warning, but keep running. */
  18931. mg_cry_ctx_internal(ctx,
  18932. "Cannot start worker thread %i: error %ld",
  18933. ctx->spawned_worker_threads + 1,
  18934. error_no);
  18935. /* If the server initialization should stop here, all
  18936. * threads that have already been created must be stopped
  18937. * first, before any free_context(ctx) call.
  18938. */
  18939. } else {
  18940. /* If the first worker thread cannot be created, stop
  18941. * initialization and free the entire server context. */
  18942. mg_cry_ctx_internal(ctx,
  18943. "Cannot create threads: error %ld",
  18944. error_no);
  18945. if (error != NULL) {
  18946. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18947. error->code_sub = (unsigned)error_no;
  18948. mg_snprintf(
  18949. NULL,
  18950. NULL, /* No truncation check for error buffers */
  18951. error->text,
  18952. error->text_buffer_size,
  18953. "Cannot create first worker thread: error %ld",
  18954. error_no);
  18955. }
  18956. free_context(ctx);
  18957. pthread_setspecific(sTlsKey, NULL);
  18958. return NULL;
  18959. }
  18960. break;
  18961. }
  18962. }
  18963. /* Start master (listening) thread */
  18964. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18965. pthread_setspecific(sTlsKey, NULL);
  18966. return ctx;
  18967. }
  18968. CIVETWEB_API struct mg_context *
  18969. mg_start(const struct mg_callbacks *callbacks,
  18970. void *user_data,
  18971. const char **options)
  18972. {
  18973. struct mg_init_data init = {0};
  18974. init.callbacks = callbacks;
  18975. init.user_data = user_data;
  18976. init.configuration_options = options;
  18977. return mg_start2(&init, NULL);
  18978. }
  18979. /* Add an additional domain to an already running web server. */
  18980. CIVETWEB_API int
  18981. mg_start_domain2(struct mg_context *ctx,
  18982. const char **options,
  18983. struct mg_error_data *error)
  18984. {
  18985. const char *name;
  18986. const char *value;
  18987. const char *default_value;
  18988. struct mg_domain_context *new_dom;
  18989. struct mg_domain_context *dom;
  18990. int idx, i;
  18991. if (error != NULL) {
  18992. error->code = MG_ERROR_DATA_CODE_OK;
  18993. error->code_sub = 0;
  18994. if (error->text_buffer_size > 0) {
  18995. *error->text = 0;
  18996. }
  18997. }
  18998. if ((ctx == NULL) || (options == NULL)) {
  18999. if (error != NULL) {
  19000. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  19001. mg_snprintf(NULL,
  19002. NULL, /* No truncation check for error buffers */
  19003. error->text,
  19004. error->text_buffer_size,
  19005. "%s",
  19006. "Invalid parameters");
  19007. }
  19008. return -1;
  19009. }
  19010. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  19011. if (error != NULL) {
  19012. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  19013. mg_snprintf(NULL,
  19014. NULL, /* No truncation check for error buffers */
  19015. error->text,
  19016. error->text_buffer_size,
  19017. "%s",
  19018. "Server already stopped");
  19019. }
  19020. return -7;
  19021. }
  19022. new_dom = (struct mg_domain_context *)
  19023. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  19024. if (!new_dom) {
  19025. /* Out of memory */
  19026. if (error != NULL) {
  19027. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  19028. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  19029. mg_snprintf(NULL,
  19030. NULL, /* No truncation check for error buffers */
  19031. error->text,
  19032. error->text_buffer_size,
  19033. "%s",
  19034. "Out or memory");
  19035. }
  19036. return -6;
  19037. }
  19038. /* Store options - TODO: unite duplicate code */
  19039. while (options && (name = *options++) != NULL) {
  19040. idx = get_option_index(name);
  19041. if (idx == -1) {
  19042. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  19043. if (error != NULL) {
  19044. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19045. error->code_sub = (unsigned)-1;
  19046. mg_snprintf(NULL,
  19047. NULL, /* No truncation check for error buffers */
  19048. error->text,
  19049. error->text_buffer_size,
  19050. "Invalid option: %s",
  19051. name);
  19052. }
  19053. mg_free(new_dom);
  19054. return -2;
  19055. } else if ((value = *options++) == NULL) {
  19056. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  19057. if (error != NULL) {
  19058. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19059. error->code_sub = (unsigned)idx;
  19060. mg_snprintf(NULL,
  19061. NULL, /* No truncation check for error buffers */
  19062. error->text,
  19063. error->text_buffer_size,
  19064. "Invalid option value: %s",
  19065. name);
  19066. }
  19067. mg_free(new_dom);
  19068. return -2;
  19069. }
  19070. if (new_dom->config[idx] != NULL) {
  19071. /* Duplicate option: Later values overwrite earlier ones. */
  19072. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  19073. mg_free(new_dom->config[idx]);
  19074. }
  19075. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  19076. DEBUG_TRACE("[%s] -> [%s]", name, value);
  19077. }
  19078. /* Authentication domain is mandatory */
  19079. /* TODO: Maybe use a new option hostname? */
  19080. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  19081. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  19082. if (error != NULL) {
  19083. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  19084. error->code_sub = AUTHENTICATION_DOMAIN;
  19085. mg_snprintf(NULL,
  19086. NULL, /* No truncation check for error buffers */
  19087. error->text,
  19088. error->text_buffer_size,
  19089. "Mandatory option %s missing",
  19090. config_options[AUTHENTICATION_DOMAIN].name);
  19091. }
  19092. mg_free(new_dom);
  19093. return -4;
  19094. }
  19095. /* Set default value if needed. Take the config value from
  19096. * ctx as a default value. */
  19097. for (i = 0; config_options[i].name != NULL; i++) {
  19098. default_value = ctx->dd.config[i];
  19099. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  19100. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  19101. }
  19102. }
  19103. new_dom->handlers = NULL;
  19104. new_dom->next = NULL;
  19105. new_dom->nonce_count = 0;
  19106. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  19107. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  19108. new_dom->shared_lua_websockets = NULL;
  19109. #endif
  19110. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  19111. if (!init_ssl_ctx(ctx, new_dom)) {
  19112. /* Init SSL failed */
  19113. if (error != NULL) {
  19114. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  19115. mg_snprintf(NULL,
  19116. NULL, /* No truncation check for error buffers */
  19117. error->text,
  19118. error->text_buffer_size,
  19119. "%s",
  19120. "Initializing SSL context failed");
  19121. }
  19122. mg_free(new_dom);
  19123. return -3;
  19124. }
  19125. #endif
  19126. /* Add element to linked list. */
  19127. mg_lock_context(ctx);
  19128. idx = 0;
  19129. dom = &(ctx->dd);
  19130. for (;;) {
  19131. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  19132. dom->config[AUTHENTICATION_DOMAIN])) {
  19133. /* Domain collision */
  19134. mg_cry_ctx_internal(ctx,
  19135. "domain %s already in use",
  19136. new_dom->config[AUTHENTICATION_DOMAIN]);
  19137. if (error != NULL) {
  19138. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  19139. mg_snprintf(NULL,
  19140. NULL, /* No truncation check for error buffers */
  19141. error->text,
  19142. error->text_buffer_size,
  19143. "Domain %s specified by %s is already in use",
  19144. new_dom->config[AUTHENTICATION_DOMAIN],
  19145. config_options[AUTHENTICATION_DOMAIN].name);
  19146. }
  19147. mg_free(new_dom);
  19148. mg_unlock_context(ctx);
  19149. return -5;
  19150. }
  19151. /* Count number of domains */
  19152. idx++;
  19153. if (dom->next == NULL) {
  19154. dom->next = new_dom;
  19155. break;
  19156. }
  19157. dom = dom->next;
  19158. }
  19159. mg_unlock_context(ctx);
  19160. /* Return domain number */
  19161. return idx;
  19162. }
  19163. CIVETWEB_API int
  19164. mg_start_domain(struct mg_context *ctx, const char **options)
  19165. {
  19166. return mg_start_domain2(ctx, options, NULL);
  19167. }
  19168. /* Feature check API function */
  19169. CIVETWEB_API unsigned
  19170. mg_check_feature(unsigned feature)
  19171. {
  19172. static const unsigned feature_set = 0
  19173. /* Set bits for available features according to API documentation.
  19174. * This bit mask is created at compile time, according to the active
  19175. * preprocessor defines. It is a single const value at runtime. */
  19176. #if !defined(NO_FILES)
  19177. | MG_FEATURES_FILES
  19178. #endif
  19179. #if !defined(NO_SSL) || defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  19180. | MG_FEATURES_SSL
  19181. #endif
  19182. #if !defined(NO_CGI)
  19183. | MG_FEATURES_CGI
  19184. #endif
  19185. #if defined(USE_IPV6)
  19186. | MG_FEATURES_IPV6
  19187. #endif
  19188. #if defined(USE_WEBSOCKET)
  19189. | MG_FEATURES_WEBSOCKET
  19190. #endif
  19191. #if defined(USE_LUA)
  19192. | MG_FEATURES_LUA
  19193. #endif
  19194. #if defined(USE_DUKTAPE)
  19195. | MG_FEATURES_SSJS
  19196. #endif
  19197. #if !defined(NO_CACHING)
  19198. | MG_FEATURES_CACHE
  19199. #endif
  19200. #if defined(USE_SERVER_STATS)
  19201. | MG_FEATURES_STATS
  19202. #endif
  19203. #if defined(USE_ZLIB)
  19204. | MG_FEATURES_COMPRESSION
  19205. #endif
  19206. #if defined(USE_HTTP2)
  19207. | MG_FEATURES_HTTP2
  19208. #endif
  19209. #if defined(USE_X_DOM_SOCKET)
  19210. | MG_FEATURES_X_DOMAIN_SOCKET
  19211. #endif
  19212. /* Set some extra bits not defined in the API documentation.
  19213. * These bits may change without further notice. */
  19214. #if defined(MG_LEGACY_INTERFACE)
  19215. | 0x80000000u
  19216. #endif
  19217. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19218. | 0x40000000u
  19219. #endif
  19220. #if !defined(NO_RESPONSE_BUFFERING)
  19221. | 0x20000000u
  19222. #endif
  19223. #if defined(MEMORY_DEBUGGING)
  19224. | 0x10000000u
  19225. #endif
  19226. ;
  19227. return (feature & feature_set);
  19228. }
  19229. static size_t
  19230. mg_str_append(char **dst, char *end, const char *src)
  19231. {
  19232. size_t len = strlen(src);
  19233. if (*dst != end) {
  19234. /* Append src if enough space, or close dst. */
  19235. if ((size_t)(end - *dst) > len) {
  19236. strcpy(*dst, src);
  19237. *dst += len;
  19238. } else {
  19239. *dst = end;
  19240. }
  19241. }
  19242. return len;
  19243. }
  19244. /* Get system information. It can be printed or stored by the caller.
  19245. * Return the size of available information. */
  19246. CIVETWEB_API int
  19247. mg_get_system_info(char *buffer, int buflen)
  19248. {
  19249. char *end, *append_eoobj = NULL, block[256];
  19250. size_t system_info_length = 0;
  19251. #if defined(_WIN32)
  19252. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19253. #else
  19254. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19255. #endif
  19256. if ((buffer == NULL) || (buflen < 1)) {
  19257. buflen = 0;
  19258. end = buffer;
  19259. } else {
  19260. *buffer = 0;
  19261. end = buffer + buflen;
  19262. }
  19263. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19264. /* has enough space to append eoobj */
  19265. append_eoobj = buffer;
  19266. if (end) {
  19267. end -= sizeof(eoobj) - 1;
  19268. }
  19269. }
  19270. system_info_length += mg_str_append(&buffer, end, "{");
  19271. /* Server version */
  19272. {
  19273. const char *version = mg_version();
  19274. mg_snprintf(NULL,
  19275. NULL,
  19276. block,
  19277. sizeof(block),
  19278. "%s\"version\" : \"%s\"",
  19279. eol,
  19280. version);
  19281. system_info_length += mg_str_append(&buffer, end, block);
  19282. }
  19283. /* System info */
  19284. {
  19285. #if defined(_WIN32)
  19286. DWORD dwVersion = 0;
  19287. DWORD dwMajorVersion = 0;
  19288. DWORD dwMinorVersion = 0;
  19289. SYSTEM_INFO si;
  19290. GetSystemInfo(&si);
  19291. #if defined(_MSC_VER)
  19292. #pragma warning(push)
  19293. /* GetVersion was declared deprecated */
  19294. #pragma warning(disable : 4996)
  19295. #endif
  19296. dwVersion = GetVersion();
  19297. #if defined(_MSC_VER)
  19298. #pragma warning(pop)
  19299. #endif
  19300. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  19301. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  19302. mg_snprintf(NULL,
  19303. NULL,
  19304. block,
  19305. sizeof(block),
  19306. ",%s\"os\" : \"Windows %u.%u\"",
  19307. eol,
  19308. (unsigned)dwMajorVersion,
  19309. (unsigned)dwMinorVersion);
  19310. system_info_length += mg_str_append(&buffer, end, block);
  19311. mg_snprintf(NULL,
  19312. NULL,
  19313. block,
  19314. sizeof(block),
  19315. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  19316. eol,
  19317. (unsigned)si.wProcessorArchitecture,
  19318. (unsigned)si.dwNumberOfProcessors,
  19319. (unsigned)si.dwActiveProcessorMask);
  19320. system_info_length += mg_str_append(&buffer, end, block);
  19321. #elif defined(__rtems__)
  19322. mg_snprintf(NULL,
  19323. NULL,
  19324. block,
  19325. sizeof(block),
  19326. ",%s\"os\" : \"%s %s\"",
  19327. eol,
  19328. "RTEMS",
  19329. rtems_version());
  19330. system_info_length += mg_str_append(&buffer, end, block);
  19331. #elif defined(__ZEPHYR__)
  19332. mg_snprintf(NULL,
  19333. NULL,
  19334. block,
  19335. sizeof(block),
  19336. ",%s\"os\" : \"%s\"",
  19337. eol,
  19338. "Zephyr OS",
  19339. ZEPHYR_VERSION);
  19340. system_info_length += mg_str_append(&buffer, end, block);
  19341. #else
  19342. struct utsname name;
  19343. memset(&name, 0, sizeof(name));
  19344. uname(&name);
  19345. mg_snprintf(NULL,
  19346. NULL,
  19347. block,
  19348. sizeof(block),
  19349. ",%s\"os\" : \"%s %s (%s) - %s\"",
  19350. eol,
  19351. name.sysname,
  19352. name.version,
  19353. name.release,
  19354. name.machine);
  19355. system_info_length += mg_str_append(&buffer, end, block);
  19356. #endif
  19357. }
  19358. /* Features */
  19359. {
  19360. mg_snprintf(NULL,
  19361. NULL,
  19362. block,
  19363. sizeof(block),
  19364. ",%s\"features\" : %lu"
  19365. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  19366. eol,
  19367. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  19368. eol,
  19369. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  19370. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  19371. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  19372. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  19373. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  19374. : "",
  19375. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  19376. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  19377. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  19378. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  19379. system_info_length += mg_str_append(&buffer, end, block);
  19380. #if defined(USE_LUA)
  19381. mg_snprintf(NULL,
  19382. NULL,
  19383. block,
  19384. sizeof(block),
  19385. ",%s\"lua_version\" : \"%u (%s)\"",
  19386. eol,
  19387. (unsigned)LUA_VERSION_NUM,
  19388. LUA_RELEASE);
  19389. system_info_length += mg_str_append(&buffer, end, block);
  19390. #endif
  19391. #if defined(USE_DUKTAPE)
  19392. mg_snprintf(NULL,
  19393. NULL,
  19394. block,
  19395. sizeof(block),
  19396. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  19397. eol,
  19398. (unsigned)DUK_VERSION / 10000,
  19399. ((unsigned)DUK_VERSION / 100) % 100,
  19400. (unsigned)DUK_VERSION % 100);
  19401. system_info_length += mg_str_append(&buffer, end, block);
  19402. #endif
  19403. }
  19404. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  19405. {
  19406. #if defined(BUILD_DATE)
  19407. const char *bd = BUILD_DATE;
  19408. #else
  19409. #if defined(GCC_DIAGNOSTIC)
  19410. #if GCC_VERSION >= 40900
  19411. #pragma GCC diagnostic push
  19412. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  19413. * does not work in some versions. If "BUILD_DATE" is defined to some
  19414. * string, it is used instead of __DATE__. */
  19415. #pragma GCC diagnostic ignored "-Wdate-time"
  19416. #endif
  19417. #endif
  19418. const char *bd = __DATE__;
  19419. #if defined(GCC_DIAGNOSTIC)
  19420. #if GCC_VERSION >= 40900
  19421. #pragma GCC diagnostic pop
  19422. #endif
  19423. #endif
  19424. #endif
  19425. mg_snprintf(
  19426. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  19427. system_info_length += mg_str_append(&buffer, end, block);
  19428. }
  19429. /* Compiler information */
  19430. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  19431. {
  19432. #if defined(_MSC_VER)
  19433. mg_snprintf(NULL,
  19434. NULL,
  19435. block,
  19436. sizeof(block),
  19437. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  19438. eol,
  19439. (unsigned)_MSC_VER,
  19440. (unsigned)_MSC_FULL_VER);
  19441. system_info_length += mg_str_append(&buffer, end, block);
  19442. #elif defined(__MINGW64__)
  19443. mg_snprintf(NULL,
  19444. NULL,
  19445. block,
  19446. sizeof(block),
  19447. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  19448. eol,
  19449. (unsigned)__MINGW64_VERSION_MAJOR,
  19450. (unsigned)__MINGW64_VERSION_MINOR);
  19451. system_info_length += mg_str_append(&buffer, end, block);
  19452. mg_snprintf(NULL,
  19453. NULL,
  19454. block,
  19455. sizeof(block),
  19456. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19457. eol,
  19458. (unsigned)__MINGW32_MAJOR_VERSION,
  19459. (unsigned)__MINGW32_MINOR_VERSION);
  19460. system_info_length += mg_str_append(&buffer, end, block);
  19461. #elif defined(__MINGW32__)
  19462. mg_snprintf(NULL,
  19463. NULL,
  19464. block,
  19465. sizeof(block),
  19466. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19467. eol,
  19468. (unsigned)__MINGW32_MAJOR_VERSION,
  19469. (unsigned)__MINGW32_MINOR_VERSION);
  19470. system_info_length += mg_str_append(&buffer, end, block);
  19471. #elif defined(__clang__)
  19472. mg_snprintf(NULL,
  19473. NULL,
  19474. block,
  19475. sizeof(block),
  19476. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  19477. eol,
  19478. __clang_major__,
  19479. __clang_minor__,
  19480. __clang_patchlevel__,
  19481. __clang_version__);
  19482. system_info_length += mg_str_append(&buffer, end, block);
  19483. #elif defined(__GNUC__)
  19484. mg_snprintf(NULL,
  19485. NULL,
  19486. block,
  19487. sizeof(block),
  19488. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  19489. eol,
  19490. (unsigned)__GNUC__,
  19491. (unsigned)__GNUC_MINOR__,
  19492. (unsigned)__GNUC_PATCHLEVEL__);
  19493. system_info_length += mg_str_append(&buffer, end, block);
  19494. #elif defined(__INTEL_COMPILER)
  19495. mg_snprintf(NULL,
  19496. NULL,
  19497. block,
  19498. sizeof(block),
  19499. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  19500. eol,
  19501. (unsigned)__INTEL_COMPILER);
  19502. system_info_length += mg_str_append(&buffer, end, block);
  19503. #elif defined(__BORLANDC__)
  19504. mg_snprintf(NULL,
  19505. NULL,
  19506. block,
  19507. sizeof(block),
  19508. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  19509. eol,
  19510. (unsigned)__BORLANDC__);
  19511. system_info_length += mg_str_append(&buffer, end, block);
  19512. #elif defined(__SUNPRO_C)
  19513. mg_snprintf(NULL,
  19514. NULL,
  19515. block,
  19516. sizeof(block),
  19517. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  19518. eol,
  19519. (unsigned)__SUNPRO_C);
  19520. system_info_length += mg_str_append(&buffer, end, block);
  19521. #else
  19522. mg_snprintf(NULL,
  19523. NULL,
  19524. block,
  19525. sizeof(block),
  19526. ",%s\"compiler\" : \"other\"",
  19527. eol);
  19528. system_info_length += mg_str_append(&buffer, end, block);
  19529. #endif
  19530. }
  19531. /* Determine 32/64 bit data mode.
  19532. * see https://en.wikipedia.org/wiki/64-bit_computing */
  19533. {
  19534. mg_snprintf(NULL,
  19535. NULL,
  19536. block,
  19537. sizeof(block),
  19538. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  19539. "char:%u/%u, "
  19540. "ptr:%u, size:%u, time:%u\"",
  19541. eol,
  19542. (unsigned)sizeof(short),
  19543. (unsigned)sizeof(int),
  19544. (unsigned)sizeof(long),
  19545. (unsigned)sizeof(long long),
  19546. (unsigned)sizeof(float),
  19547. (unsigned)sizeof(double),
  19548. (unsigned)sizeof(long double),
  19549. (unsigned)sizeof(char),
  19550. (unsigned)sizeof(wchar_t),
  19551. (unsigned)sizeof(void *),
  19552. (unsigned)sizeof(size_t),
  19553. (unsigned)sizeof(time_t));
  19554. system_info_length += mg_str_append(&buffer, end, block);
  19555. }
  19556. /* Terminate string */
  19557. if (append_eoobj) {
  19558. strcat(append_eoobj, eoobj);
  19559. }
  19560. system_info_length += sizeof(eoobj) - 1;
  19561. return (int)system_info_length;
  19562. }
  19563. /* Get context information. It can be printed or stored by the caller.
  19564. * Return the size of available information. */
  19565. CIVETWEB_API int
  19566. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19567. {
  19568. #if defined(USE_SERVER_STATS)
  19569. char *end, *append_eoobj = NULL, block[256];
  19570. size_t context_info_length = 0;
  19571. #if defined(_WIN32)
  19572. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19573. #else
  19574. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19575. #endif
  19576. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19577. if ((buffer == NULL) || (buflen < 1)) {
  19578. buflen = 0;
  19579. end = buffer;
  19580. } else {
  19581. *buffer = 0;
  19582. end = buffer + buflen;
  19583. }
  19584. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19585. /* has enough space to append eoobj */
  19586. append_eoobj = buffer;
  19587. end -= sizeof(eoobj) - 1;
  19588. }
  19589. context_info_length += mg_str_append(&buffer, end, "{");
  19590. if (ms) { /* <-- should be always true */
  19591. /* Memory information */
  19592. int blockCount = (int)ms->blockCount;
  19593. int64_t totalMemUsed = ms->totalMemUsed;
  19594. int64_t maxMemUsed = ms->maxMemUsed;
  19595. if (totalMemUsed > maxMemUsed) {
  19596. maxMemUsed = totalMemUsed;
  19597. }
  19598. mg_snprintf(NULL,
  19599. NULL,
  19600. block,
  19601. sizeof(block),
  19602. "%s\"memory\" : {%s"
  19603. "\"blocks\" : %i,%s"
  19604. "\"used\" : %" INT64_FMT ",%s"
  19605. "\"maxUsed\" : %" INT64_FMT "%s"
  19606. "}",
  19607. eol,
  19608. eol,
  19609. blockCount,
  19610. eol,
  19611. totalMemUsed,
  19612. eol,
  19613. maxMemUsed,
  19614. eol);
  19615. context_info_length += mg_str_append(&buffer, end, block);
  19616. }
  19617. if (ctx) {
  19618. /* Declare all variables at begin of the block, to comply
  19619. * with old C standards. */
  19620. char start_time_str[64] = {0};
  19621. char now_str[64] = {0};
  19622. time_t start_time = ctx->start_time;
  19623. time_t now = time(NULL);
  19624. int64_t total_data_read, total_data_written;
  19625. int active_connections = (int)ctx->active_connections;
  19626. int max_active_connections = (int)ctx->max_active_connections;
  19627. int total_connections = (int)ctx->total_connections;
  19628. if (active_connections > max_active_connections) {
  19629. max_active_connections = active_connections;
  19630. }
  19631. if (active_connections > total_connections) {
  19632. total_connections = active_connections;
  19633. }
  19634. /* Connections information */
  19635. mg_snprintf(NULL,
  19636. NULL,
  19637. block,
  19638. sizeof(block),
  19639. ",%s\"connections\" : {%s"
  19640. "\"active\" : %i,%s"
  19641. "\"maxActive\" : %i,%s"
  19642. "\"total\" : %i%s"
  19643. "}",
  19644. eol,
  19645. eol,
  19646. active_connections,
  19647. eol,
  19648. max_active_connections,
  19649. eol,
  19650. total_connections,
  19651. eol);
  19652. context_info_length += mg_str_append(&buffer, end, block);
  19653. /* Queue information */
  19654. #if !defined(ALTERNATIVE_QUEUE)
  19655. mg_snprintf(NULL,
  19656. NULL,
  19657. block,
  19658. sizeof(block),
  19659. ",%s\"queue\" : {%s"
  19660. "\"length\" : %i,%s"
  19661. "\"filled\" : %i,%s"
  19662. "\"maxFilled\" : %i,%s"
  19663. "\"full\" : %s%s"
  19664. "}",
  19665. eol,
  19666. eol,
  19667. ctx->sq_size,
  19668. eol,
  19669. ctx->sq_head - ctx->sq_tail,
  19670. eol,
  19671. ctx->sq_max_fill,
  19672. eol,
  19673. (ctx->sq_blocked ? "true" : "false"),
  19674. eol);
  19675. context_info_length += mg_str_append(&buffer, end, block);
  19676. #endif
  19677. /* Requests information */
  19678. mg_snprintf(NULL,
  19679. NULL,
  19680. block,
  19681. sizeof(block),
  19682. ",%s\"requests\" : {%s"
  19683. "\"total\" : %lu%s"
  19684. "}",
  19685. eol,
  19686. eol,
  19687. (unsigned long)ctx->total_requests,
  19688. eol);
  19689. context_info_length += mg_str_append(&buffer, end, block);
  19690. /* Data information */
  19691. total_data_read =
  19692. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19693. total_data_written =
  19694. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19695. mg_snprintf(NULL,
  19696. NULL,
  19697. block,
  19698. sizeof(block),
  19699. ",%s\"data\" : {%s"
  19700. "\"read\" : %" INT64_FMT ",%s"
  19701. "\"written\" : %" INT64_FMT "%s"
  19702. "}",
  19703. eol,
  19704. eol,
  19705. total_data_read,
  19706. eol,
  19707. total_data_written,
  19708. eol);
  19709. context_info_length += mg_str_append(&buffer, end, block);
  19710. /* Execution time information */
  19711. gmt_time_string(start_time_str,
  19712. sizeof(start_time_str) - 1,
  19713. &start_time);
  19714. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19715. mg_snprintf(NULL,
  19716. NULL,
  19717. block,
  19718. sizeof(block),
  19719. ",%s\"time\" : {%s"
  19720. "\"uptime\" : %.0f,%s"
  19721. "\"start\" : \"%s\",%s"
  19722. "\"now\" : \"%s\"%s"
  19723. "}",
  19724. eol,
  19725. eol,
  19726. difftime(now, start_time),
  19727. eol,
  19728. start_time_str,
  19729. eol,
  19730. now_str,
  19731. eol);
  19732. context_info_length += mg_str_append(&buffer, end, block);
  19733. }
  19734. /* Terminate string */
  19735. if (append_eoobj) {
  19736. strcat(append_eoobj, eoobj);
  19737. }
  19738. context_info_length += sizeof(eoobj) - 1;
  19739. return (int)context_info_length;
  19740. #else
  19741. (void)ctx;
  19742. if ((buffer != NULL) && (buflen > 0)) {
  19743. *buffer = 0;
  19744. }
  19745. return 0;
  19746. #endif
  19747. }
  19748. CIVETWEB_API void
  19749. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19750. {
  19751. /* https://github.com/civetweb/civetweb/issues/727 */
  19752. if (conn != NULL) {
  19753. conn->must_close = 1;
  19754. }
  19755. }
  19756. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19757. /* Get connection information. It can be printed or stored by the caller.
  19758. * Return the size of available information. */
  19759. CIVETWEB_API int
  19760. mg_get_connection_info(const struct mg_context *ctx,
  19761. int idx,
  19762. char *buffer,
  19763. int buflen)
  19764. {
  19765. const struct mg_connection *conn;
  19766. const struct mg_request_info *ri;
  19767. char *end, *append_eoobj = NULL, block[256];
  19768. size_t connection_info_length = 0;
  19769. int state = 0;
  19770. const char *state_str = "unknown";
  19771. #if defined(_WIN32)
  19772. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19773. #else
  19774. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19775. #endif
  19776. if ((buffer == NULL) || (buflen < 1)) {
  19777. buflen = 0;
  19778. end = buffer;
  19779. } else {
  19780. *buffer = 0;
  19781. end = buffer + buflen;
  19782. }
  19783. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19784. /* has enough space to append eoobj */
  19785. append_eoobj = buffer;
  19786. end -= sizeof(eoobj) - 1;
  19787. }
  19788. if ((ctx == NULL) || (idx < 0)) {
  19789. /* Parameter error */
  19790. return 0;
  19791. }
  19792. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19793. /* Out of range */
  19794. return 0;
  19795. }
  19796. /* Take connection [idx]. This connection is not locked in
  19797. * any way, so some other thread might use it. */
  19798. conn = (ctx->worker_connections) + idx;
  19799. /* Initialize output string */
  19800. connection_info_length += mg_str_append(&buffer, end, "{");
  19801. /* Init variables */
  19802. ri = &(conn->request_info);
  19803. #if defined(USE_SERVER_STATS)
  19804. state = conn->conn_state;
  19805. /* State as string */
  19806. switch (state) {
  19807. case 0:
  19808. state_str = "undefined";
  19809. break;
  19810. case 1:
  19811. state_str = "not used";
  19812. break;
  19813. case 2:
  19814. state_str = "init";
  19815. break;
  19816. case 3:
  19817. state_str = "ready";
  19818. break;
  19819. case 4:
  19820. state_str = "processing";
  19821. break;
  19822. case 5:
  19823. state_str = "processed";
  19824. break;
  19825. case 6:
  19826. state_str = "to close";
  19827. break;
  19828. case 7:
  19829. state_str = "closing";
  19830. break;
  19831. case 8:
  19832. state_str = "closed";
  19833. break;
  19834. case 9:
  19835. state_str = "done";
  19836. break;
  19837. }
  19838. #endif
  19839. /* Connection info */
  19840. if ((state >= 3) && (state < 9)) {
  19841. mg_snprintf(NULL,
  19842. NULL,
  19843. block,
  19844. sizeof(block),
  19845. "%s\"connection\" : {%s"
  19846. "\"remote\" : {%s"
  19847. "\"protocol\" : \"%s\",%s"
  19848. "\"addr\" : \"%s\",%s"
  19849. "\"port\" : %u%s"
  19850. "},%s"
  19851. "\"handled_requests\" : %u%s"
  19852. "}",
  19853. eol,
  19854. eol,
  19855. eol,
  19856. get_proto_name(conn),
  19857. eol,
  19858. ri->remote_addr,
  19859. eol,
  19860. ri->remote_port,
  19861. eol,
  19862. eol,
  19863. conn->handled_requests,
  19864. eol);
  19865. connection_info_length += mg_str_append(&buffer, end, block);
  19866. }
  19867. /* Request info */
  19868. if ((state >= 4) && (state < 6)) {
  19869. mg_snprintf(NULL,
  19870. NULL,
  19871. block,
  19872. sizeof(block),
  19873. "%s%s\"request_info\" : {%s"
  19874. "\"method\" : \"%s\",%s"
  19875. "\"uri\" : \"%s\",%s"
  19876. "\"query\" : %s%s%s%s"
  19877. "}",
  19878. (connection_info_length > 1 ? "," : ""),
  19879. eol,
  19880. eol,
  19881. ri->request_method,
  19882. eol,
  19883. ri->request_uri,
  19884. eol,
  19885. ri->query_string ? "\"" : "",
  19886. ri->query_string ? ri->query_string : "null",
  19887. ri->query_string ? "\"" : "",
  19888. eol);
  19889. connection_info_length += mg_str_append(&buffer, end, block);
  19890. }
  19891. /* Execution time information */
  19892. if ((state >= 2) && (state < 9)) {
  19893. char start_time_str[64] = {0};
  19894. char close_time_str[64] = {0};
  19895. time_t start_time = conn->conn_birth_time;
  19896. time_t close_time = 0;
  19897. double time_diff;
  19898. gmt_time_string(start_time_str,
  19899. sizeof(start_time_str) - 1,
  19900. &start_time);
  19901. #if defined(USE_SERVER_STATS)
  19902. close_time = conn->conn_close_time;
  19903. #endif
  19904. if (close_time != 0) {
  19905. time_diff = difftime(close_time, start_time);
  19906. gmt_time_string(close_time_str,
  19907. sizeof(close_time_str) - 1,
  19908. &close_time);
  19909. } else {
  19910. time_t now = time(NULL);
  19911. time_diff = difftime(now, start_time);
  19912. close_time_str[0] = 0; /* or use "now" ? */
  19913. }
  19914. mg_snprintf(NULL,
  19915. NULL,
  19916. block,
  19917. sizeof(block),
  19918. "%s%s\"time\" : {%s"
  19919. "\"uptime\" : %.0f,%s"
  19920. "\"start\" : \"%s\",%s"
  19921. "\"closed\" : \"%s\"%s"
  19922. "}",
  19923. (connection_info_length > 1 ? "," : ""),
  19924. eol,
  19925. eol,
  19926. time_diff,
  19927. eol,
  19928. start_time_str,
  19929. eol,
  19930. close_time_str,
  19931. eol);
  19932. connection_info_length += mg_str_append(&buffer, end, block);
  19933. }
  19934. /* Remote user name */
  19935. if ((ri->remote_user) && (state < 9)) {
  19936. mg_snprintf(NULL,
  19937. NULL,
  19938. block,
  19939. sizeof(block),
  19940. "%s%s\"user\" : {%s"
  19941. "\"name\" : \"%s\",%s"
  19942. "}",
  19943. (connection_info_length > 1 ? "," : ""),
  19944. eol,
  19945. eol,
  19946. ri->remote_user,
  19947. eol);
  19948. connection_info_length += mg_str_append(&buffer, end, block);
  19949. }
  19950. /* Data block */
  19951. if (state >= 3) {
  19952. mg_snprintf(NULL,
  19953. NULL,
  19954. block,
  19955. sizeof(block),
  19956. "%s%s\"data\" : {%s"
  19957. "\"read\" : %" INT64_FMT ",%s"
  19958. "\"written\" : %" INT64_FMT "%s"
  19959. "}",
  19960. (connection_info_length > 1 ? "," : ""),
  19961. eol,
  19962. eol,
  19963. conn->consumed_content,
  19964. eol,
  19965. conn->num_bytes_sent,
  19966. eol);
  19967. connection_info_length += mg_str_append(&buffer, end, block);
  19968. }
  19969. /* State */
  19970. mg_snprintf(NULL,
  19971. NULL,
  19972. block,
  19973. sizeof(block),
  19974. "%s%s\"state\" : \"%s\"",
  19975. (connection_info_length > 1 ? "," : ""),
  19976. eol,
  19977. state_str);
  19978. connection_info_length += mg_str_append(&buffer, end, block);
  19979. /* Terminate string */
  19980. if (append_eoobj) {
  19981. strcat(append_eoobj, eoobj);
  19982. }
  19983. connection_info_length += sizeof(eoobj) - 1;
  19984. return (int)connection_info_length;
  19985. }
  19986. #if 0
  19987. /* Get handler information. Not fully implemented. Is it required? */
  19988. CIVETWEB_API int
  19989. mg_get_handler_info(struct mg_context *ctx,
  19990. char *buffer,
  19991. int buflen)
  19992. {
  19993. int handler_info_len = 0;
  19994. struct mg_handler_info *tmp_rh;
  19995. mg_lock_context(ctx);
  19996. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19997. if (buflen > handler_info_len + tmp_rh->uri_len) {
  19998. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19999. }
  20000. handler_info_len += tmp_rh->uri_len;
  20001. switch (tmp_rh->handler_type) {
  20002. case REQUEST_HANDLER:
  20003. (void)tmp_rh->handler;
  20004. break;
  20005. case WEBSOCKET_HANDLER:
  20006. (void)tmp_rh->connect_handler;
  20007. (void)tmp_rh->ready_handler;
  20008. (void)tmp_rh->data_handler;
  20009. (void)tmp_rh->close_handler;
  20010. break;
  20011. case AUTH_HANDLER:
  20012. (void)tmp_rh->auth_handler;
  20013. break;
  20014. }
  20015. (void)cbdata;
  20016. }
  20017. mg_unlock_context(ctx);
  20018. return handler_info_len;
  20019. }
  20020. #endif
  20021. #endif
  20022. /* Initialize this library. This function does not need to be thread safe.
  20023. */
  20024. CIVETWEB_API unsigned
  20025. mg_init_library(unsigned features)
  20026. {
  20027. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  20028. unsigned features_inited = features_to_init;
  20029. if (mg_init_library_called <= 0) {
  20030. /* Not initialized yet */
  20031. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  20032. return 0;
  20033. }
  20034. }
  20035. mg_global_lock();
  20036. if (mg_init_library_called <= 0) {
  20037. int i;
  20038. size_t len;
  20039. #if defined(_WIN32)
  20040. int file_mutex_init = 1;
  20041. int wsa = 1;
  20042. #else
  20043. int mutexattr_init = 1;
  20044. #endif
  20045. int failed = 1;
  20046. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  20047. if (key_create == 0) {
  20048. #if defined(_WIN32)
  20049. file_mutex_init =
  20050. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  20051. if (file_mutex_init == 0) {
  20052. /* Start WinSock */
  20053. WSADATA data;
  20054. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  20055. }
  20056. #else
  20057. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  20058. if (mutexattr_init == 0) {
  20059. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  20060. PTHREAD_MUTEX_RECURSIVE);
  20061. }
  20062. #endif
  20063. }
  20064. if (failed) {
  20065. #if defined(_WIN32)
  20066. if (wsa == 0) {
  20067. (void)WSACleanup();
  20068. }
  20069. if (file_mutex_init == 0) {
  20070. (void)pthread_mutex_destroy(&global_log_file_lock);
  20071. }
  20072. #else
  20073. if (mutexattr_init == 0) {
  20074. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20075. }
  20076. #endif
  20077. if (key_create == 0) {
  20078. (void)pthread_key_delete(sTlsKey);
  20079. }
  20080. mg_global_unlock();
  20081. (void)pthread_mutex_destroy(&global_lock_mutex);
  20082. return 0;
  20083. }
  20084. len = 1;
  20085. for (i = 0; http_methods[i].name != NULL; i++) {
  20086. size_t sl = strlen(http_methods[i].name);
  20087. len += sl;
  20088. if (i > 0) {
  20089. len += 2;
  20090. }
  20091. }
  20092. all_methods = (char *)mg_malloc(len);
  20093. if (!all_methods) {
  20094. /* Must never happen */
  20095. mg_global_unlock();
  20096. (void)pthread_mutex_destroy(&global_lock_mutex);
  20097. return 0;
  20098. }
  20099. all_methods[0] = 0;
  20100. for (i = 0; http_methods[i].name != NULL; i++) {
  20101. if (i > 0) {
  20102. strcat(all_methods, ", ");
  20103. strcat(all_methods, http_methods[i].name);
  20104. } else {
  20105. strcpy(all_methods, http_methods[i].name);
  20106. }
  20107. }
  20108. }
  20109. #if defined(USE_LUA)
  20110. lua_init_optional_libraries();
  20111. #endif
  20112. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  20113. || defined(OPENSSL_API_3_0)) \
  20114. && !defined(NO_SSL)
  20115. if (features_to_init & MG_FEATURES_SSL) {
  20116. if (!mg_openssl_initialized) {
  20117. char ebuf[128];
  20118. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  20119. mg_openssl_initialized = 1;
  20120. } else {
  20121. (void)ebuf;
  20122. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  20123. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  20124. }
  20125. } else {
  20126. /* ssl already initialized */
  20127. }
  20128. }
  20129. #endif
  20130. if (mg_init_library_called <= 0) {
  20131. mg_init_library_called = 1;
  20132. } else {
  20133. mg_init_library_called++;
  20134. }
  20135. mg_global_unlock();
  20136. return features_inited;
  20137. }
  20138. /* Un-initialize this library. */
  20139. CIVETWEB_API unsigned
  20140. mg_exit_library(void)
  20141. {
  20142. if (mg_init_library_called <= 0) {
  20143. return 0;
  20144. }
  20145. mg_global_lock();
  20146. mg_init_library_called--;
  20147. if (mg_init_library_called == 0) {
  20148. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  20149. if (mg_openssl_initialized) {
  20150. uninitialize_openssl();
  20151. mg_openssl_initialized = 0;
  20152. }
  20153. #endif
  20154. #if defined(_WIN32)
  20155. (void)WSACleanup();
  20156. (void)pthread_mutex_destroy(&global_log_file_lock);
  20157. #else
  20158. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20159. #endif
  20160. (void)pthread_key_delete(sTlsKey);
  20161. #if defined(USE_LUA)
  20162. lua_exit_optional_libraries();
  20163. #endif
  20164. mg_free(all_methods);
  20165. all_methods = NULL;
  20166. mg_global_unlock();
  20167. (void)pthread_mutex_destroy(&global_lock_mutex);
  20168. return 1;
  20169. }
  20170. mg_global_unlock();
  20171. return 1;
  20172. }
  20173. /* End of civetweb.c */