civetweb.c 596 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426
  1. /* Copyright (c) 2013-2021 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #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) /* defined for tdm-gcc so we can use getnameinfo */
  51. #define _WIN32_WINNT 0x0502
  52. #endif
  53. #else
  54. #if !defined(_GNU_SOURCE)
  55. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  56. #endif
  57. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  58. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  59. #endif
  60. #if defined(__LSB_VERSION__) || defined(__sun)
  61. #define NEED_TIMEGM
  62. #define NO_THREAD_NAME
  63. #endif
  64. #if !defined(_LARGEFILE_SOURCE)
  65. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  66. #endif
  67. #if !defined(_FILE_OFFSET_BITS)
  68. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  69. #endif
  70. #if !defined(__STDC_FORMAT_MACROS)
  71. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  72. #endif
  73. #if !defined(__STDC_LIMIT_MACROS)
  74. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  75. #endif
  76. #if !defined(_DARWIN_UNLIMITED_SELECT)
  77. #define _DARWIN_UNLIMITED_SELECT
  78. #endif
  79. #if defined(__sun)
  80. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  81. #define __inline inline /* not recognized on older compiler versions */
  82. #endif
  83. #endif
  84. #if defined(__clang__)
  85. /* Enable reserved-id-macro warning again. */
  86. #pragma GCC diagnostic pop
  87. #endif
  88. #if defined(USE_LUA)
  89. #define USE_TIMERS
  90. #endif
  91. #if defined(_MSC_VER)
  92. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  93. #pragma warning(disable : 4306)
  94. /* conditional expression is constant: introduced by FD_SET(..) */
  95. #pragma warning(disable : 4127)
  96. /* non-constant aggregate initializer: issued due to missing C99 support */
  97. #pragma warning(disable : 4204)
  98. /* padding added after data member */
  99. #pragma warning(disable : 4820)
  100. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  101. #pragma warning(disable : 4668)
  102. /* no function prototype given: converting '()' to '(void)' */
  103. #pragma warning(disable : 4255)
  104. /* function has been selected for automatic inline expansion */
  105. #pragma warning(disable : 4711)
  106. #endif
  107. /* This code uses static_assert to check some conditions.
  108. * Unfortunately some compilers still do not support it, so we have a
  109. * replacement function here. */
  110. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  111. #define mg_static_assert _Static_assert
  112. #elif defined(__cplusplus) && __cplusplus >= 201103L
  113. #define mg_static_assert static_assert
  114. #else
  115. char static_assert_replacement[1];
  116. #define mg_static_assert(cond, txt) \
  117. extern char static_assert_replacement[(cond) ? 1 : -1]
  118. #endif
  119. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  120. "int data type size check");
  121. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  122. "pointer data type size check");
  123. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  124. /* Select queue implementation. Diagnosis features originally only implemented
  125. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  126. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  127. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  128. * implementation, since the queue length is independent from the number of
  129. * worker threads there, while the new queue is one element per worker thread.
  130. *
  131. */
  132. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  133. /* The queues are exclusive or - only one can be used. */
  134. #error \
  135. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  136. #endif
  137. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  138. /* Use a default implementation */
  139. #define NO_ALTERNATIVE_QUEUE
  140. #endif
  141. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  142. /* File system access:
  143. * NO_FILES = do not serve any files from the file system automatically.
  144. * However, with NO_FILES CivetWeb may still write log files, read access
  145. * control files, default error page files or use API functions like
  146. * mg_send_file in callbacks to send files from the server local
  147. * file system.
  148. * NO_FILES only disables the automatic mapping between URLs and local
  149. * file names.
  150. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  151. * devices without file system. Logging to files in not available
  152. * (use callbacks instead) and API functions like mg_send_file are not
  153. * available.
  154. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  155. */
  156. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  157. #endif
  158. /* DTL -- including winsock2.h works better if lean and mean */
  159. #if !defined(WIN32_LEAN_AND_MEAN)
  160. #define WIN32_LEAN_AND_MEAN
  161. #endif
  162. #if defined(__SYMBIAN32__)
  163. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  164. * Symbian is no longer maintained since 2014-01-01.
  165. * Support for Symbian has been removed from CivetWeb
  166. */
  167. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  168. #endif /* __SYMBIAN32__ */
  169. #if defined(__ZEPHYR__)
  170. #include <ctype.h>
  171. #include <fcntl.h>
  172. #include <netdb.h>
  173. #include <poll.h>
  174. #include <pthread.h>
  175. #include <stdio.h>
  176. #include <stdlib.h>
  177. #include <string.h>
  178. #include <sys/socket.h>
  179. #include <time.h>
  180. #include <zephyr/kernel.h>
  181. /* Max worker threads is the max of pthreads minus the main application thread
  182. * and minus the main civetweb thread, thus -2
  183. */
  184. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  185. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  186. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  187. #else
  188. #define ZEPHYR_STACK_SIZE (1024 * 16)
  189. #endif
  190. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  191. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  192. MAX_WORKER_THREADS,
  193. ZEPHYR_STACK_SIZE);
  194. static int zephyr_worker_stack_index;
  195. #endif
  196. #if !defined(CIVETWEB_HEADER_INCLUDED)
  197. /* Include the header file here, so the CivetWeb interface is defined for the
  198. * entire implementation, including the following forward definitions. */
  199. #include "civetweb.h"
  200. #endif
  201. #if !defined(DEBUG_TRACE)
  202. #if defined(DEBUG)
  203. static void DEBUG_TRACE_FUNC(const char *func,
  204. unsigned line,
  205. PRINTF_FORMAT_STRING(const char *fmt),
  206. ...) PRINTF_ARGS(3, 4);
  207. #define DEBUG_TRACE(fmt, ...) \
  208. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  209. #define NEED_DEBUG_TRACE_FUNC
  210. #if !defined(DEBUG_TRACE_STREAM)
  211. #define DEBUG_TRACE_STREAM stdout
  212. #endif
  213. #else
  214. #define DEBUG_TRACE(fmt, ...) \
  215. do { \
  216. } while (0)
  217. #endif /* DEBUG */
  218. #endif /* DEBUG_TRACE */
  219. #if !defined(DEBUG_ASSERT)
  220. #if defined(DEBUG)
  221. #include <stdlib.h>
  222. #define DEBUG_ASSERT(cond) \
  223. do { \
  224. if (!(cond)) { \
  225. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  226. exit(2); /* Exit with error */ \
  227. } \
  228. } while (0)
  229. #else
  230. #define DEBUG_ASSERT(cond)
  231. #endif /* DEBUG */
  232. #endif
  233. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  234. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  235. __attribute__((no_instrument_function));
  236. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  237. __attribute__((no_instrument_function));
  238. void
  239. __cyg_profile_func_enter(void *this_fn, void *call_site)
  240. {
  241. if ((void *)this_fn != (void *)printf) {
  242. printf("E %p %p\n", this_fn, call_site);
  243. }
  244. }
  245. void
  246. __cyg_profile_func_exit(void *this_fn, void *call_site)
  247. {
  248. if ((void *)this_fn != (void *)printf) {
  249. printf("X %p %p\n", this_fn, call_site);
  250. }
  251. }
  252. #endif
  253. #if !defined(IGNORE_UNUSED_RESULT)
  254. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  255. #endif
  256. #if defined(__GNUC__) || defined(__MINGW32__)
  257. /* GCC unused function attribute seems fundamentally broken.
  258. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  259. * OR UNUSED" for individual functions failed.
  260. * Either the compiler creates an "unused-function" warning if a
  261. * function is not marked with __attribute__((unused)).
  262. * On the other hand, if the function is marked with this attribute,
  263. * but is used, the compiler raises a completely idiotic
  264. * "used-but-marked-unused" warning - and
  265. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  266. * raises error: unknown option after "#pragma GCC diagnostic".
  267. * Disable this warning completely, until the GCC guys sober up
  268. * again.
  269. */
  270. #pragma GCC diagnostic ignored "-Wunused-function"
  271. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  272. #else
  273. #define FUNCTION_MAY_BE_UNUSED
  274. #endif
  275. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  276. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  277. #include <errno.h>
  278. #include <fcntl.h>
  279. #include <signal.h>
  280. #include <stdlib.h>
  281. #include <sys/stat.h>
  282. #include <sys/types.h>
  283. #endif /* !_WIN32_WCE */
  284. #if defined(__clang__)
  285. /* When using -Weverything, clang does not accept it's own headers
  286. * in a release build configuration. Disable what is too much in
  287. * -Weverything. */
  288. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  289. #endif
  290. #if defined(__GNUC__) || defined(__MINGW32__)
  291. /* Who on earth came to the conclusion, using __DATE__ should rise
  292. * an "expansion of date or time macro is not reproducible"
  293. * warning. That's exactly what was intended by using this macro.
  294. * Just disable this nonsense warning. */
  295. /* And disabling them does not work either:
  296. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  297. * #pragma clang diagnostic ignored "-Wdate-time"
  298. * So we just have to disable ALL warnings for some lines
  299. * of code.
  300. * This seems to be a known GCC bug, not resolved since 2012:
  301. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  302. */
  303. #endif
  304. #if defined(__MACH__) /* Apple OSX section */
  305. #if defined(__clang__)
  306. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  307. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  308. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  309. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  310. #endif
  311. #endif
  312. #ifndef CLOCK_MONOTONIC
  313. #define CLOCK_MONOTONIC (1)
  314. #endif
  315. #ifndef CLOCK_REALTIME
  316. #define CLOCK_REALTIME (2)
  317. #endif
  318. #include <mach/clock.h>
  319. #include <mach/mach.h>
  320. #include <mach/mach_time.h>
  321. #include <sys/errno.h>
  322. #include <sys/time.h>
  323. /* clock_gettime is not implemented on OSX prior to 10.12 */
  324. static int
  325. _civet_clock_gettime(int clk_id, struct timespec *t)
  326. {
  327. memset(t, 0, sizeof(*t));
  328. if (clk_id == CLOCK_REALTIME) {
  329. struct timeval now;
  330. int rv = gettimeofday(&now, NULL);
  331. if (rv) {
  332. return rv;
  333. }
  334. t->tv_sec = now.tv_sec;
  335. t->tv_nsec = now.tv_usec * 1000;
  336. return 0;
  337. } else if (clk_id == CLOCK_MONOTONIC) {
  338. static uint64_t clock_start_time = 0;
  339. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  340. uint64_t now = mach_absolute_time();
  341. if (clock_start_time == 0) {
  342. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  343. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  344. /* appease "unused variable" warning for release builds */
  345. (void)mach_status;
  346. clock_start_time = now;
  347. }
  348. now = (uint64_t)((double)(now - clock_start_time)
  349. * (double)timebase_ifo.numer
  350. / (double)timebase_ifo.denom);
  351. t->tv_sec = now / 1000000000;
  352. t->tv_nsec = now % 1000000000;
  353. return 0;
  354. }
  355. return -1; /* EINVAL - Clock ID is unknown */
  356. }
  357. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  358. #if defined(__CLOCK_AVAILABILITY)
  359. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  360. * declared but it may be NULL at runtime. So we need to check before using
  361. * it. */
  362. static int
  363. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  364. {
  365. if (clock_gettime) {
  366. return clock_gettime(clk_id, t);
  367. }
  368. return _civet_clock_gettime(clk_id, t);
  369. }
  370. #define clock_gettime _civet_safe_clock_gettime
  371. #else
  372. #define clock_gettime _civet_clock_gettime
  373. #endif
  374. #endif
  375. #if !defined(_WIN32)
  376. /* Unix might return different error codes indicating to try again.
  377. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  378. * decades ago, but better check both and let the compile optimize it. */
  379. #define ERROR_TRY_AGAIN(err) \
  380. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  381. #endif
  382. #if defined(USE_ZLIB)
  383. #include "zconf.h"
  384. #include "zlib.h"
  385. #endif
  386. /********************************************************************/
  387. /* CivetWeb configuration defines */
  388. /********************************************************************/
  389. /* Maximum number of threads that can be configured.
  390. * The number of threads actually created depends on the "num_threads"
  391. * configuration parameter, but this is the upper limit. */
  392. #if !defined(MAX_WORKER_THREADS)
  393. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  394. #endif
  395. /* Timeout interval for select/poll calls.
  396. * The timeouts depend on "*_timeout_ms" configuration values, but long
  397. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  398. * This reduces the time required to stop the server. */
  399. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  400. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  401. #endif
  402. /* Do not try to compress files smaller than this limit. */
  403. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  404. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  405. #endif
  406. #if !defined(PASSWORDS_FILE_NAME)
  407. #define PASSWORDS_FILE_NAME ".htpasswd"
  408. #endif
  409. /* Initial buffer size for all CGI environment variables. In case there is
  410. * not enough space, another block is allocated. */
  411. #if !defined(CGI_ENVIRONMENT_SIZE)
  412. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  413. #endif
  414. /* Maximum number of environment variables. */
  415. #if !defined(MAX_CGI_ENVIR_VARS)
  416. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  417. #endif
  418. /* General purpose buffer size. */
  419. #if !defined(MG_BUF_LEN) /* in bytes */
  420. #define MG_BUF_LEN (1024 * 8)
  421. #endif
  422. /********************************************************************/
  423. /* Helper makros */
  424. #if !defined(ARRAY_SIZE)
  425. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  426. #endif
  427. #include <stdint.h>
  428. /* Standard defines */
  429. #if !defined(INT64_MAX)
  430. #define INT64_MAX (9223372036854775807)
  431. #endif
  432. #define SHUTDOWN_RD (0)
  433. #define SHUTDOWN_WR (1)
  434. #define SHUTDOWN_BOTH (2)
  435. mg_static_assert(MAX_WORKER_THREADS >= 1,
  436. "worker threads must be a positive number");
  437. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  438. "size_t data type size check");
  439. #if defined(_WIN32) /* WINDOWS include block */
  440. #include <malloc.h> /* *alloc( */
  441. #include <stdlib.h> /* *alloc( */
  442. #include <time.h> /* struct timespec */
  443. #include <windows.h>
  444. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  445. #include <ws2tcpip.h>
  446. typedef const char *SOCK_OPT_TYPE;
  447. /* For a detailed description of these *_PATH_MAX defines, see
  448. * https://github.com/civetweb/civetweb/issues/937. */
  449. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  450. * null termination, rounded up to the next 4 bytes boundary */
  451. #define UTF8_PATH_MAX (3 * 260)
  452. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  453. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  454. #define UTF16_PATH_MAX (260)
  455. #if !defined(_IN_PORT_T)
  456. #if !defined(in_port_t)
  457. #define in_port_t u_short
  458. #endif
  459. #endif
  460. #if defined(_WIN32_WCE)
  461. #error "WinCE support has ended"
  462. #endif
  463. #include <direct.h>
  464. #include <io.h>
  465. #include <process.h>
  466. #define MAKEUQUAD(lo, hi) \
  467. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  468. #define RATE_DIFF (10000000) /* 100 nsecs */
  469. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  470. #define SYS2UNIX_TIME(lo, hi) \
  471. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  472. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  473. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  474. * Also use _strtoui64 on modern M$ compilers */
  475. #if defined(_MSC_VER)
  476. #if (_MSC_VER < 1300)
  477. #define STRX(x) #x
  478. #define STR(x) STRX(x)
  479. #define __func__ __FILE__ ":" STR(__LINE__)
  480. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  481. #define strtoll(x, y, z) (_atoi64(x))
  482. #else
  483. #define __func__ __FUNCTION__
  484. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  485. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  486. #endif
  487. #endif /* _MSC_VER */
  488. #define ERRNO ((int)(GetLastError()))
  489. #define NO_SOCKLEN_T
  490. #if defined(_WIN64) || defined(__MINGW64__)
  491. #if !defined(SSL_LIB)
  492. #if defined(OPENSSL_API_3_0)
  493. #define SSL_LIB "libssl-3-x64.dll"
  494. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  495. #endif
  496. #if defined(OPENSSL_API_1_1)
  497. #define SSL_LIB "libssl-1_1-x64.dll"
  498. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  499. #endif /* OPENSSL_API_1_1 */
  500. #if defined(OPENSSL_API_1_0)
  501. #define SSL_LIB "ssleay64.dll"
  502. #define CRYPTO_LIB "libeay64.dll"
  503. #endif /* OPENSSL_API_1_0 */
  504. #endif
  505. #else /* defined(_WIN64) || defined(__MINGW64__) */
  506. #if !defined(SSL_LIB)
  507. #if defined(OPENSSL_API_3_0)
  508. #define SSL_LIB "libssl-3.dll"
  509. #define CRYPTO_LIB "libcrypto-3.dll"
  510. #endif
  511. #if defined(OPENSSL_API_1_1)
  512. #define SSL_LIB "libssl-1_1.dll"
  513. #define CRYPTO_LIB "libcrypto-1_1.dll"
  514. #endif /* OPENSSL_API_1_1 */
  515. #if defined(OPENSSL_API_1_0)
  516. #define SSL_LIB "ssleay32.dll"
  517. #define CRYPTO_LIB "libeay32.dll"
  518. #endif /* OPENSSL_API_1_0 */
  519. #endif /* SSL_LIB */
  520. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  521. #define O_NONBLOCK (0)
  522. #if !defined(W_OK)
  523. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  524. #endif
  525. #define _POSIX_
  526. #define INT64_FMT "I64d"
  527. #define UINT64_FMT "I64u"
  528. #define WINCDECL __cdecl
  529. #define vsnprintf_impl _vsnprintf
  530. #define access _access
  531. #define mg_sleep(x) (Sleep(x))
  532. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  533. #if !defined(popen)
  534. #define popen(x, y) (_popen(x, y))
  535. #endif
  536. #if !defined(pclose)
  537. #define pclose(x) (_pclose(x))
  538. #endif
  539. #define close(x) (_close(x))
  540. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  541. #define RTLD_LAZY (0)
  542. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  543. #define fdopen(x, y) (_fdopen((x), (y)))
  544. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  545. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  546. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  547. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  548. #define sleep(x) (Sleep((x)*1000))
  549. #define rmdir(x) (_rmdir(x))
  550. #if defined(_WIN64) || !defined(__MINGW32__)
  551. /* Only MinGW 32 bit is missing this function */
  552. #define timegm(x) (_mkgmtime(x))
  553. #else
  554. time_t timegm(struct tm *tm);
  555. #define NEED_TIMEGM
  556. #endif
  557. #if !defined(fileno)
  558. #define fileno(x) (_fileno(x))
  559. #endif /* !fileno MINGW #defines fileno */
  560. typedef struct {
  561. CRITICAL_SECTION sec; /* Immovable */
  562. } pthread_mutex_t;
  563. typedef DWORD pthread_key_t;
  564. typedef HANDLE pthread_t;
  565. typedef struct {
  566. pthread_mutex_t threadIdSec;
  567. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  568. } pthread_cond_t;
  569. #if !defined(__clockid_t_defined)
  570. typedef DWORD clockid_t;
  571. #endif
  572. #if !defined(CLOCK_MONOTONIC)
  573. #define CLOCK_MONOTONIC (1)
  574. #endif
  575. #if !defined(CLOCK_REALTIME)
  576. #define CLOCK_REALTIME (2)
  577. #endif
  578. #if !defined(CLOCK_THREAD)
  579. #define CLOCK_THREAD (3)
  580. #endif
  581. #if !defined(CLOCK_PROCESS)
  582. #define CLOCK_PROCESS (4)
  583. #endif
  584. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  585. #define _TIMESPEC_DEFINED
  586. #endif
  587. #if !defined(_TIMESPEC_DEFINED)
  588. struct timespec {
  589. time_t tv_sec; /* seconds */
  590. long tv_nsec; /* nanoseconds */
  591. };
  592. #endif
  593. #if !defined(WIN_PTHREADS_TIME_H)
  594. #define MUST_IMPLEMENT_CLOCK_GETTIME
  595. #endif
  596. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  597. #define clock_gettime mg_clock_gettime
  598. static int
  599. clock_gettime(clockid_t clk_id, struct timespec *tp)
  600. {
  601. FILETIME ft;
  602. ULARGE_INTEGER li, li2;
  603. BOOL ok = FALSE;
  604. double d;
  605. static double perfcnt_per_sec = 0.0;
  606. static BOOL initialized = FALSE;
  607. if (!initialized) {
  608. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  609. perfcnt_per_sec = 1.0 / li.QuadPart;
  610. initialized = TRUE;
  611. }
  612. if (tp) {
  613. memset(tp, 0, sizeof(*tp));
  614. if (clk_id == CLOCK_REALTIME) {
  615. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  616. GetSystemTimeAsFileTime(&ft);
  617. li.LowPart = ft.dwLowDateTime;
  618. li.HighPart = ft.dwHighDateTime;
  619. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  620. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  621. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  622. ok = TRUE;
  623. /* END: CLOCK_REALTIME */
  624. } else if (clk_id == CLOCK_MONOTONIC) {
  625. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  626. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  627. d = li.QuadPart * perfcnt_per_sec;
  628. tp->tv_sec = (time_t)d;
  629. d -= (double)tp->tv_sec;
  630. tp->tv_nsec = (long)(d * 1.0E9);
  631. ok = TRUE;
  632. /* END: CLOCK_MONOTONIC */
  633. } else if (clk_id == CLOCK_THREAD) {
  634. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  635. FILETIME t_create, t_exit, t_kernel, t_user;
  636. if (GetThreadTimes(GetCurrentThread(),
  637. &t_create,
  638. &t_exit,
  639. &t_kernel,
  640. &t_user)) {
  641. li.LowPart = t_user.dwLowDateTime;
  642. li.HighPart = t_user.dwHighDateTime;
  643. li2.LowPart = t_kernel.dwLowDateTime;
  644. li2.HighPart = t_kernel.dwHighDateTime;
  645. li.QuadPart += li2.QuadPart;
  646. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  647. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  648. ok = TRUE;
  649. }
  650. /* END: CLOCK_THREAD */
  651. } else if (clk_id == CLOCK_PROCESS) {
  652. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  653. FILETIME t_create, t_exit, t_kernel, t_user;
  654. if (GetProcessTimes(GetCurrentProcess(),
  655. &t_create,
  656. &t_exit,
  657. &t_kernel,
  658. &t_user)) {
  659. li.LowPart = t_user.dwLowDateTime;
  660. li.HighPart = t_user.dwHighDateTime;
  661. li2.LowPart = t_kernel.dwLowDateTime;
  662. li2.HighPart = t_kernel.dwHighDateTime;
  663. li.QuadPart += li2.QuadPart;
  664. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  665. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  666. ok = TRUE;
  667. }
  668. /* END: CLOCK_PROCESS */
  669. } else {
  670. /* BEGIN: unknown clock */
  671. /* ok = FALSE; already set by init */
  672. /* END: unknown clock */
  673. }
  674. }
  675. return ok ? 0 : -1;
  676. }
  677. #endif
  678. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  679. static int pthread_mutex_lock(pthread_mutex_t *);
  680. static int pthread_mutex_unlock(pthread_mutex_t *);
  681. static void path_to_unicode(const struct mg_connection *conn,
  682. const char *path,
  683. wchar_t *wbuf,
  684. size_t wbuf_len);
  685. /* All file operations need to be rewritten to solve #246. */
  686. struct mg_file;
  687. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  688. /* POSIX dirent interface */
  689. struct dirent {
  690. char d_name[UTF8_PATH_MAX];
  691. };
  692. typedef struct DIR {
  693. HANDLE handle;
  694. WIN32_FIND_DATAW info;
  695. struct dirent result;
  696. } DIR;
  697. #if defined(HAVE_POLL)
  698. #define mg_pollfd pollfd
  699. #else
  700. struct mg_pollfd {
  701. SOCKET fd;
  702. short events;
  703. short revents;
  704. };
  705. #endif
  706. /* Mark required libraries */
  707. #if defined(_MSC_VER)
  708. #pragma comment(lib, "Ws2_32.lib")
  709. #endif
  710. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  711. #include <inttypes.h>
  712. /* Linux & co. internally use UTF8 */
  713. #define UTF8_PATH_MAX (PATH_MAX)
  714. typedef const void *SOCK_OPT_TYPE;
  715. #if defined(ANDROID)
  716. typedef unsigned short int in_port_t;
  717. #endif
  718. #if !defined(__ZEPHYR__)
  719. #include <arpa/inet.h>
  720. #include <ctype.h>
  721. #include <dirent.h>
  722. #include <grp.h>
  723. #include <limits.h>
  724. #include <netdb.h>
  725. #include <netinet/in.h>
  726. #include <netinet/tcp.h>
  727. #include <pthread.h>
  728. #include <pwd.h>
  729. #include <stdarg.h>
  730. #include <stddef.h>
  731. #include <stdio.h>
  732. #include <stdlib.h>
  733. #include <string.h>
  734. #include <sys/poll.h>
  735. #include <sys/socket.h>
  736. #include <sys/time.h>
  737. #include <sys/utsname.h>
  738. #include <sys/wait.h>
  739. #include <time.h>
  740. #include <unistd.h>
  741. #if defined(USE_X_DOM_SOCKET)
  742. #include <sys/un.h>
  743. #endif
  744. #endif
  745. #define vsnprintf_impl vsnprintf
  746. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  747. #include <dlfcn.h>
  748. #endif
  749. #if defined(__MACH__)
  750. #define SSL_LIB "libssl.dylib"
  751. #define CRYPTO_LIB "libcrypto.dylib"
  752. #else
  753. #if !defined(SSL_LIB)
  754. #define SSL_LIB "libssl.so"
  755. #endif
  756. #if !defined(CRYPTO_LIB)
  757. #define CRYPTO_LIB "libcrypto.so"
  758. #endif
  759. #endif
  760. #if !defined(O_BINARY)
  761. #define O_BINARY (0)
  762. #endif /* O_BINARY */
  763. #define closesocket(a) (close(a))
  764. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  765. #define mg_remove(conn, x) (remove(x))
  766. #define mg_sleep(x) (usleep((x)*1000))
  767. #define mg_opendir(conn, x) (opendir(x))
  768. #define mg_closedir(x) (closedir(x))
  769. #define mg_readdir(x) (readdir(x))
  770. #define ERRNO (errno)
  771. #define INVALID_SOCKET (-1)
  772. #define INT64_FMT PRId64
  773. #define UINT64_FMT PRIu64
  774. typedef int SOCKET;
  775. #define WINCDECL
  776. #if defined(__hpux)
  777. /* HPUX 11 does not have monotonic, fall back to realtime */
  778. #if !defined(CLOCK_MONOTONIC)
  779. #define CLOCK_MONOTONIC CLOCK_REALTIME
  780. #endif
  781. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  782. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  783. * the prototypes use int* rather than socklen_t* which matches the
  784. * actual library expectation. When called with the wrong size arg
  785. * accept() returns a zero client inet addr and check_acl() always
  786. * fails. Since socklen_t is widely used below, just force replace
  787. * their typedef with int. - DTL
  788. */
  789. #define socklen_t int
  790. #endif /* hpux */
  791. #define mg_pollfd pollfd
  792. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  793. /* In case our C library is missing "timegm", provide an implementation */
  794. #if defined(NEED_TIMEGM)
  795. static inline int
  796. is_leap(int y)
  797. {
  798. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  799. }
  800. static inline int
  801. count_leap(int y)
  802. {
  803. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  804. }
  805. time_t
  806. timegm(struct tm *tm)
  807. {
  808. static const unsigned short ydays[] = {
  809. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  810. int year = tm->tm_year + 1900;
  811. int mon = tm->tm_mon;
  812. int mday = tm->tm_mday - 1;
  813. int hour = tm->tm_hour;
  814. int min = tm->tm_min;
  815. int sec = tm->tm_sec;
  816. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  817. || (mday >= ydays[mon + 1] - ydays[mon]
  818. + (mon == 1 && is_leap(year) ? 1 : 0))
  819. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  820. return -1;
  821. time_t res = year - 1970;
  822. res *= 365;
  823. res += mday;
  824. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  825. res += count_leap(year);
  826. res *= 24;
  827. res += hour;
  828. res *= 60;
  829. res += min;
  830. res *= 60;
  831. res += sec;
  832. return res;
  833. }
  834. #endif /* NEED_TIMEGM */
  835. /* va_copy should always be a macro, C99 and C++11 - DTL */
  836. #if !defined(va_copy)
  837. #define va_copy(x, y) ((x) = (y))
  838. #endif
  839. #if defined(_WIN32)
  840. /* Create substitutes for POSIX functions in Win32. */
  841. #if defined(GCC_DIAGNOSTIC)
  842. /* Show no warning in case system functions are not used. */
  843. #pragma GCC diagnostic push
  844. #pragma GCC diagnostic ignored "-Wunused-function"
  845. #endif
  846. static pthread_mutex_t global_log_file_lock;
  847. FUNCTION_MAY_BE_UNUSED
  848. static DWORD
  849. pthread_self(void)
  850. {
  851. return GetCurrentThreadId();
  852. }
  853. FUNCTION_MAY_BE_UNUSED
  854. static int
  855. pthread_key_create(
  856. pthread_key_t *key,
  857. void (*_ignored)(void *) /* destructor not supported for Windows */
  858. )
  859. {
  860. (void)_ignored;
  861. if ((key != 0)) {
  862. *key = TlsAlloc();
  863. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  864. }
  865. return -2;
  866. }
  867. FUNCTION_MAY_BE_UNUSED
  868. static int
  869. pthread_key_delete(pthread_key_t key)
  870. {
  871. return TlsFree(key) ? 0 : 1;
  872. }
  873. FUNCTION_MAY_BE_UNUSED
  874. static int
  875. pthread_setspecific(pthread_key_t key, void *value)
  876. {
  877. return TlsSetValue(key, value) ? 0 : 1;
  878. }
  879. FUNCTION_MAY_BE_UNUSED
  880. static void *
  881. pthread_getspecific(pthread_key_t key)
  882. {
  883. return TlsGetValue(key);
  884. }
  885. #if defined(GCC_DIAGNOSTIC)
  886. /* Enable unused function warning again */
  887. #pragma GCC diagnostic pop
  888. #endif
  889. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  890. #else
  891. static pthread_mutexattr_t pthread_mutex_attr;
  892. #endif /* _WIN32 */
  893. #if defined(GCC_DIAGNOSTIC)
  894. /* Show no warning in case system functions are not used. */
  895. #pragma GCC diagnostic push
  896. #pragma GCC diagnostic ignored "-Wunused-function"
  897. #endif /* defined(GCC_DIAGNOSTIC) */
  898. #if defined(__clang__)
  899. /* Show no warning in case system functions are not used. */
  900. #pragma clang diagnostic push
  901. #pragma clang diagnostic ignored "-Wunused-function"
  902. #endif
  903. static pthread_mutex_t global_lock_mutex;
  904. FUNCTION_MAY_BE_UNUSED
  905. static void
  906. mg_global_lock(void)
  907. {
  908. (void)pthread_mutex_lock(&global_lock_mutex);
  909. }
  910. FUNCTION_MAY_BE_UNUSED
  911. static void
  912. mg_global_unlock(void)
  913. {
  914. (void)pthread_mutex_unlock(&global_lock_mutex);
  915. }
  916. #if defined(_WIN64)
  917. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  918. #elif defined(_WIN32)
  919. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  920. #endif
  921. /* Atomic functions working on ptrdiff_t ("signed size_t").
  922. * Operations: Increment, Decrement, Add, Maximum.
  923. * Up to size_t, they do not an atomic "load" operation.
  924. */
  925. FUNCTION_MAY_BE_UNUSED
  926. static ptrdiff_t
  927. mg_atomic_inc(volatile ptrdiff_t *addr)
  928. {
  929. ptrdiff_t ret;
  930. #if defined(_WIN64) && !defined(NO_ATOMICS)
  931. ret = InterlockedIncrement64(addr);
  932. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  933. ret = InterlockedIncrement(addr);
  934. #elif defined(__GNUC__) \
  935. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  936. && !defined(NO_ATOMICS)
  937. ret = __sync_add_and_fetch(addr, 1);
  938. #else
  939. mg_global_lock();
  940. ret = (++(*addr));
  941. mg_global_unlock();
  942. #endif
  943. return ret;
  944. }
  945. FUNCTION_MAY_BE_UNUSED
  946. static ptrdiff_t
  947. mg_atomic_dec(volatile ptrdiff_t *addr)
  948. {
  949. ptrdiff_t ret;
  950. #if defined(_WIN64) && !defined(NO_ATOMICS)
  951. ret = InterlockedDecrement64(addr);
  952. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  953. ret = InterlockedDecrement(addr);
  954. #elif defined(__GNUC__) \
  955. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  956. && !defined(NO_ATOMICS)
  957. ret = __sync_sub_and_fetch(addr, 1);
  958. #else
  959. mg_global_lock();
  960. ret = (--(*addr));
  961. mg_global_unlock();
  962. #endif
  963. return ret;
  964. }
  965. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  966. static ptrdiff_t
  967. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  968. {
  969. ptrdiff_t ret;
  970. #if defined(_WIN64) && !defined(NO_ATOMICS)
  971. ret = InterlockedAdd64(addr, value);
  972. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  973. ret = InterlockedExchangeAdd(addr, value) + value;
  974. #elif defined(__GNUC__) \
  975. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  976. && !defined(NO_ATOMICS)
  977. ret = __sync_add_and_fetch(addr, value);
  978. #else
  979. mg_global_lock();
  980. *addr += value;
  981. ret = (*addr);
  982. mg_global_unlock();
  983. #endif
  984. return ret;
  985. }
  986. FUNCTION_MAY_BE_UNUSED
  987. static ptrdiff_t
  988. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  989. ptrdiff_t oldval,
  990. ptrdiff_t newval)
  991. {
  992. ptrdiff_t ret;
  993. #if defined(_WIN64) && !defined(NO_ATOMICS)
  994. ret = InterlockedCompareExchange64(addr, newval, oldval);
  995. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  996. ret = InterlockedCompareExchange(addr, newval, oldval);
  997. #elif defined(__GNUC__) \
  998. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  999. && !defined(NO_ATOMICS)
  1000. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1001. #else
  1002. mg_global_lock();
  1003. ret = *addr;
  1004. if ((ret != newval) && (ret == oldval)) {
  1005. *addr = newval;
  1006. }
  1007. mg_global_unlock();
  1008. #endif
  1009. return ret;
  1010. }
  1011. static void
  1012. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1013. {
  1014. register ptrdiff_t tmp = *addr;
  1015. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1016. while (tmp < value) {
  1017. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1018. }
  1019. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1020. while (tmp < value) {
  1021. tmp = InterlockedCompareExchange(addr, value, tmp);
  1022. }
  1023. #elif defined(__GNUC__) \
  1024. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1025. && !defined(NO_ATOMICS)
  1026. while (tmp < value) {
  1027. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1028. }
  1029. #else
  1030. mg_global_lock();
  1031. if (*addr < value) {
  1032. *addr = value;
  1033. }
  1034. mg_global_unlock();
  1035. #endif
  1036. }
  1037. static int64_t
  1038. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1039. {
  1040. int64_t ret;
  1041. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1042. ret = InterlockedAdd64(addr, value);
  1043. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1044. ret = InterlockedExchangeAdd64(addr, value) + value;
  1045. #elif defined(__GNUC__) \
  1046. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1047. && !defined(NO_ATOMICS)
  1048. ret = __sync_add_and_fetch(addr, value);
  1049. #else
  1050. mg_global_lock();
  1051. *addr += value;
  1052. ret = (*addr);
  1053. mg_global_unlock();
  1054. #endif
  1055. return ret;
  1056. }
  1057. #endif
  1058. #if defined(GCC_DIAGNOSTIC)
  1059. /* Show no warning in case system functions are not used. */
  1060. #pragma GCC diagnostic pop
  1061. #endif /* defined(GCC_DIAGNOSTIC) */
  1062. #if defined(__clang__)
  1063. /* Show no warning in case system functions are not used. */
  1064. #pragma clang diagnostic pop
  1065. #endif
  1066. #if defined(USE_SERVER_STATS)
  1067. struct mg_memory_stat {
  1068. volatile ptrdiff_t totalMemUsed;
  1069. volatile ptrdiff_t maxMemUsed;
  1070. volatile ptrdiff_t blockCount;
  1071. };
  1072. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1073. static void *
  1074. mg_malloc_ex(size_t size,
  1075. struct mg_context *ctx,
  1076. const char *file,
  1077. unsigned line)
  1078. {
  1079. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1080. void *memory = 0;
  1081. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1082. #if defined(MEMORY_DEBUGGING)
  1083. char mallocStr[256];
  1084. #else
  1085. (void)file;
  1086. (void)line;
  1087. #endif
  1088. if (data) {
  1089. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1090. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1091. mg_atomic_inc(&mstat->blockCount);
  1092. ((uintptr_t *)data)[0] = size;
  1093. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1094. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1095. }
  1096. #if defined(MEMORY_DEBUGGING)
  1097. sprintf(mallocStr,
  1098. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1099. memory,
  1100. (unsigned long)size,
  1101. (unsigned long)mstat->totalMemUsed,
  1102. (unsigned long)mstat->blockCount,
  1103. file,
  1104. line);
  1105. DEBUG_TRACE("%s", mallocStr);
  1106. #endif
  1107. return memory;
  1108. }
  1109. static void *
  1110. mg_calloc_ex(size_t count,
  1111. size_t size,
  1112. struct mg_context *ctx,
  1113. const char *file,
  1114. unsigned line)
  1115. {
  1116. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1117. if (data) {
  1118. memset(data, 0, size * count);
  1119. }
  1120. return data;
  1121. }
  1122. static void
  1123. mg_free_ex(void *memory, const char *file, unsigned line)
  1124. {
  1125. #if defined(MEMORY_DEBUGGING)
  1126. char mallocStr[256];
  1127. #else
  1128. (void)file;
  1129. (void)line;
  1130. #endif
  1131. if (memory) {
  1132. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1133. uintptr_t size = ((uintptr_t *)data)[0];
  1134. struct mg_memory_stat *mstat =
  1135. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1136. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1137. mg_atomic_dec(&mstat->blockCount);
  1138. #if defined(MEMORY_DEBUGGING)
  1139. sprintf(mallocStr,
  1140. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1141. memory,
  1142. (unsigned long)size,
  1143. (unsigned long)mstat->totalMemUsed,
  1144. (unsigned long)mstat->blockCount,
  1145. file,
  1146. line);
  1147. DEBUG_TRACE("%s", mallocStr);
  1148. #endif
  1149. free(data);
  1150. }
  1151. }
  1152. static void *
  1153. mg_realloc_ex(void *memory,
  1154. size_t newsize,
  1155. struct mg_context *ctx,
  1156. const char *file,
  1157. unsigned line)
  1158. {
  1159. void *data;
  1160. void *_realloc;
  1161. uintptr_t oldsize;
  1162. #if defined(MEMORY_DEBUGGING)
  1163. char mallocStr[256];
  1164. #else
  1165. (void)file;
  1166. (void)line;
  1167. #endif
  1168. if (newsize) {
  1169. if (memory) {
  1170. /* Reallocate existing block */
  1171. struct mg_memory_stat *mstat;
  1172. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1173. oldsize = ((uintptr_t *)data)[0];
  1174. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1175. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1176. if (_realloc) {
  1177. data = _realloc;
  1178. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1179. #if defined(MEMORY_DEBUGGING)
  1180. sprintf(mallocStr,
  1181. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1182. memory,
  1183. (unsigned long)oldsize,
  1184. (unsigned long)mstat->totalMemUsed,
  1185. (unsigned long)mstat->blockCount,
  1186. file,
  1187. line);
  1188. DEBUG_TRACE("%s", mallocStr);
  1189. #endif
  1190. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1191. #if defined(MEMORY_DEBUGGING)
  1192. sprintf(mallocStr,
  1193. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1194. memory,
  1195. (unsigned long)newsize,
  1196. (unsigned long)mstat->totalMemUsed,
  1197. (unsigned long)mstat->blockCount,
  1198. file,
  1199. line);
  1200. DEBUG_TRACE("%s", mallocStr);
  1201. #endif
  1202. *(uintptr_t *)data = newsize;
  1203. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1204. } else {
  1205. #if defined(MEMORY_DEBUGGING)
  1206. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1207. #endif
  1208. return _realloc;
  1209. }
  1210. } else {
  1211. /* Allocate new block */
  1212. data = mg_malloc_ex(newsize, ctx, file, line);
  1213. }
  1214. } else {
  1215. /* Free existing block */
  1216. data = 0;
  1217. mg_free_ex(memory, file, line);
  1218. }
  1219. return data;
  1220. }
  1221. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1222. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1223. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1224. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1225. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1226. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1227. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1228. #else /* USE_SERVER_STATS */
  1229. static __inline void *
  1230. mg_malloc(size_t a)
  1231. {
  1232. return malloc(a);
  1233. }
  1234. static __inline void *
  1235. mg_calloc(size_t a, size_t b)
  1236. {
  1237. return calloc(a, b);
  1238. }
  1239. static __inline void *
  1240. mg_realloc(void *a, size_t b)
  1241. {
  1242. return realloc(a, b);
  1243. }
  1244. static __inline void
  1245. mg_free(void *a)
  1246. {
  1247. free(a);
  1248. }
  1249. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1250. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1251. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1252. #define mg_free_ctx(a, c) mg_free(a)
  1253. #endif /* USE_SERVER_STATS */
  1254. static void mg_vsnprintf(const struct mg_connection *conn,
  1255. int *truncated,
  1256. char *buf,
  1257. size_t buflen,
  1258. const char *fmt,
  1259. va_list ap);
  1260. static void mg_snprintf(const struct mg_connection *conn,
  1261. int *truncated,
  1262. char *buf,
  1263. size_t buflen,
  1264. PRINTF_FORMAT_STRING(const char *fmt),
  1265. ...) PRINTF_ARGS(5, 6);
  1266. /* This following lines are just meant as a reminder to use the mg-functions
  1267. * for memory management */
  1268. #if defined(malloc)
  1269. #undef malloc
  1270. #endif
  1271. #if defined(calloc)
  1272. #undef calloc
  1273. #endif
  1274. #if defined(realloc)
  1275. #undef realloc
  1276. #endif
  1277. #if defined(free)
  1278. #undef free
  1279. #endif
  1280. #if defined(snprintf)
  1281. #undef snprintf
  1282. #endif
  1283. #if defined(vsnprintf)
  1284. #undef vsnprintf
  1285. #endif
  1286. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1287. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1288. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1289. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1290. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1291. #if defined(_WIN32)
  1292. /* vsnprintf must not be used in any system,
  1293. * but this define only works well for Windows. */
  1294. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1295. #endif
  1296. /* mg_init_library counter */
  1297. static int mg_init_library_called = 0;
  1298. #if !defined(NO_SSL)
  1299. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1300. || defined(OPENSSL_API_3_0)
  1301. static int mg_openssl_initialized = 0;
  1302. #endif
  1303. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1304. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1305. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1306. #endif
  1307. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
  1308. && defined(OPENSSL_API_3_0)
  1309. #error "Multiple OPENSSL_API versions defined"
  1310. #endif
  1311. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1312. || defined(OPENSSL_API_3_0)) \
  1313. && defined(USE_MBEDTLS)
  1314. #error "Multiple SSL libraries defined"
  1315. #endif
  1316. #endif
  1317. static pthread_key_t sTlsKey; /* Thread local storage index */
  1318. static volatile ptrdiff_t thread_idx_max = 0;
  1319. #if defined(MG_LEGACY_INTERFACE)
  1320. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1321. #endif
  1322. struct mg_workerTLS {
  1323. int is_master;
  1324. unsigned long thread_idx;
  1325. void *user_ptr;
  1326. #if defined(_WIN32)
  1327. HANDLE pthread_cond_helper_mutex;
  1328. struct mg_workerTLS *next_waiting_thread;
  1329. #endif
  1330. const char *alpn_proto;
  1331. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1332. char txtbuf[4];
  1333. #endif
  1334. };
  1335. #if defined(GCC_DIAGNOSTIC)
  1336. /* Show no warning in case system functions are not used. */
  1337. #pragma GCC diagnostic push
  1338. #pragma GCC diagnostic ignored "-Wunused-function"
  1339. #endif /* defined(GCC_DIAGNOSTIC) */
  1340. #if defined(__clang__)
  1341. /* Show no warning in case system functions are not used. */
  1342. #pragma clang diagnostic push
  1343. #pragma clang diagnostic ignored "-Wunused-function"
  1344. #endif
  1345. /* Get a unique thread ID as unsigned long, independent from the data type
  1346. * of thread IDs defined by the operating system API.
  1347. * If two calls to mg_current_thread_id return the same value, they calls
  1348. * are done from the same thread. If they return different values, they are
  1349. * done from different threads. (Provided this function is used in the same
  1350. * process context and threads are not repeatedly created and deleted, but
  1351. * CivetWeb does not do that).
  1352. * This function must match the signature required for SSL id callbacks:
  1353. * CRYPTO_set_id_callback
  1354. */
  1355. FUNCTION_MAY_BE_UNUSED
  1356. static unsigned long
  1357. mg_current_thread_id(void)
  1358. {
  1359. #if defined(_WIN32)
  1360. return GetCurrentThreadId();
  1361. #else
  1362. #if defined(__clang__)
  1363. #pragma clang diagnostic push
  1364. #pragma clang diagnostic ignored "-Wunreachable-code"
  1365. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1366. * or not, so one of the two conditions will be unreachable by construction.
  1367. * Unfortunately the C standard does not define a way to check this at
  1368. * compile time, since the #if preprocessor conditions can not use the
  1369. * sizeof operator as an argument. */
  1370. #endif
  1371. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1372. /* This is the problematic case for CRYPTO_set_id_callback:
  1373. * The OS pthread_t can not be cast to unsigned long. */
  1374. struct mg_workerTLS *tls =
  1375. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1376. if (tls == NULL) {
  1377. /* SSL called from an unknown thread: Create some thread index.
  1378. */
  1379. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1380. tls->is_master = -2; /* -2 means "3rd party thread" */
  1381. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1382. pthread_setspecific(sTlsKey, tls);
  1383. }
  1384. return tls->thread_idx;
  1385. } else {
  1386. /* pthread_t may be any data type, so a simple cast to unsigned long
  1387. * can rise a warning/error, depending on the platform.
  1388. * Here memcpy is used as an anything-to-anything cast. */
  1389. unsigned long ret = 0;
  1390. pthread_t t = pthread_self();
  1391. memcpy(&ret, &t, sizeof(pthread_t));
  1392. return ret;
  1393. }
  1394. #if defined(__clang__)
  1395. #pragma clang diagnostic pop
  1396. #endif
  1397. #endif
  1398. }
  1399. FUNCTION_MAY_BE_UNUSED
  1400. static uint64_t
  1401. mg_get_current_time_ns(void)
  1402. {
  1403. struct timespec tsnow;
  1404. clock_gettime(CLOCK_REALTIME, &tsnow);
  1405. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1406. }
  1407. #if defined(GCC_DIAGNOSTIC)
  1408. /* Show no warning in case system functions are not used. */
  1409. #pragma GCC diagnostic pop
  1410. #endif /* defined(GCC_DIAGNOSTIC) */
  1411. #if defined(__clang__)
  1412. /* Show no warning in case system functions are not used. */
  1413. #pragma clang diagnostic pop
  1414. #endif
  1415. #if defined(NEED_DEBUG_TRACE_FUNC)
  1416. static void
  1417. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1418. {
  1419. va_list args;
  1420. struct timespec tsnow;
  1421. /* Get some operating system independent thread id */
  1422. unsigned long thread_id = mg_current_thread_id();
  1423. clock_gettime(CLOCK_REALTIME, &tsnow);
  1424. flockfile(DEBUG_TRACE_STREAM);
  1425. fprintf(DEBUG_TRACE_STREAM,
  1426. "*** %lu.%09lu %lu %s:%u: ",
  1427. (unsigned long)tsnow.tv_sec,
  1428. (unsigned long)tsnow.tv_nsec,
  1429. thread_id,
  1430. func,
  1431. line);
  1432. va_start(args, fmt);
  1433. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1434. va_end(args);
  1435. putc('\n', DEBUG_TRACE_STREAM);
  1436. fflush(DEBUG_TRACE_STREAM);
  1437. funlockfile(DEBUG_TRACE_STREAM);
  1438. }
  1439. #endif /* NEED_DEBUG_TRACE_FUNC */
  1440. #define MD5_STATIC static
  1441. #include "md5.inl"
  1442. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1443. #if defined(NO_SOCKLEN_T)
  1444. typedef int socklen_t;
  1445. #endif /* NO_SOCKLEN_T */
  1446. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1447. #if !defined(MSG_NOSIGNAL)
  1448. #define MSG_NOSIGNAL (0)
  1449. #endif
  1450. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1451. #if defined(USE_MBEDTLS)
  1452. /* mbedTLS */
  1453. #include "mod_mbedtls.inl"
  1454. #elif defined(NO_SSL)
  1455. /* no SSL */
  1456. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1457. typedef struct SSL_CTX SSL_CTX;
  1458. #elif defined(NO_SSL_DL)
  1459. /* OpenSSL without dynamic loading */
  1460. #include <openssl/bn.h>
  1461. #include <openssl/conf.h>
  1462. #include <openssl/crypto.h>
  1463. #include <openssl/dh.h>
  1464. #include <openssl/engine.h>
  1465. #include <openssl/err.h>
  1466. #include <openssl/opensslv.h>
  1467. #include <openssl/pem.h>
  1468. #include <openssl/ssl.h>
  1469. #include <openssl/tls1.h>
  1470. #include <openssl/x509.h>
  1471. #if defined(WOLFSSL_VERSION)
  1472. /* Additional defines for WolfSSL, see
  1473. * https://github.com/civetweb/civetweb/issues/583 */
  1474. #include "wolfssl_extras.inl"
  1475. #endif
  1476. #if defined(OPENSSL_IS_BORINGSSL)
  1477. /* From boringssl/src/include/openssl/mem.h:
  1478. *
  1479. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1480. * However, that was written in a time before Valgrind and ASAN. Since we now
  1481. * have those tools, the OpenSSL allocation functions are simply macros around
  1482. * the standard memory functions.
  1483. *
  1484. * #define OPENSSL_free free */
  1485. #define free free
  1486. // disable for boringssl
  1487. #define CONF_modules_unload(a) ((void)0)
  1488. #define ENGINE_cleanup() ((void)0)
  1489. #endif
  1490. /* If OpenSSL headers are included, automatically select the API version */
  1491. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1492. #if !defined(OPENSSL_API_3_0)
  1493. #define OPENSSL_API_3_0
  1494. #endif
  1495. #define OPENSSL_REMOVE_THREAD_STATE()
  1496. #else
  1497. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1498. #if !defined(OPENSSL_API_1_1)
  1499. #define OPENSSL_API_1_1
  1500. #endif
  1501. #define OPENSSL_REMOVE_THREAD_STATE()
  1502. #else
  1503. #if !defined(OPENSSL_API_1_0)
  1504. #define OPENSSL_API_1_0
  1505. #endif
  1506. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1507. #endif
  1508. #endif
  1509. #else
  1510. /* SSL loaded dynamically from DLL / shared object */
  1511. /* Add all prototypes here, to be independent from OpenSSL source
  1512. * installation. */
  1513. #include "openssl_dl.inl"
  1514. #endif /* Various SSL bindings */
  1515. #if !defined(NO_CACHING)
  1516. static const char month_names[][4] = {"Jan",
  1517. "Feb",
  1518. "Mar",
  1519. "Apr",
  1520. "May",
  1521. "Jun",
  1522. "Jul",
  1523. "Aug",
  1524. "Sep",
  1525. "Oct",
  1526. "Nov",
  1527. "Dec"};
  1528. #endif /* !NO_CACHING */
  1529. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1530. * the union u. */
  1531. union usa {
  1532. struct sockaddr sa;
  1533. struct sockaddr_in sin;
  1534. #if defined(USE_IPV6)
  1535. struct sockaddr_in6 sin6;
  1536. #endif
  1537. #if defined(USE_X_DOM_SOCKET)
  1538. struct sockaddr_un sun;
  1539. #endif
  1540. };
  1541. #if defined(USE_X_DOM_SOCKET)
  1542. static unsigned short
  1543. USA_IN_PORT_UNSAFE(union usa *s)
  1544. {
  1545. if (s->sa.sa_family == AF_INET)
  1546. return s->sin.sin_port;
  1547. #if defined(USE_IPV6)
  1548. if (s->sa.sa_family == AF_INET6)
  1549. return s->sin6.sin6_port;
  1550. #endif
  1551. return 0;
  1552. }
  1553. #endif
  1554. #if defined(USE_IPV6)
  1555. #define USA_IN_PORT_UNSAFE(s) \
  1556. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1557. #else
  1558. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1559. #endif
  1560. /* Describes a string (chunk of memory). */
  1561. struct vec {
  1562. const char *ptr;
  1563. size_t len;
  1564. };
  1565. struct mg_file_stat {
  1566. /* File properties filled by mg_stat: */
  1567. uint64_t size;
  1568. time_t last_modified;
  1569. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1570. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1571. * case we need a "Content-Eencoding: gzip" header */
  1572. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1573. };
  1574. struct mg_file_access {
  1575. /* File properties filled by mg_fopen: */
  1576. FILE *fp;
  1577. };
  1578. struct mg_file {
  1579. struct mg_file_stat stat;
  1580. struct mg_file_access access;
  1581. };
  1582. #define STRUCT_FILE_INITIALIZER \
  1583. { \
  1584. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1585. { \
  1586. (FILE *)NULL \
  1587. } \
  1588. }
  1589. /* Describes listening socket, or socket which was accept()-ed by the master
  1590. * thread and queued for future handling by the worker thread. */
  1591. struct socket {
  1592. SOCKET sock; /* Listening socket */
  1593. union usa lsa; /* Local socket address */
  1594. union usa rsa; /* Remote socket address */
  1595. unsigned char is_ssl; /* Is port SSL-ed */
  1596. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1597. * port */
  1598. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1599. };
  1600. /* Enum const for all options must be in sync with
  1601. * static struct mg_option config_options[]
  1602. * This is tested in the unit test (test/private.c)
  1603. * "Private Config Options"
  1604. */
  1605. enum {
  1606. /* Once for each server */
  1607. LISTENING_PORTS,
  1608. NUM_THREADS,
  1609. RUN_AS_USER,
  1610. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1611. * socket option typedef TCP_NODELAY. */
  1612. MAX_REQUEST_SIZE,
  1613. LINGER_TIMEOUT,
  1614. CONNECTION_QUEUE_SIZE,
  1615. LISTEN_BACKLOG_SIZE,
  1616. #if defined(__linux__)
  1617. ALLOW_SENDFILE_CALL,
  1618. #endif
  1619. #if defined(_WIN32)
  1620. CASE_SENSITIVE_FILES,
  1621. #endif
  1622. THROTTLE,
  1623. ENABLE_KEEP_ALIVE,
  1624. REQUEST_TIMEOUT,
  1625. KEEP_ALIVE_TIMEOUT,
  1626. #if defined(USE_WEBSOCKET)
  1627. WEBSOCKET_TIMEOUT,
  1628. ENABLE_WEBSOCKET_PING_PONG,
  1629. #endif
  1630. DECODE_URL,
  1631. DECODE_QUERY_STRING,
  1632. #if defined(USE_LUA)
  1633. LUA_BACKGROUND_SCRIPT,
  1634. LUA_BACKGROUND_SCRIPT_PARAMS,
  1635. #endif
  1636. #if defined(USE_HTTP2)
  1637. ENABLE_HTTP2,
  1638. #endif
  1639. /* Once for each domain */
  1640. DOCUMENT_ROOT,
  1641. ACCESS_LOG_FILE,
  1642. ERROR_LOG_FILE,
  1643. CGI_EXTENSIONS,
  1644. CGI_ENVIRONMENT,
  1645. CGI_INTERPRETER,
  1646. CGI_INTERPRETER_ARGS,
  1647. #if defined(USE_TIMERS)
  1648. CGI_TIMEOUT,
  1649. #endif
  1650. CGI_BUFFERING,
  1651. CGI2_EXTENSIONS,
  1652. CGI2_ENVIRONMENT,
  1653. CGI2_INTERPRETER,
  1654. CGI2_INTERPRETER_ARGS,
  1655. #if defined(USE_TIMERS)
  1656. CGI2_TIMEOUT,
  1657. #endif
  1658. CGI2_BUFFERING,
  1659. #if defined(USE_4_CGI)
  1660. CGI3_EXTENSIONS,
  1661. CGI3_ENVIRONMENT,
  1662. CGI3_INTERPRETER,
  1663. CGI3_INTERPRETER_ARGS,
  1664. #if defined(USE_TIMERS)
  1665. CGI3_TIMEOUT,
  1666. #endif
  1667. CGI3_BUFFERING,
  1668. CGI4_EXTENSIONS,
  1669. CGI4_ENVIRONMENT,
  1670. CGI4_INTERPRETER,
  1671. CGI4_INTERPRETER_ARGS,
  1672. #if defined(USE_TIMERS)
  1673. CGI4_TIMEOUT,
  1674. #endif
  1675. CGI4_BUFFERING,
  1676. #endif
  1677. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1678. PROTECT_URI,
  1679. AUTHENTICATION_DOMAIN,
  1680. ENABLE_AUTH_DOMAIN_CHECK,
  1681. SSI_EXTENSIONS,
  1682. ENABLE_DIRECTORY_LISTING,
  1683. ENABLE_WEBDAV,
  1684. GLOBAL_PASSWORDS_FILE,
  1685. INDEX_FILES,
  1686. ACCESS_CONTROL_LIST,
  1687. EXTRA_MIME_TYPES,
  1688. SSL_CERTIFICATE,
  1689. SSL_CERTIFICATE_CHAIN,
  1690. URL_REWRITE_PATTERN,
  1691. HIDE_FILES,
  1692. SSL_DO_VERIFY_PEER,
  1693. SSL_CACHE_TIMEOUT,
  1694. SSL_CA_PATH,
  1695. SSL_CA_FILE,
  1696. SSL_VERIFY_DEPTH,
  1697. SSL_DEFAULT_VERIFY_PATHS,
  1698. SSL_CIPHER_LIST,
  1699. SSL_PROTOCOL_VERSION,
  1700. SSL_SHORT_TRUST,
  1701. #if defined(USE_LUA)
  1702. LUA_PRELOAD_FILE,
  1703. LUA_SCRIPT_EXTENSIONS,
  1704. LUA_SERVER_PAGE_EXTENSIONS,
  1705. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1706. LUA_DEBUG_PARAMS,
  1707. #endif
  1708. #endif
  1709. #if defined(USE_DUKTAPE)
  1710. DUKTAPE_SCRIPT_EXTENSIONS,
  1711. #endif
  1712. #if defined(USE_WEBSOCKET)
  1713. WEBSOCKET_ROOT,
  1714. #endif
  1715. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1716. LUA_WEBSOCKET_EXTENSIONS,
  1717. #endif
  1718. ACCESS_CONTROL_ALLOW_ORIGIN,
  1719. ACCESS_CONTROL_ALLOW_METHODS,
  1720. ACCESS_CONTROL_ALLOW_HEADERS,
  1721. ERROR_PAGES,
  1722. #if !defined(NO_CACHING)
  1723. STATIC_FILE_MAX_AGE,
  1724. STATIC_FILE_CACHE_CONTROL,
  1725. #endif
  1726. #if !defined(NO_SSL)
  1727. STRICT_HTTPS_MAX_AGE,
  1728. #endif
  1729. ADDITIONAL_HEADER,
  1730. ALLOW_INDEX_SCRIPT_SUB_RES,
  1731. NUM_OPTIONS
  1732. };
  1733. /* Config option name, config types, default value.
  1734. * Must be in the same order as the enum const above.
  1735. */
  1736. static const struct mg_option config_options[] = {
  1737. /* Once for each server */
  1738. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1739. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1740. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1741. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1742. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1743. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1744. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1745. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1746. #if defined(__linux__)
  1747. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1748. #endif
  1749. #if defined(_WIN32)
  1750. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1751. #endif
  1752. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1753. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1754. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1755. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1756. #if defined(USE_WEBSOCKET)
  1757. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1758. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1759. #endif
  1760. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1761. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1762. #if defined(USE_LUA)
  1763. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1764. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1765. #endif
  1766. #if defined(USE_HTTP2)
  1767. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1768. #endif
  1769. /* Once for each domain */
  1770. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1771. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1772. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1773. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1774. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1775. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1776. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1777. #if defined(USE_TIMERS)
  1778. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1779. #endif
  1780. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1781. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1782. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1783. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1784. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1785. #if defined(USE_TIMERS)
  1786. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1787. #endif
  1788. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1789. #if defined(USE_4_CGI)
  1790. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1791. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1792. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1793. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1794. #if defined(USE_TIMERS)
  1795. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1796. #endif
  1797. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1798. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1799. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1800. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1801. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1802. #if defined(USE_TIMERS)
  1803. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1804. #endif
  1805. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1806. #endif
  1807. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1808. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1809. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1810. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1811. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1812. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1813. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1814. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1815. {"index_files",
  1816. MG_CONFIG_TYPE_STRING_LIST,
  1817. #if defined(USE_LUA)
  1818. "index.xhtml,index.html,index.htm,"
  1819. "index.lp,index.lsp,index.lua,index.cgi,"
  1820. "index.shtml,index.php"},
  1821. #else
  1822. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1823. #endif
  1824. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1825. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1826. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1827. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1828. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1829. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1830. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1831. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1832. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1833. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1834. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1835. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1836. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1837. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1838. * as a minimum in 2020 */
  1839. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1840. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1841. #if defined(USE_LUA)
  1842. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1843. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1844. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1845. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1846. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1847. #endif
  1848. #endif
  1849. #if defined(USE_DUKTAPE)
  1850. /* The support for duktape is still in alpha version state.
  1851. * The name of this config option might change. */
  1852. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1853. #endif
  1854. #if defined(USE_WEBSOCKET)
  1855. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1856. #endif
  1857. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1858. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1859. #endif
  1860. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1861. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1862. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1863. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1864. #if !defined(NO_CACHING)
  1865. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1866. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1867. #endif
  1868. #if !defined(NO_SSL)
  1869. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1870. #endif
  1871. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1872. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1873. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1874. /* Check if the config_options and the corresponding enum have compatible
  1875. * sizes. */
  1876. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1877. == (NUM_OPTIONS + 1),
  1878. "config_options and enum not sync");
  1879. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1880. struct mg_handler_info {
  1881. /* Name/Pattern of the URI. */
  1882. char *uri;
  1883. size_t uri_len;
  1884. /* handler type */
  1885. int handler_type;
  1886. /* Handler for http/https or requests. */
  1887. mg_request_handler handler;
  1888. unsigned int refcount;
  1889. int removing;
  1890. /* Handler for ws/wss (websocket) requests. */
  1891. mg_websocket_connect_handler connect_handler;
  1892. mg_websocket_ready_handler ready_handler;
  1893. mg_websocket_data_handler data_handler;
  1894. mg_websocket_close_handler close_handler;
  1895. /* accepted subprotocols for ws/wss requests. */
  1896. struct mg_websocket_subprotocols *subprotocols;
  1897. /* Handler for authorization requests */
  1898. mg_authorization_handler auth_handler;
  1899. /* User supplied argument for the handler function. */
  1900. void *cbdata;
  1901. /* next handler in a linked list */
  1902. struct mg_handler_info *next;
  1903. };
  1904. enum {
  1905. CONTEXT_INVALID,
  1906. CONTEXT_SERVER,
  1907. CONTEXT_HTTP_CLIENT,
  1908. CONTEXT_WS_CLIENT
  1909. };
  1910. struct mg_domain_context {
  1911. SSL_CTX *ssl_ctx; /* SSL context */
  1912. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1913. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1914. int64_t ssl_cert_last_mtime;
  1915. /* Server nonce */
  1916. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1917. unsigned long nonce_count; /* Used nonces, used for authentication */
  1918. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1919. /* linked list of shared lua websockets */
  1920. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1921. #endif
  1922. /* Linked list of domains */
  1923. struct mg_domain_context *next;
  1924. };
  1925. /* Stop flag can be "volatile" or require a lock.
  1926. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1927. * states a read operation for int is always atomic. */
  1928. #if defined(STOP_FLAG_NEEDS_LOCK)
  1929. typedef ptrdiff_t volatile stop_flag_t;
  1930. static int
  1931. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1932. {
  1933. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1934. return (sf == 0);
  1935. }
  1936. static int
  1937. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1938. {
  1939. stop_flag_t sf = mg_atomic_add(f, 0);
  1940. return (sf == 2);
  1941. }
  1942. static void
  1943. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1944. {
  1945. stop_flag_t sf;
  1946. do {
  1947. sf = mg_atomic_compare_and_swap(f, *f, v);
  1948. } while (sf != v);
  1949. }
  1950. #else /* STOP_FLAG_NEEDS_LOCK */
  1951. typedef int volatile stop_flag_t;
  1952. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1953. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1954. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1955. #endif /* STOP_FLAG_NEEDS_LOCK */
  1956. #if !defined(NUM_WEBDAV_LOCKS)
  1957. #define NUM_WEBDAV_LOCKS 10
  1958. #endif
  1959. #if !defined(LOCK_DURATION_S)
  1960. #define LOCK_DURATION_S 60
  1961. #endif
  1962. struct twebdav_lock {
  1963. uint64_t locktime;
  1964. char token[33];
  1965. char path[UTF8_PATH_MAX * 2];
  1966. char user[UTF8_PATH_MAX * 2];
  1967. };
  1968. struct mg_context {
  1969. /* Part 1 - Physical context:
  1970. * This holds threads, ports, timeouts, ...
  1971. * set for the entire server, independent from the
  1972. * addressed hostname.
  1973. */
  1974. /* Connection related */
  1975. int context_type; /* See CONTEXT_* above */
  1976. struct socket *listening_sockets;
  1977. struct mg_pollfd *listening_socket_fds;
  1978. unsigned int num_listening_sockets;
  1979. struct mg_connection *worker_connections; /* The connection struct, pre-
  1980. * allocated for each worker */
  1981. #if defined(USE_SERVER_STATS)
  1982. volatile ptrdiff_t active_connections;
  1983. volatile ptrdiff_t max_active_connections;
  1984. volatile ptrdiff_t total_connections;
  1985. volatile ptrdiff_t total_requests;
  1986. volatile int64_t total_data_read;
  1987. volatile int64_t total_data_written;
  1988. #endif
  1989. /* Thread related */
  1990. stop_flag_t stop_flag; /* Should we stop event loop */
  1991. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  1992. pthread_t masterthreadid; /* The master thread ID */
  1993. unsigned int
  1994. cfg_worker_threads; /* The number of configured worker threads. */
  1995. pthread_t *worker_threadids; /* The worker thread IDs */
  1996. unsigned long starter_thread_idx; /* thread index which called mg_start */
  1997. /* Connection to thread dispatching */
  1998. #if defined(ALTERNATIVE_QUEUE)
  1999. struct socket *client_socks;
  2000. void **client_wait_events;
  2001. #else
  2002. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2003. worker thread */
  2004. volatile int sq_head; /* Head of the socket queue */
  2005. volatile int sq_tail; /* Tail of the socket queue */
  2006. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2007. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2008. volatile int sq_blocked; /* Status information: sq is full */
  2009. int sq_size; /* No of elements in socket queue */
  2010. #if defined(USE_SERVER_STATS)
  2011. int sq_max_fill;
  2012. #endif /* USE_SERVER_STATS */
  2013. #endif /* ALTERNATIVE_QUEUE */
  2014. /* Memory related */
  2015. unsigned int max_request_size; /* The max request size */
  2016. #if defined(USE_SERVER_STATS)
  2017. struct mg_memory_stat ctx_memory;
  2018. #endif
  2019. /* WebDAV lock structures */
  2020. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2021. /* Operating system related */
  2022. char *systemName; /* What operating system is running */
  2023. time_t start_time; /* Server start time, used for authentication
  2024. * and for diagnstics. */
  2025. #if defined(USE_TIMERS)
  2026. struct ttimers *timers;
  2027. #endif
  2028. /* Lua specific: Background operations and shared websockets */
  2029. #if defined(USE_LUA)
  2030. void *lua_background_state; /* lua_State (here as void *) */
  2031. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2032. int lua_bg_log_available; /* Use Lua background state for access log */
  2033. #endif
  2034. /* Server nonce */
  2035. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2036. * ssl_cert_last_mtime, nonce_count, and
  2037. * next (linked list) */
  2038. /* Server callbacks */
  2039. struct mg_callbacks callbacks; /* User-defined callback function */
  2040. void *user_data; /* User-defined data */
  2041. /* Part 2 - Logical domain:
  2042. * This holds hostname, TLS certificate, document root, ...
  2043. * set for a domain hosted at the server.
  2044. * There may be multiple domains hosted at one physical server.
  2045. * The default domain "dd" is the first element of a list of
  2046. * domains.
  2047. */
  2048. struct mg_domain_context dd; /* default domain */
  2049. };
  2050. #if defined(USE_SERVER_STATS)
  2051. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2052. static struct mg_memory_stat *
  2053. get_memory_stat(struct mg_context *ctx)
  2054. {
  2055. if (ctx) {
  2056. return &(ctx->ctx_memory);
  2057. }
  2058. return &mg_common_memory;
  2059. }
  2060. #endif
  2061. enum {
  2062. CONNECTION_TYPE_INVALID = 0,
  2063. CONNECTION_TYPE_REQUEST = 1,
  2064. CONNECTION_TYPE_RESPONSE = 2
  2065. };
  2066. enum {
  2067. PROTOCOL_TYPE_HTTP1 = 0,
  2068. PROTOCOL_TYPE_WEBSOCKET = 1,
  2069. PROTOCOL_TYPE_HTTP2 = 2
  2070. };
  2071. #if defined(USE_HTTP2)
  2072. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2073. #define HTTP2_DYN_TABLE_SIZE (256)
  2074. #endif
  2075. struct mg_http2_connection {
  2076. uint32_t stream_id;
  2077. uint32_t dyn_table_size;
  2078. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2079. };
  2080. #endif
  2081. struct mg_connection {
  2082. int connection_type; /* see CONNECTION_TYPE_* above */
  2083. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2084. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2085. fully sent */
  2086. #if defined(USE_HTTP2)
  2087. struct mg_http2_connection http2;
  2088. #endif
  2089. struct mg_request_info request_info;
  2090. struct mg_response_info response_info;
  2091. struct mg_context *phys_ctx;
  2092. struct mg_domain_context *dom_ctx;
  2093. #if defined(USE_SERVER_STATS)
  2094. int conn_state; /* 0 = undef, numerical value may change in different
  2095. * versions. For the current definition, see
  2096. * mg_get_connection_info_impl */
  2097. #endif
  2098. SSL *ssl; /* SSL descriptor */
  2099. struct socket client; /* Connected client */
  2100. time_t conn_birth_time; /* Time (wall clock) when connection was
  2101. * established */
  2102. #if defined(USE_SERVER_STATS)
  2103. time_t conn_close_time; /* Time (wall clock) when connection was
  2104. * closed (or 0 if still open) */
  2105. double processing_time; /* Procesing time for one request. */
  2106. #endif
  2107. struct timespec req_time; /* Time (since system start) when the request
  2108. * was received */
  2109. int64_t num_bytes_sent; /* Total bytes sent to client */
  2110. int64_t content_len; /* How many bytes of content can be read
  2111. * !is_chunked: Content-Length header value
  2112. * or -1 (until connection closed,
  2113. * not allowed for a request)
  2114. * is_chunked: >= 0, appended gradually
  2115. */
  2116. int64_t consumed_content; /* How many bytes of content have been read */
  2117. int is_chunked; /* Transfer-Encoding is chunked:
  2118. * 0 = not chunked,
  2119. * 1 = chunked, not yet, or some data read,
  2120. * 2 = chunked, has error,
  2121. * 3 = chunked, all data read except trailer,
  2122. * 4 = chunked, all data read
  2123. */
  2124. char *buf; /* Buffer for received data */
  2125. char *path_info; /* PATH_INFO part of the URL */
  2126. int must_close; /* 1 if connection must be closed */
  2127. int accept_gzip; /* 1 if gzip encoding is accepted */
  2128. int in_error_handler; /* 1 if in handler for user defined error
  2129. * pages */
  2130. #if defined(USE_WEBSOCKET)
  2131. int in_websocket_handling; /* 1 if in read_websocket */
  2132. #endif
  2133. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2134. && defined(MG_EXPERIMENTAL_INTERFACES)
  2135. /* Parameters for websocket data compression according to rfc7692 */
  2136. int websocket_deflate_server_max_windows_bits;
  2137. int websocket_deflate_client_max_windows_bits;
  2138. int websocket_deflate_server_no_context_takeover;
  2139. int websocket_deflate_client_no_context_takeover;
  2140. int websocket_deflate_initialized;
  2141. int websocket_deflate_flush;
  2142. z_stream websocket_deflate_state;
  2143. z_stream websocket_inflate_state;
  2144. #endif
  2145. int handled_requests; /* Number of requests handled by this connection
  2146. */
  2147. int buf_size; /* Buffer size */
  2148. int request_len; /* Size of the request + headers in a buffer */
  2149. int data_len; /* Total size of data in a buffer */
  2150. int status_code; /* HTTP reply status code, e.g. 200 */
  2151. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2152. * throttle */
  2153. time_t last_throttle_time; /* Last time throttled data was sent */
  2154. int last_throttle_bytes; /* Bytes sent this second */
  2155. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2156. * atomic transmissions for websockets */
  2157. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2158. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2159. #endif
  2160. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2161. * for quick access */
  2162. };
  2163. /* Directory entry */
  2164. struct de {
  2165. char *file_name;
  2166. struct mg_file_stat file;
  2167. };
  2168. #define mg_cry_internal(conn, fmt, ...) \
  2169. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2170. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2171. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2172. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2173. struct mg_context *ctx,
  2174. const char *func,
  2175. unsigned line,
  2176. const char *fmt,
  2177. ...) PRINTF_ARGS(5, 6);
  2178. #if !defined(NO_THREAD_NAME)
  2179. #if defined(_WIN32) && defined(_MSC_VER)
  2180. /* Set the thread name for debugging purposes in Visual Studio
  2181. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2182. */
  2183. #pragma pack(push, 8)
  2184. typedef struct tagTHREADNAME_INFO {
  2185. DWORD dwType; /* Must be 0x1000. */
  2186. LPCSTR szName; /* Pointer to name (in user addr space). */
  2187. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2188. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2189. } THREADNAME_INFO;
  2190. #pragma pack(pop)
  2191. #elif defined(__linux__)
  2192. #include <sys/prctl.h>
  2193. #include <sys/sendfile.h>
  2194. #if defined(ALTERNATIVE_QUEUE)
  2195. #include <sys/eventfd.h>
  2196. #endif /* ALTERNATIVE_QUEUE */
  2197. #if defined(ALTERNATIVE_QUEUE)
  2198. static void *
  2199. event_create(void)
  2200. {
  2201. int evhdl = eventfd(0, EFD_CLOEXEC);
  2202. int *ret;
  2203. if (evhdl == -1) {
  2204. /* Linux uses -1 on error, Windows NULL. */
  2205. /* However, Linux does not return 0 on success either. */
  2206. return 0;
  2207. }
  2208. ret = (int *)mg_malloc(sizeof(int));
  2209. if (ret) {
  2210. *ret = evhdl;
  2211. } else {
  2212. (void)close(evhdl);
  2213. }
  2214. return (void *)ret;
  2215. }
  2216. static int
  2217. event_wait(void *eventhdl)
  2218. {
  2219. uint64_t u;
  2220. int evhdl, s;
  2221. if (!eventhdl) {
  2222. /* error */
  2223. return 0;
  2224. }
  2225. evhdl = *(int *)eventhdl;
  2226. s = (int)read(evhdl, &u, sizeof(u));
  2227. if (s != sizeof(u)) {
  2228. /* error */
  2229. return 0;
  2230. }
  2231. (void)u; /* the value is not required */
  2232. return 1;
  2233. }
  2234. static int
  2235. event_signal(void *eventhdl)
  2236. {
  2237. uint64_t u = 1;
  2238. int evhdl, s;
  2239. if (!eventhdl) {
  2240. /* error */
  2241. return 0;
  2242. }
  2243. evhdl = *(int *)eventhdl;
  2244. s = (int)write(evhdl, &u, sizeof(u));
  2245. if (s != sizeof(u)) {
  2246. /* error */
  2247. return 0;
  2248. }
  2249. return 1;
  2250. }
  2251. static void
  2252. event_destroy(void *eventhdl)
  2253. {
  2254. int evhdl;
  2255. if (!eventhdl) {
  2256. /* error */
  2257. return;
  2258. }
  2259. evhdl = *(int *)eventhdl;
  2260. close(evhdl);
  2261. mg_free(eventhdl);
  2262. }
  2263. #endif
  2264. #endif
  2265. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2266. struct posix_event {
  2267. pthread_mutex_t mutex;
  2268. pthread_cond_t cond;
  2269. int signaled;
  2270. };
  2271. static void *
  2272. event_create(void)
  2273. {
  2274. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2275. if (ret == 0) {
  2276. /* out of memory */
  2277. return 0;
  2278. }
  2279. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2280. /* pthread mutex not available */
  2281. mg_free(ret);
  2282. return 0;
  2283. }
  2284. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2285. /* pthread cond not available */
  2286. pthread_mutex_destroy(&(ret->mutex));
  2287. mg_free(ret);
  2288. return 0;
  2289. }
  2290. ret->signaled = 0;
  2291. return (void *)ret;
  2292. }
  2293. static int
  2294. event_wait(void *eventhdl)
  2295. {
  2296. struct posix_event *ev = (struct posix_event *)eventhdl;
  2297. pthread_mutex_lock(&(ev->mutex));
  2298. while (!ev->signaled) {
  2299. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2300. }
  2301. ev->signaled = 0;
  2302. pthread_mutex_unlock(&(ev->mutex));
  2303. return 1;
  2304. }
  2305. static int
  2306. event_signal(void *eventhdl)
  2307. {
  2308. struct posix_event *ev = (struct posix_event *)eventhdl;
  2309. pthread_mutex_lock(&(ev->mutex));
  2310. pthread_cond_signal(&(ev->cond));
  2311. ev->signaled = 1;
  2312. pthread_mutex_unlock(&(ev->mutex));
  2313. return 1;
  2314. }
  2315. static void
  2316. event_destroy(void *eventhdl)
  2317. {
  2318. struct posix_event *ev = (struct posix_event *)eventhdl;
  2319. pthread_cond_destroy(&(ev->cond));
  2320. pthread_mutex_destroy(&(ev->mutex));
  2321. mg_free(ev);
  2322. }
  2323. #endif
  2324. static void
  2325. mg_set_thread_name(const char *name)
  2326. {
  2327. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2328. mg_snprintf(
  2329. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2330. #if defined(_WIN32)
  2331. #if defined(_MSC_VER)
  2332. /* Windows and Visual Studio Compiler */
  2333. __try {
  2334. THREADNAME_INFO info;
  2335. info.dwType = 0x1000;
  2336. info.szName = threadName;
  2337. info.dwThreadID = ~0U;
  2338. info.dwFlags = 0;
  2339. RaiseException(0x406D1388,
  2340. 0,
  2341. sizeof(info) / sizeof(ULONG_PTR),
  2342. (ULONG_PTR *)&info);
  2343. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2344. }
  2345. #elif defined(__MINGW32__)
  2346. /* No option known to set thread name for MinGW known */
  2347. #endif
  2348. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2349. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2350. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2351. #if defined(__MACH__)
  2352. /* OS X only current thread name can be changed */
  2353. (void)pthread_setname_np(threadName);
  2354. #else
  2355. (void)pthread_setname_np(pthread_self(), threadName);
  2356. #endif
  2357. #elif defined(__linux__)
  2358. /* On Linux we can use the prctl function.
  2359. * When building for Linux Standard Base (LSB) use
  2360. * NO_THREAD_NAME. However, thread names are a big
  2361. * help for debugging, so the stadard is to set them.
  2362. */
  2363. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2364. #endif
  2365. }
  2366. #else /* !defined(NO_THREAD_NAME) */
  2367. static void
  2368. mg_set_thread_name(const char *threadName)
  2369. {
  2370. }
  2371. #endif
  2372. CIVETWEB_API const struct mg_option *
  2373. mg_get_valid_options(void)
  2374. {
  2375. return config_options;
  2376. }
  2377. /* Do not open file (unused) */
  2378. #define MG_FOPEN_MODE_NONE (0)
  2379. /* Open file for read only access */
  2380. #define MG_FOPEN_MODE_READ (1)
  2381. /* Open file for writing, create and overwrite */
  2382. #define MG_FOPEN_MODE_WRITE (2)
  2383. /* Open file for writing, create and append */
  2384. #define MG_FOPEN_MODE_APPEND (4)
  2385. static int
  2386. is_file_opened(const struct mg_file_access *fileacc)
  2387. {
  2388. if (!fileacc) {
  2389. return 0;
  2390. }
  2391. return (fileacc->fp != NULL);
  2392. }
  2393. #if !defined(NO_FILESYSTEMS)
  2394. static int mg_stat(const struct mg_connection *conn,
  2395. const char *path,
  2396. struct mg_file_stat *filep);
  2397. /* Reject files with special characters (for Windows) */
  2398. static int
  2399. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2400. {
  2401. const uint8_t *c = (const uint8_t *)path;
  2402. (void)conn; /* not used */
  2403. if ((c == NULL) || (c[0] == 0)) {
  2404. /* Null pointer or empty path --> suspicious */
  2405. return 1;
  2406. }
  2407. #if defined(_WIN32)
  2408. while (*c) {
  2409. if (*c < 32) {
  2410. /* Control character */
  2411. return 1;
  2412. }
  2413. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2414. /* stdin/stdout redirection character */
  2415. return 1;
  2416. }
  2417. if ((*c == '*') || (*c == '?')) {
  2418. /* Wildcard character */
  2419. return 1;
  2420. }
  2421. if (*c == '"') {
  2422. /* Windows quotation */
  2423. return 1;
  2424. }
  2425. c++;
  2426. }
  2427. #endif
  2428. /* Nothing suspicious found */
  2429. return 0;
  2430. }
  2431. /* mg_fopen will open a file either in memory or on the disk.
  2432. * The input parameter path is a string in UTF-8 encoding.
  2433. * The input parameter mode is MG_FOPEN_MODE_*
  2434. * On success, fp will be set in the output struct mg_file.
  2435. * All status members will also be set.
  2436. * The function returns 1 on success, 0 on error. */
  2437. static int
  2438. mg_fopen(const struct mg_connection *conn,
  2439. const char *path,
  2440. int mode,
  2441. struct mg_file *filep)
  2442. {
  2443. int found;
  2444. if (!filep) {
  2445. return 0;
  2446. }
  2447. filep->access.fp = NULL;
  2448. if (mg_path_suspicious(conn, path)) {
  2449. return 0;
  2450. }
  2451. /* filep is initialized in mg_stat: all fields with memset to,
  2452. * some fields like size and modification date with values */
  2453. found = mg_stat(conn, path, &(filep->stat));
  2454. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2455. /* file does not exist and will not be created */
  2456. return 0;
  2457. }
  2458. #if defined(_WIN32)
  2459. {
  2460. wchar_t wbuf[UTF16_PATH_MAX];
  2461. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2462. switch (mode) {
  2463. case MG_FOPEN_MODE_READ:
  2464. filep->access.fp = _wfopen(wbuf, L"rb");
  2465. break;
  2466. case MG_FOPEN_MODE_WRITE:
  2467. filep->access.fp = _wfopen(wbuf, L"wb");
  2468. break;
  2469. case MG_FOPEN_MODE_APPEND:
  2470. filep->access.fp = _wfopen(wbuf, L"ab");
  2471. break;
  2472. }
  2473. }
  2474. #else
  2475. /* Linux et al already use unicode. No need to convert. */
  2476. switch (mode) {
  2477. case MG_FOPEN_MODE_READ:
  2478. filep->access.fp = fopen(path, "r");
  2479. break;
  2480. case MG_FOPEN_MODE_WRITE:
  2481. filep->access.fp = fopen(path, "w");
  2482. break;
  2483. case MG_FOPEN_MODE_APPEND:
  2484. filep->access.fp = fopen(path, "a");
  2485. break;
  2486. }
  2487. #endif
  2488. if (!found) {
  2489. /* File did not exist before fopen was called.
  2490. * Maybe it has been created now. Get stat info
  2491. * like creation time now. */
  2492. found = mg_stat(conn, path, &(filep->stat));
  2493. (void)found;
  2494. }
  2495. /* return OK if file is opened */
  2496. return (filep->access.fp != NULL);
  2497. }
  2498. /* return 0 on success, just like fclose */
  2499. static int
  2500. mg_fclose(struct mg_file_access *fileacc)
  2501. {
  2502. int ret = -1;
  2503. if (fileacc != NULL) {
  2504. if (fileacc->fp != NULL) {
  2505. ret = fclose(fileacc->fp);
  2506. }
  2507. /* reset all members of fileacc */
  2508. memset(fileacc, 0, sizeof(*fileacc));
  2509. }
  2510. return ret;
  2511. }
  2512. #endif /* NO_FILESYSTEMS */
  2513. static void
  2514. mg_strlcpy(char *dst, const char *src, size_t n)
  2515. {
  2516. for (; *src != '\0' && n > 1; n--) {
  2517. *dst++ = *src++;
  2518. }
  2519. *dst = '\0';
  2520. }
  2521. static int
  2522. lowercase(const char *s)
  2523. {
  2524. return tolower((unsigned char)*s);
  2525. }
  2526. CIVETWEB_API int
  2527. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2528. {
  2529. int diff = 0;
  2530. if (len > 0) {
  2531. do {
  2532. diff = lowercase(s1++) - lowercase(s2++);
  2533. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2534. }
  2535. return diff;
  2536. }
  2537. CIVETWEB_API int
  2538. mg_strcasecmp(const char *s1, const char *s2)
  2539. {
  2540. int diff;
  2541. do {
  2542. diff = lowercase(s1++) - lowercase(s2++);
  2543. } while (diff == 0 && s1[-1] != '\0');
  2544. return diff;
  2545. }
  2546. static char *
  2547. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2548. {
  2549. char *p;
  2550. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2551. * defined */
  2552. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2553. mg_strlcpy(p, ptr, len + 1);
  2554. }
  2555. return p;
  2556. }
  2557. static char *
  2558. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2559. {
  2560. return mg_strndup_ctx(str, strlen(str), ctx);
  2561. }
  2562. static char *
  2563. mg_strdup(const char *str)
  2564. {
  2565. return mg_strndup_ctx(str, strlen(str), NULL);
  2566. }
  2567. static const char *
  2568. mg_strcasestr(const char *big_str, const char *small_str)
  2569. {
  2570. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2571. if (big_len >= small_len) {
  2572. for (i = 0; i <= (big_len - small_len); i++) {
  2573. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2574. return big_str + i;
  2575. }
  2576. }
  2577. }
  2578. return NULL;
  2579. }
  2580. /* Return null terminated string of given maximum length.
  2581. * Report errors if length is exceeded. */
  2582. static void
  2583. mg_vsnprintf(const struct mg_connection *conn,
  2584. int *truncated,
  2585. char *buf,
  2586. size_t buflen,
  2587. const char *fmt,
  2588. va_list ap)
  2589. {
  2590. int n, ok;
  2591. if (buflen == 0) {
  2592. if (truncated) {
  2593. *truncated = 1;
  2594. }
  2595. return;
  2596. }
  2597. #if defined(__clang__)
  2598. #pragma clang diagnostic push
  2599. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2600. /* Using fmt as a non-literal is intended here, since it is mostly called
  2601. * indirectly by mg_snprintf */
  2602. #endif
  2603. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2604. ok = (n >= 0) && ((size_t)n < buflen);
  2605. #if defined(__clang__)
  2606. #pragma clang diagnostic pop
  2607. #endif
  2608. if (ok) {
  2609. if (truncated) {
  2610. *truncated = 0;
  2611. }
  2612. } else {
  2613. if (truncated) {
  2614. *truncated = 1;
  2615. }
  2616. mg_cry_internal(conn,
  2617. "truncating vsnprintf buffer: [%.*s]",
  2618. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2619. buf);
  2620. n = (int)buflen - 1;
  2621. }
  2622. buf[n] = '\0';
  2623. }
  2624. static void
  2625. mg_snprintf(const struct mg_connection *conn,
  2626. int *truncated,
  2627. char *buf,
  2628. size_t buflen,
  2629. const char *fmt,
  2630. ...)
  2631. {
  2632. va_list ap;
  2633. va_start(ap, fmt);
  2634. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2635. va_end(ap);
  2636. }
  2637. static int
  2638. get_option_index(const char *name)
  2639. {
  2640. int i;
  2641. for (i = 0; config_options[i].name != NULL; i++) {
  2642. if (strcmp(config_options[i].name, name) == 0) {
  2643. return i;
  2644. }
  2645. }
  2646. return -1;
  2647. }
  2648. CIVETWEB_API const char *
  2649. mg_get_option(const struct mg_context *ctx, const char *name)
  2650. {
  2651. int i;
  2652. if ((i = get_option_index(name)) == -1) {
  2653. return NULL;
  2654. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2655. return "";
  2656. } else {
  2657. return ctx->dd.config[i];
  2658. }
  2659. }
  2660. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2661. CIVETWEB_API struct mg_context *
  2662. mg_get_context(const struct mg_connection *conn)
  2663. {
  2664. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2665. }
  2666. CIVETWEB_API void *
  2667. mg_get_user_data(const struct mg_context *ctx)
  2668. {
  2669. return (ctx == NULL) ? NULL : ctx->user_data;
  2670. }
  2671. CIVETWEB_API void *
  2672. mg_get_user_context_data(const struct mg_connection *conn)
  2673. {
  2674. return mg_get_user_data(mg_get_context(conn));
  2675. }
  2676. CIVETWEB_API void *
  2677. mg_get_thread_pointer(const struct mg_connection *conn)
  2678. {
  2679. /* both methods should return the same pointer */
  2680. if (conn) {
  2681. /* quick access, in case conn is known */
  2682. return conn->tls_user_ptr;
  2683. } else {
  2684. /* otherwise get pointer from thread local storage (TLS) */
  2685. struct mg_workerTLS *tls =
  2686. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2687. return tls->user_ptr;
  2688. }
  2689. }
  2690. CIVETWEB_API void
  2691. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2692. {
  2693. if (const_conn != NULL) {
  2694. /* Const cast, since "const struct mg_connection *" does not mean
  2695. * the connection object is not modified. Here "const" is used,
  2696. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2697. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2698. conn->request_info.conn_data = data;
  2699. }
  2700. }
  2701. CIVETWEB_API void *
  2702. mg_get_user_connection_data(const struct mg_connection *conn)
  2703. {
  2704. if (conn != NULL) {
  2705. return conn->request_info.conn_data;
  2706. }
  2707. return NULL;
  2708. }
  2709. CIVETWEB_API int
  2710. mg_get_server_ports(const struct mg_context *ctx,
  2711. int size,
  2712. struct mg_server_port *ports)
  2713. {
  2714. int i, cnt = 0;
  2715. if (size <= 0) {
  2716. return -1;
  2717. }
  2718. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2719. if (!ctx) {
  2720. return -1;
  2721. }
  2722. if (!ctx->listening_sockets) {
  2723. return -1;
  2724. }
  2725. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2726. ports[cnt].port =
  2727. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2728. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2729. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2730. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2731. /* IPv4 */
  2732. ports[cnt].protocol = 1;
  2733. cnt++;
  2734. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2735. /* IPv6 */
  2736. ports[cnt].protocol = 3;
  2737. cnt++;
  2738. }
  2739. }
  2740. return cnt;
  2741. }
  2742. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2743. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2744. #endif
  2745. static void
  2746. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2747. {
  2748. buf[0] = '\0';
  2749. if (!usa) {
  2750. return;
  2751. }
  2752. if (usa->sa.sa_family == AF_INET) {
  2753. getnameinfo(&usa->sa,
  2754. sizeof(usa->sin),
  2755. buf,
  2756. (unsigned)len,
  2757. NULL,
  2758. 0,
  2759. NI_NUMERICHOST);
  2760. }
  2761. #if defined(USE_IPV6)
  2762. else if (usa->sa.sa_family == AF_INET6) {
  2763. getnameinfo(&usa->sa,
  2764. sizeof(usa->sin6),
  2765. buf,
  2766. (unsigned)len,
  2767. NULL,
  2768. 0,
  2769. NI_NUMERICHOST);
  2770. }
  2771. #endif
  2772. #if defined(USE_X_DOM_SOCKET)
  2773. else if (usa->sa.sa_family == AF_UNIX) {
  2774. /* TODO: Define a remote address for unix domain sockets.
  2775. * This code will always return "localhost", identical to http+tcp:
  2776. getnameinfo(&usa->sa,
  2777. sizeof(usa->sun),
  2778. buf,
  2779. (unsigned)len,
  2780. NULL,
  2781. 0,
  2782. NI_NUMERICHOST);
  2783. */
  2784. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2785. buf[len] = 0;
  2786. }
  2787. #endif
  2788. }
  2789. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2790. * included in all responses other than 100, 101, 5xx. */
  2791. static void
  2792. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2793. {
  2794. #if !defined(REENTRANT_TIME)
  2795. struct tm *tm;
  2796. tm = ((t != NULL) ? gmtime(t) : NULL);
  2797. if (tm != NULL) {
  2798. #else
  2799. struct tm _tm;
  2800. struct tm *tm = &_tm;
  2801. if (t != NULL) {
  2802. gmtime_r(t, tm);
  2803. #endif
  2804. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2805. } else {
  2806. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2807. buf[buf_len - 1] = '\0';
  2808. }
  2809. }
  2810. /* difftime for struct timespec. Return value is in seconds. */
  2811. static double
  2812. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2813. {
  2814. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2815. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2816. }
  2817. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2818. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2819. const char *func,
  2820. unsigned line,
  2821. const char *fmt,
  2822. va_list ap);
  2823. #include "external_mg_cry_internal_impl.inl"
  2824. #elif !defined(NO_FILESYSTEMS)
  2825. /* Print error message to the opened error log stream. */
  2826. static void
  2827. mg_cry_internal_impl(const struct mg_connection *conn,
  2828. const char *func,
  2829. unsigned line,
  2830. const char *fmt,
  2831. va_list ap)
  2832. {
  2833. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2834. struct mg_file fi;
  2835. time_t timestamp;
  2836. /* Unused, in the RELEASE build */
  2837. (void)func;
  2838. (void)line;
  2839. #if defined(GCC_DIAGNOSTIC)
  2840. #pragma GCC diagnostic push
  2841. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2842. #endif
  2843. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2844. #if defined(GCC_DIAGNOSTIC)
  2845. #pragma GCC diagnostic pop
  2846. #endif
  2847. buf[sizeof(buf) - 1] = 0;
  2848. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2849. if (!conn) {
  2850. puts(buf);
  2851. return;
  2852. }
  2853. /* Do not lock when getting the callback value, here and below.
  2854. * I suppose this is fine, since function cannot disappear in the
  2855. * same way string option can. */
  2856. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2857. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2858. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2859. if (mg_fopen(conn,
  2860. conn->dom_ctx->config[ERROR_LOG_FILE],
  2861. MG_FOPEN_MODE_APPEND,
  2862. &fi)
  2863. == 0) {
  2864. fi.access.fp = NULL;
  2865. }
  2866. } else {
  2867. fi.access.fp = NULL;
  2868. }
  2869. if (fi.access.fp != NULL) {
  2870. flockfile(fi.access.fp);
  2871. timestamp = time(NULL);
  2872. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2873. fprintf(fi.access.fp,
  2874. "[%010lu] [error] [client %s] ",
  2875. (unsigned long)timestamp,
  2876. src_addr);
  2877. if (conn->request_info.request_method != NULL) {
  2878. fprintf(fi.access.fp,
  2879. "%s %s: ",
  2880. conn->request_info.request_method,
  2881. conn->request_info.request_uri
  2882. ? conn->request_info.request_uri
  2883. : "");
  2884. }
  2885. fprintf(fi.access.fp, "%s", buf);
  2886. fputc('\n', fi.access.fp);
  2887. fflush(fi.access.fp);
  2888. funlockfile(fi.access.fp);
  2889. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2890. * mg_cry here anyway ;-) */
  2891. }
  2892. }
  2893. }
  2894. #else
  2895. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2896. #endif /* Externally provided function */
  2897. /* Construct fake connection structure. Used for logging, if connection
  2898. * is not applicable at the moment of logging. */
  2899. static struct mg_connection *
  2900. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2901. {
  2902. static const struct mg_connection conn_zero = {0};
  2903. *fc = conn_zero;
  2904. fc->phys_ctx = ctx;
  2905. fc->dom_ctx = &(ctx->dd);
  2906. return fc;
  2907. }
  2908. static void
  2909. mg_cry_internal_wrap(const struct mg_connection *conn,
  2910. struct mg_context *ctx,
  2911. const char *func,
  2912. unsigned line,
  2913. const char *fmt,
  2914. ...)
  2915. {
  2916. va_list ap;
  2917. va_start(ap, fmt);
  2918. if (!conn && ctx) {
  2919. struct mg_connection fc;
  2920. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2921. } else {
  2922. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2923. }
  2924. va_end(ap);
  2925. }
  2926. CIVETWEB_API void
  2927. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2928. {
  2929. va_list ap;
  2930. va_start(ap, fmt);
  2931. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2932. va_end(ap);
  2933. }
  2934. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2935. CIVETWEB_API const char *
  2936. mg_version(void)
  2937. {
  2938. return CIVETWEB_VERSION;
  2939. }
  2940. CIVETWEB_API const struct mg_request_info *
  2941. mg_get_request_info(const struct mg_connection *conn)
  2942. {
  2943. if (!conn) {
  2944. return NULL;
  2945. }
  2946. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2947. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2948. char txt[16];
  2949. struct mg_workerTLS *tls =
  2950. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2951. sprintf(txt, "%03i", conn->response_info.status_code);
  2952. if (strlen(txt) == 3) {
  2953. memcpy(tls->txtbuf, txt, 4);
  2954. } else {
  2955. strcpy(tls->txtbuf, "ERR");
  2956. }
  2957. ((struct mg_connection *)conn)->request_info.local_uri =
  2958. tls->txtbuf; /* use thread safe buffer */
  2959. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2960. tls->txtbuf; /* use the same thread safe buffer */
  2961. ((struct mg_connection *)conn)->request_info.request_uri =
  2962. tls->txtbuf; /* use the same thread safe buffer */
  2963. ((struct mg_connection *)conn)->request_info.num_headers =
  2964. conn->response_info.num_headers;
  2965. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2966. conn->response_info.http_headers,
  2967. sizeof(conn->response_info.http_headers));
  2968. } else
  2969. #endif
  2970. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2971. return NULL;
  2972. }
  2973. return &conn->request_info;
  2974. }
  2975. CIVETWEB_API const struct mg_response_info *
  2976. mg_get_response_info(const struct mg_connection *conn)
  2977. {
  2978. if (!conn) {
  2979. return NULL;
  2980. }
  2981. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2982. return NULL;
  2983. }
  2984. return &conn->response_info;
  2985. }
  2986. static const char *
  2987. get_proto_name(const struct mg_connection *conn)
  2988. {
  2989. #if defined(__clang__)
  2990. #pragma clang diagnostic push
  2991. #pragma clang diagnostic ignored "-Wunreachable-code"
  2992. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2993. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2994. * unreachable, but splitting into four different #ifdef clauses here is
  2995. * more complicated.
  2996. */
  2997. #endif
  2998. const struct mg_request_info *ri = &conn->request_info;
  2999. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3000. ? (ri->is_ssl ? "wss" : "ws")
  3001. : (ri->is_ssl ? "https" : "http"));
  3002. return proto;
  3003. #if defined(__clang__)
  3004. #pragma clang diagnostic pop
  3005. #endif
  3006. }
  3007. static int
  3008. mg_construct_local_link(const struct mg_connection *conn,
  3009. char *buf,
  3010. size_t buflen,
  3011. const char *define_proto,
  3012. int define_port,
  3013. const char *define_uri)
  3014. {
  3015. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3016. return -1;
  3017. } else {
  3018. int i, j;
  3019. int truncated = 0;
  3020. const struct mg_request_info *ri = &conn->request_info;
  3021. const char *proto =
  3022. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3023. const char *uri =
  3024. (define_uri != NULL)
  3025. ? define_uri
  3026. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3027. int port = (define_port > 0) ? define_port : ri->server_port;
  3028. int default_port = 80;
  3029. char *uri_encoded;
  3030. size_t uri_encoded_len;
  3031. if (uri == NULL) {
  3032. return -1;
  3033. }
  3034. uri_encoded_len = strlen(uri) * 3 + 1;
  3035. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3036. if (uri_encoded == NULL) {
  3037. return -1;
  3038. }
  3039. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3040. /* Directory separator should be preserved. */
  3041. for (i = j = 0; uri_encoded[i]; j++) {
  3042. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3043. uri_encoded[j] = '/';
  3044. i += 3;
  3045. } else {
  3046. uri_encoded[j] = uri_encoded[i++];
  3047. }
  3048. }
  3049. uri_encoded[j] = '\0';
  3050. #if defined(USE_X_DOM_SOCKET)
  3051. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3052. /* TODO: Define and document a link for UNIX domain sockets. */
  3053. /* There seems to be no official standard for this.
  3054. * Common uses seem to be "httpunix://", "http.unix://" or
  3055. * "http+unix://" as a protocol definition string, followed by
  3056. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3057. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3058. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3059. * "" (completely skipping the server name part). In any case, the
  3060. * last part is the server local path. */
  3061. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3062. mg_snprintf(conn,
  3063. &truncated,
  3064. buf,
  3065. buflen,
  3066. "%s.unix://%s%s",
  3067. proto,
  3068. server_name,
  3069. ri->local_uri);
  3070. default_port = 0;
  3071. mg_free(uri_encoded);
  3072. return 0;
  3073. }
  3074. #endif
  3075. if (define_proto) {
  3076. /* If we got a protocol name, use the default port accordingly. */
  3077. if ((0 == strcmp(define_proto, "https"))
  3078. || (0 == strcmp(define_proto, "wss"))) {
  3079. default_port = 443;
  3080. }
  3081. } else if (ri->is_ssl) {
  3082. /* If we did not get a protocol name, use TLS as default if it is
  3083. * already used. */
  3084. default_port = 443;
  3085. }
  3086. {
  3087. #if defined(USE_IPV6)
  3088. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3089. #endif
  3090. int auth_domain_check_enabled =
  3091. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3092. && (!mg_strcasecmp(
  3093. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3094. const char *server_domain =
  3095. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3096. char portstr[16];
  3097. char server_ip[48];
  3098. if (port != default_port) {
  3099. sprintf(portstr, ":%u", (unsigned)port);
  3100. } else {
  3101. portstr[0] = 0;
  3102. }
  3103. if (!auth_domain_check_enabled || !server_domain) {
  3104. sockaddr_to_string(server_ip,
  3105. sizeof(server_ip),
  3106. &conn->client.lsa);
  3107. server_domain = server_ip;
  3108. }
  3109. mg_snprintf(conn,
  3110. &truncated,
  3111. buf,
  3112. buflen,
  3113. #if defined(USE_IPV6)
  3114. "%s://%s%s%s%s%s",
  3115. proto,
  3116. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3117. server_domain,
  3118. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3119. #else
  3120. "%s://%s%s%s",
  3121. proto,
  3122. server_domain,
  3123. #endif
  3124. portstr,
  3125. uri_encoded);
  3126. mg_free(uri_encoded);
  3127. if (truncated) {
  3128. return -1;
  3129. }
  3130. return 0;
  3131. }
  3132. }
  3133. }
  3134. CIVETWEB_API int
  3135. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3136. {
  3137. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3138. }
  3139. /* Skip the characters until one of the delimiters characters found.
  3140. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3141. * Advance pointer to buffer to the next word. Return found 0-terminated
  3142. * word.
  3143. * Delimiters can be quoted with quotechar. */
  3144. static char *
  3145. skip_quoted(char **buf,
  3146. const char *delimiters,
  3147. const char *whitespace,
  3148. char quotechar)
  3149. {
  3150. char *p, *begin_word, *end_word, *end_whitespace;
  3151. begin_word = *buf;
  3152. end_word = begin_word + strcspn(begin_word, delimiters);
  3153. /* Check for quotechar */
  3154. if (end_word > begin_word) {
  3155. p = end_word - 1;
  3156. while (*p == quotechar) {
  3157. /* While the delimiter is quoted, look for the next delimiter. */
  3158. /* This happens, e.g., in calls from parse_auth_header,
  3159. * if the user name contains a " character. */
  3160. /* If there is anything beyond end_word, copy it. */
  3161. if (*end_word != '\0') {
  3162. size_t end_off = strcspn(end_word + 1, delimiters);
  3163. memmove(p, end_word, end_off + 1);
  3164. p += end_off; /* p must correspond to end_word - 1 */
  3165. end_word += end_off + 1;
  3166. } else {
  3167. *p = '\0';
  3168. break;
  3169. }
  3170. }
  3171. for (p++; p < end_word; p++) {
  3172. *p = '\0';
  3173. }
  3174. }
  3175. if (*end_word == '\0') {
  3176. *buf = end_word;
  3177. } else {
  3178. #if defined(GCC_DIAGNOSTIC)
  3179. /* Disable spurious conversion warning for GCC */
  3180. #pragma GCC diagnostic push
  3181. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3182. #endif /* defined(GCC_DIAGNOSTIC) */
  3183. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3184. #if defined(GCC_DIAGNOSTIC)
  3185. #pragma GCC diagnostic pop
  3186. #endif /* defined(GCC_DIAGNOSTIC) */
  3187. for (p = end_word; p < end_whitespace; p++) {
  3188. *p = '\0';
  3189. }
  3190. *buf = end_whitespace;
  3191. }
  3192. return begin_word;
  3193. }
  3194. /* Return HTTP header value, or NULL if not found. */
  3195. static const char *
  3196. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3197. {
  3198. int i;
  3199. for (i = 0; i < num_hdr; i++) {
  3200. if (!mg_strcasecmp(name, hdr[i].name)) {
  3201. return hdr[i].value;
  3202. }
  3203. }
  3204. return NULL;
  3205. }
  3206. #if defined(USE_WEBSOCKET)
  3207. /* Retrieve requested HTTP header multiple values, and return the number of
  3208. * found occurrences */
  3209. static int
  3210. get_req_headers(const struct mg_request_info *ri,
  3211. const char *name,
  3212. const char **output,
  3213. int output_max_size)
  3214. {
  3215. int i;
  3216. int cnt = 0;
  3217. if (ri) {
  3218. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3219. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3220. output[cnt++] = ri->http_headers[i].value;
  3221. }
  3222. }
  3223. }
  3224. return cnt;
  3225. }
  3226. #endif
  3227. CIVETWEB_API const char *
  3228. mg_get_header(const struct mg_connection *conn, const char *name)
  3229. {
  3230. if (!conn) {
  3231. return NULL;
  3232. }
  3233. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3234. return get_header(conn->request_info.http_headers,
  3235. conn->request_info.num_headers,
  3236. name);
  3237. }
  3238. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3239. return get_header(conn->response_info.http_headers,
  3240. conn->response_info.num_headers,
  3241. name);
  3242. }
  3243. return NULL;
  3244. }
  3245. static const char *
  3246. get_http_version(const struct mg_connection *conn)
  3247. {
  3248. if (!conn) {
  3249. return NULL;
  3250. }
  3251. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3252. return conn->request_info.http_version;
  3253. }
  3254. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3255. return conn->response_info.http_version;
  3256. }
  3257. return NULL;
  3258. }
  3259. /* A helper function for traversing a comma separated list of values.
  3260. * It returns a list pointer shifted to the next value, or NULL if the end
  3261. * of the list found.
  3262. * Value is stored in val vector. If value has form "x=y", then eq_val
  3263. * vector is initialized to point to the "y" part, and val vector length
  3264. * is adjusted to point only to "x". */
  3265. static const char *
  3266. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3267. {
  3268. int end;
  3269. reparse:
  3270. if (val == NULL || list == NULL || *list == '\0') {
  3271. /* End of the list */
  3272. return NULL;
  3273. }
  3274. /* Skip over leading LWS */
  3275. while (*list == ' ' || *list == '\t')
  3276. list++;
  3277. val->ptr = list;
  3278. if ((list = strchr(val->ptr, ',')) != NULL) {
  3279. /* Comma found. Store length and shift the list ptr */
  3280. val->len = ((size_t)(list - val->ptr));
  3281. list++;
  3282. } else {
  3283. /* This value is the last one */
  3284. list = val->ptr + strlen(val->ptr);
  3285. val->len = ((size_t)(list - val->ptr));
  3286. }
  3287. /* Adjust length for trailing LWS */
  3288. end = (int)val->len - 1;
  3289. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3290. end--;
  3291. val->len = (size_t)(end) + (size_t)(1);
  3292. if (val->len == 0) {
  3293. /* Ignore any empty entries. */
  3294. goto reparse;
  3295. }
  3296. if (eq_val != NULL) {
  3297. /* Value has form "x=y", adjust pointers and lengths
  3298. * so that val points to "x", and eq_val points to "y". */
  3299. eq_val->len = 0;
  3300. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3301. if (eq_val->ptr != NULL) {
  3302. eq_val->ptr++; /* Skip over '=' character */
  3303. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3304. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3305. }
  3306. }
  3307. return list;
  3308. }
  3309. /* A helper function for checking if a comma separated list of values
  3310. * contains
  3311. * the given option (case insensitvely).
  3312. * 'header' can be NULL, in which case false is returned. */
  3313. static int
  3314. header_has_option(const char *header, const char *option)
  3315. {
  3316. struct vec opt_vec;
  3317. struct vec eq_vec;
  3318. DEBUG_ASSERT(option != NULL);
  3319. DEBUG_ASSERT(option[0] != '\0');
  3320. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3321. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3322. return 1;
  3323. }
  3324. return 0;
  3325. }
  3326. /* Sorting function implemented in a separate file */
  3327. #include "sort.inl"
  3328. /* Pattern matching has been reimplemented in a new file */
  3329. #include "match.inl"
  3330. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3331. * This function must tolerate situations when connection info is not
  3332. * set up, for example if request parsing failed. */
  3333. static int
  3334. should_keep_alive(const struct mg_connection *conn)
  3335. {
  3336. const char *http_version;
  3337. const char *header;
  3338. /* First satisfy needs of the server */
  3339. if ((conn == NULL) || conn->must_close) {
  3340. /* Close, if civetweb framework needs to close */
  3341. return 0;
  3342. }
  3343. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3344. /* Close, if keep alive is not enabled */
  3345. return 0;
  3346. }
  3347. /* Check explicit wish of the client */
  3348. header = mg_get_header(conn, "Connection");
  3349. if (header) {
  3350. /* If there is a connection header from the client, obey */
  3351. if (header_has_option(header, "keep-alive")) {
  3352. return 1;
  3353. }
  3354. return 0;
  3355. }
  3356. /* Use default of the standard */
  3357. http_version = get_http_version(conn);
  3358. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3359. /* HTTP 1.1 default is keep alive */
  3360. return 1;
  3361. }
  3362. /* HTTP 1.0 (and earlier) default is to close the connection */
  3363. return 0;
  3364. }
  3365. static int
  3366. should_decode_url(const struct mg_connection *conn)
  3367. {
  3368. if (!conn || !conn->dom_ctx) {
  3369. return 0;
  3370. }
  3371. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3372. }
  3373. static int
  3374. should_decode_query_string(const struct mg_connection *conn)
  3375. {
  3376. if (!conn || !conn->dom_ctx) {
  3377. return 0;
  3378. }
  3379. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3380. == 0);
  3381. }
  3382. static const char *
  3383. suggest_connection_header(const struct mg_connection *conn)
  3384. {
  3385. return should_keep_alive(conn) ? "keep-alive" : "close";
  3386. }
  3387. #include "response.inl"
  3388. static void
  3389. send_no_cache_header(struct mg_connection *conn)
  3390. {
  3391. /* Send all current and obsolete cache opt-out directives. */
  3392. mg_response_header_add(conn,
  3393. "Cache-Control",
  3394. "no-cache, no-store, "
  3395. "must-revalidate, private, max-age=0",
  3396. -1);
  3397. mg_response_header_add(conn, "Expires", "0", -1);
  3398. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3399. /* Obsolete, but still send it for HTTP/1.0 */
  3400. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3401. }
  3402. }
  3403. static void
  3404. send_static_cache_header(struct mg_connection *conn)
  3405. {
  3406. #if !defined(NO_CACHING)
  3407. int max_age;
  3408. char val[64];
  3409. const char *cache_control =
  3410. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3411. /* If there is a full cache-control option configured,0 use it */
  3412. if (cache_control != NULL) {
  3413. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3414. return;
  3415. }
  3416. /* Read the server config to check how long a file may be cached.
  3417. * The configuration is in seconds. */
  3418. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3419. if (max_age <= 0) {
  3420. /* 0 means "do not cache". All values <0 are reserved
  3421. * and may be used differently in the future. */
  3422. /* If a file should not be cached, do not only send
  3423. * max-age=0, but also pragmas and Expires headers. */
  3424. send_no_cache_header(conn);
  3425. return;
  3426. }
  3427. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3428. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3429. /* See also https://www.mnot.net/cache_docs/ */
  3430. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3431. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3432. * leap
  3433. * year to 31622400 seconds. For the moment, we just send whatever has
  3434. * been configured, still the behavior for >1 year should be considered
  3435. * as undefined. */
  3436. mg_snprintf(
  3437. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3438. mg_response_header_add(conn, "Cache-Control", val, -1);
  3439. #else /* NO_CACHING */
  3440. send_no_cache_header(conn);
  3441. #endif /* !NO_CACHING */
  3442. }
  3443. static void
  3444. send_additional_header(struct mg_connection *conn)
  3445. {
  3446. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3447. #if !defined(NO_SSL)
  3448. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3449. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3450. if (max_age >= 0) {
  3451. char val[64];
  3452. mg_snprintf(conn,
  3453. NULL,
  3454. val,
  3455. sizeof(val),
  3456. "max-age=%lu",
  3457. (unsigned long)max_age);
  3458. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3459. }
  3460. }
  3461. #endif
  3462. if (header && header[0]) {
  3463. mg_response_header_add_lines(conn, header);
  3464. }
  3465. }
  3466. static void
  3467. send_cors_header(struct mg_connection *conn)
  3468. {
  3469. const char *origin_hdr = mg_get_header(conn, "Origin");
  3470. const char *cors_orig_cfg =
  3471. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3472. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3473. /* Cross-origin resource sharing (CORS), see
  3474. * http://www.html5rocks.com/en/tutorials/cors/,
  3475. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3476. * CORS preflight is not supported for files. */
  3477. mg_response_header_add(conn,
  3478. "Access-Control-Allow-Origin",
  3479. cors_orig_cfg,
  3480. -1);
  3481. }
  3482. }
  3483. #if !defined(NO_FILESYSTEMS)
  3484. static void handle_file_based_request(struct mg_connection *conn,
  3485. const char *path,
  3486. struct mg_file *filep);
  3487. #endif /* NO_FILESYSTEMS */
  3488. CIVETWEB_API const char *
  3489. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3490. {
  3491. /* See IANA HTTP status code assignment:
  3492. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3493. */
  3494. switch (response_code) {
  3495. /* RFC2616 Section 10.1 - Informational 1xx */
  3496. case 100:
  3497. return "Continue"; /* RFC2616 Section 10.1.1 */
  3498. case 101:
  3499. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3500. case 102:
  3501. return "Processing"; /* RFC2518 Section 10.1 */
  3502. /* RFC2616 Section 10.2 - Successful 2xx */
  3503. case 200:
  3504. return "OK"; /* RFC2616 Section 10.2.1 */
  3505. case 201:
  3506. return "Created"; /* RFC2616 Section 10.2.2 */
  3507. case 202:
  3508. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3509. case 203:
  3510. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3511. case 204:
  3512. return "No Content"; /* RFC2616 Section 10.2.5 */
  3513. case 205:
  3514. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3515. case 206:
  3516. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3517. case 207:
  3518. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3519. */
  3520. case 208:
  3521. return "Already Reported"; /* RFC5842 Section 7.1 */
  3522. case 226:
  3523. return "IM used"; /* RFC3229 Section 10.4.1 */
  3524. /* RFC2616 Section 10.3 - Redirection 3xx */
  3525. case 300:
  3526. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3527. case 301:
  3528. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3529. case 302:
  3530. return "Found"; /* RFC2616 Section 10.3.3 */
  3531. case 303:
  3532. return "See Other"; /* RFC2616 Section 10.3.4 */
  3533. case 304:
  3534. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3535. case 305:
  3536. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3537. case 307:
  3538. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3539. case 308:
  3540. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3541. /* RFC2616 Section 10.4 - Client Error 4xx */
  3542. case 400:
  3543. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3544. case 401:
  3545. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3546. case 402:
  3547. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3548. case 403:
  3549. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3550. case 404:
  3551. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3552. case 405:
  3553. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3554. case 406:
  3555. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3556. case 407:
  3557. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3558. case 408:
  3559. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3560. case 409:
  3561. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3562. case 410:
  3563. return "Gone"; /* RFC2616 Section 10.4.11 */
  3564. case 411:
  3565. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3566. case 412:
  3567. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3568. case 413:
  3569. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3570. case 414:
  3571. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3572. case 415:
  3573. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3574. case 416:
  3575. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3576. */
  3577. case 417:
  3578. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3579. case 421:
  3580. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3581. case 422:
  3582. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3583. * Section 11.2 */
  3584. case 423:
  3585. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3586. case 424:
  3587. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3588. * Section 11.4 */
  3589. case 426:
  3590. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3591. case 428:
  3592. return "Precondition Required"; /* RFC 6585, Section 3 */
  3593. case 429:
  3594. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3595. case 431:
  3596. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3597. case 451:
  3598. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3599. * Section 3 */
  3600. /* RFC2616 Section 10.5 - Server Error 5xx */
  3601. case 500:
  3602. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3603. case 501:
  3604. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3605. case 502:
  3606. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3607. case 503:
  3608. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3609. case 504:
  3610. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3611. case 505:
  3612. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3613. case 506:
  3614. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3615. case 507:
  3616. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3617. * Section 11.5 */
  3618. case 508:
  3619. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3620. case 510:
  3621. return "Not Extended"; /* RFC 2774, Section 7 */
  3622. case 511:
  3623. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3624. /* Other status codes, not shown in the IANA HTTP status code
  3625. * assignment.
  3626. * E.g., "de facto" standards due to common use, ... */
  3627. case 418:
  3628. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3629. case 419:
  3630. return "Authentication Timeout"; /* common use */
  3631. case 420:
  3632. return "Enhance Your Calm"; /* common use */
  3633. case 440:
  3634. return "Login Timeout"; /* common use */
  3635. case 509:
  3636. return "Bandwidth Limit Exceeded"; /* common use */
  3637. default:
  3638. /* This error code is unknown. This should not happen. */
  3639. if (conn) {
  3640. mg_cry_internal(conn,
  3641. "Unknown HTTP response code: %u",
  3642. response_code);
  3643. }
  3644. /* Return at least a category according to RFC 2616 Section 10. */
  3645. if (response_code >= 100 && response_code < 200) {
  3646. /* Unknown informational status code */
  3647. return "Information";
  3648. }
  3649. if (response_code >= 200 && response_code < 300) {
  3650. /* Unknown success code */
  3651. return "Success";
  3652. }
  3653. if (response_code >= 300 && response_code < 400) {
  3654. /* Unknown redirection code */
  3655. return "Redirection";
  3656. }
  3657. if (response_code >= 400 && response_code < 500) {
  3658. /* Unknown request error code */
  3659. return "Client Error";
  3660. }
  3661. if (response_code >= 500 && response_code < 600) {
  3662. /* Unknown server error code */
  3663. return "Server Error";
  3664. }
  3665. /* Response code not even within reasonable range */
  3666. return "";
  3667. }
  3668. }
  3669. static int
  3670. mg_send_http_error_impl(struct mg_connection *conn,
  3671. int status,
  3672. const char *fmt,
  3673. va_list args)
  3674. {
  3675. char errmsg_buf[MG_BUF_LEN];
  3676. va_list ap;
  3677. int has_body;
  3678. #if !defined(NO_FILESYSTEMS)
  3679. char path_buf[UTF8_PATH_MAX];
  3680. int len, i, page_handler_found, scope, truncated;
  3681. const char *error_handler = NULL;
  3682. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3683. const char *error_page_file_ext, *tstr;
  3684. #endif /* NO_FILESYSTEMS */
  3685. int handled_by_callback = 0;
  3686. if ((conn == NULL) || (fmt == NULL)) {
  3687. return -2;
  3688. }
  3689. /* Set status (for log) */
  3690. conn->status_code = status;
  3691. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3692. has_body = ((status > 199) && (status != 204) && (status != 304));
  3693. /* Prepare message in buf, if required */
  3694. if (has_body
  3695. || (!conn->in_error_handler
  3696. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3697. /* Store error message in errmsg_buf */
  3698. va_copy(ap, args);
  3699. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3700. va_end(ap);
  3701. /* In a debug build, print all html errors */
  3702. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3703. }
  3704. /* If there is a http_error callback, call it.
  3705. * But don't do it recursively, if callback calls mg_send_http_error again.
  3706. */
  3707. if (!conn->in_error_handler
  3708. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3709. /* Mark in_error_handler to avoid recursion and call user callback. */
  3710. conn->in_error_handler = 1;
  3711. handled_by_callback =
  3712. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3713. == 0);
  3714. conn->in_error_handler = 0;
  3715. }
  3716. if (!handled_by_callback) {
  3717. /* Check for recursion */
  3718. if (conn->in_error_handler) {
  3719. DEBUG_TRACE(
  3720. "Recursion when handling error %u - fall back to default",
  3721. status);
  3722. #if !defined(NO_FILESYSTEMS)
  3723. } else {
  3724. /* Send user defined error pages, if defined */
  3725. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3726. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3727. page_handler_found = 0;
  3728. if (error_handler != NULL) {
  3729. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3730. switch (scope) {
  3731. case 1: /* Handler for specific error, e.g. 404 error */
  3732. mg_snprintf(conn,
  3733. &truncated,
  3734. path_buf,
  3735. sizeof(path_buf) - 32,
  3736. "%serror%03u.",
  3737. error_handler,
  3738. status);
  3739. break;
  3740. case 2: /* Handler for error group, e.g., 5xx error
  3741. * handler
  3742. * for all server errors (500-599) */
  3743. mg_snprintf(conn,
  3744. &truncated,
  3745. path_buf,
  3746. sizeof(path_buf) - 32,
  3747. "%serror%01uxx.",
  3748. error_handler,
  3749. status / 100);
  3750. break;
  3751. default: /* Handler for all errors */
  3752. mg_snprintf(conn,
  3753. &truncated,
  3754. path_buf,
  3755. sizeof(path_buf) - 32,
  3756. "%serror.",
  3757. error_handler);
  3758. break;
  3759. }
  3760. /* String truncation in buf may only occur if
  3761. * error_handler is too long. This string is
  3762. * from the config, not from a client. */
  3763. (void)truncated;
  3764. /* The following code is redundant, but it should avoid
  3765. * false positives in static source code analyzers and
  3766. * vulnerability scanners.
  3767. */
  3768. path_buf[sizeof(path_buf) - 32] = 0;
  3769. len = (int)strlen(path_buf);
  3770. if (len > (int)sizeof(path_buf) - 32) {
  3771. len = (int)sizeof(path_buf) - 32;
  3772. }
  3773. /* Start with the file extenstion from the configuration. */
  3774. tstr = strchr(error_page_file_ext, '.');
  3775. while (tstr) {
  3776. for (i = 1;
  3777. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3778. i++) {
  3779. /* buffer overrun is not possible here, since
  3780. * (i < 32) && (len < sizeof(path_buf) - 32)
  3781. * ==> (i + len) < sizeof(path_buf) */
  3782. path_buf[len + i - 1] = tstr[i];
  3783. }
  3784. /* buffer overrun is not possible here, since
  3785. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3786. * ==> (i + len) <= sizeof(path_buf) */
  3787. path_buf[len + i - 1] = 0;
  3788. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3789. DEBUG_TRACE("Check error page %s - found",
  3790. path_buf);
  3791. page_handler_found = 1;
  3792. break;
  3793. }
  3794. DEBUG_TRACE("Check error page %s - not found",
  3795. path_buf);
  3796. /* Continue with the next file extenstion from the
  3797. * configuration (if there is a next one). */
  3798. tstr = strchr(tstr + i, '.');
  3799. }
  3800. }
  3801. }
  3802. if (page_handler_found) {
  3803. conn->in_error_handler = 1;
  3804. handle_file_based_request(conn, path_buf, &error_page_file);
  3805. conn->in_error_handler = 0;
  3806. return 0;
  3807. }
  3808. #endif /* NO_FILESYSTEMS */
  3809. }
  3810. /* No custom error page. Send default error page. */
  3811. conn->must_close = 1;
  3812. mg_response_header_start(conn, status);
  3813. send_no_cache_header(conn);
  3814. send_additional_header(conn);
  3815. send_cors_header(conn);
  3816. if (has_body) {
  3817. mg_response_header_add(conn,
  3818. "Content-Type",
  3819. "text/plain; charset=utf-8",
  3820. -1);
  3821. }
  3822. mg_response_header_send(conn);
  3823. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3824. if (has_body) {
  3825. /* For other errors, send a generic error message. */
  3826. const char *status_text = mg_get_response_code_text(conn, status);
  3827. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3828. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3829. } else {
  3830. /* No body allowed. Close the connection. */
  3831. DEBUG_TRACE("Error %i", status);
  3832. }
  3833. }
  3834. return 0;
  3835. }
  3836. CIVETWEB_API int
  3837. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3838. {
  3839. va_list ap;
  3840. int ret;
  3841. va_start(ap, fmt);
  3842. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3843. va_end(ap);
  3844. return ret;
  3845. }
  3846. CIVETWEB_API int
  3847. mg_send_http_ok(struct mg_connection *conn,
  3848. const char *mime_type,
  3849. long long content_length)
  3850. {
  3851. if ((mime_type == NULL) || (*mime_type == 0)) {
  3852. /* No content type defined: default to text/html */
  3853. mime_type = "text/html";
  3854. }
  3855. mg_response_header_start(conn, 200);
  3856. send_no_cache_header(conn);
  3857. send_additional_header(conn);
  3858. send_cors_header(conn);
  3859. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3860. if (content_length < 0) {
  3861. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3862. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3863. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3864. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3865. }
  3866. } else {
  3867. char len[32];
  3868. int trunc = 0;
  3869. mg_snprintf(conn,
  3870. &trunc,
  3871. len,
  3872. sizeof(len),
  3873. "%" UINT64_FMT,
  3874. (uint64_t)content_length);
  3875. if (!trunc) {
  3876. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3877. * !trunc is always true */
  3878. mg_response_header_add(conn, "Content-Length", len, -1);
  3879. }
  3880. }
  3881. mg_response_header_send(conn);
  3882. return 0;
  3883. }
  3884. CIVETWEB_API int
  3885. mg_send_http_redirect(struct mg_connection *conn,
  3886. const char *target_url,
  3887. int redirect_code)
  3888. {
  3889. /* Send a 30x redirect response.
  3890. *
  3891. * Redirect types (status codes):
  3892. *
  3893. * Status | Perm/Temp | Method | Version
  3894. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3895. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3896. * 303 | temporary | always use GET | HTTP/1.1
  3897. * 307 | temporary | always keep method | HTTP/1.1
  3898. * 308 | permanent | always keep method | HTTP/1.1
  3899. */
  3900. #if defined(MG_SEND_REDIRECT_BODY)
  3901. char redirect_body[MG_BUF_LEN];
  3902. size_t content_len = 0;
  3903. char content_len_text[32];
  3904. #endif
  3905. /* In case redirect_code=0, use 307. */
  3906. if (redirect_code == 0) {
  3907. redirect_code = 307;
  3908. }
  3909. /* In case redirect_code is none of the above, return error. */
  3910. if ((redirect_code != 301) && (redirect_code != 302)
  3911. && (redirect_code != 303) && (redirect_code != 307)
  3912. && (redirect_code != 308)) {
  3913. /* Parameter error */
  3914. return -2;
  3915. }
  3916. /* If target_url is not defined, redirect to "/". */
  3917. if ((target_url == NULL) || (*target_url == 0)) {
  3918. target_url = "/";
  3919. }
  3920. #if defined(MG_SEND_REDIRECT_BODY)
  3921. /* TODO: condition name? */
  3922. /* Prepare a response body with a hyperlink.
  3923. *
  3924. * According to RFC2616 (and RFC1945 before):
  3925. * Unless the request method was HEAD, the entity of the
  3926. * response SHOULD contain a short hypertext note with a hyperlink to
  3927. * the new URI(s).
  3928. *
  3929. * However, this response body is not useful in M2M communication.
  3930. * Probably the original reason in the RFC was, clients not supporting
  3931. * a 30x HTTP redirect could still show the HTML page and let the user
  3932. * press the link. Since current browsers support 30x HTTP, the additional
  3933. * HTML body does not seem to make sense anymore.
  3934. *
  3935. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3936. * but it only notes:
  3937. * The server's response payload usually contains a short
  3938. * hypertext note with a hyperlink to the new URI(s).
  3939. *
  3940. * Deactivated by default. If you need the 30x body, set the define.
  3941. */
  3942. mg_snprintf(
  3943. conn,
  3944. NULL /* ignore truncation */,
  3945. redirect_body,
  3946. sizeof(redirect_body),
  3947. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3948. redirect_text,
  3949. target_url,
  3950. target_url);
  3951. content_len = strlen(reply);
  3952. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  3953. #endif
  3954. /* Send all required headers */
  3955. mg_response_header_start(conn, redirect_code);
  3956. mg_response_header_add(conn, "Location", target_url, -1);
  3957. if ((redirect_code == 301) || (redirect_code == 308)) {
  3958. /* Permanent redirect */
  3959. send_static_cache_header(conn);
  3960. } else {
  3961. /* Temporary redirect */
  3962. send_no_cache_header(conn);
  3963. }
  3964. send_additional_header(conn);
  3965. send_cors_header(conn);
  3966. #if defined(MG_SEND_REDIRECT_BODY)
  3967. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  3968. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  3969. #else
  3970. mg_response_header_add(conn, "Content-Length", "0", 1);
  3971. #endif
  3972. mg_response_header_send(conn);
  3973. #if defined(MG_SEND_REDIRECT_BODY)
  3974. /* Send response body */
  3975. /* ... unless it is a HEAD request */
  3976. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  3977. ret = mg_write(conn, redirect_body, content_len);
  3978. }
  3979. #endif
  3980. return 1;
  3981. }
  3982. #if defined(_WIN32)
  3983. /* Create substitutes for POSIX functions in Win32. */
  3984. #if defined(GCC_DIAGNOSTIC)
  3985. /* Show no warning in case system functions are not used. */
  3986. #pragma GCC diagnostic push
  3987. #pragma GCC diagnostic ignored "-Wunused-function"
  3988. #endif
  3989. static int
  3990. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3991. {
  3992. (void)unused;
  3993. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  3994. InitializeCriticalSection(&mutex->sec);
  3995. return 0;
  3996. }
  3997. static int
  3998. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3999. {
  4000. DeleteCriticalSection(&mutex->sec);
  4001. return 0;
  4002. }
  4003. static int
  4004. pthread_mutex_lock(pthread_mutex_t *mutex)
  4005. {
  4006. EnterCriticalSection(&mutex->sec);
  4007. return 0;
  4008. }
  4009. static int
  4010. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4011. {
  4012. LeaveCriticalSection(&mutex->sec);
  4013. return 0;
  4014. }
  4015. FUNCTION_MAY_BE_UNUSED
  4016. static int
  4017. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4018. {
  4019. (void)unused;
  4020. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4021. cv->waiting_thread = NULL;
  4022. return 0;
  4023. }
  4024. FUNCTION_MAY_BE_UNUSED
  4025. static int
  4026. pthread_cond_timedwait(pthread_cond_t *cv,
  4027. pthread_mutex_t *mutex,
  4028. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4029. {
  4030. struct mg_workerTLS **ptls,
  4031. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4032. int ok;
  4033. uint64_t nsnow, nswaitabs;
  4034. int64_t nswaitrel;
  4035. DWORD mswaitrel;
  4036. pthread_mutex_lock(&cv->threadIdSec);
  4037. /* Add this thread to cv's waiting list */
  4038. ptls = &cv->waiting_thread;
  4039. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4040. ;
  4041. tls->next_waiting_thread = NULL;
  4042. *ptls = tls;
  4043. pthread_mutex_unlock(&cv->threadIdSec);
  4044. if (abstime) {
  4045. nsnow = mg_get_current_time_ns();
  4046. nswaitabs =
  4047. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4048. nswaitrel = nswaitabs - nsnow;
  4049. if (nswaitrel < 0) {
  4050. nswaitrel = 0;
  4051. }
  4052. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4053. } else {
  4054. mswaitrel = (DWORD)INFINITE;
  4055. }
  4056. pthread_mutex_unlock(mutex);
  4057. ok = (WAIT_OBJECT_0
  4058. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4059. if (!ok) {
  4060. ok = 1;
  4061. pthread_mutex_lock(&cv->threadIdSec);
  4062. ptls = &cv->waiting_thread;
  4063. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4064. if (*ptls == tls) {
  4065. *ptls = tls->next_waiting_thread;
  4066. ok = 0;
  4067. break;
  4068. }
  4069. }
  4070. pthread_mutex_unlock(&cv->threadIdSec);
  4071. if (ok) {
  4072. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4073. (DWORD)INFINITE);
  4074. }
  4075. }
  4076. /* This thread has been removed from cv's waiting list */
  4077. pthread_mutex_lock(mutex);
  4078. return ok ? 0 : -1;
  4079. }
  4080. FUNCTION_MAY_BE_UNUSED
  4081. static int
  4082. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4083. {
  4084. return pthread_cond_timedwait(cv, mutex, NULL);
  4085. }
  4086. FUNCTION_MAY_BE_UNUSED
  4087. static int
  4088. pthread_cond_signal(pthread_cond_t *cv)
  4089. {
  4090. HANDLE wkup = NULL;
  4091. BOOL ok = FALSE;
  4092. pthread_mutex_lock(&cv->threadIdSec);
  4093. if (cv->waiting_thread) {
  4094. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4095. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4096. ok = SetEvent(wkup);
  4097. DEBUG_ASSERT(ok);
  4098. }
  4099. pthread_mutex_unlock(&cv->threadIdSec);
  4100. return ok ? 0 : 1;
  4101. }
  4102. FUNCTION_MAY_BE_UNUSED
  4103. static int
  4104. pthread_cond_broadcast(pthread_cond_t *cv)
  4105. {
  4106. pthread_mutex_lock(&cv->threadIdSec);
  4107. while (cv->waiting_thread) {
  4108. pthread_cond_signal(cv);
  4109. }
  4110. pthread_mutex_unlock(&cv->threadIdSec);
  4111. return 0;
  4112. }
  4113. FUNCTION_MAY_BE_UNUSED
  4114. static int
  4115. pthread_cond_destroy(pthread_cond_t *cv)
  4116. {
  4117. pthread_mutex_lock(&cv->threadIdSec);
  4118. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4119. pthread_mutex_unlock(&cv->threadIdSec);
  4120. pthread_mutex_destroy(&cv->threadIdSec);
  4121. return 0;
  4122. }
  4123. #if defined(ALTERNATIVE_QUEUE)
  4124. FUNCTION_MAY_BE_UNUSED
  4125. static void *
  4126. event_create(void)
  4127. {
  4128. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4129. }
  4130. FUNCTION_MAY_BE_UNUSED
  4131. static int
  4132. event_wait(void *eventhdl)
  4133. {
  4134. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4135. return (res == WAIT_OBJECT_0);
  4136. }
  4137. FUNCTION_MAY_BE_UNUSED
  4138. static int
  4139. event_signal(void *eventhdl)
  4140. {
  4141. return (int)SetEvent((HANDLE)eventhdl);
  4142. }
  4143. FUNCTION_MAY_BE_UNUSED
  4144. static void
  4145. event_destroy(void *eventhdl)
  4146. {
  4147. CloseHandle((HANDLE)eventhdl);
  4148. }
  4149. #endif
  4150. #if defined(GCC_DIAGNOSTIC)
  4151. /* Enable unused function warning again */
  4152. #pragma GCC diagnostic pop
  4153. #endif
  4154. /* For Windows, change all slashes to backslashes in path names. */
  4155. static void
  4156. change_slashes_to_backslashes(char *path)
  4157. {
  4158. int i;
  4159. for (i = 0; path[i] != '\0'; i++) {
  4160. if (path[i] == '/') {
  4161. path[i] = '\\';
  4162. }
  4163. /* remove double backslash (check i > 0 to preserve UNC paths,
  4164. * like \\server\file.txt) */
  4165. if ((i > 0) && (path[i] == '\\')) {
  4166. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4167. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4168. }
  4169. }
  4170. }
  4171. }
  4172. static int
  4173. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4174. {
  4175. int diff;
  4176. do {
  4177. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4178. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4179. s1++;
  4180. s2++;
  4181. } while ((diff == 0) && (s1[-1] != L'\0'));
  4182. return diff;
  4183. }
  4184. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4185. * wbuf and wbuf_len is a target buffer and its length. */
  4186. static void
  4187. path_to_unicode(const struct mg_connection *conn,
  4188. const char *path,
  4189. wchar_t *wbuf,
  4190. size_t wbuf_len)
  4191. {
  4192. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4193. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4194. DWORD long_len, err;
  4195. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4196. mg_strlcpy(buf, path, sizeof(buf));
  4197. change_slashes_to_backslashes(buf);
  4198. /* Convert to Unicode and back. If doubly-converted string does not
  4199. * match the original, something is fishy, reject. */
  4200. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4201. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4202. WideCharToMultiByte(
  4203. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4204. if (strcmp(buf, buf2) != 0) {
  4205. wbuf[0] = L'\0';
  4206. }
  4207. /* Windows file systems are not case sensitive, but you can still use
  4208. * uppercase and lowercase letters (on all modern file systems).
  4209. * The server can check if the URI uses the same upper/lowercase
  4210. * letters an the file system, effectively making Windows servers
  4211. * case sensitive (like Linux servers are). It is still not possible
  4212. * to use two files with the same name in different cases on Windows
  4213. * (like /a and /A) - this would be possible in Linux.
  4214. * As a default, Windows is not case sensitive, but the case sensitive
  4215. * file name check can be activated by an additional configuration. */
  4216. if (conn) {
  4217. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4218. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4219. "yes")) {
  4220. /* Use case sensitive compare function */
  4221. fcompare = wcscmp;
  4222. }
  4223. }
  4224. (void)conn; /* conn is currently unused */
  4225. /* Only accept a full file path, not a Windows short (8.3) path. */
  4226. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4227. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4228. if (long_len == 0) {
  4229. err = GetLastError();
  4230. if (err == ERROR_FILE_NOT_FOUND) {
  4231. /* File does not exist. This is not always a problem here. */
  4232. return;
  4233. }
  4234. }
  4235. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4236. /* Short name is used. */
  4237. wbuf[0] = L'\0';
  4238. }
  4239. }
  4240. #if !defined(NO_FILESYSTEMS)
  4241. /* Get file information, return 1 if file exists, 0 if not */
  4242. static int
  4243. mg_stat(const struct mg_connection *conn,
  4244. const char *path,
  4245. struct mg_file_stat *filep)
  4246. {
  4247. wchar_t wbuf[UTF16_PATH_MAX];
  4248. WIN32_FILE_ATTRIBUTE_DATA info;
  4249. time_t creation_time;
  4250. size_t len;
  4251. if (!filep) {
  4252. return 0;
  4253. }
  4254. memset(filep, 0, sizeof(*filep));
  4255. if (mg_path_suspicious(conn, path)) {
  4256. return 0;
  4257. }
  4258. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4259. /* Windows happily opens files with some garbage at the end of file name.
  4260. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4261. * "a.cgi", despite one would expect an error back. */
  4262. len = strlen(path);
  4263. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4264. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4265. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4266. filep->last_modified =
  4267. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4268. info.ftLastWriteTime.dwHighDateTime);
  4269. /* On Windows, the file creation time can be higher than the
  4270. * modification time, e.g. when a file is copied.
  4271. * Since the Last-Modified timestamp is used for caching
  4272. * it should be based on the most recent timestamp. */
  4273. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4274. info.ftCreationTime.dwHighDateTime);
  4275. if (creation_time > filep->last_modified) {
  4276. filep->last_modified = creation_time;
  4277. }
  4278. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4279. return 1;
  4280. }
  4281. return 0;
  4282. }
  4283. #endif
  4284. static int
  4285. mg_remove(const struct mg_connection *conn, const char *path)
  4286. {
  4287. wchar_t wbuf[UTF16_PATH_MAX];
  4288. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4289. return DeleteFileW(wbuf) ? 0 : -1;
  4290. }
  4291. static int
  4292. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4293. {
  4294. wchar_t wbuf[UTF16_PATH_MAX];
  4295. (void)mode;
  4296. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4297. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4298. }
  4299. /* Create substitutes for POSIX functions in Win32. */
  4300. #if defined(GCC_DIAGNOSTIC)
  4301. /* Show no warning in case system functions are not used. */
  4302. #pragma GCC diagnostic push
  4303. #pragma GCC diagnostic ignored "-Wunused-function"
  4304. #endif
  4305. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4306. FUNCTION_MAY_BE_UNUSED
  4307. static DIR *
  4308. mg_opendir(const struct mg_connection *conn, const char *name)
  4309. {
  4310. DIR *dir = NULL;
  4311. wchar_t wpath[UTF16_PATH_MAX];
  4312. DWORD attrs;
  4313. if (name == NULL) {
  4314. SetLastError(ERROR_BAD_ARGUMENTS);
  4315. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4316. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4317. } else {
  4318. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4319. attrs = GetFileAttributesW(wpath);
  4320. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4321. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4322. (void)wcscat(wpath, L"\\*");
  4323. dir->handle = FindFirstFileW(wpath, &dir->info);
  4324. dir->result.d_name[0] = '\0';
  4325. } else {
  4326. mg_free(dir);
  4327. dir = NULL;
  4328. }
  4329. }
  4330. return dir;
  4331. }
  4332. FUNCTION_MAY_BE_UNUSED
  4333. static int
  4334. mg_closedir(DIR *dir)
  4335. {
  4336. int result = 0;
  4337. if (dir != NULL) {
  4338. if (dir->handle != INVALID_HANDLE_VALUE)
  4339. result = FindClose(dir->handle) ? 0 : -1;
  4340. mg_free(dir);
  4341. } else {
  4342. result = -1;
  4343. SetLastError(ERROR_BAD_ARGUMENTS);
  4344. }
  4345. return result;
  4346. }
  4347. FUNCTION_MAY_BE_UNUSED
  4348. static struct dirent *
  4349. mg_readdir(DIR *dir)
  4350. {
  4351. struct dirent *result = 0;
  4352. if (dir) {
  4353. if (dir->handle != INVALID_HANDLE_VALUE) {
  4354. result = &dir->result;
  4355. (void)WideCharToMultiByte(CP_UTF8,
  4356. 0,
  4357. dir->info.cFileName,
  4358. -1,
  4359. result->d_name,
  4360. sizeof(result->d_name),
  4361. NULL,
  4362. NULL);
  4363. if (!FindNextFileW(dir->handle, &dir->info)) {
  4364. (void)FindClose(dir->handle);
  4365. dir->handle = INVALID_HANDLE_VALUE;
  4366. }
  4367. } else {
  4368. SetLastError(ERROR_FILE_NOT_FOUND);
  4369. }
  4370. } else {
  4371. SetLastError(ERROR_BAD_ARGUMENTS);
  4372. }
  4373. return result;
  4374. }
  4375. #if !defined(HAVE_POLL)
  4376. #undef POLLIN
  4377. #undef POLLPRI
  4378. #undef POLLOUT
  4379. #undef POLLERR
  4380. #define POLLIN (1) /* Data ready - read will not block. */
  4381. #define POLLPRI (2) /* Priority data ready. */
  4382. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4383. #define POLLERR (8) /* Error event */
  4384. FUNCTION_MAY_BE_UNUSED
  4385. static int
  4386. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4387. {
  4388. struct timeval tv;
  4389. fd_set rset;
  4390. fd_set wset;
  4391. fd_set eset;
  4392. unsigned int i;
  4393. int result;
  4394. SOCKET maxfd = 0;
  4395. memset(&tv, 0, sizeof(tv));
  4396. tv.tv_sec = milliseconds / 1000;
  4397. tv.tv_usec = (milliseconds % 1000) * 1000;
  4398. FD_ZERO(&rset);
  4399. FD_ZERO(&wset);
  4400. FD_ZERO(&eset);
  4401. for (i = 0; i < n; i++) {
  4402. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4403. if (pfd[i].events & POLLIN) {
  4404. FD_SET(pfd[i].fd, &rset);
  4405. }
  4406. if (pfd[i].events & POLLOUT) {
  4407. FD_SET(pfd[i].fd, &wset);
  4408. }
  4409. /* Check for errors for any FD in the set */
  4410. FD_SET(pfd[i].fd, &eset);
  4411. }
  4412. pfd[i].revents = 0;
  4413. if (pfd[i].fd > maxfd) {
  4414. maxfd = pfd[i].fd;
  4415. }
  4416. }
  4417. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4418. for (i = 0; i < n; i++) {
  4419. if (FD_ISSET(pfd[i].fd, &rset)) {
  4420. pfd[i].revents |= POLLIN;
  4421. }
  4422. if (FD_ISSET(pfd[i].fd, &wset)) {
  4423. pfd[i].revents |= POLLOUT;
  4424. }
  4425. if (FD_ISSET(pfd[i].fd, &eset)) {
  4426. pfd[i].revents |= POLLERR;
  4427. }
  4428. }
  4429. }
  4430. /* We should subtract the time used in select from remaining
  4431. * "milliseconds", in particular if called from mg_poll with a
  4432. * timeout quantum.
  4433. * Unfortunately, the remaining time is not stored in "tv" in all
  4434. * implementations, so the result in "tv" must be considered undefined.
  4435. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4436. return result;
  4437. }
  4438. #endif /* HAVE_POLL */
  4439. #if defined(GCC_DIAGNOSTIC)
  4440. /* Enable unused function warning again */
  4441. #pragma GCC diagnostic pop
  4442. #endif
  4443. static void
  4444. set_close_on_exec(SOCKET sock,
  4445. const struct mg_connection *conn /* may be null */,
  4446. struct mg_context *ctx /* may be null */)
  4447. {
  4448. (void)conn; /* Unused. */
  4449. (void)ctx;
  4450. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4451. }
  4452. CIVETWEB_API int
  4453. mg_start_thread(mg_thread_func_t f, void *p)
  4454. {
  4455. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4456. /* Compile-time option to control stack size, e.g.
  4457. * -DUSE_STACK_SIZE=16384
  4458. */
  4459. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4460. == ((uintptr_t)(-1L)))
  4461. ? -1
  4462. : 0);
  4463. #else
  4464. return (
  4465. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4466. ? -1
  4467. : 0);
  4468. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4469. }
  4470. /* Start a thread storing the thread context. */
  4471. static int
  4472. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4473. void *p,
  4474. pthread_t *threadidptr)
  4475. {
  4476. uintptr_t uip;
  4477. HANDLE threadhandle;
  4478. int result = -1;
  4479. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4480. threadhandle = (HANDLE)uip;
  4481. if ((uip != 0) && (threadidptr != NULL)) {
  4482. *threadidptr = threadhandle;
  4483. result = 0;
  4484. }
  4485. return result;
  4486. }
  4487. /* Wait for a thread to finish. */
  4488. static int
  4489. mg_join_thread(pthread_t threadid)
  4490. {
  4491. int result;
  4492. DWORD dwevent;
  4493. result = -1;
  4494. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4495. if (dwevent == WAIT_FAILED) {
  4496. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4497. } else {
  4498. if (dwevent == WAIT_OBJECT_0) {
  4499. CloseHandle(threadid);
  4500. result = 0;
  4501. }
  4502. }
  4503. return result;
  4504. }
  4505. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4506. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4507. /* Create substitutes for POSIX functions in Win32. */
  4508. #if defined(GCC_DIAGNOSTIC)
  4509. /* Show no warning in case system functions are not used. */
  4510. #pragma GCC diagnostic push
  4511. #pragma GCC diagnostic ignored "-Wunused-function"
  4512. #endif
  4513. FUNCTION_MAY_BE_UNUSED
  4514. static HANDLE
  4515. dlopen(const char *dll_name, int flags)
  4516. {
  4517. wchar_t wbuf[UTF16_PATH_MAX];
  4518. (void)flags;
  4519. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4520. return LoadLibraryW(wbuf);
  4521. }
  4522. FUNCTION_MAY_BE_UNUSED
  4523. static int
  4524. dlclose(void *handle)
  4525. {
  4526. int result;
  4527. if (FreeLibrary((HMODULE)handle) != 0) {
  4528. result = 0;
  4529. } else {
  4530. result = -1;
  4531. }
  4532. return result;
  4533. }
  4534. #if defined(GCC_DIAGNOSTIC)
  4535. /* Enable unused function warning again */
  4536. #pragma GCC diagnostic pop
  4537. #endif
  4538. #endif
  4539. #if !defined(NO_CGI)
  4540. #define SIGKILL (0)
  4541. static int
  4542. kill(pid_t pid, int sig_num)
  4543. {
  4544. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4545. (void)CloseHandle((HANDLE)pid);
  4546. return 0;
  4547. }
  4548. #if !defined(WNOHANG)
  4549. #define WNOHANG (1)
  4550. #endif
  4551. static pid_t
  4552. waitpid(pid_t pid, int *status, int flags)
  4553. {
  4554. DWORD timeout = INFINITE;
  4555. DWORD waitres;
  4556. (void)status; /* Currently not used by any client here */
  4557. if ((flags | WNOHANG) == WNOHANG) {
  4558. timeout = 0;
  4559. }
  4560. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4561. if (waitres == WAIT_OBJECT_0) {
  4562. return pid;
  4563. }
  4564. if (waitres == WAIT_TIMEOUT) {
  4565. return 0;
  4566. }
  4567. return (pid_t)-1;
  4568. }
  4569. static void
  4570. trim_trailing_whitespaces(char *s)
  4571. {
  4572. char *e = s + strlen(s);
  4573. while ((e > s) && isspace((unsigned char)e[-1])) {
  4574. *(--e) = '\0';
  4575. }
  4576. }
  4577. static pid_t
  4578. spawn_process(struct mg_connection *conn,
  4579. const char *prog,
  4580. char *envblk,
  4581. char *envp[],
  4582. int fdin[2],
  4583. int fdout[2],
  4584. int fderr[2],
  4585. const char *dir,
  4586. unsigned char cgi_config_idx)
  4587. {
  4588. HANDLE me;
  4589. char *interp;
  4590. char *interp_arg = 0;
  4591. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4592. int truncated;
  4593. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4594. STARTUPINFOA si;
  4595. PROCESS_INFORMATION pi = {0};
  4596. (void)envp;
  4597. memset(&si, 0, sizeof(si));
  4598. si.cb = sizeof(si);
  4599. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4600. si.wShowWindow = SW_HIDE;
  4601. me = GetCurrentProcess();
  4602. DuplicateHandle(me,
  4603. (HANDLE)_get_osfhandle(fdin[0]),
  4604. me,
  4605. &si.hStdInput,
  4606. 0,
  4607. TRUE,
  4608. DUPLICATE_SAME_ACCESS);
  4609. DuplicateHandle(me,
  4610. (HANDLE)_get_osfhandle(fdout[1]),
  4611. me,
  4612. &si.hStdOutput,
  4613. 0,
  4614. TRUE,
  4615. DUPLICATE_SAME_ACCESS);
  4616. DuplicateHandle(me,
  4617. (HANDLE)_get_osfhandle(fderr[1]),
  4618. me,
  4619. &si.hStdError,
  4620. 0,
  4621. TRUE,
  4622. DUPLICATE_SAME_ACCESS);
  4623. /* Mark handles that should not be inherited. See
  4624. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4625. */
  4626. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4627. HANDLE_FLAG_INHERIT,
  4628. 0);
  4629. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4630. HANDLE_FLAG_INHERIT,
  4631. 0);
  4632. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4633. HANDLE_FLAG_INHERIT,
  4634. 0);
  4635. /* First check, if there is a CGI interpreter configured for all CGI
  4636. * scripts. */
  4637. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4638. if (interp != NULL) {
  4639. /* If there is a configured interpreter, check for additional arguments
  4640. */
  4641. interp_arg =
  4642. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4643. } else {
  4644. /* Otherwise, the interpreter must be stated in the first line of the
  4645. * CGI script file, after a #! (shebang) mark. */
  4646. buf[0] = buf[1] = '\0';
  4647. /* Get the full script path */
  4648. mg_snprintf(
  4649. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4650. if (truncated) {
  4651. pi.hProcess = (pid_t)-1;
  4652. goto spawn_cleanup;
  4653. }
  4654. /* Open the script file, to read the first line */
  4655. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4656. /* Read the first line of the script into the buffer */
  4657. mg_fgets(buf, sizeof(buf), &file);
  4658. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4659. buf[sizeof(buf) - 1] = '\0';
  4660. }
  4661. if ((buf[0] == '#') && (buf[1] == '!')) {
  4662. trim_trailing_whitespaces(buf + 2);
  4663. } else {
  4664. buf[2] = '\0';
  4665. }
  4666. interp = buf + 2;
  4667. }
  4668. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4669. if (interp[0] != '\0') {
  4670. /* This is an interpreted script file. We must call the interpreter. */
  4671. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4672. mg_snprintf(conn,
  4673. &truncated,
  4674. cmdline,
  4675. sizeof(cmdline),
  4676. "\"%s\" %s \"%s\\%s\"",
  4677. interp,
  4678. interp_arg,
  4679. full_dir,
  4680. prog);
  4681. } else {
  4682. mg_snprintf(conn,
  4683. &truncated,
  4684. cmdline,
  4685. sizeof(cmdline),
  4686. "\"%s\" \"%s\\%s\"",
  4687. interp,
  4688. full_dir,
  4689. prog);
  4690. }
  4691. } else {
  4692. /* This is (probably) a compiled program. We call it directly. */
  4693. mg_snprintf(conn,
  4694. &truncated,
  4695. cmdline,
  4696. sizeof(cmdline),
  4697. "\"%s\\%s\"",
  4698. full_dir,
  4699. prog);
  4700. }
  4701. if (truncated) {
  4702. pi.hProcess = (pid_t)-1;
  4703. goto spawn_cleanup;
  4704. }
  4705. DEBUG_TRACE("Running [%s]", cmdline);
  4706. if (CreateProcessA(NULL,
  4707. cmdline,
  4708. NULL,
  4709. NULL,
  4710. TRUE,
  4711. CREATE_NEW_PROCESS_GROUP,
  4712. envblk,
  4713. NULL,
  4714. &si,
  4715. &pi)
  4716. == 0) {
  4717. mg_cry_internal(
  4718. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4719. pi.hProcess = (pid_t)-1;
  4720. /* goto spawn_cleanup; */
  4721. }
  4722. spawn_cleanup:
  4723. (void)CloseHandle(si.hStdOutput);
  4724. (void)CloseHandle(si.hStdError);
  4725. (void)CloseHandle(si.hStdInput);
  4726. if (pi.hThread != NULL) {
  4727. (void)CloseHandle(pi.hThread);
  4728. }
  4729. return (pid_t)pi.hProcess;
  4730. }
  4731. #endif /* !NO_CGI */
  4732. static int
  4733. set_blocking_mode(SOCKET sock)
  4734. {
  4735. unsigned long non_blocking = 0;
  4736. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4737. }
  4738. static int
  4739. set_non_blocking_mode(SOCKET sock)
  4740. {
  4741. unsigned long non_blocking = 1;
  4742. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4743. }
  4744. #else
  4745. #if !defined(NO_FILESYSTEMS)
  4746. static int
  4747. mg_stat(const struct mg_connection *conn,
  4748. const char *path,
  4749. struct mg_file_stat *filep)
  4750. {
  4751. struct stat st;
  4752. if (!filep) {
  4753. return 0;
  4754. }
  4755. memset(filep, 0, sizeof(*filep));
  4756. if (mg_path_suspicious(conn, path)) {
  4757. return 0;
  4758. }
  4759. if (0 == stat(path, &st)) {
  4760. filep->size = (uint64_t)(st.st_size);
  4761. filep->last_modified = st.st_mtime;
  4762. filep->is_directory = S_ISDIR(st.st_mode);
  4763. return 1;
  4764. }
  4765. return 0;
  4766. }
  4767. #endif /* NO_FILESYSTEMS */
  4768. static void
  4769. set_close_on_exec(int fd,
  4770. const struct mg_connection *conn /* may be null */,
  4771. struct mg_context *ctx /* may be null */)
  4772. {
  4773. #if defined(__ZEPHYR__)
  4774. (void)fd;
  4775. (void)conn;
  4776. (void)ctx;
  4777. #else
  4778. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4779. if (conn || ctx) {
  4780. struct mg_connection fc;
  4781. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4782. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4783. __func__,
  4784. strerror(ERRNO));
  4785. }
  4786. }
  4787. #endif
  4788. }
  4789. CIVETWEB_API int
  4790. mg_start_thread(mg_thread_func_t func, void *param)
  4791. {
  4792. pthread_t thread_id;
  4793. pthread_attr_t attr;
  4794. int result;
  4795. (void)pthread_attr_init(&attr);
  4796. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4797. #if defined(__ZEPHYR__)
  4798. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4799. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4800. /* Compile-time option to control stack size,
  4801. * e.g. -DUSE_STACK_SIZE=16384 */
  4802. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4803. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4804. result = pthread_create(&thread_id, &attr, func, param);
  4805. pthread_attr_destroy(&attr);
  4806. return result;
  4807. }
  4808. /* Start a thread storing the thread context. */
  4809. static int
  4810. mg_start_thread_with_id(mg_thread_func_t func,
  4811. void *param,
  4812. pthread_t *threadidptr)
  4813. {
  4814. pthread_t thread_id;
  4815. pthread_attr_t attr;
  4816. int result;
  4817. (void)pthread_attr_init(&attr);
  4818. #if defined(__ZEPHYR__)
  4819. pthread_attr_setstack(&attr,
  4820. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4821. ZEPHYR_STACK_SIZE);
  4822. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4823. /* Compile-time option to control stack size,
  4824. * e.g. -DUSE_STACK_SIZE=16384 */
  4825. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4826. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4827. result = pthread_create(&thread_id, &attr, func, param);
  4828. pthread_attr_destroy(&attr);
  4829. if ((result == 0) && (threadidptr != NULL)) {
  4830. *threadidptr = thread_id;
  4831. }
  4832. return result;
  4833. }
  4834. /* Wait for a thread to finish. */
  4835. static int
  4836. mg_join_thread(pthread_t threadid)
  4837. {
  4838. int result;
  4839. result = pthread_join(threadid, NULL);
  4840. return result;
  4841. }
  4842. #if !defined(NO_CGI)
  4843. static pid_t
  4844. spawn_process(struct mg_connection *conn,
  4845. const char *prog,
  4846. char *envblk,
  4847. char *envp[],
  4848. int fdin[2],
  4849. int fdout[2],
  4850. int fderr[2],
  4851. const char *dir,
  4852. unsigned char cgi_config_idx)
  4853. {
  4854. pid_t pid;
  4855. const char *interp;
  4856. (void)envblk;
  4857. if ((pid = fork()) == -1) {
  4858. /* Parent */
  4859. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4860. } else if (pid != 0) {
  4861. /* Make sure children close parent-side descriptors.
  4862. * The caller will close the child-side immediately. */
  4863. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4864. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4865. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4866. } else {
  4867. /* Child */
  4868. if (chdir(dir) != 0) {
  4869. mg_cry_internal(
  4870. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4871. } else if (dup2(fdin[0], 0) == -1) {
  4872. mg_cry_internal(conn,
  4873. "%s: dup2(%d, 0): %s",
  4874. __func__,
  4875. fdin[0],
  4876. strerror(ERRNO));
  4877. } else if (dup2(fdout[1], 1) == -1) {
  4878. mg_cry_internal(conn,
  4879. "%s: dup2(%d, 1): %s",
  4880. __func__,
  4881. fdout[1],
  4882. strerror(ERRNO));
  4883. } else if (dup2(fderr[1], 2) == -1) {
  4884. mg_cry_internal(conn,
  4885. "%s: dup2(%d, 2): %s",
  4886. __func__,
  4887. fderr[1],
  4888. strerror(ERRNO));
  4889. } else {
  4890. struct sigaction sa;
  4891. /* Keep stderr and stdout in two different pipes.
  4892. * Stdout will be sent back to the client,
  4893. * stderr should go into a server error log. */
  4894. (void)close(fdin[0]);
  4895. (void)close(fdout[1]);
  4896. (void)close(fderr[1]);
  4897. /* Close write end fdin and read end fdout and fderr */
  4898. (void)close(fdin[1]);
  4899. (void)close(fdout[0]);
  4900. (void)close(fderr[0]);
  4901. /* After exec, all signal handlers are restored to their default
  4902. * values, with one exception of SIGCHLD. According to
  4903. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4904. * will leave unchanged after exec if it was set to be ignored.
  4905. * Restore it to default action. */
  4906. memset(&sa, 0, sizeof(sa));
  4907. sa.sa_handler = SIG_DFL;
  4908. sigaction(SIGCHLD, &sa, NULL);
  4909. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4910. if (interp == NULL) {
  4911. /* no interpreter configured, call the programm directly */
  4912. (void)execle(prog, prog, NULL, envp);
  4913. mg_cry_internal(conn,
  4914. "%s: execle(%s): %s",
  4915. __func__,
  4916. prog,
  4917. strerror(ERRNO));
  4918. } else {
  4919. /* call the configured interpreter */
  4920. const char *interp_args =
  4921. conn->dom_ctx
  4922. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4923. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4924. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4925. } else {
  4926. (void)execle(interp, interp, prog, NULL, envp);
  4927. }
  4928. mg_cry_internal(conn,
  4929. "%s: execle(%s %s): %s",
  4930. __func__,
  4931. interp,
  4932. prog,
  4933. strerror(ERRNO));
  4934. }
  4935. }
  4936. exit(EXIT_FAILURE);
  4937. }
  4938. return pid;
  4939. }
  4940. #endif /* !NO_CGI */
  4941. static int
  4942. set_non_blocking_mode(SOCKET sock)
  4943. {
  4944. int flags = fcntl(sock, F_GETFL, 0);
  4945. if (flags < 0) {
  4946. return -1;
  4947. }
  4948. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4949. return -1;
  4950. }
  4951. return 0;
  4952. }
  4953. static int
  4954. set_blocking_mode(SOCKET sock)
  4955. {
  4956. int flags = fcntl(sock, F_GETFL, 0);
  4957. if (flags < 0) {
  4958. return -1;
  4959. }
  4960. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4961. return -1;
  4962. }
  4963. return 0;
  4964. }
  4965. #endif /* _WIN32 / else */
  4966. /* End of initial operating system specific define block. */
  4967. /* Get a random number (independent of C rand function) */
  4968. static uint64_t
  4969. get_random(void)
  4970. {
  4971. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4972. static uint64_t lcg = 0; /* Linear congruential generator */
  4973. uint64_t now = mg_get_current_time_ns();
  4974. if (lfsr == 0) {
  4975. /* lfsr will be only 0 if has not been initialized,
  4976. * so this code is called only once. */
  4977. lfsr = mg_get_current_time_ns();
  4978. lcg = mg_get_current_time_ns();
  4979. } else {
  4980. /* Get the next step of both random number generators. */
  4981. lfsr = (lfsr >> 1)
  4982. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4983. << 63);
  4984. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4985. }
  4986. /* Combining two pseudo-random number generators and a high resolution
  4987. * part
  4988. * of the current server time will make it hard (impossible?) to guess
  4989. * the
  4990. * next number. */
  4991. return (lfsr ^ lcg ^ now);
  4992. }
  4993. static int
  4994. mg_poll(struct mg_pollfd *pfd,
  4995. unsigned int n,
  4996. int milliseconds,
  4997. const stop_flag_t *stop_flag)
  4998. {
  4999. /* Call poll, but only for a maximum time of a few seconds.
  5000. * This will allow to stop the server after some seconds, instead
  5001. * of having to wait for a long socket timeout. */
  5002. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5003. int check_pollerr = 0;
  5004. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5005. /* If we wait for only one file descriptor, wait on error as well */
  5006. pfd[0].events |= POLLERR;
  5007. check_pollerr = 1;
  5008. }
  5009. do {
  5010. int result;
  5011. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5012. /* Shut down signal */
  5013. return -2;
  5014. }
  5015. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5016. ms_now = milliseconds;
  5017. }
  5018. result = poll(pfd, n, ms_now);
  5019. if (result != 0) {
  5020. /* Poll returned either success (1) or error (-1).
  5021. * Forward both to the caller. */
  5022. if ((check_pollerr)
  5023. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5024. == POLLERR)) {
  5025. /* One and only file descriptor returned error */
  5026. return -1;
  5027. }
  5028. return result;
  5029. }
  5030. /* Poll returned timeout (0). */
  5031. if (milliseconds > 0) {
  5032. milliseconds -= ms_now;
  5033. }
  5034. } while (milliseconds > 0);
  5035. /* timeout: return 0 */
  5036. return 0;
  5037. }
  5038. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5039. * descriptor.
  5040. * Return value:
  5041. * >=0 .. number of bytes successfully written
  5042. * -1 .. timeout
  5043. * -2 .. error
  5044. */
  5045. static int
  5046. push_inner(struct mg_context *ctx,
  5047. FILE *fp,
  5048. SOCKET sock,
  5049. SSL *ssl,
  5050. const char *buf,
  5051. int len,
  5052. double timeout)
  5053. {
  5054. uint64_t start = 0, now = 0, timeout_ns = 0;
  5055. int n, err;
  5056. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5057. #if defined(_WIN32)
  5058. typedef int len_t;
  5059. #else
  5060. typedef size_t len_t;
  5061. #endif
  5062. if (timeout > 0) {
  5063. now = mg_get_current_time_ns();
  5064. start = now;
  5065. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5066. }
  5067. if (ctx == NULL) {
  5068. return -2;
  5069. }
  5070. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5071. if (ssl) {
  5072. return -2;
  5073. }
  5074. #endif
  5075. /* Try to read until it succeeds, fails, times out, or the server
  5076. * shuts down. */
  5077. for (;;) {
  5078. #if defined(USE_MBEDTLS)
  5079. if (ssl != NULL) {
  5080. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5081. if (n <= 0) {
  5082. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5083. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5084. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5085. n = 0;
  5086. } else {
  5087. fprintf(stderr, "SSL write failed, error %d\n", n);
  5088. return -2;
  5089. }
  5090. } else {
  5091. err = 0;
  5092. }
  5093. } else
  5094. #elif !defined(NO_SSL)
  5095. if (ssl != NULL) {
  5096. ERR_clear_error();
  5097. n = SSL_write(ssl, buf, len);
  5098. if (n <= 0) {
  5099. err = SSL_get_error(ssl, n);
  5100. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5101. err = ERRNO;
  5102. } else if ((err == SSL_ERROR_WANT_READ)
  5103. || (err == SSL_ERROR_WANT_WRITE)) {
  5104. n = 0;
  5105. } else {
  5106. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5107. ERR_clear_error();
  5108. return -2;
  5109. }
  5110. ERR_clear_error();
  5111. } else {
  5112. err = 0;
  5113. }
  5114. } else
  5115. #endif
  5116. if (fp != NULL) {
  5117. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5118. if (ferror(fp)) {
  5119. n = -1;
  5120. err = ERRNO;
  5121. } else {
  5122. err = 0;
  5123. }
  5124. } else {
  5125. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5126. err = (n < 0) ? ERRNO : 0;
  5127. #if defined(_WIN32)
  5128. if (err == WSAEWOULDBLOCK) {
  5129. err = 0;
  5130. n = 0;
  5131. }
  5132. #else
  5133. if (ERROR_TRY_AGAIN(err)) {
  5134. err = 0;
  5135. n = 0;
  5136. }
  5137. #endif
  5138. if (n < 0) {
  5139. /* shutdown of the socket at client side */
  5140. return -2;
  5141. }
  5142. }
  5143. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5144. return -2;
  5145. }
  5146. if ((n > 0) || ((n == 0) && (len == 0))) {
  5147. /* some data has been read, or no data was requested */
  5148. return n;
  5149. }
  5150. if (n < 0) {
  5151. /* socket error - check errno */
  5152. DEBUG_TRACE("send() failed, error %d", err);
  5153. /* TODO (mid): error handling depending on the error code.
  5154. * These codes are different between Windows and Linux.
  5155. * Currently there is no problem with failing send calls,
  5156. * if there is a reproducible situation, it should be
  5157. * investigated in detail.
  5158. */
  5159. return -2;
  5160. }
  5161. /* Only in case n=0 (timeout), repeat calling the write function */
  5162. /* If send failed, wait before retry */
  5163. if (fp != NULL) {
  5164. /* For files, just wait a fixed time.
  5165. * Maybe it helps, maybe not. */
  5166. mg_sleep(5);
  5167. } else {
  5168. /* For sockets, wait for the socket using poll */
  5169. struct mg_pollfd pfd[1];
  5170. int pollres;
  5171. pfd[0].fd = sock;
  5172. pfd[0].events = POLLOUT;
  5173. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5174. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5175. return -2;
  5176. }
  5177. if (pollres > 0) {
  5178. continue;
  5179. }
  5180. }
  5181. if (timeout > 0) {
  5182. now = mg_get_current_time_ns();
  5183. if ((now - start) > timeout_ns) {
  5184. /* Timeout */
  5185. break;
  5186. }
  5187. }
  5188. }
  5189. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5190. used */
  5191. return -1;
  5192. }
  5193. static int
  5194. push_all(struct mg_context *ctx,
  5195. FILE *fp,
  5196. SOCKET sock,
  5197. SSL *ssl,
  5198. const char *buf,
  5199. int len)
  5200. {
  5201. double timeout = -1.0;
  5202. int n, nwritten = 0;
  5203. if (ctx == NULL) {
  5204. return -1;
  5205. }
  5206. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5207. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5208. }
  5209. if (timeout <= 0.0) {
  5210. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5211. / 1000.0;
  5212. }
  5213. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5214. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5215. if (n < 0) {
  5216. if (nwritten == 0) {
  5217. nwritten = -1; /* Propagate the error */
  5218. }
  5219. break;
  5220. } else if (n == 0) {
  5221. break; /* No more data to write */
  5222. } else {
  5223. nwritten += n;
  5224. len -= n;
  5225. }
  5226. }
  5227. return nwritten;
  5228. }
  5229. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5230. * Return value:
  5231. * >=0 .. number of bytes successfully read
  5232. * -1 .. timeout
  5233. * -2 .. error
  5234. */
  5235. static int
  5236. pull_inner(FILE *fp,
  5237. struct mg_connection *conn,
  5238. char *buf,
  5239. int len,
  5240. double timeout)
  5241. {
  5242. int nread, err = 0;
  5243. #if defined(_WIN32)
  5244. typedef int len_t;
  5245. #else
  5246. typedef size_t len_t;
  5247. #endif
  5248. /* We need an additional wait loop around this, because in some cases
  5249. * with TLSwe may get data from the socket but not from SSL_read.
  5250. * In this case we need to repeat at least once.
  5251. */
  5252. if (fp != NULL) {
  5253. /* Use read() instead of fread(), because if we're reading from the
  5254. * CGI pipe, fread() may block until IO buffer is filled up. We
  5255. * cannot afford to block and must pass all read bytes immediately
  5256. * to the client. */
  5257. nread = (int)read(fileno(fp), buf, (size_t)len);
  5258. err = (nread < 0) ? ERRNO : 0;
  5259. if ((nread == 0) && (len > 0)) {
  5260. /* Should get data, but got EOL */
  5261. return -2;
  5262. }
  5263. #if defined(USE_MBEDTLS)
  5264. } else if (conn->ssl != NULL) {
  5265. struct mg_pollfd pfd[1];
  5266. int to_read;
  5267. int pollres;
  5268. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5269. if (to_read > 0) {
  5270. /* We already know there is no more data buffered in conn->buf
  5271. * but there is more available in the SSL layer. So don't poll
  5272. * conn->client.sock yet. */
  5273. pollres = 1;
  5274. if (to_read > len)
  5275. to_read = len;
  5276. } else {
  5277. pfd[0].fd = conn->client.sock;
  5278. pfd[0].events = POLLIN;
  5279. to_read = len;
  5280. pollres = mg_poll(pfd,
  5281. 1,
  5282. (int)(timeout * 1000.0),
  5283. &(conn->phys_ctx->stop_flag));
  5284. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5285. return -2;
  5286. }
  5287. }
  5288. if (pollres > 0) {
  5289. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5290. if (nread <= 0) {
  5291. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5292. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5293. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5294. nread = 0;
  5295. } else {
  5296. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5297. return -2;
  5298. }
  5299. } else {
  5300. err = 0;
  5301. }
  5302. } else if (pollres < 0) {
  5303. /* Error */
  5304. return -2;
  5305. } else {
  5306. /* pollres = 0 means timeout */
  5307. nread = 0;
  5308. }
  5309. #elif !defined(NO_SSL)
  5310. } else if (conn->ssl != NULL) {
  5311. int ssl_pending;
  5312. struct mg_pollfd pfd[1];
  5313. int pollres;
  5314. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5315. /* We already know there is no more data buffered in conn->buf
  5316. * but there is more available in the SSL layer. So don't poll
  5317. * conn->client.sock yet. */
  5318. if (ssl_pending > len) {
  5319. ssl_pending = len;
  5320. }
  5321. pollres = 1;
  5322. } else {
  5323. pfd[0].fd = conn->client.sock;
  5324. pfd[0].events = POLLIN;
  5325. pollres = mg_poll(pfd,
  5326. 1,
  5327. (int)(timeout * 1000.0),
  5328. &(conn->phys_ctx->stop_flag));
  5329. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5330. return -2;
  5331. }
  5332. }
  5333. if (pollres > 0) {
  5334. ERR_clear_error();
  5335. nread =
  5336. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5337. if (nread <= 0) {
  5338. err = SSL_get_error(conn->ssl, nread);
  5339. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5340. err = ERRNO;
  5341. } else if ((err == SSL_ERROR_WANT_READ)
  5342. || (err == SSL_ERROR_WANT_WRITE)) {
  5343. nread = 0;
  5344. } else {
  5345. /* All errors should return -2 */
  5346. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5347. ERR_clear_error();
  5348. return -2;
  5349. }
  5350. ERR_clear_error();
  5351. } else {
  5352. err = 0;
  5353. }
  5354. } else if (pollres < 0) {
  5355. /* Error */
  5356. return -2;
  5357. } else {
  5358. /* pollres = 0 means timeout */
  5359. nread = 0;
  5360. }
  5361. #endif
  5362. } else {
  5363. struct mg_pollfd pfd[1];
  5364. int pollres;
  5365. pfd[0].fd = conn->client.sock;
  5366. pfd[0].events = POLLIN;
  5367. pollres = mg_poll(pfd,
  5368. 1,
  5369. (int)(timeout * 1000.0),
  5370. &(conn->phys_ctx->stop_flag));
  5371. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5372. return -2;
  5373. }
  5374. if (pollres > 0) {
  5375. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5376. err = (nread < 0) ? ERRNO : 0;
  5377. if (nread <= 0) {
  5378. /* shutdown of the socket at client side */
  5379. return -2;
  5380. }
  5381. } else if (pollres < 0) {
  5382. /* error callint poll */
  5383. return -2;
  5384. } else {
  5385. /* pollres = 0 means timeout */
  5386. nread = 0;
  5387. }
  5388. }
  5389. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5390. return -2;
  5391. }
  5392. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5393. /* some data has been read, or no data was requested */
  5394. return nread;
  5395. }
  5396. if (nread < 0) {
  5397. /* socket error - check errno */
  5398. #if defined(_WIN32)
  5399. if (err == WSAEWOULDBLOCK) {
  5400. /* TODO (low): check if this is still required */
  5401. /* standard case if called from close_socket_gracefully */
  5402. return -2;
  5403. } else if (err == WSAETIMEDOUT) {
  5404. /* TODO (low): check if this is still required */
  5405. /* timeout is handled by the while loop */
  5406. return 0;
  5407. } else if (err == WSAECONNABORTED) {
  5408. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5409. return -2;
  5410. } else {
  5411. DEBUG_TRACE("recv() failed, error %d", err);
  5412. return -2;
  5413. }
  5414. #else
  5415. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5416. * if the timeout is reached and if the socket was set to non-
  5417. * blocking in close_socket_gracefully, so we can not distinguish
  5418. * here. We have to wait for the timeout in both cases for now.
  5419. */
  5420. if (ERROR_TRY_AGAIN(err)) {
  5421. /* TODO (low): check if this is still required */
  5422. /* EAGAIN/EWOULDBLOCK:
  5423. * standard case if called from close_socket_gracefully
  5424. * => should return -1 */
  5425. /* or timeout occurred
  5426. * => the code must stay in the while loop */
  5427. /* EINTR can be generated on a socket with a timeout set even
  5428. * when SA_RESTART is effective for all relevant signals
  5429. * (see signal(7)).
  5430. * => stay in the while loop */
  5431. } else {
  5432. DEBUG_TRACE("recv() failed, error %d", err);
  5433. return -2;
  5434. }
  5435. #endif
  5436. }
  5437. /* Timeout occurred, but no data available. */
  5438. return -1;
  5439. }
  5440. static int
  5441. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5442. {
  5443. int n, nread = 0;
  5444. double timeout = -1.0;
  5445. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5446. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5447. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5448. }
  5449. if (timeout <= 0.0) {
  5450. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5451. / 1000.0;
  5452. }
  5453. start_time = mg_get_current_time_ns();
  5454. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5455. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5456. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5457. if (n == -2) {
  5458. if (nread == 0) {
  5459. nread = -1; /* Propagate the error */
  5460. }
  5461. break;
  5462. } else if (n == -1) {
  5463. /* timeout */
  5464. if (timeout >= 0.0) {
  5465. now = mg_get_current_time_ns();
  5466. if ((now - start_time) <= timeout_ns) {
  5467. continue;
  5468. }
  5469. }
  5470. break;
  5471. } else if (n == 0) {
  5472. break; /* No more data to read */
  5473. } else {
  5474. nread += n;
  5475. len -= n;
  5476. }
  5477. }
  5478. return nread;
  5479. }
  5480. static void
  5481. discard_unread_request_data(struct mg_connection *conn)
  5482. {
  5483. char buf[MG_BUF_LEN];
  5484. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5485. ;
  5486. }
  5487. static int
  5488. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5489. {
  5490. int64_t content_len, n, buffered_len, nread;
  5491. int64_t len64 =
  5492. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5493. * int, we may not read more
  5494. * bytes */
  5495. const char *body;
  5496. if (conn == NULL) {
  5497. return 0;
  5498. }
  5499. /* If Content-Length is not set for a response with body data,
  5500. * we do not know in advance how much data should be read. */
  5501. content_len = conn->content_len;
  5502. if (content_len < 0) {
  5503. /* The body data is completed when the connection is closed. */
  5504. content_len = INT64_MAX;
  5505. }
  5506. nread = 0;
  5507. if (conn->consumed_content < content_len) {
  5508. /* Adjust number of bytes to read. */
  5509. int64_t left_to_read = content_len - conn->consumed_content;
  5510. if (left_to_read < len64) {
  5511. /* Do not read more than the total content length of the
  5512. * request.
  5513. */
  5514. len64 = left_to_read;
  5515. }
  5516. /* Return buffered data */
  5517. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5518. - conn->consumed_content;
  5519. if (buffered_len > 0) {
  5520. if (len64 < buffered_len) {
  5521. buffered_len = len64;
  5522. }
  5523. body = conn->buf + conn->request_len + conn->consumed_content;
  5524. memcpy(buf, body, (size_t)buffered_len);
  5525. len64 -= buffered_len;
  5526. conn->consumed_content += buffered_len;
  5527. nread += buffered_len;
  5528. buf = (char *)buf + buffered_len;
  5529. }
  5530. /* We have returned all buffered data. Read new data from the remote
  5531. * socket.
  5532. */
  5533. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5534. conn->consumed_content += n;
  5535. nread += n;
  5536. } else {
  5537. nread = ((nread > 0) ? nread : n);
  5538. }
  5539. }
  5540. return (int)nread;
  5541. }
  5542. /* Forward declarations */
  5543. static void handle_request(struct mg_connection *);
  5544. static void log_access(const struct mg_connection *);
  5545. /* Handle request, update statistics and call access log */
  5546. static void
  5547. handle_request_stat_log(struct mg_connection *conn)
  5548. {
  5549. #if defined(USE_SERVER_STATS)
  5550. struct timespec tnow;
  5551. conn->conn_state = 4; /* processing */
  5552. #endif
  5553. handle_request(conn);
  5554. #if defined(USE_SERVER_STATS)
  5555. conn->conn_state = 5; /* processed */
  5556. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5557. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5558. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5559. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5560. conn->num_bytes_sent);
  5561. #endif
  5562. DEBUG_TRACE("%s", "handle_request done");
  5563. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5564. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5565. DEBUG_TRACE("%s", "end_request callback done");
  5566. }
  5567. log_access(conn);
  5568. }
  5569. #if defined(USE_HTTP2)
  5570. #if defined(NO_SSL)
  5571. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5572. #endif
  5573. #define USE_ALPN
  5574. #include "http2.inl"
  5575. /* Not supported with HTTP/2 */
  5576. #define HTTP1_only \
  5577. { \
  5578. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5579. http2_must_use_http1(conn); \
  5580. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5581. return; \
  5582. } \
  5583. }
  5584. #else
  5585. #define HTTP1_only
  5586. #endif
  5587. CIVETWEB_API int
  5588. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5589. {
  5590. if (len > INT_MAX) {
  5591. len = INT_MAX;
  5592. }
  5593. if (conn == NULL) {
  5594. return 0;
  5595. }
  5596. if (conn->is_chunked) {
  5597. size_t all_read = 0;
  5598. while (len > 0) {
  5599. if (conn->is_chunked >= 3) {
  5600. /* No more data left to read */
  5601. return 0;
  5602. }
  5603. if (conn->is_chunked != 1) {
  5604. /* Has error */
  5605. return -1;
  5606. }
  5607. if (conn->consumed_content != conn->content_len) {
  5608. /* copy from the current chunk */
  5609. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5610. if (read_ret < 1) {
  5611. /* read error */
  5612. conn->is_chunked = 2;
  5613. return -1;
  5614. }
  5615. all_read += (size_t)read_ret;
  5616. len -= (size_t)read_ret;
  5617. if (conn->consumed_content == conn->content_len) {
  5618. /* Add data bytes in the current chunk have been read,
  5619. * so we are expecting \r\n now. */
  5620. char x[2];
  5621. conn->content_len += 2;
  5622. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5623. || (x[1] != '\n')) {
  5624. /* Protocol violation */
  5625. conn->is_chunked = 2;
  5626. return -1;
  5627. }
  5628. }
  5629. } else {
  5630. /* fetch a new chunk */
  5631. size_t i;
  5632. char lenbuf[64];
  5633. char *end = NULL;
  5634. unsigned long chunkSize = 0;
  5635. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5636. conn->content_len++;
  5637. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5638. lenbuf[i] = 0;
  5639. }
  5640. if ((i > 0) && (lenbuf[i] == '\r')
  5641. && (lenbuf[i - 1] != '\r')) {
  5642. continue;
  5643. }
  5644. if ((i > 1) && (lenbuf[i] == '\n')
  5645. && (lenbuf[i - 1] == '\r')) {
  5646. lenbuf[i + 1] = 0;
  5647. chunkSize = strtoul(lenbuf, &end, 16);
  5648. if (chunkSize == 0) {
  5649. /* regular end of content */
  5650. conn->is_chunked = 3;
  5651. }
  5652. break;
  5653. }
  5654. if (!isxdigit((unsigned char)lenbuf[i])) {
  5655. /* illegal character for chunk length */
  5656. conn->is_chunked = 2;
  5657. return -1;
  5658. }
  5659. }
  5660. if ((end == NULL) || (*end != '\r')) {
  5661. /* chunksize not set correctly */
  5662. conn->is_chunked = 2;
  5663. return -1;
  5664. }
  5665. if (chunkSize == 0) {
  5666. /* try discarding trailer for keep-alive */
  5667. conn->content_len += 2;
  5668. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5669. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5670. conn->is_chunked = 4;
  5671. }
  5672. break;
  5673. }
  5674. /* append a new chunk */
  5675. conn->content_len += (int64_t)chunkSize;
  5676. }
  5677. }
  5678. return (int)all_read;
  5679. }
  5680. return mg_read_inner(conn, buf, len);
  5681. }
  5682. CIVETWEB_API int
  5683. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5684. {
  5685. time_t now;
  5686. int n, total, allowed;
  5687. if (conn == NULL) {
  5688. return 0;
  5689. }
  5690. if (len > INT_MAX) {
  5691. return -1;
  5692. }
  5693. /* Mark connection as "data sent" */
  5694. conn->request_state = 10;
  5695. #if defined(USE_HTTP2)
  5696. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5697. http2_data_frame_head(conn, len, 0);
  5698. }
  5699. #endif
  5700. if (conn->throttle > 0) {
  5701. if ((now = time(NULL)) != conn->last_throttle_time) {
  5702. conn->last_throttle_time = now;
  5703. conn->last_throttle_bytes = 0;
  5704. }
  5705. allowed = conn->throttle - conn->last_throttle_bytes;
  5706. if (allowed > (int)len) {
  5707. allowed = (int)len;
  5708. }
  5709. total = push_all(conn->phys_ctx,
  5710. NULL,
  5711. conn->client.sock,
  5712. conn->ssl,
  5713. (const char *)buf,
  5714. allowed);
  5715. if (total == allowed) {
  5716. buf = (const char *)buf + total;
  5717. conn->last_throttle_bytes += total;
  5718. while ((total < (int)len)
  5719. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5720. allowed = (conn->throttle > ((int)len - total))
  5721. ? (int)len - total
  5722. : conn->throttle;
  5723. n = push_all(conn->phys_ctx,
  5724. NULL,
  5725. conn->client.sock,
  5726. conn->ssl,
  5727. (const char *)buf,
  5728. allowed);
  5729. if (n != allowed) {
  5730. break;
  5731. }
  5732. sleep(1);
  5733. conn->last_throttle_bytes = allowed;
  5734. conn->last_throttle_time = time(NULL);
  5735. buf = (const char *)buf + n;
  5736. total += n;
  5737. }
  5738. }
  5739. } else {
  5740. total = push_all(conn->phys_ctx,
  5741. NULL,
  5742. conn->client.sock,
  5743. conn->ssl,
  5744. (const char *)buf,
  5745. (int)len);
  5746. }
  5747. if (total > 0) {
  5748. conn->num_bytes_sent += total;
  5749. }
  5750. return total;
  5751. }
  5752. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5753. CIVETWEB_API int
  5754. mg_send_chunk(struct mg_connection *conn,
  5755. const char *chunk,
  5756. unsigned int chunk_len)
  5757. {
  5758. char lenbuf[16];
  5759. size_t lenbuf_len;
  5760. int ret;
  5761. int t;
  5762. /* First store the length information in a text buffer. */
  5763. sprintf(lenbuf, "%x\r\n", chunk_len);
  5764. lenbuf_len = strlen(lenbuf);
  5765. /* Then send length information, chunk and terminating \r\n. */
  5766. ret = mg_write(conn, lenbuf, lenbuf_len);
  5767. if (ret != (int)lenbuf_len) {
  5768. return -1;
  5769. }
  5770. t = ret;
  5771. ret = mg_write(conn, chunk, chunk_len);
  5772. if (ret != (int)chunk_len) {
  5773. return -1;
  5774. }
  5775. t += ret;
  5776. ret = mg_write(conn, "\r\n", 2);
  5777. if (ret != 2) {
  5778. return -1;
  5779. }
  5780. t += ret;
  5781. return t;
  5782. }
  5783. #if defined(GCC_DIAGNOSTIC)
  5784. /* This block forwards format strings to printf implementations,
  5785. * so we need to disable the format-nonliteral warning. */
  5786. #pragma GCC diagnostic push
  5787. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5788. #endif
  5789. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5790. static int
  5791. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5792. {
  5793. va_list ap_copy;
  5794. size_t size = MG_BUF_LEN / 4;
  5795. int len = -1;
  5796. *buf = NULL;
  5797. while (len < 0) {
  5798. if (*buf) {
  5799. mg_free(*buf);
  5800. }
  5801. size *= 4;
  5802. *buf = (char *)mg_malloc(size);
  5803. if (!*buf) {
  5804. break;
  5805. }
  5806. va_copy(ap_copy, ap);
  5807. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5808. va_end(ap_copy);
  5809. (*buf)[size - 1] = 0;
  5810. }
  5811. return len;
  5812. }
  5813. /* Print message to buffer. If buffer is large enough to hold the message,
  5814. * return buffer. If buffer is to small, allocate large enough buffer on
  5815. * heap,
  5816. * and return allocated buffer. */
  5817. static int
  5818. alloc_vprintf(char **out_buf,
  5819. char *prealloc_buf,
  5820. size_t prealloc_size,
  5821. const char *fmt,
  5822. va_list ap)
  5823. {
  5824. va_list ap_copy;
  5825. int len;
  5826. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5827. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5828. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5829. * Therefore, we make two passes: on first pass, get required message
  5830. * length.
  5831. * On second pass, actually print the message. */
  5832. va_copy(ap_copy, ap);
  5833. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5834. va_end(ap_copy);
  5835. if (len < 0) {
  5836. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5837. * Switch to alternative code path that uses incremental
  5838. * allocations.
  5839. */
  5840. va_copy(ap_copy, ap);
  5841. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5842. va_end(ap_copy);
  5843. } else if ((size_t)(len) >= prealloc_size) {
  5844. /* The pre-allocated buffer not large enough. */
  5845. /* Allocate a new buffer. */
  5846. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5847. if (!*out_buf) {
  5848. /* Allocation failed. Return -1 as "out of memory" error. */
  5849. return -1;
  5850. }
  5851. /* Buffer allocation successful. Store the string there. */
  5852. va_copy(ap_copy, ap);
  5853. IGNORE_UNUSED_RESULT(
  5854. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5855. va_end(ap_copy);
  5856. } else {
  5857. /* The pre-allocated buffer is large enough.
  5858. * Use it to store the string and return the address. */
  5859. va_copy(ap_copy, ap);
  5860. IGNORE_UNUSED_RESULT(
  5861. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5862. va_end(ap_copy);
  5863. *out_buf = prealloc_buf;
  5864. }
  5865. return len;
  5866. }
  5867. static int
  5868. alloc_printf(char **out_buf, const char *fmt, ...)
  5869. {
  5870. va_list ap;
  5871. int result;
  5872. va_start(ap, fmt);
  5873. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  5874. va_end(ap);
  5875. return result;
  5876. }
  5877. #if defined(GCC_DIAGNOSTIC)
  5878. /* Enable format-nonliteral warning again. */
  5879. #pragma GCC diagnostic pop
  5880. #endif
  5881. static int
  5882. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5883. {
  5884. char mem[MG_BUF_LEN];
  5885. char *buf = NULL;
  5886. int len;
  5887. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5888. len = mg_write(conn, buf, (size_t)len);
  5889. }
  5890. if (buf != mem) {
  5891. mg_free(buf);
  5892. }
  5893. return len;
  5894. }
  5895. CIVETWEB_API int
  5896. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5897. {
  5898. va_list ap;
  5899. int result;
  5900. va_start(ap, fmt);
  5901. result = mg_vprintf(conn, fmt, ap);
  5902. va_end(ap);
  5903. return result;
  5904. }
  5905. CIVETWEB_API int
  5906. mg_url_decode(const char *src,
  5907. int src_len,
  5908. char *dst,
  5909. int dst_len,
  5910. int is_form_url_encoded)
  5911. {
  5912. int i, j, a, b;
  5913. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5914. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5915. if ((i < src_len - 2) && (src[i] == '%')
  5916. && isxdigit((unsigned char)src[i + 1])
  5917. && isxdigit((unsigned char)src[i + 2])) {
  5918. a = tolower((unsigned char)src[i + 1]);
  5919. b = tolower((unsigned char)src[i + 2]);
  5920. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5921. i += 2;
  5922. } else if (is_form_url_encoded && (src[i] == '+')) {
  5923. dst[j] = ' ';
  5924. } else {
  5925. dst[j] = src[i];
  5926. }
  5927. }
  5928. dst[j] = '\0'; /* Null-terminate the destination */
  5929. return (i >= src_len) ? j : -1;
  5930. }
  5931. /* form url decoding of an entire string */
  5932. static void
  5933. url_decode_in_place(char *buf)
  5934. {
  5935. int len = (int)strlen(buf);
  5936. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5937. }
  5938. CIVETWEB_API int
  5939. mg_get_var(const char *data,
  5940. size_t data_len,
  5941. const char *name,
  5942. char *dst,
  5943. size_t dst_len)
  5944. {
  5945. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5946. }
  5947. CIVETWEB_API int
  5948. mg_get_var2(const char *data,
  5949. size_t data_len,
  5950. const char *name,
  5951. char *dst,
  5952. size_t dst_len,
  5953. size_t occurrence)
  5954. {
  5955. const char *p, *e, *s;
  5956. size_t name_len;
  5957. int len;
  5958. if ((dst == NULL) || (dst_len == 0)) {
  5959. len = -2;
  5960. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5961. len = -1;
  5962. dst[0] = '\0';
  5963. } else {
  5964. name_len = strlen(name);
  5965. e = data + data_len;
  5966. len = -1;
  5967. dst[0] = '\0';
  5968. /* data is "var1=val1&var2=val2...". Find variable first */
  5969. for (p = data; p + name_len < e; p++) {
  5970. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5971. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5972. /* Point p to variable value */
  5973. p += name_len + 1;
  5974. /* Point s to the end of the value */
  5975. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5976. if (s == NULL) {
  5977. s = e;
  5978. }
  5979. DEBUG_ASSERT(s >= p);
  5980. if (s < p) {
  5981. return -3;
  5982. }
  5983. /* Decode variable into destination buffer */
  5984. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5985. /* Redirect error code from -1 to -2 (destination buffer too
  5986. * small). */
  5987. if (len == -1) {
  5988. len = -2;
  5989. }
  5990. break;
  5991. }
  5992. }
  5993. }
  5994. return len;
  5995. }
  5996. /* split a string "key1=val1&key2=val2" into key/value pairs */
  5997. CIVETWEB_API int
  5998. mg_split_form_urlencoded(char *data,
  5999. struct mg_header *form_fields,
  6000. unsigned num_form_fields)
  6001. {
  6002. char *b;
  6003. int i;
  6004. int num = 0;
  6005. if (data == NULL) {
  6006. /* parameter error */
  6007. return -1;
  6008. }
  6009. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6010. /* determine the number of expected fields */
  6011. if (data[0] == 0) {
  6012. return 0;
  6013. }
  6014. /* count number of & to return the number of key-value-pairs */
  6015. num = 1;
  6016. while (*data) {
  6017. if (*data == '&') {
  6018. num++;
  6019. }
  6020. data++;
  6021. }
  6022. return num;
  6023. }
  6024. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6025. /* parameter error */
  6026. return -1;
  6027. }
  6028. for (i = 0; i < (int)num_form_fields; i++) {
  6029. /* extract key-value pairs from input data */
  6030. while ((*data == ' ') || (*data == '\t')) {
  6031. /* skip initial spaces */
  6032. data++;
  6033. }
  6034. if (*data == 0) {
  6035. /* end of string reached */
  6036. break;
  6037. }
  6038. form_fields[num].name = data;
  6039. /* find & or = */
  6040. b = data;
  6041. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6042. b++;
  6043. }
  6044. if (*b == 0) {
  6045. /* last key without value */
  6046. form_fields[num].value = NULL;
  6047. } else if (*b == '&') {
  6048. /* mid key without value */
  6049. form_fields[num].value = NULL;
  6050. } else {
  6051. /* terminate string */
  6052. *b = 0;
  6053. /* value starts after '=' */
  6054. data = b + 1;
  6055. form_fields[num].value = data;
  6056. }
  6057. /* new field is stored */
  6058. num++;
  6059. /* find a next key */
  6060. b = strchr(data, '&');
  6061. if (b == 0) {
  6062. /* no more data */
  6063. break;
  6064. } else {
  6065. /* terminate value of last field at '&' */
  6066. *b = 0;
  6067. /* next key-value-pairs starts after '&' */
  6068. data = b + 1;
  6069. }
  6070. }
  6071. /* Decode all values */
  6072. for (i = 0; i < num; i++) {
  6073. if (form_fields[i].name) {
  6074. url_decode_in_place((char *)form_fields[i].name);
  6075. }
  6076. if (form_fields[i].value) {
  6077. url_decode_in_place((char *)form_fields[i].value);
  6078. }
  6079. }
  6080. /* return number of fields found */
  6081. return num;
  6082. }
  6083. /* HCP24: some changes to compare whole var_name */
  6084. CIVETWEB_API int
  6085. mg_get_cookie(const char *cookie_header,
  6086. const char *var_name,
  6087. char *dst,
  6088. size_t dst_size)
  6089. {
  6090. const char *s, *p, *end;
  6091. int name_len, len = -1;
  6092. if ((dst == NULL) || (dst_size == 0)) {
  6093. return -2;
  6094. }
  6095. dst[0] = '\0';
  6096. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6097. return -1;
  6098. }
  6099. name_len = (int)strlen(var_name);
  6100. end = s + strlen(s);
  6101. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6102. if (s[name_len] == '=') {
  6103. /* HCP24: now check is it a substring or a full cookie name */
  6104. if ((s == cookie_header) || (s[-1] == ' ')) {
  6105. s += name_len + 1;
  6106. if ((p = strchr(s, ' ')) == NULL) {
  6107. p = end;
  6108. }
  6109. if (p[-1] == ';') {
  6110. p--;
  6111. }
  6112. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6113. s++;
  6114. p--;
  6115. }
  6116. if ((size_t)(p - s) < dst_size) {
  6117. len = (int)(p - s);
  6118. mg_strlcpy(dst, s, (size_t)len + 1);
  6119. } else {
  6120. len = -3;
  6121. }
  6122. break;
  6123. }
  6124. }
  6125. }
  6126. return len;
  6127. }
  6128. CIVETWEB_API int
  6129. mg_base64_encode(const unsigned char *src,
  6130. size_t src_len,
  6131. char *dst,
  6132. size_t *dst_len)
  6133. {
  6134. static const char *b64 =
  6135. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6136. size_t i, j;
  6137. int a, b, c;
  6138. if (dst_len != NULL) {
  6139. /* Expected length including 0 termination: */
  6140. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6141. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6142. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6143. if (*dst_len < expected_len) {
  6144. if (*dst_len > 0) {
  6145. dst[0] = '\0';
  6146. }
  6147. *dst_len = expected_len;
  6148. return 0;
  6149. }
  6150. }
  6151. for (i = j = 0; i < src_len; i += 3) {
  6152. a = src[i];
  6153. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6154. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6155. dst[j++] = b64[a >> 2];
  6156. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6157. if (i + 1 < src_len) {
  6158. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6159. }
  6160. if (i + 2 < src_len) {
  6161. dst[j++] = b64[c & 63];
  6162. }
  6163. }
  6164. while (j % 4 != 0) {
  6165. dst[j++] = '=';
  6166. }
  6167. dst[j++] = '\0';
  6168. if (dst_len != NULL) {
  6169. *dst_len = (size_t)j;
  6170. }
  6171. /* Return -1 for "OK" */
  6172. return -1;
  6173. }
  6174. static unsigned char
  6175. b64reverse(char letter)
  6176. {
  6177. if ((letter >= 'A') && (letter <= 'Z')) {
  6178. return letter - 'A';
  6179. }
  6180. if ((letter >= 'a') && (letter <= 'z')) {
  6181. return letter - 'a' + 26;
  6182. }
  6183. if ((letter >= '0') && (letter <= '9')) {
  6184. return letter - '0' + 52;
  6185. }
  6186. if (letter == '+') {
  6187. return 62;
  6188. }
  6189. if (letter == '/') {
  6190. return 63;
  6191. }
  6192. if (letter == '=') {
  6193. return 255; /* normal end */
  6194. }
  6195. return 254; /* error */
  6196. }
  6197. CIVETWEB_API int
  6198. mg_base64_decode(const char *src,
  6199. size_t src_len,
  6200. unsigned char *dst,
  6201. size_t *dst_len)
  6202. {
  6203. size_t i;
  6204. unsigned char a, b, c, d;
  6205. size_t dst_len_limit = (size_t)-1;
  6206. size_t dst_len_used = 0;
  6207. if (dst_len != NULL) {
  6208. dst_len_limit = *dst_len;
  6209. *dst_len = 0;
  6210. }
  6211. for (i = 0; i < src_len; i += 4) {
  6212. /* Read 4 characters from BASE64 string */
  6213. a = b64reverse(src[i]);
  6214. if (a >= 254) {
  6215. return (int)i;
  6216. }
  6217. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6218. if (b >= 254) {
  6219. return (int)i + 1;
  6220. }
  6221. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6222. if (c == 254) {
  6223. return (int)i + 2;
  6224. }
  6225. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6226. if (d == 254) {
  6227. return (int)i + 3;
  6228. }
  6229. /* Add first (of 3) decoded character */
  6230. if (dst_len_used < dst_len_limit) {
  6231. dst[dst_len_used] = (a << 2) + (b >> 4);
  6232. }
  6233. dst_len_used++;
  6234. if (c != 255) {
  6235. if (dst_len_used < dst_len_limit) {
  6236. dst[dst_len_used] = (b << 4) + (c >> 2);
  6237. }
  6238. dst_len_used++;
  6239. if (d != 255) {
  6240. if (dst_len_used < dst_len_limit) {
  6241. dst[dst_len_used] = (c << 6) + d;
  6242. }
  6243. dst_len_used++;
  6244. }
  6245. }
  6246. }
  6247. /* Add terminating zero */
  6248. if (dst_len_used < dst_len_limit) {
  6249. dst[dst_len_used] = '\0';
  6250. }
  6251. dst_len_used++;
  6252. if (dst_len != NULL) {
  6253. *dst_len = dst_len_used;
  6254. }
  6255. if (dst_len_used > dst_len_limit) {
  6256. /* Out of memory */
  6257. return 0;
  6258. }
  6259. /* Return -1 for "OK" */
  6260. return -1;
  6261. }
  6262. static int
  6263. is_put_or_delete_method(const struct mg_connection *conn)
  6264. {
  6265. if (conn) {
  6266. const char *s = conn->request_info.request_method;
  6267. if (s != NULL) {
  6268. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6269. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6270. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6271. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6272. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6273. || !strcmp(s, "COPY"));
  6274. }
  6275. }
  6276. return 0;
  6277. }
  6278. static int
  6279. is_civetweb_webdav_method(const struct mg_connection *conn)
  6280. {
  6281. /* Note: Here we only have to identify the WebDav methods that need special
  6282. * handling in the CivetWeb code - not all methods used in WebDav. In
  6283. * particular, methods used on directories (when using Windows Explorer as
  6284. * WebDav client).
  6285. */
  6286. if (conn) {
  6287. const char *s = conn->request_info.request_method;
  6288. if (s != NULL) {
  6289. /* These are the civetweb builtin DAV methods */
  6290. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6291. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6292. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6293. }
  6294. }
  6295. return 0;
  6296. }
  6297. #if !defined(NO_FILES)
  6298. static int
  6299. extention_matches_script(
  6300. struct mg_connection *conn, /* in: request (must be valid) */
  6301. const char *filename /* in: filename (must be valid) */
  6302. )
  6303. {
  6304. #if !defined(NO_CGI)
  6305. unsigned char cgi_config_idx, inc, max;
  6306. #endif
  6307. #if defined(USE_LUA)
  6308. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6309. filename)
  6310. > 0) {
  6311. return 1;
  6312. }
  6313. #endif
  6314. #if defined(USE_DUKTAPE)
  6315. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6316. filename)
  6317. > 0) {
  6318. return 1;
  6319. }
  6320. #endif
  6321. #if !defined(NO_CGI)
  6322. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6323. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6324. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6325. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6326. && (match_prefix_strlen(
  6327. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6328. filename)
  6329. > 0)) {
  6330. return 1;
  6331. }
  6332. }
  6333. #endif
  6334. /* filename and conn could be unused, if all preocessor conditions
  6335. * are false (no script language supported). */
  6336. (void)filename;
  6337. (void)conn;
  6338. return 0;
  6339. }
  6340. static int
  6341. extention_matches_template_text(
  6342. struct mg_connection *conn, /* in: request (must be valid) */
  6343. const char *filename /* in: filename (must be valid) */
  6344. )
  6345. {
  6346. #if defined(USE_LUA)
  6347. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6348. filename)
  6349. > 0) {
  6350. return 1;
  6351. }
  6352. #endif
  6353. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6354. > 0) {
  6355. return 1;
  6356. }
  6357. return 0;
  6358. }
  6359. /* For given directory path, substitute it to valid index file.
  6360. * Return 1 if index file has been found, 0 if not found.
  6361. * If the file is found, it's stats is returned in stp. */
  6362. static int
  6363. substitute_index_file(struct mg_connection *conn,
  6364. char *path,
  6365. size_t path_len,
  6366. struct mg_file_stat *filestat)
  6367. {
  6368. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6369. struct vec filename_vec;
  6370. size_t n = strlen(path);
  6371. int found = 0;
  6372. /* The 'path' given to us points to the directory. Remove all trailing
  6373. * directory separator characters from the end of the path, and
  6374. * then append single directory separator character. */
  6375. while ((n > 0) && (path[n - 1] == '/')) {
  6376. n--;
  6377. }
  6378. path[n] = '/';
  6379. /* Traverse index files list. For each entry, append it to the given
  6380. * path and see if the file exists. If it exists, break the loop */
  6381. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6382. /* Ignore too long entries that may overflow path buffer */
  6383. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6384. continue;
  6385. }
  6386. /* Prepare full path to the index file */
  6387. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6388. /* Does it exist? */
  6389. if (mg_stat(conn, path, filestat)) {
  6390. /* Yes it does, break the loop */
  6391. found = 1;
  6392. break;
  6393. }
  6394. }
  6395. /* If no index file exists, restore directory path */
  6396. if (!found) {
  6397. path[n] = '\0';
  6398. }
  6399. return found;
  6400. }
  6401. #endif
  6402. static void
  6403. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6404. char *filename, /* out: filename */
  6405. size_t filename_buf_len, /* in: size of filename buffer */
  6406. struct mg_file_stat *filestat, /* out: file status structure */
  6407. int *is_found, /* out: file found (directly) */
  6408. int *is_script_resource, /* out: handled by a script? */
  6409. int *is_websocket_request, /* out: websocket connetion? */
  6410. int *is_put_or_delete_request, /* out: put/delete a file? */
  6411. int *is_webdav_request, /* out: webdav request? */
  6412. int *is_template_text /* out: SSI file or LSP file? */
  6413. )
  6414. {
  6415. char const *accept_encoding;
  6416. #if !defined(NO_FILES)
  6417. const char *uri = conn->request_info.local_uri;
  6418. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6419. const char *rewrite;
  6420. struct vec a, b;
  6421. ptrdiff_t match_len;
  6422. char gz_path[UTF8_PATH_MAX];
  6423. int truncated;
  6424. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6425. char *tmp_str;
  6426. size_t tmp_str_len, sep_pos;
  6427. int allow_substitute_script_subresources;
  6428. #endif
  6429. #else
  6430. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6431. #endif
  6432. /* Step 1: Set all initially unknown outputs to zero */
  6433. memset(filestat, 0, sizeof(*filestat));
  6434. *filename = 0;
  6435. *is_found = 0;
  6436. *is_script_resource = 0;
  6437. *is_template_text = 0;
  6438. /* Step 2: Classify the request method */
  6439. /* Step 2a: Check if the request attempts to modify the file system */
  6440. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6441. /* Step 2b: Check if the request uses WebDav method that requires special
  6442. * handling */
  6443. *is_webdav_request = is_civetweb_webdav_method(conn);
  6444. /* Step 3: Check if it is a websocket request, and modify the document
  6445. * root if required */
  6446. #if defined(USE_WEBSOCKET)
  6447. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6448. #if !defined(NO_FILES)
  6449. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6450. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6451. }
  6452. #endif /* !NO_FILES */
  6453. #else /* USE_WEBSOCKET */
  6454. *is_websocket_request = 0;
  6455. #endif /* USE_WEBSOCKET */
  6456. /* Step 4: Check if gzip encoded response is allowed */
  6457. conn->accept_gzip = 0;
  6458. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6459. if (strstr(accept_encoding, "gzip") != NULL) {
  6460. conn->accept_gzip = 1;
  6461. }
  6462. }
  6463. #if !defined(NO_FILES)
  6464. /* Step 5: If there is no root directory, don't look for files. */
  6465. /* Note that root == NULL is a regular use case here. This occurs,
  6466. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6467. * config is not required. */
  6468. if (root == NULL) {
  6469. /* all file related outputs have already been set to 0, just return
  6470. */
  6471. return;
  6472. }
  6473. /* Step 6: Determine the local file path from the root path and the
  6474. * request uri. */
  6475. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6476. * part of the path one byte on the right. */
  6477. truncated = 0;
  6478. mg_snprintf(
  6479. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6480. if (truncated) {
  6481. goto interpret_cleanup;
  6482. }
  6483. /* Step 7: URI rewriting */
  6484. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6485. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6486. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6487. mg_snprintf(conn,
  6488. &truncated,
  6489. filename,
  6490. filename_buf_len - 1,
  6491. "%.*s%s",
  6492. (int)b.len,
  6493. b.ptr,
  6494. uri + match_len);
  6495. break;
  6496. }
  6497. }
  6498. if (truncated) {
  6499. goto interpret_cleanup;
  6500. }
  6501. /* Step 8: Check if the file exists at the server */
  6502. /* Local file path and name, corresponding to requested URI
  6503. * is now stored in "filename" variable. */
  6504. if (mg_stat(conn, filename, filestat)) {
  6505. int uri_len = (int)strlen(uri);
  6506. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6507. /* 8.1: File exists. */
  6508. *is_found = 1;
  6509. /* 8.2: Check if it is a script type. */
  6510. if (extention_matches_script(conn, filename)) {
  6511. /* The request addresses a CGI resource, Lua script or
  6512. * server-side javascript.
  6513. * The URI corresponds to the script itself (like
  6514. * /path/script.cgi), and there is no additional resource
  6515. * path (like /path/script.cgi/something).
  6516. * Requests that modify (replace or delete) a resource, like
  6517. * PUT and DELETE requests, should replace/delete the script
  6518. * file.
  6519. * Requests that read or write from/to a resource, like GET and
  6520. * POST requests, should call the script and return the
  6521. * generated response. */
  6522. *is_script_resource = (!*is_put_or_delete_request);
  6523. }
  6524. /* 8.3: Check for SSI and LSP files */
  6525. if (extention_matches_template_text(conn, filename)) {
  6526. /* Same as above, but for *.lsp and *.shtml files. */
  6527. /* A "template text" is a file delivered directly to the client,
  6528. * but with some text tags replaced by dynamic content.
  6529. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6530. * (LP, LSP) file. */
  6531. *is_template_text = (!*is_put_or_delete_request);
  6532. }
  6533. /* 8.4: If the request target is a directory, there could be
  6534. * a substitute file (index.html, index.cgi, ...). */
  6535. /* But do not substitute a directory for a WebDav request */
  6536. if (filestat->is_directory && is_uri_end_slash
  6537. && (!*is_webdav_request)) {
  6538. /* Use a local copy here, since substitute_index_file will
  6539. * change the content of the file status */
  6540. struct mg_file_stat tmp_filestat;
  6541. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6542. if (substitute_index_file(
  6543. conn, filename, filename_buf_len, &tmp_filestat)) {
  6544. /* Substitute file found. Copy stat to the output, then
  6545. * check if the file is a script file */
  6546. *filestat = tmp_filestat;
  6547. if (extention_matches_script(conn, filename)) {
  6548. /* Substitute file is a script file */
  6549. *is_script_resource = 1;
  6550. } else if (extention_matches_template_text(conn, filename)) {
  6551. /* Substitute file is a LSP or SSI file */
  6552. *is_template_text = 1;
  6553. } else {
  6554. /* Substitute file is a regular file */
  6555. *is_script_resource = 0;
  6556. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6557. }
  6558. }
  6559. /* If there is no substitute file, the server could return
  6560. * a directory listing in a later step */
  6561. }
  6562. return;
  6563. }
  6564. /* Step 9: Check for zipped files: */
  6565. /* If we can't find the actual file, look for the file
  6566. * with the same name but a .gz extension. If we find it,
  6567. * use that and set the gzipped flag in the file struct
  6568. * to indicate that the response need to have the content-
  6569. * encoding: gzip header.
  6570. * We can only do this if the browser declares support. */
  6571. if (conn->accept_gzip) {
  6572. mg_snprintf(
  6573. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6574. if (truncated) {
  6575. goto interpret_cleanup;
  6576. }
  6577. if (mg_stat(conn, gz_path, filestat)) {
  6578. if (filestat) {
  6579. filestat->is_gzipped = 1;
  6580. *is_found = 1;
  6581. }
  6582. /* Currently gz files can not be scripts. */
  6583. return;
  6584. }
  6585. }
  6586. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6587. /* Step 10: Script resources may handle sub-resources */
  6588. /* Support PATH_INFO for CGI scripts. */
  6589. tmp_str_len = strlen(filename);
  6590. tmp_str =
  6591. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6592. if (!tmp_str) {
  6593. /* Out of memory */
  6594. goto interpret_cleanup;
  6595. }
  6596. memcpy(tmp_str, filename, tmp_str_len + 1);
  6597. /* Check config, if index scripts may have sub-resources */
  6598. allow_substitute_script_subresources =
  6599. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6600. "yes");
  6601. if (*is_webdav_request) {
  6602. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6603. * PROPFIND fo their subresources? */
  6604. /* allow_substitute_script_subresources = 0; */
  6605. }
  6606. sep_pos = tmp_str_len;
  6607. while (sep_pos > 0) {
  6608. sep_pos--;
  6609. if (tmp_str[sep_pos] == '/') {
  6610. int is_script = 0, does_exist = 0;
  6611. tmp_str[sep_pos] = 0;
  6612. if (tmp_str[0]) {
  6613. is_script = extention_matches_script(conn, tmp_str);
  6614. does_exist = mg_stat(conn, tmp_str, filestat);
  6615. }
  6616. if (does_exist && is_script) {
  6617. filename[sep_pos] = 0;
  6618. memmove(filename + sep_pos + 2,
  6619. filename + sep_pos + 1,
  6620. strlen(filename + sep_pos + 1) + 1);
  6621. conn->path_info = filename + sep_pos + 1;
  6622. filename[sep_pos + 1] = '/';
  6623. *is_script_resource = 1;
  6624. *is_found = 1;
  6625. break;
  6626. }
  6627. if (allow_substitute_script_subresources) {
  6628. if (substitute_index_file(
  6629. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6630. /* some intermediate directory has an index file */
  6631. if (extention_matches_script(conn, tmp_str)) {
  6632. size_t script_name_len = strlen(tmp_str);
  6633. /* subres_name read before this memory locatio will be
  6634. overwritten */
  6635. char *subres_name = filename + sep_pos;
  6636. size_t subres_name_len = strlen(subres_name);
  6637. DEBUG_TRACE("Substitute script %s serving path %s",
  6638. tmp_str,
  6639. filename);
  6640. /* this index file is a script */
  6641. if ((script_name_len + subres_name_len + 2)
  6642. >= filename_buf_len) {
  6643. mg_free(tmp_str);
  6644. goto interpret_cleanup;
  6645. }
  6646. conn->path_info =
  6647. filename + script_name_len + 1; /* new target */
  6648. memmove(conn->path_info, subres_name, subres_name_len);
  6649. conn->path_info[subres_name_len] = 0;
  6650. memcpy(filename, tmp_str, script_name_len + 1);
  6651. *is_script_resource = 1;
  6652. *is_found = 1;
  6653. break;
  6654. } else {
  6655. DEBUG_TRACE("Substitute file %s serving path %s",
  6656. tmp_str,
  6657. filename);
  6658. /* non-script files will not have sub-resources */
  6659. filename[sep_pos] = 0;
  6660. conn->path_info = 0;
  6661. *is_script_resource = 0;
  6662. *is_found = 0;
  6663. break;
  6664. }
  6665. }
  6666. }
  6667. tmp_str[sep_pos] = '/';
  6668. }
  6669. }
  6670. mg_free(tmp_str);
  6671. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6672. #endif /* !defined(NO_FILES) */
  6673. return;
  6674. #if !defined(NO_FILES)
  6675. /* Reset all outputs */
  6676. interpret_cleanup:
  6677. memset(filestat, 0, sizeof(*filestat));
  6678. *filename = 0;
  6679. *is_found = 0;
  6680. *is_script_resource = 0;
  6681. *is_websocket_request = 0;
  6682. *is_put_or_delete_request = 0;
  6683. #endif /* !defined(NO_FILES) */
  6684. }
  6685. /* Check whether full request is buffered. Return:
  6686. * -1 if request or response is malformed
  6687. * 0 if request or response is not yet fully buffered
  6688. * >0 actual request length, including last \r\n\r\n */
  6689. static int
  6690. get_http_header_len(const char *buf, int buflen)
  6691. {
  6692. int i;
  6693. for (i = 0; i < buflen; i++) {
  6694. /* Do an unsigned comparison in some conditions below */
  6695. const unsigned char c = (unsigned char)buf[i];
  6696. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6697. && !isprint(c)) {
  6698. /* abort scan as soon as one malformed character is found */
  6699. return -1;
  6700. }
  6701. if (i < buflen - 1) {
  6702. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6703. /* Two newline, no carriage return - not standard compliant,
  6704. * but it should be accepted */
  6705. return i + 2;
  6706. }
  6707. }
  6708. if (i < buflen - 3) {
  6709. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6710. && (buf[i + 3] == '\n')) {
  6711. /* Two \r\n - standard compliant */
  6712. return i + 4;
  6713. }
  6714. }
  6715. }
  6716. return 0;
  6717. }
  6718. #if !defined(NO_CACHING)
  6719. /* Convert month to the month number. Return -1 on error, or month number */
  6720. static int
  6721. get_month_index(const char *s)
  6722. {
  6723. size_t i;
  6724. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6725. if (!strcmp(s, month_names[i])) {
  6726. return (int)i;
  6727. }
  6728. }
  6729. return -1;
  6730. }
  6731. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6732. static time_t
  6733. parse_date_string(const char *datetime)
  6734. {
  6735. char month_str[32] = {0};
  6736. int second, minute, hour, day, month, year;
  6737. time_t result = (time_t)0;
  6738. struct tm tm;
  6739. if ((sscanf(datetime,
  6740. "%d/%3s/%d %d:%d:%d",
  6741. &day,
  6742. month_str,
  6743. &year,
  6744. &hour,
  6745. &minute,
  6746. &second)
  6747. == 6)
  6748. || (sscanf(datetime,
  6749. "%d %3s %d %d:%d:%d",
  6750. &day,
  6751. month_str,
  6752. &year,
  6753. &hour,
  6754. &minute,
  6755. &second)
  6756. == 6)
  6757. || (sscanf(datetime,
  6758. "%*3s, %d %3s %d %d:%d:%d",
  6759. &day,
  6760. month_str,
  6761. &year,
  6762. &hour,
  6763. &minute,
  6764. &second)
  6765. == 6)
  6766. || (sscanf(datetime,
  6767. "%d-%3s-%d %d:%d:%d",
  6768. &day,
  6769. month_str,
  6770. &year,
  6771. &hour,
  6772. &minute,
  6773. &second)
  6774. == 6)) {
  6775. month = get_month_index(month_str);
  6776. if ((month >= 0) && (year >= 1970)) {
  6777. memset(&tm, 0, sizeof(tm));
  6778. tm.tm_year = year - 1900;
  6779. tm.tm_mon = month;
  6780. tm.tm_mday = day;
  6781. tm.tm_hour = hour;
  6782. tm.tm_min = minute;
  6783. tm.tm_sec = second;
  6784. result = timegm(&tm);
  6785. }
  6786. }
  6787. return result;
  6788. }
  6789. #endif /* !NO_CACHING */
  6790. /* Pre-process URIs according to RFC + protect against directory disclosure
  6791. * attacks by removing '..', excessive '/' and '\' characters */
  6792. static void
  6793. remove_dot_segments(char *inout)
  6794. {
  6795. /* Windows backend protection
  6796. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6797. * in URI by slash */
  6798. char *out_end = inout;
  6799. char *in = inout;
  6800. if (!in) {
  6801. /* Param error. */
  6802. return;
  6803. }
  6804. while (*in) {
  6805. if (*in == '\\') {
  6806. *in = '/';
  6807. }
  6808. in++;
  6809. }
  6810. /* Algorithm "remove_dot_segments" from
  6811. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6812. /* Step 1:
  6813. * The input buffer is initialized.
  6814. * The output buffer is initialized to the empty string.
  6815. */
  6816. in = inout;
  6817. /* Step 2:
  6818. * While the input buffer is not empty, loop as follows:
  6819. */
  6820. /* Less than out_end of the inout buffer is used as output, so keep
  6821. * condition: out_end <= in */
  6822. while (*in) {
  6823. /* Step 2a:
  6824. * If the input buffer begins with a prefix of "../" or "./",
  6825. * then remove that prefix from the input buffer;
  6826. */
  6827. if (!strncmp(in, "../", 3)) {
  6828. in += 3;
  6829. } else if (!strncmp(in, "./", 2)) {
  6830. in += 2;
  6831. }
  6832. /* otherwise */
  6833. /* Step 2b:
  6834. * if the input buffer begins with a prefix of "/./" or "/.",
  6835. * where "." is a complete path segment, then replace that
  6836. * prefix with "/" in the input buffer;
  6837. */
  6838. else if (!strncmp(in, "/./", 3)) {
  6839. in += 2;
  6840. } else if (!strcmp(in, "/.")) {
  6841. in[1] = 0;
  6842. }
  6843. /* otherwise */
  6844. /* Step 2c:
  6845. * if the input buffer begins with a prefix of "/../" or "/..",
  6846. * where ".." is a complete path segment, then replace that
  6847. * prefix with "/" in the input buffer and remove the last
  6848. * segment and its preceding "/" (if any) from the output
  6849. * buffer;
  6850. */
  6851. else if (!strncmp(in, "/../", 4)) {
  6852. in += 3;
  6853. if (inout != out_end) {
  6854. /* remove last segment */
  6855. do {
  6856. out_end--;
  6857. } while ((inout != out_end) && (*out_end != '/'));
  6858. }
  6859. } else if (!strcmp(in, "/..")) {
  6860. in[1] = 0;
  6861. if (inout != out_end) {
  6862. /* remove last segment */
  6863. do {
  6864. out_end--;
  6865. } while ((inout != out_end) && (*out_end != '/'));
  6866. }
  6867. }
  6868. /* otherwise */
  6869. /* Step 2d:
  6870. * if the input buffer consists only of "." or "..", then remove
  6871. * that from the input buffer;
  6872. */
  6873. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6874. *in = 0;
  6875. }
  6876. /* otherwise */
  6877. /* Step 2e:
  6878. * move the first path segment in the input buffer to the end of
  6879. * the output buffer, including the initial "/" character (if
  6880. * any) and any subsequent characters up to, but not including,
  6881. * the next "/" character or the end of the input buffer.
  6882. */
  6883. else {
  6884. do {
  6885. *out_end = *in;
  6886. out_end++;
  6887. in++;
  6888. } while ((*in != 0) && (*in != '/'));
  6889. }
  6890. }
  6891. /* Step 3:
  6892. * Finally, the output buffer is returned as the result of
  6893. * remove_dot_segments.
  6894. */
  6895. /* Terminate output */
  6896. *out_end = 0;
  6897. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6898. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6899. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6900. * or "//" anymore.
  6901. */
  6902. out_end = in = inout;
  6903. while (*in) {
  6904. if (*in == '.') {
  6905. /* remove . at the end or preceding of / */
  6906. char *in_ahead = in;
  6907. do {
  6908. in_ahead++;
  6909. } while (*in_ahead == '.');
  6910. if (*in_ahead == '/') {
  6911. in = in_ahead;
  6912. if ((out_end != inout) && (out_end[-1] == '/')) {
  6913. /* remove generated // */
  6914. out_end--;
  6915. }
  6916. } else if (*in_ahead == 0) {
  6917. in = in_ahead;
  6918. } else {
  6919. do {
  6920. *out_end++ = '.';
  6921. in++;
  6922. } while (in != in_ahead);
  6923. }
  6924. } else if (*in == '/') {
  6925. /* replace // by / */
  6926. *out_end++ = '/';
  6927. do {
  6928. in++;
  6929. } while (*in == '/');
  6930. } else {
  6931. *out_end++ = *in;
  6932. in++;
  6933. }
  6934. }
  6935. *out_end = 0;
  6936. }
  6937. static const struct {
  6938. const char *extension;
  6939. size_t ext_len;
  6940. const char *mime_type;
  6941. } builtin_mime_types[] = {
  6942. /* IANA registered MIME types
  6943. * (http://www.iana.org/assignments/media-types)
  6944. * application types */
  6945. {".bin", 4, "application/octet-stream"},
  6946. {".deb", 4, "application/octet-stream"},
  6947. {".dmg", 4, "application/octet-stream"},
  6948. {".dll", 4, "application/octet-stream"},
  6949. {".doc", 4, "application/msword"},
  6950. {".eps", 4, "application/postscript"},
  6951. {".exe", 4, "application/octet-stream"},
  6952. {".iso", 4, "application/octet-stream"},
  6953. {".js", 3, "application/javascript"},
  6954. {".json", 5, "application/json"},
  6955. {".msi", 4, "application/octet-stream"},
  6956. {".pdf", 4, "application/pdf"},
  6957. {".ps", 3, "application/postscript"},
  6958. {".rtf", 4, "application/rtf"},
  6959. {".xhtml", 6, "application/xhtml+xml"},
  6960. {".xsl", 4, "application/xml"},
  6961. {".xslt", 5, "application/xml"},
  6962. /* fonts */
  6963. {".ttf", 4, "application/font-sfnt"},
  6964. {".cff", 4, "application/font-sfnt"},
  6965. {".otf", 4, "application/font-sfnt"},
  6966. {".aat", 4, "application/font-sfnt"},
  6967. {".sil", 4, "application/font-sfnt"},
  6968. {".pfr", 4, "application/font-tdpfr"},
  6969. {".woff", 5, "application/font-woff"},
  6970. {".woff2", 6, "application/font-woff2"},
  6971. /* audio */
  6972. {".mp3", 4, "audio/mpeg"},
  6973. {".oga", 4, "audio/ogg"},
  6974. {".ogg", 4, "audio/ogg"},
  6975. /* image */
  6976. {".gif", 4, "image/gif"},
  6977. {".ief", 4, "image/ief"},
  6978. {".jpeg", 5, "image/jpeg"},
  6979. {".jpg", 4, "image/jpeg"},
  6980. {".jpm", 4, "image/jpm"},
  6981. {".jpx", 4, "image/jpx"},
  6982. {".png", 4, "image/png"},
  6983. {".svg", 4, "image/svg+xml"},
  6984. {".tif", 4, "image/tiff"},
  6985. {".tiff", 5, "image/tiff"},
  6986. /* model */
  6987. {".wrl", 4, "model/vrml"},
  6988. /* text */
  6989. {".css", 4, "text/css"},
  6990. {".csv", 4, "text/csv"},
  6991. {".htm", 4, "text/html"},
  6992. {".html", 5, "text/html"},
  6993. {".sgm", 4, "text/sgml"},
  6994. {".shtm", 5, "text/html"},
  6995. {".shtml", 6, "text/html"},
  6996. {".txt", 4, "text/plain"},
  6997. {".xml", 4, "text/xml"},
  6998. /* video */
  6999. {".mov", 4, "video/quicktime"},
  7000. {".mp4", 4, "video/mp4"},
  7001. {".mpeg", 5, "video/mpeg"},
  7002. {".mpg", 4, "video/mpeg"},
  7003. {".ogv", 4, "video/ogg"},
  7004. {".qt", 3, "video/quicktime"},
  7005. /* not registered types
  7006. * (http://reference.sitepoint.com/html/mime-types-full,
  7007. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7008. {".arj", 4, "application/x-arj-compressed"},
  7009. {".gz", 3, "application/x-gunzip"},
  7010. {".rar", 4, "application/x-arj-compressed"},
  7011. {".swf", 4, "application/x-shockwave-flash"},
  7012. {".tar", 4, "application/x-tar"},
  7013. {".tgz", 4, "application/x-tar-gz"},
  7014. {".torrent", 8, "application/x-bittorrent"},
  7015. {".ppt", 4, "application/x-mspowerpoint"},
  7016. {".xls", 4, "application/x-msexcel"},
  7017. {".zip", 4, "application/x-zip-compressed"},
  7018. {".aac",
  7019. 4,
  7020. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7021. {".flac", 5, "audio/flac"},
  7022. {".aif", 4, "audio/x-aif"},
  7023. {".m3u", 4, "audio/x-mpegurl"},
  7024. {".mid", 4, "audio/x-midi"},
  7025. {".ra", 3, "audio/x-pn-realaudio"},
  7026. {".ram", 4, "audio/x-pn-realaudio"},
  7027. {".wav", 4, "audio/x-wav"},
  7028. {".bmp", 4, "image/bmp"},
  7029. {".ico", 4, "image/x-icon"},
  7030. {".pct", 4, "image/x-pct"},
  7031. {".pict", 5, "image/pict"},
  7032. {".rgb", 4, "image/x-rgb"},
  7033. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7034. {".asf", 4, "video/x-ms-asf"},
  7035. {".avi", 4, "video/x-msvideo"},
  7036. {".m4v", 4, "video/x-m4v"},
  7037. {NULL, 0, NULL}};
  7038. CIVETWEB_API const char *
  7039. mg_get_builtin_mime_type(const char *path)
  7040. {
  7041. const char *ext;
  7042. size_t i, path_len;
  7043. path_len = strlen(path);
  7044. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7045. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7046. if ((path_len > builtin_mime_types[i].ext_len)
  7047. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7048. return builtin_mime_types[i].mime_type;
  7049. }
  7050. }
  7051. return "text/plain";
  7052. }
  7053. /* Look at the "path" extension and figure what mime type it has.
  7054. * Store mime type in the vector. */
  7055. static void
  7056. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7057. {
  7058. struct vec ext_vec, mime_vec;
  7059. const char *list, *ext;
  7060. size_t path_len;
  7061. path_len = strlen(path);
  7062. if ((conn == NULL) || (vec == NULL)) {
  7063. if (vec != NULL) {
  7064. memset(vec, '\0', sizeof(struct vec));
  7065. }
  7066. return;
  7067. }
  7068. /* Scan user-defined mime types first, in case user wants to
  7069. * override default mime types. */
  7070. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7071. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7072. /* ext now points to the path suffix */
  7073. ext = path + path_len - ext_vec.len;
  7074. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7075. *vec = mime_vec;
  7076. return;
  7077. }
  7078. }
  7079. vec->ptr = mg_get_builtin_mime_type(path);
  7080. vec->len = strlen(vec->ptr);
  7081. }
  7082. /* Stringify binary data. Output buffer must be twice as big as input,
  7083. * because each byte takes 2 bytes in string representation */
  7084. static void
  7085. bin2str(char *to, const unsigned char *p, size_t len)
  7086. {
  7087. static const char *hex = "0123456789abcdef";
  7088. for (; len--; p++) {
  7089. *to++ = hex[p[0] >> 4];
  7090. *to++ = hex[p[0] & 0x0f];
  7091. }
  7092. *to = '\0';
  7093. }
  7094. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7095. */
  7096. CIVETWEB_API char *
  7097. mg_md5(char buf[33], ...)
  7098. {
  7099. md5_byte_t hash[16];
  7100. const char *p;
  7101. va_list ap;
  7102. md5_state_t ctx;
  7103. md5_init(&ctx);
  7104. va_start(ap, buf);
  7105. while ((p = va_arg(ap, const char *)) != NULL) {
  7106. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7107. }
  7108. va_end(ap);
  7109. md5_finish(&ctx, hash);
  7110. bin2str(buf, hash, sizeof(hash));
  7111. return buf;
  7112. }
  7113. /* Check the user's password, return 1 if OK */
  7114. static int
  7115. check_password_digest(const char *method,
  7116. const char *ha1,
  7117. const char *uri,
  7118. const char *nonce,
  7119. const char *nc,
  7120. const char *cnonce,
  7121. const char *qop,
  7122. const char *response)
  7123. {
  7124. char ha2[32 + 1], expected_response[32 + 1];
  7125. /* Some of the parameters may be NULL */
  7126. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7127. || (qop == NULL) || (response == NULL)) {
  7128. return 0;
  7129. }
  7130. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7131. if (strlen(response) != 32) {
  7132. return 0;
  7133. }
  7134. mg_md5(ha2, method, ":", uri, NULL);
  7135. mg_md5(expected_response,
  7136. ha1,
  7137. ":",
  7138. nonce,
  7139. ":",
  7140. nc,
  7141. ":",
  7142. cnonce,
  7143. ":",
  7144. qop,
  7145. ":",
  7146. ha2,
  7147. NULL);
  7148. return mg_strcasecmp(response, expected_response) == 0;
  7149. }
  7150. #if !defined(NO_FILESYSTEMS)
  7151. /* Use the global passwords file, if specified by auth_gpass option,
  7152. * or search for .htpasswd in the requested directory. */
  7153. static void
  7154. open_auth_file(struct mg_connection *conn,
  7155. const char *path,
  7156. struct mg_file *filep)
  7157. {
  7158. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7159. char name[UTF8_PATH_MAX];
  7160. const char *p, *e,
  7161. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7162. int truncated;
  7163. if (gpass != NULL) {
  7164. /* Use global passwords file */
  7165. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7166. #if defined(DEBUG)
  7167. /* Use mg_cry_internal here, since gpass has been
  7168. * configured. */
  7169. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7170. #endif
  7171. }
  7172. /* Important: using local struct mg_file to test path for
  7173. * is_directory flag. If filep is used, mg_stat() makes it
  7174. * appear as if auth file was opened.
  7175. * TODO(mid): Check if this is still required after rewriting
  7176. * mg_stat */
  7177. } else if (mg_stat(conn, path, &filep->stat)
  7178. && filep->stat.is_directory) {
  7179. mg_snprintf(conn,
  7180. &truncated,
  7181. name,
  7182. sizeof(name),
  7183. "%s/%s",
  7184. path,
  7185. PASSWORDS_FILE_NAME);
  7186. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7187. #if defined(DEBUG)
  7188. /* Don't use mg_cry_internal here, but only a trace, since
  7189. * this is a typical case. It will occur for every directory
  7190. * without a password file. */
  7191. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7192. #endif
  7193. }
  7194. } else {
  7195. /* Try to find .htpasswd in requested directory. */
  7196. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7197. if (e[0] == '/') {
  7198. break;
  7199. }
  7200. }
  7201. mg_snprintf(conn,
  7202. &truncated,
  7203. name,
  7204. sizeof(name),
  7205. "%.*s/%s",
  7206. (int)(e - p),
  7207. p,
  7208. PASSWORDS_FILE_NAME);
  7209. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7210. #if defined(DEBUG)
  7211. /* Don't use mg_cry_internal here, but only a trace, since
  7212. * this is a typical case. It will occur for every directory
  7213. * without a password file. */
  7214. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7215. #endif
  7216. }
  7217. }
  7218. }
  7219. }
  7220. #endif /* NO_FILESYSTEMS */
  7221. /* Parsed Authorization header */
  7222. struct ah {
  7223. char *user;
  7224. int type; /* 1 = basic, 2 = digest */
  7225. char *plain_password; /* Basic only */
  7226. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7227. };
  7228. /* Return 1 on success. Always initializes the ah structure. */
  7229. static int
  7230. parse_auth_header(struct mg_connection *conn,
  7231. char *buf,
  7232. size_t buf_size,
  7233. struct ah *ah)
  7234. {
  7235. char *name, *value, *s;
  7236. const char *auth_header;
  7237. uint64_t nonce;
  7238. if (!ah || !conn) {
  7239. return 0;
  7240. }
  7241. (void)memset(ah, 0, sizeof(*ah));
  7242. auth_header = mg_get_header(conn, "Authorization");
  7243. if (auth_header == NULL) {
  7244. /* No Authorization header at all */
  7245. return 0;
  7246. }
  7247. if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
  7248. /* Basic Auth (we never asked for this, but some client may send it) */
  7249. char *split;
  7250. const char *userpw_b64 = auth_header + 6;
  7251. size_t userpw_b64_len = strlen(userpw_b64);
  7252. size_t buf_len_r = buf_size;
  7253. if (mg_base64_decode(userpw_b64, userpw_b64_len, buf, &buf_len_r)
  7254. != -1) {
  7255. return 0; /* decode error */
  7256. }
  7257. split = strchr(buf, ':');
  7258. if (!split) {
  7259. return 0; /* Format error */
  7260. }
  7261. /* Separate string at ':' */
  7262. *split = 0;
  7263. /* User name is before ':', Password is after ':' */
  7264. ah->user = buf;
  7265. ah->type = 1;
  7266. ah->plain_password = split + 1;
  7267. return 1;
  7268. } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
  7269. /* Digest Auth ... implemented below */
  7270. ah->type = 2;
  7271. } else {
  7272. /* Unknown or invalid Auth method */
  7273. return 0;
  7274. }
  7275. /* Make modifiable copy of the auth header */
  7276. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7277. s = buf;
  7278. /* Parse authorization header */
  7279. for (;;) {
  7280. /* Gobble initial spaces */
  7281. while (isspace((unsigned char)*s)) {
  7282. s++;
  7283. }
  7284. name = skip_quoted(&s, "=", " ", 0);
  7285. /* Value is either quote-delimited, or ends at first comma or space.
  7286. */
  7287. if (s[0] == '\"') {
  7288. s++;
  7289. value = skip_quoted(&s, "\"", " ", '\\');
  7290. if (s[0] == ',') {
  7291. s++;
  7292. }
  7293. } else {
  7294. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7295. * uses spaces */
  7296. }
  7297. if (*name == '\0') {
  7298. break;
  7299. }
  7300. if (!strcmp(name, "username")) {
  7301. ah->user = value;
  7302. } else if (!strcmp(name, "cnonce")) {
  7303. ah->cnonce = value;
  7304. } else if (!strcmp(name, "response")) {
  7305. ah->response = value;
  7306. } else if (!strcmp(name, "uri")) {
  7307. ah->uri = value;
  7308. } else if (!strcmp(name, "qop")) {
  7309. ah->qop = value;
  7310. } else if (!strcmp(name, "nc")) {
  7311. ah->nc = value;
  7312. } else if (!strcmp(name, "nonce")) {
  7313. ah->nonce = value;
  7314. }
  7315. }
  7316. #if !defined(NO_NONCE_CHECK)
  7317. /* Read the nonce from the response. */
  7318. if (ah->nonce == NULL) {
  7319. return 0;
  7320. }
  7321. s = NULL;
  7322. nonce = strtoull(ah->nonce, &s, 10);
  7323. if ((s == NULL) || (*s != 0)) {
  7324. return 0;
  7325. }
  7326. /* Convert the nonce from the client to a number. */
  7327. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7328. /* The converted number corresponds to the time the nounce has been
  7329. * created. This should not be earlier than the server start. */
  7330. /* Server side nonce check is valuable in all situations but one:
  7331. * if the server restarts frequently, but the client should not see
  7332. * that, so the server should accept nonces from previous starts. */
  7333. /* However, the reasonable default is to not accept a nonce from a
  7334. * previous start, so if anyone changed the access rights between
  7335. * two restarts, a new login is required. */
  7336. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7337. /* nonce is from a previous start of the server and no longer valid
  7338. * (replay attack?) */
  7339. return 0;
  7340. }
  7341. /* Check if the nonce is too high, so it has not (yet) been used by the
  7342. * server. */
  7343. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7344. + conn->dom_ctx->nonce_count)) {
  7345. return 0;
  7346. }
  7347. #else
  7348. (void)nonce;
  7349. #endif
  7350. return (ah->user != NULL);
  7351. }
  7352. static const char *
  7353. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7354. {
  7355. if (!filep) {
  7356. return NULL;
  7357. }
  7358. if (filep->access.fp != NULL) {
  7359. return fgets(buf, (int)size, filep->access.fp);
  7360. } else {
  7361. return NULL;
  7362. }
  7363. }
  7364. /* Define the initial recursion depth for procesesing htpasswd files that
  7365. * include other htpasswd
  7366. * (or even the same) files. It is not difficult to provide a file or files
  7367. * s.t. they force civetweb
  7368. * to infinitely recurse and then crash.
  7369. */
  7370. #define INITIAL_DEPTH 9
  7371. #if INITIAL_DEPTH <= 0
  7372. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7373. #endif
  7374. #if !defined(NO_FILESYSTEMS)
  7375. struct read_auth_file_struct {
  7376. struct mg_connection *conn;
  7377. struct ah ah;
  7378. const char *domain;
  7379. char buf[256 + 256 + 40];
  7380. const char *f_user;
  7381. const char *f_domain;
  7382. const char *f_ha1;
  7383. };
  7384. static int
  7385. read_auth_file(struct mg_file *filep,
  7386. struct read_auth_file_struct *workdata,
  7387. int depth)
  7388. {
  7389. int is_authorized = 0;
  7390. struct mg_file fp;
  7391. size_t l;
  7392. if (!filep || !workdata || (0 == depth)) {
  7393. return 0;
  7394. }
  7395. /* Loop over passwords file */
  7396. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7397. l = strlen(workdata->buf);
  7398. while (l > 0) {
  7399. if (isspace((unsigned char)workdata->buf[l - 1])
  7400. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7401. l--;
  7402. workdata->buf[l] = 0;
  7403. } else
  7404. break;
  7405. }
  7406. if (l < 1) {
  7407. continue;
  7408. }
  7409. workdata->f_user = workdata->buf;
  7410. if (workdata->f_user[0] == ':') {
  7411. /* user names may not contain a ':' and may not be empty,
  7412. * so lines starting with ':' may be used for a special purpose
  7413. */
  7414. if (workdata->f_user[1] == '#') {
  7415. /* :# is a comment */
  7416. continue;
  7417. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7418. if (mg_fopen(workdata->conn,
  7419. workdata->f_user + 9,
  7420. MG_FOPEN_MODE_READ,
  7421. &fp)) {
  7422. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7423. (void)mg_fclose(
  7424. &fp.access); /* ignore error on read only file */
  7425. /* No need to continue processing files once we have a
  7426. * match, since nothing will reset it back
  7427. * to 0.
  7428. */
  7429. if (is_authorized) {
  7430. return is_authorized;
  7431. }
  7432. } else {
  7433. mg_cry_internal(workdata->conn,
  7434. "%s: cannot open authorization file: %s",
  7435. __func__,
  7436. workdata->buf);
  7437. }
  7438. continue;
  7439. }
  7440. /* everything is invalid for the moment (might change in the
  7441. * future) */
  7442. mg_cry_internal(workdata->conn,
  7443. "%s: syntax error in authorization file: %s",
  7444. __func__,
  7445. workdata->buf);
  7446. continue;
  7447. }
  7448. workdata->f_domain = strchr(workdata->f_user, ':');
  7449. if (workdata->f_domain == NULL) {
  7450. mg_cry_internal(workdata->conn,
  7451. "%s: syntax error in authorization file: %s",
  7452. __func__,
  7453. workdata->buf);
  7454. continue;
  7455. }
  7456. *(char *)(workdata->f_domain) = 0;
  7457. (workdata->f_domain)++;
  7458. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7459. if (workdata->f_ha1 == NULL) {
  7460. mg_cry_internal(workdata->conn,
  7461. "%s: syntax error in authorization file: %s",
  7462. __func__,
  7463. workdata->buf);
  7464. continue;
  7465. }
  7466. *(char *)(workdata->f_ha1) = 0;
  7467. (workdata->f_ha1)++;
  7468. if (!strcmp(workdata->ah.user, workdata->f_user)
  7469. && !strcmp(workdata->domain, workdata->f_domain)) {
  7470. switch (workdata->ah.type) {
  7471. case 1: /* Basic */
  7472. {
  7473. size_t mlen = strlen(workdata->f_user)
  7474. + strlen(workdata->domain)
  7475. + strlen(workdata->ah.plain_password) + 3;
  7476. char md5[33];
  7477. mg_md5(md5,
  7478. workdata->f_user,
  7479. ":",
  7480. workdata->domain,
  7481. ":",
  7482. workdata->ah.plain_password,
  7483. NULL);
  7484. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7485. }
  7486. case 2: /* Digest */
  7487. return check_password_digest(
  7488. workdata->conn->request_info.request_method,
  7489. workdata->f_ha1,
  7490. workdata->ah.uri,
  7491. workdata->ah.nonce,
  7492. workdata->ah.nc,
  7493. workdata->ah.cnonce,
  7494. workdata->ah.qop,
  7495. workdata->ah.response);
  7496. default: /* None/Other/Unknown */
  7497. return 0;
  7498. }
  7499. }
  7500. }
  7501. return is_authorized;
  7502. }
  7503. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7504. static int
  7505. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7506. {
  7507. struct read_auth_file_struct workdata;
  7508. char buf[MG_BUF_LEN];
  7509. if (!conn || !conn->dom_ctx) {
  7510. return 0;
  7511. }
  7512. memset(&workdata, 0, sizeof(workdata));
  7513. workdata.conn = conn;
  7514. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7515. return 0;
  7516. }
  7517. /* CGI needs it as REMOTE_USER */
  7518. conn->request_info.remote_user =
  7519. mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
  7520. if (realm) {
  7521. workdata.domain = realm;
  7522. } else {
  7523. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7524. }
  7525. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7526. }
  7527. /* Public function to check http digest authentication header */
  7528. CIVETWEB_API int
  7529. mg_check_digest_access_authentication(struct mg_connection *conn,
  7530. const char *realm,
  7531. const char *filename)
  7532. {
  7533. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7534. int auth;
  7535. if (!conn || !filename) {
  7536. return -1;
  7537. }
  7538. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7539. return -2;
  7540. }
  7541. auth = authorize(conn, &file, realm);
  7542. mg_fclose(&file.access);
  7543. return auth;
  7544. }
  7545. #endif /* NO_FILESYSTEMS */
  7546. /* Return 1 if request is authorised, 0 otherwise. */
  7547. static int
  7548. check_authorization(struct mg_connection *conn, const char *path)
  7549. {
  7550. #if !defined(NO_FILESYSTEMS)
  7551. char fname[UTF8_PATH_MAX];
  7552. struct vec uri_vec, filename_vec;
  7553. const char *list;
  7554. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7555. int authorized = 1, truncated;
  7556. if (!conn || !conn->dom_ctx) {
  7557. return 0;
  7558. }
  7559. list = conn->dom_ctx->config[PROTECT_URI];
  7560. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7561. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7562. mg_snprintf(conn,
  7563. &truncated,
  7564. fname,
  7565. sizeof(fname),
  7566. "%.*s",
  7567. (int)filename_vec.len,
  7568. filename_vec.ptr);
  7569. if (truncated
  7570. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7571. mg_cry_internal(conn,
  7572. "%s: cannot open %s: %s",
  7573. __func__,
  7574. fname,
  7575. strerror(errno));
  7576. }
  7577. break;
  7578. }
  7579. }
  7580. if (!is_file_opened(&file.access)) {
  7581. open_auth_file(conn, path, &file);
  7582. }
  7583. if (is_file_opened(&file.access)) {
  7584. authorized = authorize(conn, &file, NULL);
  7585. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7586. }
  7587. return authorized;
  7588. #else
  7589. (void)conn;
  7590. (void)path;
  7591. return 1;
  7592. #endif /* NO_FILESYSTEMS */
  7593. }
  7594. /* Internal function. Assumes conn is valid */
  7595. static void
  7596. send_authorization_request(struct mg_connection *conn, const char *realm)
  7597. {
  7598. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7599. int trunc = 0;
  7600. char buf[128];
  7601. if (!realm) {
  7602. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7603. }
  7604. mg_lock_context(conn->phys_ctx);
  7605. nonce += conn->dom_ctx->nonce_count;
  7606. ++conn->dom_ctx->nonce_count;
  7607. mg_unlock_context(conn->phys_ctx);
  7608. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7609. conn->must_close = 1;
  7610. /* Create 401 response */
  7611. mg_response_header_start(conn, 401);
  7612. send_no_cache_header(conn);
  7613. send_additional_header(conn);
  7614. mg_response_header_add(conn, "Content-Length", "0", -1);
  7615. /* Content for "WWW-Authenticate" header */
  7616. mg_snprintf(conn,
  7617. &trunc,
  7618. buf,
  7619. sizeof(buf),
  7620. "Digest qop=\"auth\", realm=\"%s\", "
  7621. "nonce=\"%" UINT64_FMT "\"",
  7622. realm,
  7623. nonce);
  7624. if (!trunc) {
  7625. /* !trunc should always be true */
  7626. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7627. }
  7628. /* Send all headers */
  7629. mg_response_header_send(conn);
  7630. }
  7631. /* Interface function. Parameters are provided by the user, so do
  7632. * at least some basic checks.
  7633. */
  7634. CIVETWEB_API int
  7635. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7636. const char *realm)
  7637. {
  7638. if (conn && conn->dom_ctx) {
  7639. send_authorization_request(conn, realm);
  7640. return 0;
  7641. }
  7642. return -1;
  7643. }
  7644. #if !defined(NO_FILES)
  7645. static int
  7646. is_authorized_for_put(struct mg_connection *conn)
  7647. {
  7648. int ret = 0;
  7649. if (conn) {
  7650. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7651. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7652. if (passfile != NULL
  7653. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7654. ret = authorize(conn, &file, NULL);
  7655. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7656. }
  7657. }
  7658. DEBUG_TRACE("file write autorization: %i", ret);
  7659. return ret;
  7660. }
  7661. #endif
  7662. CIVETWEB_API int
  7663. mg_modify_passwords_file_ha1(const char *fname,
  7664. const char *domain,
  7665. const char *user,
  7666. const char *ha1)
  7667. {
  7668. int found = 0, i, result = 1;
  7669. char line[512], u[256], d[256], h[256];
  7670. struct stat st = {0};
  7671. FILE *fp = NULL;
  7672. char *temp_file = NULL;
  7673. int temp_file_offs = 0;
  7674. /* Regard empty password as no password - remove user record. */
  7675. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7676. ha1 = NULL;
  7677. }
  7678. /* Other arguments must not be empty */
  7679. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7680. return 0;
  7681. }
  7682. /* Using the given file format, user name and domain must not contain
  7683. * the ':' character */
  7684. if (strchr(user, ':') != NULL) {
  7685. return 0;
  7686. }
  7687. if (strchr(domain, ':') != NULL) {
  7688. return 0;
  7689. }
  7690. /* Do not allow control characters like newline in user name and domain.
  7691. * Do not allow excessively long names either. */
  7692. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7693. if (iscntrl((unsigned char)user[i])) {
  7694. return 0;
  7695. }
  7696. }
  7697. if (user[i]) {
  7698. return 0; /* user name too long */
  7699. }
  7700. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7701. if (iscntrl((unsigned char)domain[i])) {
  7702. return 0;
  7703. }
  7704. }
  7705. if (domain[i]) {
  7706. return 0; /* domain name too long */
  7707. }
  7708. /* The maximum length of the path to the password file is limited */
  7709. if (strlen(fname) >= UTF8_PATH_MAX) {
  7710. return 0;
  7711. }
  7712. /* Check if the file exists, and get file size */
  7713. if (0 == stat(fname, &st)) {
  7714. int temp_buf_len = (int)st.st_size + 1024;
  7715. /* Allocate memory (instead of using a temporary file) */
  7716. temp_file = (char *)mg_calloc(temp_buf_len, 1);
  7717. if (!temp_file) {
  7718. /* Out of memory */
  7719. return 0;
  7720. }
  7721. /* File exists. Read it into a memory buffer. */
  7722. fp = fopen(fname, "r");
  7723. if (fp == NULL) {
  7724. /* Cannot read file. No permission? */
  7725. mg_free(temp_file);
  7726. return 0;
  7727. }
  7728. /* Read content and store in memory */
  7729. while ((fgets(line, sizeof(line), fp) != NULL)
  7730. && ((temp_file_offs + 600) < temp_buf_len)) {
  7731. /* file format is "user:domain:hash\n" */
  7732. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7733. continue;
  7734. }
  7735. u[255] = 0;
  7736. d[255] = 0;
  7737. h[255] = 0;
  7738. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7739. /* Found the user: change the password hash or drop the user
  7740. */
  7741. if ((ha1 != NULL) && (!found)) {
  7742. i = sprintf(temp_file + temp_file_offs,
  7743. "%s:%s:%s\n",
  7744. user,
  7745. domain,
  7746. ha1);
  7747. if (i < 1) {
  7748. fclose(fp);
  7749. mg_free(temp_file);
  7750. return 0;
  7751. }
  7752. temp_file_offs += i;
  7753. }
  7754. found = 1;
  7755. } else {
  7756. /* Copy existing user, including password hash */
  7757. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7758. if (i < 1) {
  7759. fclose(fp);
  7760. mg_free(temp_file);
  7761. return 0;
  7762. }
  7763. temp_file_offs += i;
  7764. }
  7765. }
  7766. fclose(fp);
  7767. }
  7768. /* Create new file */
  7769. fp = fopen(fname, "w");
  7770. if (!fp) {
  7771. mg_free(temp_file);
  7772. return 0;
  7773. }
  7774. #if !defined(_WIN32)
  7775. /* On Linux & co., restrict file read/write permissions to the owner */
  7776. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7777. result = 0;
  7778. }
  7779. #endif
  7780. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7781. /* Store buffered content of old file */
  7782. if (fwrite(temp_file, 1, temp_file_offs, fp)
  7783. != (size_t)temp_file_offs) {
  7784. result = 0;
  7785. }
  7786. }
  7787. /* If new user, just add it */
  7788. if ((ha1 != NULL) && (!found)) {
  7789. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7790. result = 0;
  7791. }
  7792. }
  7793. /* All data written */
  7794. if (fclose(fp) != 0) {
  7795. result = 0;
  7796. }
  7797. mg_free(temp_file);
  7798. return result;
  7799. }
  7800. CIVETWEB_API int
  7801. mg_modify_passwords_file(const char *fname,
  7802. const char *domain,
  7803. const char *user,
  7804. const char *pass)
  7805. {
  7806. char ha1buf[33];
  7807. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7808. return 0;
  7809. }
  7810. if ((pass == NULL) || (pass[0] == 0)) {
  7811. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7812. }
  7813. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7814. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7815. }
  7816. static int
  7817. is_valid_port(unsigned long port)
  7818. {
  7819. return (port <= 0xffff);
  7820. }
  7821. static int
  7822. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7823. {
  7824. struct addrinfo hints, *res, *ressave;
  7825. int func_ret = 0;
  7826. int gai_ret;
  7827. memset(&hints, 0, sizeof(struct addrinfo));
  7828. hints.ai_family = af;
  7829. if (!resolve_src) {
  7830. hints.ai_flags = AI_NUMERICHOST;
  7831. }
  7832. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7833. if (gai_ret != 0) {
  7834. /* gai_strerror could be used to convert gai_ret to a string */
  7835. /* POSIX return values: see
  7836. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7837. */
  7838. /* Windows return values: see
  7839. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7840. */
  7841. return 0;
  7842. }
  7843. ressave = res;
  7844. while (res) {
  7845. if ((dstlen >= (size_t)res->ai_addrlen)
  7846. && (res->ai_addr->sa_family == af)) {
  7847. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7848. func_ret = 1;
  7849. }
  7850. res = res->ai_next;
  7851. }
  7852. freeaddrinfo(ressave);
  7853. return func_ret;
  7854. }
  7855. static int
  7856. connect_socket(
  7857. struct mg_context *ctx /* may be NULL */,
  7858. const char *host,
  7859. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7860. int use_ssl, /* 0 or 1 */
  7861. struct mg_error_data *error,
  7862. SOCKET *sock /* output: socket, must not be NULL */,
  7863. union usa *sa /* output: socket address, must not be NULL */
  7864. )
  7865. {
  7866. int ip_ver = 0;
  7867. int conn_ret = -1;
  7868. int sockerr = 0;
  7869. *sock = INVALID_SOCKET;
  7870. memset(sa, 0, sizeof(*sa));
  7871. if (host == NULL) {
  7872. if (error != NULL) {
  7873. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7874. mg_snprintf(NULL,
  7875. NULL, /* No truncation check for ebuf */
  7876. error->text,
  7877. error->text_buffer_size,
  7878. "%s",
  7879. "NULL host");
  7880. }
  7881. return 0;
  7882. }
  7883. #if defined(USE_X_DOM_SOCKET)
  7884. if (port == -99) {
  7885. /* Unix domain socket */
  7886. size_t hostlen = strlen(host);
  7887. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7888. if (error != NULL) {
  7889. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7890. mg_snprintf(NULL,
  7891. NULL, /* No truncation check for ebuf */
  7892. error->text,
  7893. error->text_buffer_size,
  7894. "%s",
  7895. "host length exceeds limit");
  7896. }
  7897. return 0;
  7898. }
  7899. } else
  7900. #endif
  7901. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7902. if (error != NULL) {
  7903. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7904. mg_snprintf(NULL,
  7905. NULL, /* No truncation check for ebuf */
  7906. error->text,
  7907. error->text_buffer_size,
  7908. "%s",
  7909. "invalid port");
  7910. }
  7911. return 0;
  7912. }
  7913. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7914. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7915. if (use_ssl && (TLS_client_method == NULL)) {
  7916. if (error != NULL) {
  7917. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  7918. mg_snprintf(NULL,
  7919. NULL, /* No truncation check for ebuf */
  7920. error->text,
  7921. error->text_buffer_size,
  7922. "%s",
  7923. "SSL is not initialized");
  7924. }
  7925. return 0;
  7926. }
  7927. #else
  7928. if (use_ssl && (SSLv23_client_method == NULL)) {
  7929. if (error != 0) {
  7930. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  7931. mg_snprintf(NULL,
  7932. NULL, /* No truncation check for ebuf */
  7933. error->text,
  7934. error->text_buffer_size,
  7935. "%s",
  7936. "SSL is not initialized");
  7937. }
  7938. return 0;
  7939. }
  7940. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7941. #else
  7942. (void)use_ssl;
  7943. #endif /* NO SSL */
  7944. #if defined(USE_X_DOM_SOCKET)
  7945. if (port == -99) {
  7946. size_t hostlen = strlen(host);
  7947. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  7948. ip_ver = -99;
  7949. sa->sun.sun_family = AF_UNIX;
  7950. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  7951. memcpy(sa->sun.sun_path, host, hostlen);
  7952. } else
  7953. #endif
  7954. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7955. sa->sin.sin_port = htons((uint16_t)port);
  7956. ip_ver = 4;
  7957. #if defined(USE_IPV6)
  7958. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7959. sa->sin6.sin6_port = htons((uint16_t)port);
  7960. ip_ver = 6;
  7961. } else if (host[0] == '[') {
  7962. /* While getaddrinfo on Windows will work with [::1],
  7963. * getaddrinfo on Linux only works with ::1 (without []). */
  7964. size_t l = strlen(host + 1);
  7965. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7966. if (h) {
  7967. h[l - 1] = 0;
  7968. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7969. sa->sin6.sin6_port = htons((uint16_t)port);
  7970. ip_ver = 6;
  7971. }
  7972. mg_free(h);
  7973. }
  7974. #endif
  7975. }
  7976. if (ip_ver == 0) {
  7977. if (error != NULL) {
  7978. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  7979. mg_snprintf(NULL,
  7980. NULL, /* No truncation check for ebuf */
  7981. error->text,
  7982. error->text_buffer_size,
  7983. "%s",
  7984. "host not found");
  7985. }
  7986. return 0;
  7987. }
  7988. if (ip_ver == 4) {
  7989. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7990. }
  7991. #if defined(USE_IPV6)
  7992. else if (ip_ver == 6) {
  7993. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7994. }
  7995. #endif
  7996. #if defined(USE_X_DOM_SOCKET)
  7997. else if (ip_ver == -99) {
  7998. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  7999. }
  8000. #endif
  8001. if (*sock == INVALID_SOCKET) {
  8002. if (error != NULL) {
  8003. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8004. error->code_sub = ERRNO;
  8005. mg_snprintf(NULL,
  8006. NULL, /* No truncation check for ebuf */
  8007. error->text,
  8008. error->text_buffer_size,
  8009. "socket(): %s",
  8010. strerror(ERRNO));
  8011. }
  8012. return 0;
  8013. }
  8014. if (0 != set_non_blocking_mode(*sock)) {
  8015. if (error != NULL) {
  8016. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8017. error->code_sub = ERRNO;
  8018. mg_snprintf(NULL,
  8019. NULL, /* No truncation check for ebuf */
  8020. error->text,
  8021. error->text_buffer_size,
  8022. "Cannot set socket to non-blocking: %s",
  8023. strerror(ERRNO));
  8024. }
  8025. closesocket(*sock);
  8026. *sock = INVALID_SOCKET;
  8027. return 0;
  8028. }
  8029. set_close_on_exec(*sock, NULL, ctx);
  8030. if (ip_ver == 4) {
  8031. /* connected with IPv4 */
  8032. conn_ret = connect(*sock,
  8033. (struct sockaddr *)((void *)&sa->sin),
  8034. sizeof(sa->sin));
  8035. }
  8036. #if defined(USE_IPV6)
  8037. else if (ip_ver == 6) {
  8038. /* connected with IPv6 */
  8039. conn_ret = connect(*sock,
  8040. (struct sockaddr *)((void *)&sa->sin6),
  8041. sizeof(sa->sin6));
  8042. }
  8043. #endif
  8044. #if defined(USE_X_DOM_SOCKET)
  8045. else if (ip_ver == -99) {
  8046. /* connected to domain socket */
  8047. conn_ret = connect(*sock,
  8048. (struct sockaddr *)((void *)&sa->sun),
  8049. sizeof(sa->sun));
  8050. }
  8051. #endif
  8052. if (conn_ret != 0) {
  8053. sockerr = ERRNO;
  8054. }
  8055. #if defined(_WIN32)
  8056. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8057. #else
  8058. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8059. #endif
  8060. /* Data for getsockopt */
  8061. void *psockerr = &sockerr;
  8062. int ret;
  8063. #if defined(_WIN32)
  8064. int len = (int)sizeof(sockerr);
  8065. #else
  8066. socklen_t len = (socklen_t)sizeof(sockerr);
  8067. #endif
  8068. /* Data for poll */
  8069. struct mg_pollfd pfd[1];
  8070. int pollres;
  8071. int ms_wait = 10000; /* 10 second timeout */
  8072. stop_flag_t nonstop;
  8073. STOP_FLAG_ASSIGN(&nonstop, 0);
  8074. /* For a non-blocking socket, the connect sequence is:
  8075. * 1) call connect (will not block)
  8076. * 2) wait until the socket is ready for writing (select or poll)
  8077. * 3) check connection state with getsockopt
  8078. */
  8079. pfd[0].fd = *sock;
  8080. pfd[0].events = POLLOUT;
  8081. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8082. if (pollres != 1) {
  8083. /* Not connected */
  8084. if (error != NULL) {
  8085. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8086. mg_snprintf(NULL,
  8087. NULL, /* No truncation check for ebuf */
  8088. error->text,
  8089. error->text_buffer_size,
  8090. "connect(%s:%d): timeout",
  8091. host,
  8092. port);
  8093. }
  8094. closesocket(*sock);
  8095. *sock = INVALID_SOCKET;
  8096. return 0;
  8097. }
  8098. #if defined(_WIN32)
  8099. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8100. #else
  8101. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8102. #endif
  8103. if ((ret == 0) && (sockerr == 0)) {
  8104. conn_ret = 0;
  8105. }
  8106. }
  8107. if (conn_ret != 0) {
  8108. /* Not connected */
  8109. if (error != NULL) {
  8110. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8111. error->code_sub = ERRNO;
  8112. mg_snprintf(NULL,
  8113. NULL, /* No truncation check for ebuf */
  8114. error->text,
  8115. error->text_buffer_size,
  8116. "connect(%s:%d): error %s",
  8117. host,
  8118. port,
  8119. strerror(sockerr));
  8120. }
  8121. closesocket(*sock);
  8122. *sock = INVALID_SOCKET;
  8123. return 0;
  8124. }
  8125. return 1;
  8126. }
  8127. CIVETWEB_API int
  8128. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8129. {
  8130. static const char *dont_escape = "._-$,;~()";
  8131. static const char *hex = "0123456789abcdef";
  8132. char *pos = dst;
  8133. const char *end = dst + dst_len - 1;
  8134. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8135. if (isalnum((unsigned char)*src)
  8136. || (strchr(dont_escape, *src) != NULL)) {
  8137. *pos = *src;
  8138. } else if (pos + 2 < end) {
  8139. pos[0] = '%';
  8140. pos[1] = hex[(unsigned char)*src >> 4];
  8141. pos[2] = hex[(unsigned char)*src & 0xf];
  8142. pos += 2;
  8143. } else {
  8144. break;
  8145. }
  8146. }
  8147. *pos = '\0';
  8148. return (*src == '\0') ? (int)(pos - dst) : -1;
  8149. }
  8150. /* Return 0 on success, non-zero if an error occurs. */
  8151. static int
  8152. print_dir_entry(struct mg_connection *conn, struct de *de)
  8153. {
  8154. size_t namesize, escsize, i;
  8155. char *href, *esc, *p;
  8156. char size[64], mod[64];
  8157. #if defined(REENTRANT_TIME)
  8158. struct tm _tm;
  8159. struct tm *tm = &_tm;
  8160. #else
  8161. struct tm *tm;
  8162. #endif
  8163. /* Estimate worst case size for encoding and escaping */
  8164. namesize = strlen(de->file_name) + 1;
  8165. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8166. href = (char *)mg_malloc(namesize * 3 + escsize);
  8167. if (href == NULL) {
  8168. return -1;
  8169. }
  8170. mg_url_encode(de->file_name, href, namesize * 3);
  8171. esc = NULL;
  8172. if (escsize > 0) {
  8173. /* HTML escaping needed */
  8174. esc = href + namesize * 3;
  8175. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8176. mg_strlcpy(p, de->file_name + i, 2);
  8177. if (*p == '&') {
  8178. strcpy(p, "&amp;");
  8179. } else if (*p == '<') {
  8180. strcpy(p, "&lt;");
  8181. } else if (*p == '>') {
  8182. strcpy(p, "&gt;");
  8183. }
  8184. }
  8185. }
  8186. if (de->file.is_directory) {
  8187. mg_snprintf(conn,
  8188. NULL, /* Buffer is big enough */
  8189. size,
  8190. sizeof(size),
  8191. "%s",
  8192. "[DIRECTORY]");
  8193. } else {
  8194. /* We use (signed) cast below because MSVC 6 compiler cannot
  8195. * convert unsigned __int64 to double. Sigh. */
  8196. if (de->file.size < 1024) {
  8197. mg_snprintf(conn,
  8198. NULL, /* Buffer is big enough */
  8199. size,
  8200. sizeof(size),
  8201. "%d",
  8202. (int)de->file.size);
  8203. } else if (de->file.size < 0x100000) {
  8204. mg_snprintf(conn,
  8205. NULL, /* Buffer is big enough */
  8206. size,
  8207. sizeof(size),
  8208. "%.1fk",
  8209. (double)de->file.size / 1024.0);
  8210. } else if (de->file.size < 0x40000000) {
  8211. mg_snprintf(conn,
  8212. NULL, /* Buffer is big enough */
  8213. size,
  8214. sizeof(size),
  8215. "%.1fM",
  8216. (double)de->file.size / 1048576);
  8217. } else {
  8218. mg_snprintf(conn,
  8219. NULL, /* Buffer is big enough */
  8220. size,
  8221. sizeof(size),
  8222. "%.1fG",
  8223. (double)de->file.size / 1073741824);
  8224. }
  8225. }
  8226. /* Note: mg_snprintf will not cause a buffer overflow above.
  8227. * So, string truncation checks are not required here. */
  8228. #if defined(REENTRANT_TIME)
  8229. localtime_r(&de->file.last_modified, tm);
  8230. #else
  8231. tm = localtime(&de->file.last_modified);
  8232. #endif
  8233. if (tm != NULL) {
  8234. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8235. } else {
  8236. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8237. mod[sizeof(mod) - 1] = '\0';
  8238. }
  8239. mg_printf(conn,
  8240. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8241. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8242. href,
  8243. de->file.is_directory ? "/" : "",
  8244. esc ? esc : de->file_name,
  8245. de->file.is_directory ? "/" : "",
  8246. mod,
  8247. size);
  8248. mg_free(href);
  8249. return 0;
  8250. }
  8251. /* This function is called from send_directory() and used for
  8252. * sorting directory entries by size, name, or modification time. */
  8253. static int
  8254. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8255. {
  8256. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8257. if (p1 && p2) {
  8258. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8259. int cmp_result = 0;
  8260. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8261. query_string = "n";
  8262. }
  8263. /* Sort Directories vs Files */
  8264. if (a->file.is_directory && !b->file.is_directory) {
  8265. return -1; /* Always put directories on top */
  8266. } else if (!a->file.is_directory && b->file.is_directory) {
  8267. return 1; /* Always put directories on top */
  8268. }
  8269. /* Sort by size or date */
  8270. if (*query_string == 's') {
  8271. cmp_result = (a->file.size == b->file.size)
  8272. ? 0
  8273. : ((a->file.size > b->file.size) ? 1 : -1);
  8274. } else if (*query_string == 'd') {
  8275. cmp_result =
  8276. (a->file.last_modified == b->file.last_modified)
  8277. ? 0
  8278. : ((a->file.last_modified > b->file.last_modified) ? 1
  8279. : -1);
  8280. }
  8281. /* Sort by name:
  8282. * if (*query_string == 'n') ...
  8283. * but also sort files of same size/date by name as secondary criterion.
  8284. */
  8285. if (cmp_result == 0) {
  8286. cmp_result = strcmp(a->file_name, b->file_name);
  8287. }
  8288. /* For descending order, invert result */
  8289. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8290. }
  8291. return 0;
  8292. }
  8293. static int
  8294. must_hide_file(struct mg_connection *conn, const char *path)
  8295. {
  8296. if (conn && conn->dom_ctx) {
  8297. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8298. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8299. return (match_prefix_strlen(pw_pattern, path) > 0)
  8300. || (match_prefix_strlen(pattern, path) > 0);
  8301. }
  8302. return 0;
  8303. }
  8304. #if !defined(NO_FILESYSTEMS)
  8305. static int
  8306. scan_directory(struct mg_connection *conn,
  8307. const char *dir,
  8308. void *data,
  8309. int (*cb)(struct de *, void *))
  8310. {
  8311. char path[UTF8_PATH_MAX];
  8312. struct dirent *dp;
  8313. DIR *dirp;
  8314. struct de de;
  8315. int truncated;
  8316. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8317. return 0;
  8318. } else {
  8319. while ((dp = mg_readdir(dirp)) != NULL) {
  8320. /* Do not show current dir and hidden files */
  8321. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8322. || must_hide_file(conn, dp->d_name)) {
  8323. continue;
  8324. }
  8325. mg_snprintf(
  8326. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8327. /* If we don't memset stat structure to zero, mtime will have
  8328. * garbage and strftime() will segfault later on in
  8329. * print_dir_entry(). memset is required only if mg_stat()
  8330. * fails. For more details, see
  8331. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8332. memset(&de.file, 0, sizeof(de.file));
  8333. if (truncated) {
  8334. /* If the path is not complete, skip processing. */
  8335. continue;
  8336. }
  8337. if (!mg_stat(conn, path, &de.file)) {
  8338. mg_cry_internal(conn,
  8339. "%s: mg_stat(%s) failed: %s",
  8340. __func__,
  8341. path,
  8342. strerror(ERRNO));
  8343. }
  8344. de.file_name = dp->d_name;
  8345. if (cb(&de, data)) {
  8346. /* stopped */
  8347. break;
  8348. }
  8349. }
  8350. (void)mg_closedir(dirp);
  8351. }
  8352. return 1;
  8353. }
  8354. #endif /* NO_FILESYSTEMS */
  8355. #if !defined(NO_FILES)
  8356. static int
  8357. remove_directory(struct mg_connection *conn, const char *dir)
  8358. {
  8359. char path[UTF8_PATH_MAX];
  8360. struct dirent *dp;
  8361. DIR *dirp;
  8362. struct de de;
  8363. int truncated;
  8364. int ok = 1;
  8365. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8366. return 0;
  8367. } else {
  8368. while ((dp = mg_readdir(dirp)) != NULL) {
  8369. /* Do not show current dir (but show hidden files as they will
  8370. * also be removed) */
  8371. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8372. continue;
  8373. }
  8374. mg_snprintf(
  8375. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8376. /* If we don't memset stat structure to zero, mtime will have
  8377. * garbage and strftime() will segfault later on in
  8378. * print_dir_entry(). memset is required only if mg_stat()
  8379. * fails. For more details, see
  8380. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8381. memset(&de.file, 0, sizeof(de.file));
  8382. if (truncated) {
  8383. /* Do not delete anything shorter */
  8384. ok = 0;
  8385. continue;
  8386. }
  8387. if (!mg_stat(conn, path, &de.file)) {
  8388. mg_cry_internal(conn,
  8389. "%s: mg_stat(%s) failed: %s",
  8390. __func__,
  8391. path,
  8392. strerror(ERRNO));
  8393. ok = 0;
  8394. }
  8395. if (de.file.is_directory) {
  8396. if (remove_directory(conn, path) == 0) {
  8397. ok = 0;
  8398. }
  8399. } else {
  8400. /* This will fail file is the file is in memory */
  8401. if (mg_remove(conn, path) == 0) {
  8402. ok = 0;
  8403. }
  8404. }
  8405. }
  8406. (void)mg_closedir(dirp);
  8407. IGNORE_UNUSED_RESULT(rmdir(dir));
  8408. }
  8409. return ok;
  8410. }
  8411. #endif
  8412. struct dir_scan_data {
  8413. struct de *entries;
  8414. size_t num_entries;
  8415. size_t arr_size;
  8416. };
  8417. #if !defined(NO_FILESYSTEMS)
  8418. static int
  8419. dir_scan_callback(struct de *de, void *data)
  8420. {
  8421. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8422. struct de *entries = dsd->entries;
  8423. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8424. /* Here "entries" is a temporary pointer and can be replaced,
  8425. * "dsd->entries" is the original pointer */
  8426. entries =
  8427. (struct de *)mg_realloc(entries,
  8428. dsd->arr_size * 2 * sizeof(entries[0]));
  8429. if (entries == NULL) {
  8430. /* stop scan */
  8431. return 1;
  8432. }
  8433. dsd->entries = entries;
  8434. dsd->arr_size *= 2;
  8435. }
  8436. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8437. if (entries[dsd->num_entries].file_name == NULL) {
  8438. /* stop scan */
  8439. return 1;
  8440. }
  8441. entries[dsd->num_entries].file = de->file;
  8442. dsd->num_entries++;
  8443. return 0;
  8444. }
  8445. static void
  8446. handle_directory_request(struct mg_connection *conn, const char *dir)
  8447. {
  8448. size_t i;
  8449. int sort_direction;
  8450. struct dir_scan_data data = {NULL, 0, 128};
  8451. char date[64], *esc, *p;
  8452. const char *title;
  8453. time_t curtime = time(NULL);
  8454. if (!conn) {
  8455. return;
  8456. }
  8457. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8458. mg_send_http_error(conn,
  8459. 500,
  8460. "Error: Cannot open directory\nopendir(%s): %s",
  8461. dir,
  8462. strerror(ERRNO));
  8463. return;
  8464. }
  8465. gmt_time_string(date, sizeof(date), &curtime);
  8466. esc = NULL;
  8467. title = conn->request_info.local_uri;
  8468. if (title[strcspn(title, "&<>")]) {
  8469. /* HTML escaping needed */
  8470. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8471. if (esc) {
  8472. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8473. mg_strlcpy(p, title + i, 2);
  8474. if (*p == '&') {
  8475. strcpy(p, "&amp;");
  8476. } else if (*p == '<') {
  8477. strcpy(p, "&lt;");
  8478. } else if (*p == '>') {
  8479. strcpy(p, "&gt;");
  8480. }
  8481. }
  8482. } else {
  8483. title = "";
  8484. }
  8485. }
  8486. sort_direction = ((conn->request_info.query_string != NULL)
  8487. && (conn->request_info.query_string[0] != '\0')
  8488. && (conn->request_info.query_string[1] == 'd'))
  8489. ? 'a'
  8490. : 'd';
  8491. conn->must_close = 1;
  8492. /* Create 200 OK response */
  8493. mg_response_header_start(conn, 200);
  8494. send_static_cache_header(conn);
  8495. send_additional_header(conn);
  8496. mg_response_header_add(conn,
  8497. "Content-Type",
  8498. "text/html; charset=utf-8",
  8499. -1);
  8500. /* Send all headers */
  8501. mg_response_header_send(conn);
  8502. /* Body */
  8503. mg_printf(conn,
  8504. "<html><head><title>Index of %s</title>"
  8505. "<style>th {text-align: left;}</style></head>"
  8506. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8507. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8508. "<th><a href=\"?d%c\">Modified</a></th>"
  8509. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8510. "<tr><td colspan=\"3\"><hr></td></tr>",
  8511. esc ? esc : title,
  8512. esc ? esc : title,
  8513. sort_direction,
  8514. sort_direction,
  8515. sort_direction);
  8516. mg_free(esc);
  8517. /* Print first entry - link to a parent directory */
  8518. mg_printf(conn,
  8519. "<tr><td><a href=\"%s\">%s</a></td>"
  8520. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8521. "..",
  8522. "Parent directory",
  8523. "-",
  8524. "-");
  8525. /* Sort and print directory entries */
  8526. if (data.entries != NULL) {
  8527. mg_sort(data.entries,
  8528. data.num_entries,
  8529. sizeof(data.entries[0]),
  8530. compare_dir_entries,
  8531. (void *)conn->request_info.query_string);
  8532. for (i = 0; i < data.num_entries; i++) {
  8533. print_dir_entry(conn, &data.entries[i]);
  8534. mg_free(data.entries[i].file_name);
  8535. }
  8536. mg_free(data.entries);
  8537. }
  8538. mg_printf(conn, "%s", "</table></pre></body></html>");
  8539. conn->status_code = 200;
  8540. }
  8541. #endif /* NO_FILESYSTEMS */
  8542. /* Send len bytes from the opened file to the client. */
  8543. static void
  8544. send_file_data(struct mg_connection *conn,
  8545. struct mg_file *filep,
  8546. int64_t offset,
  8547. int64_t len,
  8548. int no_buffering)
  8549. {
  8550. char buf[MG_BUF_LEN];
  8551. int to_read, num_read, num_written;
  8552. int64_t size;
  8553. if (!filep || !conn) {
  8554. return;
  8555. }
  8556. /* Sanity check the offset */
  8557. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8558. : (int64_t)(filep->stat.size);
  8559. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8560. if (len > 0 && filep->access.fp != NULL) {
  8561. /* file stored on disk */
  8562. #if defined(__linux__)
  8563. /* sendfile is only available for Linux */
  8564. if ((conn->ssl == 0) && (conn->throttle == 0)
  8565. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8566. "yes"))) {
  8567. off_t sf_offs = (off_t)offset;
  8568. ssize_t sf_sent;
  8569. int sf_file = fileno(filep->access.fp);
  8570. int loop_cnt = 0;
  8571. do {
  8572. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8573. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8574. size_t sf_tosend =
  8575. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8576. sf_sent =
  8577. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8578. if (sf_sent > 0) {
  8579. len -= sf_sent;
  8580. offset += sf_sent;
  8581. } else if (loop_cnt == 0) {
  8582. /* This file can not be sent using sendfile.
  8583. * This might be the case for pseudo-files in the
  8584. * /sys/ and /proc/ file system.
  8585. * Use the regular user mode copy code instead. */
  8586. break;
  8587. } else if (sf_sent == 0) {
  8588. /* No error, but 0 bytes sent. May be EOF? */
  8589. return;
  8590. }
  8591. loop_cnt++;
  8592. } while ((len > 0) && (sf_sent >= 0));
  8593. if (sf_sent > 0) {
  8594. return; /* OK */
  8595. }
  8596. /* sf_sent<0 means error, thus fall back to the classic way */
  8597. /* This is always the case, if sf_file is not a "normal" file,
  8598. * e.g., for sending data from the output of a CGI process. */
  8599. offset = (int64_t)sf_offs;
  8600. }
  8601. #endif
  8602. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8603. mg_cry_internal(conn,
  8604. "%s: fseeko() failed: %s",
  8605. __func__,
  8606. strerror(ERRNO));
  8607. mg_send_http_error(
  8608. conn,
  8609. 500,
  8610. "%s",
  8611. "Error: Unable to access file at requested position.");
  8612. } else {
  8613. while (len > 0) {
  8614. /* Calculate how much to read from the file into the buffer. */
  8615. /* If no_buffering is set, we should not wait until the
  8616. * CGI->Server buffer is filled, but send everything
  8617. * immediately. In theory buffering could be turned off using
  8618. * setbuf(filep->access.fp, NULL);
  8619. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8620. * but in practice this does not work. A "Linux only" solution
  8621. * may be to use select(). The only portable way is to read byte
  8622. * by byte, but this is quite inefficient from a performance
  8623. * point of view. */
  8624. to_read = no_buffering ? 1 : sizeof(buf);
  8625. if ((int64_t)to_read > len) {
  8626. to_read = (int)len;
  8627. }
  8628. /* Read from file, exit the loop on error */
  8629. if ((num_read =
  8630. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8631. <= 0) {
  8632. break;
  8633. }
  8634. /* Send read bytes to the client, exit the loop on error */
  8635. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8636. != num_read) {
  8637. break;
  8638. }
  8639. /* Both read and were successful, adjust counters */
  8640. len -= num_written;
  8641. }
  8642. }
  8643. }
  8644. }
  8645. static int
  8646. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8647. {
  8648. return sscanf(header,
  8649. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8650. a,
  8651. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8652. // to an integer value, but function will not report
  8653. // conversion errors; consider using 'strtol' instead
  8654. }
  8655. static void
  8656. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8657. {
  8658. if ((filestat != NULL) && (buf != NULL)) {
  8659. mg_snprintf(NULL,
  8660. NULL, /* All calls to construct_etag use 64 byte buffer */
  8661. buf,
  8662. buf_len,
  8663. "\"%lx.%" INT64_FMT "\"",
  8664. (unsigned long)filestat->last_modified,
  8665. filestat->size);
  8666. }
  8667. }
  8668. static void
  8669. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8670. {
  8671. if (filep != NULL && filep->fp != NULL) {
  8672. #if defined(_WIN32)
  8673. (void)conn; /* Unused. */
  8674. #else
  8675. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8676. mg_cry_internal(conn,
  8677. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8678. __func__,
  8679. strerror(ERRNO));
  8680. }
  8681. #endif
  8682. }
  8683. }
  8684. #if defined(USE_ZLIB)
  8685. #include "mod_zlib.inl"
  8686. #endif
  8687. #if !defined(NO_FILESYSTEMS)
  8688. static void
  8689. handle_static_file_request(struct mg_connection *conn,
  8690. const char *path,
  8691. struct mg_file *filep,
  8692. const char *mime_type,
  8693. const char *additional_headers)
  8694. {
  8695. char lm[64], etag[64];
  8696. char range[128]; /* large enough, so there will be no overflow */
  8697. const char *range_hdr;
  8698. int64_t cl, r1, r2;
  8699. struct vec mime_vec;
  8700. int n, truncated;
  8701. char gz_path[UTF8_PATH_MAX];
  8702. const char *encoding = 0;
  8703. int is_head_request;
  8704. #if defined(USE_ZLIB)
  8705. /* Compression is allowed, unless there is a reason not to use
  8706. * compression. If the file is already compressed, too small or a
  8707. * "range" request was made, on the fly compression is not possible. */
  8708. int allow_on_the_fly_compression = 1;
  8709. #endif
  8710. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8711. return;
  8712. }
  8713. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8714. if (mime_type == NULL) {
  8715. get_mime_type(conn, path, &mime_vec);
  8716. } else {
  8717. mime_vec.ptr = mime_type;
  8718. mime_vec.len = strlen(mime_type);
  8719. }
  8720. if (filep->stat.size > INT64_MAX) {
  8721. mg_send_http_error(conn,
  8722. 500,
  8723. "Error: File size is too large to send\n%" INT64_FMT,
  8724. filep->stat.size);
  8725. return;
  8726. }
  8727. cl = (int64_t)filep->stat.size;
  8728. conn->status_code = 200;
  8729. range[0] = '\0';
  8730. #if defined(USE_ZLIB)
  8731. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8732. * it's important to rewrite the filename after resolving
  8733. * the mime type from it, to preserve the actual file's type */
  8734. if (!conn->accept_gzip) {
  8735. allow_on_the_fly_compression = 0;
  8736. }
  8737. #endif
  8738. /* Check if there is a range header */
  8739. range_hdr = mg_get_header(conn, "Range");
  8740. /* For gzipped files, add *.gz */
  8741. if (filep->stat.is_gzipped) {
  8742. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8743. if (truncated) {
  8744. mg_send_http_error(conn,
  8745. 500,
  8746. "Error: Path of zipped file too long (%s)",
  8747. path);
  8748. return;
  8749. }
  8750. path = gz_path;
  8751. encoding = "gzip";
  8752. #if defined(USE_ZLIB)
  8753. /* File is already compressed. No "on the fly" compression. */
  8754. allow_on_the_fly_compression = 0;
  8755. #endif
  8756. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8757. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8758. struct mg_file_stat file_stat;
  8759. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8760. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8761. && !file_stat.is_directory) {
  8762. file_stat.is_gzipped = 1;
  8763. filep->stat = file_stat;
  8764. cl = (int64_t)filep->stat.size;
  8765. path = gz_path;
  8766. encoding = "gzip";
  8767. #if defined(USE_ZLIB)
  8768. /* File is already compressed. No "on the fly" compression. */
  8769. allow_on_the_fly_compression = 0;
  8770. #endif
  8771. }
  8772. }
  8773. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8774. mg_send_http_error(conn,
  8775. 500,
  8776. "Error: Cannot open file\nfopen(%s): %s",
  8777. path,
  8778. strerror(ERRNO));
  8779. return;
  8780. }
  8781. fclose_on_exec(&filep->access, conn);
  8782. /* If "Range" request was made: parse header, send only selected part
  8783. * of the file. */
  8784. r1 = r2 = 0;
  8785. if ((range_hdr != NULL)
  8786. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8787. && (r2 >= 0)) {
  8788. /* actually, range requests don't play well with a pre-gzipped
  8789. * file (since the range is specified in the uncompressed space) */
  8790. if (filep->stat.is_gzipped) {
  8791. mg_send_http_error(
  8792. conn,
  8793. 416, /* 416 = Range Not Satisfiable */
  8794. "%s",
  8795. "Error: Range requests in gzipped files are not supported");
  8796. (void)mg_fclose(
  8797. &filep->access); /* ignore error on read only file */
  8798. return;
  8799. }
  8800. conn->status_code = 206;
  8801. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8802. mg_snprintf(conn,
  8803. NULL, /* range buffer is big enough */
  8804. range,
  8805. sizeof(range),
  8806. "bytes "
  8807. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8808. r1,
  8809. r1 + cl - 1,
  8810. filep->stat.size);
  8811. #if defined(USE_ZLIB)
  8812. /* Do not compress ranges. */
  8813. allow_on_the_fly_compression = 0;
  8814. #endif
  8815. }
  8816. /* Do not compress small files. Small files do not benefit from file
  8817. * compression, but there is still some overhead. */
  8818. #if defined(USE_ZLIB)
  8819. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8820. /* File is below the size limit. */
  8821. allow_on_the_fly_compression = 0;
  8822. }
  8823. #endif
  8824. /* Prepare Etag, and Last-Modified headers. */
  8825. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8826. construct_etag(etag, sizeof(etag), &filep->stat);
  8827. /* Create 2xx (200, 206) response */
  8828. mg_response_header_start(conn, conn->status_code);
  8829. send_static_cache_header(conn);
  8830. send_additional_header(conn);
  8831. send_cors_header(conn);
  8832. mg_response_header_add(conn,
  8833. "Content-Type",
  8834. mime_vec.ptr,
  8835. (int)mime_vec.len);
  8836. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8837. mg_response_header_add(conn, "Etag", etag, -1);
  8838. #if defined(USE_ZLIB)
  8839. /* On the fly compression allowed */
  8840. if (allow_on_the_fly_compression) {
  8841. /* For on the fly compression, we don't know the content size in
  8842. * advance, so we have to use chunked encoding */
  8843. encoding = "gzip";
  8844. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8845. /* HTTP/2 is always using "chunks" (frames) */
  8846. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8847. }
  8848. } else
  8849. #endif
  8850. {
  8851. /* Without on-the-fly compression, we know the content-length
  8852. * and we can use ranges (with on-the-fly compression we cannot).
  8853. * So we send these response headers only in this case. */
  8854. char len[32];
  8855. int trunc = 0;
  8856. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8857. if (!trunc) {
  8858. mg_response_header_add(conn, "Content-Length", len, -1);
  8859. }
  8860. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8861. }
  8862. if (encoding) {
  8863. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8864. }
  8865. if (range[0] != 0) {
  8866. mg_response_header_add(conn, "Content-Range", range, -1);
  8867. }
  8868. /* The code above does not add any header starting with X- to make
  8869. * sure no one of the additional_headers is included twice */
  8870. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8871. mg_response_header_add_lines(conn, additional_headers);
  8872. }
  8873. /* Send all headers */
  8874. mg_response_header_send(conn);
  8875. if (!is_head_request) {
  8876. #if defined(USE_ZLIB)
  8877. if (allow_on_the_fly_compression) {
  8878. /* Compress and send */
  8879. send_compressed_data(conn, filep);
  8880. } else
  8881. #endif
  8882. {
  8883. /* Send file directly */
  8884. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  8885. }
  8886. }
  8887. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8888. }
  8889. CIVETWEB_API int
  8890. mg_send_file_body(struct mg_connection *conn, const char *path)
  8891. {
  8892. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8893. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8894. return -1;
  8895. }
  8896. fclose_on_exec(&file.access, conn);
  8897. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  8898. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8899. return 0; /* >= 0 for OK */
  8900. }
  8901. #endif /* NO_FILESYSTEMS */
  8902. #if !defined(NO_CACHING)
  8903. /* Return True if we should reply 304 Not Modified. */
  8904. static int
  8905. is_not_modified(const struct mg_connection *conn,
  8906. const struct mg_file_stat *filestat)
  8907. {
  8908. char etag[64];
  8909. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8910. const char *inm = mg_get_header(conn, "If-None-Match");
  8911. construct_etag(etag, sizeof(etag), filestat);
  8912. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8913. || ((ims != NULL)
  8914. && (filestat->last_modified <= parse_date_string(ims)));
  8915. }
  8916. static void
  8917. handle_not_modified_static_file_request(struct mg_connection *conn,
  8918. struct mg_file *filep)
  8919. {
  8920. char lm[64], etag[64];
  8921. if ((conn == NULL) || (filep == NULL)) {
  8922. return;
  8923. }
  8924. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8925. construct_etag(etag, sizeof(etag), &filep->stat);
  8926. /* Create 304 "not modified" response */
  8927. mg_response_header_start(conn, 304);
  8928. send_static_cache_header(conn);
  8929. send_additional_header(conn);
  8930. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8931. mg_response_header_add(conn, "Etag", etag, -1);
  8932. /* Send all headers */
  8933. mg_response_header_send(conn);
  8934. }
  8935. #endif
  8936. #if !defined(NO_FILESYSTEMS)
  8937. CIVETWEB_API void
  8938. mg_send_file(struct mg_connection *conn, const char *path)
  8939. {
  8940. mg_send_mime_file2(conn, path, NULL, NULL);
  8941. }
  8942. CIVETWEB_API void
  8943. mg_send_mime_file(struct mg_connection *conn,
  8944. const char *path,
  8945. const char *mime_type)
  8946. {
  8947. mg_send_mime_file2(conn, path, mime_type, NULL);
  8948. }
  8949. CIVETWEB_API void
  8950. mg_send_mime_file2(struct mg_connection *conn,
  8951. const char *path,
  8952. const char *mime_type,
  8953. const char *additional_headers)
  8954. {
  8955. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8956. if (!conn) {
  8957. /* No conn */
  8958. return;
  8959. }
  8960. if (mg_stat(conn, path, &file.stat)) {
  8961. #if !defined(NO_CACHING)
  8962. if (is_not_modified(conn, &file.stat)) {
  8963. /* Send 304 "Not Modified" - this must not send any body data */
  8964. handle_not_modified_static_file_request(conn, &file);
  8965. } else
  8966. #endif /* NO_CACHING */
  8967. if (file.stat.is_directory) {
  8968. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8969. "yes")) {
  8970. handle_directory_request(conn, path);
  8971. } else {
  8972. mg_send_http_error(conn,
  8973. 403,
  8974. "%s",
  8975. "Error: Directory listing denied");
  8976. }
  8977. } else {
  8978. handle_static_file_request(
  8979. conn, path, &file, mime_type, additional_headers);
  8980. }
  8981. } else {
  8982. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8983. }
  8984. }
  8985. /* For a given PUT path, create all intermediate subdirectories.
  8986. * Return 0 if the path itself is a directory.
  8987. * Return 1 if the path leads to a file.
  8988. * Return -1 for if the path is too long.
  8989. * Return -2 if path can not be created.
  8990. */
  8991. static int
  8992. put_dir(struct mg_connection *conn, const char *path)
  8993. {
  8994. char buf[UTF8_PATH_MAX];
  8995. const char *s, *p;
  8996. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8997. size_t len;
  8998. int res = 1;
  8999. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9000. len = (size_t)(p - path);
  9001. if (len >= sizeof(buf)) {
  9002. /* path too long */
  9003. res = -1;
  9004. break;
  9005. }
  9006. memcpy(buf, path, len);
  9007. buf[len] = '\0';
  9008. /* Try to create intermediate directory */
  9009. DEBUG_TRACE("mkdir(%s)", buf);
  9010. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9011. /* path does not exixt and can not be created */
  9012. res = -2;
  9013. break;
  9014. }
  9015. /* Is path itself a directory? */
  9016. if (p[1] == '\0') {
  9017. res = 0;
  9018. }
  9019. }
  9020. return res;
  9021. }
  9022. static void
  9023. remove_bad_file(const struct mg_connection *conn, const char *path)
  9024. {
  9025. int r = mg_remove(conn, path);
  9026. if (r != 0) {
  9027. mg_cry_internal(conn,
  9028. "%s: Cannot remove invalid file %s",
  9029. __func__,
  9030. path);
  9031. }
  9032. }
  9033. CIVETWEB_API long long
  9034. mg_store_body(struct mg_connection *conn, const char *path)
  9035. {
  9036. char buf[MG_BUF_LEN];
  9037. long long len = 0;
  9038. int ret, n;
  9039. struct mg_file fi;
  9040. if (conn->consumed_content != 0) {
  9041. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9042. return -11;
  9043. }
  9044. ret = put_dir(conn, path);
  9045. if (ret < 0) {
  9046. /* -1 for path too long,
  9047. * -2 for path can not be created. */
  9048. return ret;
  9049. }
  9050. if (ret != 1) {
  9051. /* Return 0 means, path itself is a directory. */
  9052. return 0;
  9053. }
  9054. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9055. return -12;
  9056. }
  9057. ret = mg_read(conn, buf, sizeof(buf));
  9058. while (ret > 0) {
  9059. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9060. if (n != ret) {
  9061. (void)mg_fclose(
  9062. &fi.access); /* File is bad and will be removed anyway. */
  9063. remove_bad_file(conn, path);
  9064. return -13;
  9065. }
  9066. len += ret;
  9067. ret = mg_read(conn, buf, sizeof(buf));
  9068. }
  9069. /* File is open for writing. If fclose fails, there was probably an
  9070. * error flushing the buffer to disk, so the file on disk might be
  9071. * broken. Delete it and return an error to the caller. */
  9072. if (mg_fclose(&fi.access) != 0) {
  9073. remove_bad_file(conn, path);
  9074. return -14;
  9075. }
  9076. return len;
  9077. }
  9078. #endif /* NO_FILESYSTEMS */
  9079. /* Parse a buffer:
  9080. * Forward the string pointer till the end of a word, then
  9081. * terminate it and forward till the begin of the next word.
  9082. */
  9083. static int
  9084. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9085. {
  9086. /* Forward until a space is found - use isgraph here */
  9087. /* See http://www.cplusplus.com/reference/cctype/ */
  9088. while (isgraph((unsigned char)**ppw)) {
  9089. (*ppw)++;
  9090. }
  9091. /* Check end of word */
  9092. if (eol) {
  9093. /* must be a end of line */
  9094. if ((**ppw != '\r') && (**ppw != '\n')) {
  9095. return -1;
  9096. }
  9097. } else {
  9098. /* must be a end of a word, but not a line */
  9099. if (**ppw != ' ') {
  9100. return -1;
  9101. }
  9102. }
  9103. /* Terminate and forward to the next word */
  9104. do {
  9105. **ppw = 0;
  9106. (*ppw)++;
  9107. } while (isspace((unsigned char)**ppw));
  9108. /* Check after term */
  9109. if (!eol) {
  9110. /* if it's not the end of line, there must be a next word */
  9111. if (!isgraph((unsigned char)**ppw)) {
  9112. return -1;
  9113. }
  9114. }
  9115. /* ok */
  9116. return 1;
  9117. }
  9118. /* Parse HTTP headers from the given buffer, advance buf pointer
  9119. * to the point where parsing stopped.
  9120. * All parameters must be valid pointers (not NULL).
  9121. * Return <0 on error. */
  9122. static int
  9123. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9124. {
  9125. int i;
  9126. int num_headers = 0;
  9127. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9128. char *dp = *buf;
  9129. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9130. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9131. dp++;
  9132. }
  9133. if (dp == *buf) {
  9134. /* End of headers reached. */
  9135. break;
  9136. }
  9137. /* Drop all spaces after header name before : */
  9138. while (*dp == ' ') {
  9139. *dp = 0;
  9140. dp++;
  9141. }
  9142. if (*dp != ':') {
  9143. /* This is not a valid field. */
  9144. return -1;
  9145. }
  9146. /* End of header key (*dp == ':') */
  9147. /* Truncate here and set the key name */
  9148. *dp = 0;
  9149. hdr[i].name = *buf;
  9150. /* Skip all spaces */
  9151. do {
  9152. dp++;
  9153. } while ((*dp == ' ') || (*dp == '\t'));
  9154. /* The rest of the line is the value */
  9155. hdr[i].value = dp;
  9156. /* Find end of line */
  9157. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9158. dp++;
  9159. };
  9160. /* eliminate \r */
  9161. if (*dp == '\r') {
  9162. *dp = 0;
  9163. dp++;
  9164. if (*dp != '\n') {
  9165. /* This is not a valid line. */
  9166. return -1;
  9167. }
  9168. }
  9169. /* here *dp is either 0 or '\n' */
  9170. /* in any case, we have a new header */
  9171. num_headers = i + 1;
  9172. if (*dp) {
  9173. *dp = 0;
  9174. dp++;
  9175. *buf = dp;
  9176. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9177. /* This is the end of the header */
  9178. break;
  9179. }
  9180. } else {
  9181. *buf = dp;
  9182. break;
  9183. }
  9184. }
  9185. return num_headers;
  9186. }
  9187. struct mg_http_method_info {
  9188. const char *name;
  9189. int request_has_body;
  9190. int response_has_body;
  9191. int is_safe;
  9192. int is_idempotent;
  9193. int is_cacheable;
  9194. };
  9195. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9196. static const struct mg_http_method_info http_methods[] = {
  9197. /* HTTP (RFC 2616) */
  9198. {"GET", 0, 1, 1, 1, 1},
  9199. {"POST", 1, 1, 0, 0, 0},
  9200. {"PUT", 1, 0, 0, 1, 0},
  9201. {"DELETE", 0, 0, 0, 1, 0},
  9202. {"HEAD", 0, 0, 1, 1, 1},
  9203. {"OPTIONS", 0, 0, 1, 1, 0},
  9204. {"CONNECT", 1, 1, 0, 0, 0},
  9205. /* TRACE method (RFC 2616) is not supported for security reasons */
  9206. /* PATCH method (RFC 5789) */
  9207. {"PATCH", 1, 0, 0, 0, 0},
  9208. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9209. /* WEBDAV (RFC 2518) */
  9210. {"PROPFIND", 0, 1, 1, 1, 0},
  9211. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9212. * Some PROPFIND results MAY be cached, with care,
  9213. * as there is no cache validation mechanism for
  9214. * most properties. This method is both safe and
  9215. * idempotent (see Section 9.1 of [RFC2616]). */
  9216. {"MKCOL", 0, 0, 0, 1, 0},
  9217. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9218. * When MKCOL is invoked without a request body,
  9219. * the newly created collection SHOULD have no
  9220. * members. A MKCOL request message may contain
  9221. * a message body. The precise behavior of a MKCOL
  9222. * request when the body is present is undefined,
  9223. * ... ==> We do not support MKCOL with body data.
  9224. * This method is idempotent, but not safe (see
  9225. * Section 9.1 of [RFC2616]). Responses to this
  9226. * method MUST NOT be cached. */
  9227. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9228. {"LOCK", 1, 1, 0, 0, 0},
  9229. {"UNLOCK", 1, 0, 0, 0, 0},
  9230. {"PROPPATCH", 1, 1, 0, 0, 0},
  9231. {"COPY", 1, 0, 0, 0, 0},
  9232. {"MOVE", 1, 1, 0, 0, 0},
  9233. /* Unsupported WEBDAV Methods: */
  9234. /* + 11 methods from RFC 3253 */
  9235. /* ORDERPATCH (RFC 3648) */
  9236. /* ACL (RFC 3744) */
  9237. /* SEARCH (RFC 5323) */
  9238. /* + MicroSoft extensions
  9239. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9240. /* REPORT method (RFC 3253) */
  9241. {"REPORT", 1, 1, 1, 1, 1},
  9242. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9243. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9244. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9245. * to be useful for REST in case a "GET request with body" is
  9246. * required. */
  9247. {NULL, 0, 0, 0, 0, 0}
  9248. /* end of list */
  9249. };
  9250. /* All method names */
  9251. static char *all_methods = NULL; /* Built by mg_init_library */
  9252. static const struct mg_http_method_info *
  9253. get_http_method_info(const char *method)
  9254. {
  9255. /* Check if the method is known to the server. The list of all known
  9256. * HTTP methods can be found here at
  9257. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9258. */
  9259. const struct mg_http_method_info *m = http_methods;
  9260. while (m->name) {
  9261. if (!strcmp(m->name, method)) {
  9262. return m;
  9263. }
  9264. m++;
  9265. }
  9266. return NULL;
  9267. }
  9268. static int
  9269. is_valid_http_method(const char *method)
  9270. {
  9271. return (get_http_method_info(method) != NULL);
  9272. }
  9273. /* Parse HTTP request, fill in mg_request_info structure.
  9274. * This function modifies the buffer by NUL-terminating
  9275. * HTTP request components, header names and header values.
  9276. * Parameters:
  9277. * buf (in/out): pointer to the HTTP header to parse and split
  9278. * len (in): length of HTTP header buffer
  9279. * re (out): parsed header as mg_request_info
  9280. * buf and ri must be valid pointers (not NULL), len>0.
  9281. * Returns <0 on error. */
  9282. static int
  9283. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9284. {
  9285. int request_length;
  9286. int init_skip = 0;
  9287. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9288. * remote_port */
  9289. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9290. NULL;
  9291. ri->num_headers = 0;
  9292. /* RFC says that all initial whitespaces should be ignored */
  9293. /* This included all leading \r and \n (isspace) */
  9294. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9295. while ((len > 0) && isspace((unsigned char)*buf)) {
  9296. buf++;
  9297. len--;
  9298. init_skip++;
  9299. }
  9300. if (len == 0) {
  9301. /* Incomplete request */
  9302. return 0;
  9303. }
  9304. /* Control characters are not allowed, including zero */
  9305. if (iscntrl((unsigned char)*buf)) {
  9306. return -1;
  9307. }
  9308. /* Find end of HTTP header */
  9309. request_length = get_http_header_len(buf, len);
  9310. if (request_length <= 0) {
  9311. return request_length;
  9312. }
  9313. buf[request_length - 1] = '\0';
  9314. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9315. return -1;
  9316. }
  9317. /* The first word has to be the HTTP method */
  9318. ri->request_method = buf;
  9319. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9320. return -1;
  9321. }
  9322. /* The second word is the URI */
  9323. ri->request_uri = buf;
  9324. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9325. return -1;
  9326. }
  9327. /* Next would be the HTTP version */
  9328. ri->http_version = buf;
  9329. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9330. return -1;
  9331. }
  9332. /* Check for a valid HTTP version key */
  9333. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9334. /* Invalid request */
  9335. return -1;
  9336. }
  9337. ri->http_version += 5;
  9338. /* Check for a valid http method */
  9339. if (!is_valid_http_method(ri->request_method)) {
  9340. return -1;
  9341. }
  9342. /* Parse all HTTP headers */
  9343. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9344. if (ri->num_headers < 0) {
  9345. /* Error while parsing headers */
  9346. return -1;
  9347. }
  9348. return request_length + init_skip;
  9349. }
  9350. static int
  9351. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9352. {
  9353. int response_length;
  9354. int init_skip = 0;
  9355. char *tmp, *tmp2;
  9356. long l;
  9357. /* Initialize elements. */
  9358. ri->http_version = ri->status_text = NULL;
  9359. ri->num_headers = ri->status_code = 0;
  9360. /* RFC says that all initial whitespaces should be ingored */
  9361. /* This included all leading \r and \n (isspace) */
  9362. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9363. while ((len > 0) && isspace((unsigned char)*buf)) {
  9364. buf++;
  9365. len--;
  9366. init_skip++;
  9367. }
  9368. if (len == 0) {
  9369. /* Incomplete request */
  9370. return 0;
  9371. }
  9372. /* Control characters are not allowed, including zero */
  9373. if (iscntrl((unsigned char)*buf)) {
  9374. return -1;
  9375. }
  9376. /* Find end of HTTP header */
  9377. response_length = get_http_header_len(buf, len);
  9378. if (response_length <= 0) {
  9379. return response_length;
  9380. }
  9381. buf[response_length - 1] = '\0';
  9382. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9383. return -1;
  9384. }
  9385. /* The first word is the HTTP version */
  9386. /* Check for a valid HTTP version key */
  9387. if (strncmp(buf, "HTTP/", 5) != 0) {
  9388. /* Invalid request */
  9389. return -1;
  9390. }
  9391. buf += 5;
  9392. if (!isgraph((unsigned char)buf[0])) {
  9393. /* Invalid request */
  9394. return -1;
  9395. }
  9396. ri->http_version = buf;
  9397. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9398. return -1;
  9399. }
  9400. /* The second word is the status as a number */
  9401. tmp = buf;
  9402. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9403. return -1;
  9404. }
  9405. l = strtol(tmp, &tmp2, 10);
  9406. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9407. /* Everything else but a 3 digit code is invalid */
  9408. return -1;
  9409. }
  9410. ri->status_code = (int)l;
  9411. /* The rest of the line is the status text */
  9412. ri->status_text = buf;
  9413. /* Find end of status text */
  9414. /* isgraph or isspace = isprint */
  9415. while (isprint((unsigned char)*buf)) {
  9416. buf++;
  9417. }
  9418. if ((*buf != '\r') && (*buf != '\n')) {
  9419. return -1;
  9420. }
  9421. /* Terminate string and forward buf to next line */
  9422. do {
  9423. *buf = 0;
  9424. buf++;
  9425. } while (isspace((unsigned char)*buf));
  9426. /* Parse all HTTP headers */
  9427. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9428. if (ri->num_headers < 0) {
  9429. /* Error while parsing headers */
  9430. return -1;
  9431. }
  9432. return response_length + init_skip;
  9433. }
  9434. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9435. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9436. * buffer (which marks the end of HTTP request). Buffer buf may already
  9437. * have some data. The length of the data is stored in nread.
  9438. * Upon every read operation, increase nread by the number of bytes read. */
  9439. static int
  9440. read_message(FILE *fp,
  9441. struct mg_connection *conn,
  9442. char *buf,
  9443. int bufsiz,
  9444. int *nread)
  9445. {
  9446. int request_len, n = 0;
  9447. struct timespec last_action_time;
  9448. double request_timeout;
  9449. if (!conn) {
  9450. return 0;
  9451. }
  9452. memset(&last_action_time, 0, sizeof(last_action_time));
  9453. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9454. /* value of request_timeout is in seconds, config in milliseconds */
  9455. request_timeout =
  9456. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9457. } else {
  9458. request_timeout =
  9459. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9460. / 1000.0;
  9461. }
  9462. if (conn->handled_requests > 0) {
  9463. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9464. request_timeout =
  9465. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9466. / 1000.0;
  9467. }
  9468. }
  9469. request_len = get_http_header_len(buf, *nread);
  9470. while (request_len == 0) {
  9471. /* Full request not yet received */
  9472. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9473. /* Server is to be stopped. */
  9474. return -1;
  9475. }
  9476. if (*nread >= bufsiz) {
  9477. /* Request too long */
  9478. return -2;
  9479. }
  9480. n = pull_inner(
  9481. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9482. if (n == -2) {
  9483. /* Receive error */
  9484. return -1;
  9485. }
  9486. /* update clock after every read request */
  9487. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9488. if (n > 0) {
  9489. *nread += n;
  9490. request_len = get_http_header_len(buf, *nread);
  9491. }
  9492. if ((request_len == 0) && (request_timeout >= 0)) {
  9493. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9494. > request_timeout) {
  9495. /* Timeout */
  9496. return -1;
  9497. }
  9498. }
  9499. }
  9500. return request_len;
  9501. }
  9502. #if !defined(NO_CGI) || !defined(NO_FILES)
  9503. static int
  9504. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9505. {
  9506. const char *expect;
  9507. char buf[MG_BUF_LEN];
  9508. int success = 0;
  9509. if (!conn) {
  9510. return 0;
  9511. }
  9512. expect = mg_get_header(conn, "Expect");
  9513. DEBUG_ASSERT(fp != NULL);
  9514. if (!fp) {
  9515. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9516. return 0;
  9517. }
  9518. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9519. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9520. */
  9521. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9522. } else {
  9523. if (expect != NULL) {
  9524. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9525. conn->status_code = 100;
  9526. } else {
  9527. conn->status_code = 200;
  9528. }
  9529. DEBUG_ASSERT(conn->consumed_content == 0);
  9530. if (conn->consumed_content != 0) {
  9531. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9532. return 0;
  9533. }
  9534. for (;;) {
  9535. int nread = mg_read(conn, buf, sizeof(buf));
  9536. if (nread <= 0) {
  9537. success = (nread == 0);
  9538. break;
  9539. }
  9540. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9541. break;
  9542. }
  9543. }
  9544. /* Each error code path in this function must send an error */
  9545. if (!success) {
  9546. /* NOTE: Maybe some data has already been sent. */
  9547. /* TODO (low): If some data has been sent, a correct error
  9548. * reply can no longer be sent, so just close the connection */
  9549. mg_send_http_error(conn, 500, "%s", "");
  9550. }
  9551. }
  9552. return success;
  9553. }
  9554. #endif
  9555. #if defined(USE_TIMERS)
  9556. #define TIMER_API static
  9557. #include "timer.inl"
  9558. #endif /* USE_TIMERS */
  9559. #if !defined(NO_CGI)
  9560. /* This structure helps to create an environment for the spawned CGI
  9561. * program.
  9562. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9563. * last element must be NULL.
  9564. * However, on Windows there is a requirement that all these
  9565. * VARIABLE=VALUE\0
  9566. * strings must reside in a contiguous buffer. The end of the buffer is
  9567. * marked by two '\0' characters.
  9568. * We satisfy both worlds: we create an envp array (which is vars), all
  9569. * entries are actually pointers inside buf. */
  9570. struct cgi_environment {
  9571. struct mg_connection *conn;
  9572. /* Data block */
  9573. char *buf; /* Environment buffer */
  9574. size_t buflen; /* Space available in buf */
  9575. size_t bufused; /* Space taken in buf */
  9576. /* Index block */
  9577. char **var; /* char **envp */
  9578. size_t varlen; /* Number of variables available in var */
  9579. size_t varused; /* Number of variables stored in var */
  9580. };
  9581. static void addenv(struct cgi_environment *env,
  9582. PRINTF_FORMAT_STRING(const char *fmt),
  9583. ...) PRINTF_ARGS(2, 3);
  9584. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9585. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9586. static void
  9587. addenv(struct cgi_environment *env, const char *fmt, ...)
  9588. {
  9589. size_t i, n, space;
  9590. int truncated = 0;
  9591. char *added;
  9592. va_list ap;
  9593. if ((env->varlen - env->varused) < 2) {
  9594. mg_cry_internal(env->conn,
  9595. "%s: Cannot register CGI variable [%s]",
  9596. __func__,
  9597. fmt);
  9598. return;
  9599. }
  9600. /* Calculate how much space is left in the buffer */
  9601. space = (env->buflen - env->bufused);
  9602. do {
  9603. /* Space for "\0\0" is always needed. */
  9604. if (space <= 2) {
  9605. /* Allocate new buffer */
  9606. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9607. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9608. if (!added) {
  9609. /* Out of memory */
  9610. mg_cry_internal(
  9611. env->conn,
  9612. "%s: Cannot allocate memory for CGI variable [%s]",
  9613. __func__,
  9614. fmt);
  9615. return;
  9616. }
  9617. /* Retarget pointers */
  9618. env->buf = added;
  9619. env->buflen = n;
  9620. for (i = 0, n = 0; i < env->varused; i++) {
  9621. env->var[i] = added + n;
  9622. n += strlen(added + n) + 1;
  9623. }
  9624. space = (env->buflen - env->bufused);
  9625. }
  9626. /* Make a pointer to the free space int the buffer */
  9627. added = env->buf + env->bufused;
  9628. /* Copy VARIABLE=VALUE\0 string into the free space */
  9629. va_start(ap, fmt);
  9630. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9631. va_end(ap);
  9632. /* Do not add truncated strings to the environment */
  9633. if (truncated) {
  9634. /* Reallocate the buffer */
  9635. space = 0;
  9636. }
  9637. } while (truncated);
  9638. /* Calculate number of bytes added to the environment */
  9639. n = strlen(added) + 1;
  9640. env->bufused += n;
  9641. /* Append a pointer to the added string into the envp array */
  9642. env->var[env->varused] = added;
  9643. env->varused++;
  9644. }
  9645. /* Return 0 on success, non-zero if an error occurs. */
  9646. static int
  9647. prepare_cgi_environment(struct mg_connection *conn,
  9648. const char *prog,
  9649. struct cgi_environment *env,
  9650. unsigned char cgi_config_idx)
  9651. {
  9652. const char *s;
  9653. struct vec var_vec;
  9654. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9655. int i, truncated, uri_len;
  9656. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9657. return -1;
  9658. }
  9659. env->conn = conn;
  9660. env->buflen = CGI_ENVIRONMENT_SIZE;
  9661. env->bufused = 0;
  9662. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9663. if (env->buf == NULL) {
  9664. mg_cry_internal(conn,
  9665. "%s: Not enough memory for environmental buffer",
  9666. __func__);
  9667. return -1;
  9668. }
  9669. env->varlen = MAX_CGI_ENVIR_VARS;
  9670. env->varused = 0;
  9671. env->var =
  9672. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9673. if (env->var == NULL) {
  9674. mg_cry_internal(conn,
  9675. "%s: Not enough memory for environmental variables",
  9676. __func__);
  9677. mg_free(env->buf);
  9678. return -1;
  9679. }
  9680. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9681. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9682. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9683. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9684. /* Prepare the environment block */
  9685. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9686. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9687. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9688. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9689. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9690. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9691. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9692. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9693. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9694. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9695. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9696. /* SCRIPT_NAME */
  9697. uri_len = (int)strlen(conn->request_info.local_uri);
  9698. if (conn->path_info == NULL) {
  9699. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9700. /* URI: /path_to_script/script.cgi */
  9701. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9702. } else {
  9703. /* URI: /path_to_script/ ... using index.cgi */
  9704. const char *index_file = strrchr(prog, '/');
  9705. if (index_file) {
  9706. addenv(env,
  9707. "SCRIPT_NAME=%s%s",
  9708. conn->request_info.local_uri,
  9709. index_file + 1);
  9710. }
  9711. }
  9712. } else {
  9713. /* URI: /path_to_script/script.cgi/path_info */
  9714. addenv(env,
  9715. "SCRIPT_NAME=%.*s",
  9716. uri_len - (int)strlen(conn->path_info),
  9717. conn->request_info.local_uri);
  9718. }
  9719. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9720. if (conn->path_info == NULL) {
  9721. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9722. } else {
  9723. addenv(env,
  9724. "PATH_TRANSLATED=%s%s",
  9725. conn->dom_ctx->config[DOCUMENT_ROOT],
  9726. conn->path_info);
  9727. }
  9728. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9729. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9730. addenv(env, "CONTENT_TYPE=%s", s);
  9731. }
  9732. if (conn->request_info.query_string != NULL) {
  9733. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9734. }
  9735. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9736. addenv(env, "CONTENT_LENGTH=%s", s);
  9737. }
  9738. if ((s = getenv("PATH")) != NULL) {
  9739. addenv(env, "PATH=%s", s);
  9740. }
  9741. if (conn->path_info != NULL) {
  9742. addenv(env, "PATH_INFO=%s", conn->path_info);
  9743. }
  9744. if (conn->status_code > 0) {
  9745. /* CGI error handler should show the status code */
  9746. addenv(env, "STATUS=%d", conn->status_code);
  9747. }
  9748. #if defined(_WIN32)
  9749. if ((s = getenv("COMSPEC")) != NULL) {
  9750. addenv(env, "COMSPEC=%s", s);
  9751. }
  9752. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9753. addenv(env, "SYSTEMROOT=%s", s);
  9754. }
  9755. if ((s = getenv("SystemDrive")) != NULL) {
  9756. addenv(env, "SystemDrive=%s", s);
  9757. }
  9758. if ((s = getenv("ProgramFiles")) != NULL) {
  9759. addenv(env, "ProgramFiles=%s", s);
  9760. }
  9761. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9762. addenv(env, "ProgramFiles(x86)=%s", s);
  9763. }
  9764. #else
  9765. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9766. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9767. }
  9768. #endif /* _WIN32 */
  9769. if ((s = getenv("PERLLIB")) != NULL) {
  9770. addenv(env, "PERLLIB=%s", s);
  9771. }
  9772. if (conn->request_info.remote_user != NULL) {
  9773. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9774. addenv(env, "%s", "AUTH_TYPE=Digest");
  9775. }
  9776. /* Add all headers as HTTP_* variables */
  9777. for (i = 0; i < conn->request_info.num_headers; i++) {
  9778. (void)mg_snprintf(conn,
  9779. &truncated,
  9780. http_var_name,
  9781. sizeof(http_var_name),
  9782. "HTTP_%s",
  9783. conn->request_info.http_headers[i].name);
  9784. if (truncated) {
  9785. mg_cry_internal(conn,
  9786. "%s: HTTP header variable too long [%s]",
  9787. __func__,
  9788. conn->request_info.http_headers[i].name);
  9789. continue;
  9790. }
  9791. /* Convert variable name into uppercase, and change - to _ */
  9792. for (p = http_var_name; *p != '\0'; p++) {
  9793. if (*p == '-') {
  9794. *p = '_';
  9795. }
  9796. *p = (char)toupper((unsigned char)*p);
  9797. }
  9798. addenv(env,
  9799. "%s=%s",
  9800. http_var_name,
  9801. conn->request_info.http_headers[i].value);
  9802. }
  9803. /* Add user-specified variables */
  9804. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9805. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9806. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9807. }
  9808. env->var[env->varused] = NULL;
  9809. env->buf[env->bufused] = '\0';
  9810. return 0;
  9811. }
  9812. /* Data for CGI process control: PID and number of references */
  9813. struct process_control_data {
  9814. pid_t pid;
  9815. ptrdiff_t references;
  9816. };
  9817. static int
  9818. abort_cgi_process(void *data)
  9819. {
  9820. /* Waitpid checks for child status and won't work for a pid that does
  9821. * not identify a child of the current process. Thus, if the pid is
  9822. * reused, we will not affect a different process. */
  9823. struct process_control_data *proc = (struct process_control_data *)data;
  9824. int status = 0;
  9825. ptrdiff_t refs;
  9826. pid_t ret_pid;
  9827. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9828. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9829. /* Stop child process */
  9830. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9831. kill(proc->pid, SIGABRT);
  9832. /* Wait until process is terminated (don't leave zombies) */
  9833. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9834. ;
  9835. } else {
  9836. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9837. }
  9838. /* Dec reference counter */
  9839. refs = mg_atomic_dec(&proc->references);
  9840. if (refs == 0) {
  9841. /* no more references - free data */
  9842. mg_free(data);
  9843. }
  9844. return 0;
  9845. }
  9846. /* Local (static) function assumes all arguments are valid. */
  9847. static void
  9848. handle_cgi_request(struct mg_connection *conn,
  9849. const char *prog,
  9850. unsigned char cgi_config_idx)
  9851. {
  9852. char *buf;
  9853. size_t buflen;
  9854. int headers_len, data_len, i, truncated;
  9855. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9856. const char *status, *status_text, *connection_state;
  9857. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9858. struct mg_request_info ri;
  9859. struct cgi_environment blk;
  9860. FILE *in = NULL, *out = NULL, *err = NULL;
  9861. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9862. pid_t pid = (pid_t)-1;
  9863. struct process_control_data *proc = NULL;
  9864. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  9865. int no_buffering = 0;
  9866. #if defined(USE_TIMERS)
  9867. double cgi_timeout;
  9868. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9869. /* Get timeout in seconds */
  9870. cgi_timeout =
  9871. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9872. } else {
  9873. cgi_timeout =
  9874. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9875. }
  9876. #endif
  9877. if (cfg_buffering != NULL) {
  9878. if (!mg_strcasecmp(cfg_buffering, "no")) {
  9879. no_buffering = 1;
  9880. }
  9881. }
  9882. buf = NULL;
  9883. buflen = conn->phys_ctx->max_request_size;
  9884. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9885. if (i != 0) {
  9886. blk.buf = NULL;
  9887. blk.var = NULL;
  9888. goto done;
  9889. }
  9890. /* CGI must be executed in its own directory. 'dir' must point to the
  9891. * directory containing executable program, 'p' must point to the
  9892. * executable program name relative to 'dir'. */
  9893. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9894. if (truncated) {
  9895. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9896. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9897. goto done;
  9898. }
  9899. if ((p = strrchr(dir, '/')) != NULL) {
  9900. *p++ = '\0';
  9901. } else {
  9902. dir[0] = '.';
  9903. dir[1] = '\0';
  9904. p = (char *)prog;
  9905. }
  9906. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9907. status = strerror(ERRNO);
  9908. mg_cry_internal(
  9909. conn,
  9910. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9911. prog,
  9912. status);
  9913. mg_send_http_error(conn,
  9914. 500,
  9915. "Error: Cannot create CGI pipe: %s",
  9916. status);
  9917. goto done;
  9918. }
  9919. proc = (struct process_control_data *)
  9920. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9921. if (proc == NULL) {
  9922. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9923. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9924. goto done;
  9925. }
  9926. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9927. pid = spawn_process(
  9928. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9929. if (pid == (pid_t)-1) {
  9930. status = strerror(ERRNO);
  9931. mg_cry_internal(
  9932. conn,
  9933. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9934. prog,
  9935. status);
  9936. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9937. mg_free(proc);
  9938. proc = NULL;
  9939. goto done;
  9940. }
  9941. /* Store data in shared process_control_data */
  9942. proc->pid = pid;
  9943. proc->references = 1;
  9944. #if defined(USE_TIMERS)
  9945. if (cgi_timeout > 0.0) {
  9946. proc->references = 2;
  9947. // Start a timer for CGI
  9948. timer_add(conn->phys_ctx,
  9949. cgi_timeout /* in seconds */,
  9950. 0.0,
  9951. 1,
  9952. abort_cgi_process,
  9953. (void *)proc,
  9954. NULL);
  9955. }
  9956. #endif
  9957. /* Parent closes only one side of the pipes.
  9958. * If we don't mark them as closed, close() attempt before
  9959. * return from this function throws an exception on Windows.
  9960. * Windows does not like when closed descriptor is closed again. */
  9961. (void)close(fdin[0]);
  9962. (void)close(fdout[1]);
  9963. (void)close(fderr[1]);
  9964. fdin[0] = fdout[1] = fderr[1] = -1;
  9965. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9966. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9967. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9968. status = strerror(ERRNO);
  9969. mg_cry_internal(conn,
  9970. "Error: CGI program \"%s\": Can not open fd: %s",
  9971. prog,
  9972. status);
  9973. mg_send_http_error(conn,
  9974. 500,
  9975. "Error: CGI can not open fd\nfdopen: %s",
  9976. status);
  9977. goto done;
  9978. }
  9979. setbuf(in, NULL);
  9980. setbuf(out, NULL);
  9981. setbuf(err, NULL);
  9982. fout.access.fp = out;
  9983. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9984. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9985. conn->content_len);
  9986. /* This is a POST/PUT request, or another request with body data. */
  9987. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9988. /* Error sending the body data */
  9989. mg_cry_internal(
  9990. conn,
  9991. "Error: CGI program \"%s\": Forward body data failed",
  9992. prog);
  9993. goto done;
  9994. }
  9995. }
  9996. /* Close so child gets an EOF. */
  9997. fclose(in);
  9998. in = NULL;
  9999. fdin[1] = -1;
  10000. /* Now read CGI reply into a buffer. We need to set correct
  10001. * status code, thus we need to see all HTTP headers first.
  10002. * Do not send anything back to client, until we buffer in all
  10003. * HTTP headers. */
  10004. data_len = 0;
  10005. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10006. if (buf == NULL) {
  10007. mg_send_http_error(conn,
  10008. 500,
  10009. "Error: Not enough memory for CGI buffer (%u bytes)",
  10010. (unsigned int)buflen);
  10011. mg_cry_internal(
  10012. conn,
  10013. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10014. "bytes)",
  10015. prog,
  10016. (unsigned int)buflen);
  10017. goto done;
  10018. }
  10019. DEBUG_TRACE("CGI: %s", "wait for response");
  10020. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10021. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10022. if (headers_len <= 0) {
  10023. /* Could not parse the CGI response. Check if some error message on
  10024. * stderr. */
  10025. i = pull_all(err, conn, buf, (int)buflen);
  10026. if (i > 0) {
  10027. /* CGI program explicitly sent an error */
  10028. /* Write the error message to the internal log */
  10029. mg_cry_internal(conn,
  10030. "Error: CGI program \"%s\" sent error "
  10031. "message: [%.*s]",
  10032. prog,
  10033. i,
  10034. buf);
  10035. /* Don't send the error message back to the client */
  10036. mg_send_http_error(conn,
  10037. 500,
  10038. "Error: CGI program \"%s\" failed.",
  10039. prog);
  10040. } else {
  10041. /* CGI program did not explicitly send an error, but a broken
  10042. * respon header */
  10043. mg_cry_internal(conn,
  10044. "Error: CGI program sent malformed or too big "
  10045. "(>%u bytes) HTTP headers: [%.*s]",
  10046. (unsigned)buflen,
  10047. data_len,
  10048. buf);
  10049. mg_send_http_error(conn,
  10050. 500,
  10051. "Error: CGI program sent malformed or too big "
  10052. "(>%u bytes) HTTP headers: [%.*s]",
  10053. (unsigned)buflen,
  10054. data_len,
  10055. buf);
  10056. }
  10057. /* in both cases, abort processing CGI */
  10058. goto done;
  10059. }
  10060. pbuf = buf;
  10061. buf[headers_len - 1] = '\0';
  10062. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10063. /* Make up and send the status line */
  10064. status_text = "OK";
  10065. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10066. != NULL) {
  10067. conn->status_code = atoi(status);
  10068. status_text = status;
  10069. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10070. status_text++;
  10071. }
  10072. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10073. != NULL) {
  10074. conn->status_code = 307;
  10075. } else {
  10076. conn->status_code = 200;
  10077. }
  10078. connection_state =
  10079. get_header(ri.http_headers, ri.num_headers, "Connection");
  10080. if (!header_has_option(connection_state, "keep-alive")) {
  10081. conn->must_close = 1;
  10082. }
  10083. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10084. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10085. /* Send headers */
  10086. for (i = 0; i < ri.num_headers; i++) {
  10087. DEBUG_TRACE("CGI header: %s: %s",
  10088. ri.http_headers[i].name,
  10089. ri.http_headers[i].value);
  10090. mg_printf(conn,
  10091. "%s: %s\r\n",
  10092. ri.http_headers[i].name,
  10093. ri.http_headers[i].value);
  10094. }
  10095. mg_write(conn, "\r\n", 2);
  10096. /* Send chunk of data that may have been read after the headers */
  10097. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10098. /* Read the rest of CGI output and send to the client */
  10099. DEBUG_TRACE("CGI: %s", "forward all data");
  10100. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10101. DEBUG_TRACE("CGI: %s", "all data sent");
  10102. done:
  10103. mg_free(blk.var);
  10104. mg_free(blk.buf);
  10105. if (pid != (pid_t)-1) {
  10106. abort_cgi_process((void *)proc);
  10107. }
  10108. if (fdin[0] != -1) {
  10109. close(fdin[0]);
  10110. }
  10111. if (fdout[1] != -1) {
  10112. close(fdout[1]);
  10113. }
  10114. if (fderr[1] != -1) {
  10115. close(fderr[1]);
  10116. }
  10117. if (in != NULL) {
  10118. fclose(in);
  10119. } else if (fdin[1] != -1) {
  10120. close(fdin[1]);
  10121. }
  10122. if (out != NULL) {
  10123. fclose(out);
  10124. } else if (fdout[0] != -1) {
  10125. close(fdout[0]);
  10126. }
  10127. if (err != NULL) {
  10128. fclose(err);
  10129. } else if (fderr[0] != -1) {
  10130. close(fderr[0]);
  10131. }
  10132. mg_free(buf);
  10133. }
  10134. #endif /* !NO_CGI */
  10135. #if !defined(NO_FILES)
  10136. static void
  10137. dav_mkcol(struct mg_connection *conn, const char *path)
  10138. {
  10139. int rc, body_len;
  10140. struct de de;
  10141. if (conn == NULL) {
  10142. return;
  10143. }
  10144. /* TODO (mid): Check the mg_send_http_error situations in this function
  10145. */
  10146. memset(&de.file, 0, sizeof(de.file));
  10147. if (!mg_stat(conn, path, &de.file)) {
  10148. mg_cry_internal(conn,
  10149. "%s: mg_stat(%s) failed: %s",
  10150. __func__,
  10151. path,
  10152. strerror(ERRNO));
  10153. }
  10154. if (de.file.last_modified) {
  10155. /* TODO (mid): This check does not seem to make any sense ! */
  10156. /* TODO (mid): Add a webdav unit test first, before changing
  10157. * anything here. */
  10158. mg_send_http_error(
  10159. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10160. return;
  10161. }
  10162. body_len = conn->data_len - conn->request_len;
  10163. if (body_len > 0) {
  10164. mg_send_http_error(
  10165. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10166. return;
  10167. }
  10168. rc = mg_mkdir(conn, path, 0755);
  10169. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10170. if (rc == 0) {
  10171. /* Create 201 "Created" response */
  10172. mg_response_header_start(conn, 201);
  10173. send_static_cache_header(conn);
  10174. send_additional_header(conn);
  10175. mg_response_header_add(conn, "Content-Length", "0", -1);
  10176. /* Send all headers - there is no body */
  10177. mg_response_header_send(conn);
  10178. } else {
  10179. int http_status = 500;
  10180. switch (errno) {
  10181. case EEXIST:
  10182. http_status = 405;
  10183. break;
  10184. case EACCES:
  10185. http_status = 403;
  10186. break;
  10187. case ENOENT:
  10188. http_status = 409;
  10189. break;
  10190. }
  10191. mg_send_http_error(conn,
  10192. http_status,
  10193. "Error processing %s: %s",
  10194. path,
  10195. strerror(ERRNO));
  10196. }
  10197. }
  10198. /* Forward decrlaration */
  10199. static int get_uri_type(const char *uri);
  10200. static const char *
  10201. get_rel_url_at_current_server(const char *uri,
  10202. const struct mg_connection *conn);
  10203. static void
  10204. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10205. {
  10206. const char *overwrite_hdr;
  10207. const char *destination_hdr;
  10208. const char *root;
  10209. int rc, dest_uri_type;
  10210. int http_status = 400;
  10211. int do_overwrite = 0;
  10212. int destination_ok = 0;
  10213. char dest_path[UTF8_PATH_MAX];
  10214. struct mg_file_stat ignored;
  10215. if (conn == NULL) {
  10216. return;
  10217. }
  10218. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10219. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10220. destination_hdr = mg_get_header(conn, "Destination");
  10221. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10222. do_overwrite = 1;
  10223. }
  10224. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10225. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10226. return;
  10227. }
  10228. if (root != NULL) {
  10229. char *local_dest = NULL;
  10230. dest_uri_type = get_uri_type(destination_hdr);
  10231. if (dest_uri_type == 2) {
  10232. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10233. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10234. const char *h =
  10235. get_rel_url_at_current_server(destination_hdr, conn);
  10236. if (h) {
  10237. int len = (int)strlen(h);
  10238. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10239. mg_url_decode(h, len, local_dest, len + 1, 0);
  10240. }
  10241. }
  10242. if (local_dest != NULL) {
  10243. remove_dot_segments(local_dest);
  10244. if (local_dest[0] == '/') {
  10245. int trunc_check = 0;
  10246. mg_snprintf(conn,
  10247. &trunc_check,
  10248. dest_path,
  10249. sizeof(dest_path),
  10250. "%s/%s",
  10251. root,
  10252. local_dest);
  10253. if (trunc_check == 0) {
  10254. destination_ok = 1;
  10255. }
  10256. }
  10257. mg_free(local_dest);
  10258. }
  10259. }
  10260. if (!destination_ok) {
  10261. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10262. return;
  10263. }
  10264. /* Check now if this file exists */
  10265. if (mg_stat(conn, dest_path, &ignored)) {
  10266. /* File exists */
  10267. if (do_overwrite) {
  10268. /* Overwrite allowed: delete the file first */
  10269. if (0 != remove(dest_path)) {
  10270. /* No overwrite: return error */
  10271. mg_send_http_error(conn,
  10272. 403,
  10273. "Cannot overwrite file: %s",
  10274. dest_path);
  10275. return;
  10276. }
  10277. } else {
  10278. /* No overwrite: return error */
  10279. mg_send_http_error(conn,
  10280. 412,
  10281. "Destination already exists: %s",
  10282. dest_path);
  10283. return;
  10284. }
  10285. }
  10286. /* Copy / Move / Rename operation. */
  10287. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10288. #if defined(_WIN32)
  10289. {
  10290. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10291. wchar_t wSource[UTF16_PATH_MAX];
  10292. wchar_t wDest[UTF16_PATH_MAX];
  10293. BOOL ok;
  10294. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10295. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10296. if (do_copy) {
  10297. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10298. } else {
  10299. ok = MoveFileExW(wSource,
  10300. wDest,
  10301. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10302. }
  10303. if (ok) {
  10304. rc = 0;
  10305. } else {
  10306. DWORD lastErr = GetLastError();
  10307. if (lastErr == ERROR_ALREADY_EXISTS) {
  10308. mg_send_http_error(conn,
  10309. 412,
  10310. "Destination already exists: %s",
  10311. dest_path);
  10312. return;
  10313. }
  10314. rc = -1;
  10315. http_status = 400;
  10316. }
  10317. }
  10318. #else
  10319. {
  10320. /* Linux uses already UTF-8, we don't need to convert file names. */
  10321. if (do_copy) {
  10322. /* TODO: COPY for Linux. */
  10323. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10324. return;
  10325. }
  10326. rc = rename(path, dest_path);
  10327. if (rc) {
  10328. switch (errno) {
  10329. case EEXIST:
  10330. http_status = 412;
  10331. break;
  10332. case EACCES:
  10333. http_status = 403;
  10334. break;
  10335. case ENOENT:
  10336. http_status = 409;
  10337. break;
  10338. }
  10339. }
  10340. }
  10341. #endif
  10342. if (rc == 0) {
  10343. /* Create 204 "No Content" response */
  10344. mg_response_header_start(conn, 204);
  10345. mg_response_header_add(conn, "Content-Length", "0", -1);
  10346. /* Send all headers - there is no body */
  10347. mg_response_header_send(conn);
  10348. } else {
  10349. mg_send_http_error(conn, http_status, "Operation failed");
  10350. }
  10351. }
  10352. static void
  10353. put_file(struct mg_connection *conn, const char *path)
  10354. {
  10355. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10356. const char *range;
  10357. int64_t r1, r2;
  10358. int rc;
  10359. if (conn == NULL) {
  10360. return;
  10361. }
  10362. DEBUG_TRACE("store %s", path);
  10363. if (mg_stat(conn, path, &file.stat)) {
  10364. /* File already exists */
  10365. conn->status_code = 200;
  10366. if (file.stat.is_directory) {
  10367. /* This is an already existing directory,
  10368. * so there is nothing to do for the server. */
  10369. rc = 0;
  10370. } else {
  10371. /* File exists and is not a directory. */
  10372. /* Can it be replaced? */
  10373. /* Check if the server may write this file */
  10374. if (access(path, W_OK) == 0) {
  10375. /* Access granted */
  10376. rc = 1;
  10377. } else {
  10378. mg_send_http_error(
  10379. conn,
  10380. 403,
  10381. "Error: Put not possible\nReplacing %s is not allowed",
  10382. path);
  10383. return;
  10384. }
  10385. }
  10386. } else {
  10387. /* File should be created */
  10388. conn->status_code = 201;
  10389. rc = put_dir(conn, path);
  10390. }
  10391. if (rc == 0) {
  10392. /* put_dir returns 0 if path is a directory */
  10393. /* Create response */
  10394. mg_response_header_start(conn, conn->status_code);
  10395. send_no_cache_header(conn);
  10396. send_additional_header(conn);
  10397. mg_response_header_add(conn, "Content-Length", "0", -1);
  10398. /* Send all headers - there is no body */
  10399. mg_response_header_send(conn);
  10400. /* Request to create a directory has been fulfilled successfully.
  10401. * No need to put a file. */
  10402. return;
  10403. }
  10404. if (rc == -1) {
  10405. /* put_dir returns -1 if the path is too long */
  10406. mg_send_http_error(conn,
  10407. 414,
  10408. "Error: Path too long\nput_dir(%s): %s",
  10409. path,
  10410. strerror(ERRNO));
  10411. return;
  10412. }
  10413. if (rc == -2) {
  10414. /* put_dir returns -2 if the directory can not be created */
  10415. mg_send_http_error(conn,
  10416. 500,
  10417. "Error: Can not create directory\nput_dir(%s): %s",
  10418. path,
  10419. strerror(ERRNO));
  10420. return;
  10421. }
  10422. /* A file should be created or overwritten. */
  10423. /* Currently CivetWeb does not nead read+write access. */
  10424. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10425. || file.access.fp == NULL) {
  10426. (void)mg_fclose(&file.access);
  10427. mg_send_http_error(conn,
  10428. 500,
  10429. "Error: Can not create file\nfopen(%s): %s",
  10430. path,
  10431. strerror(ERRNO));
  10432. return;
  10433. }
  10434. fclose_on_exec(&file.access, conn);
  10435. range = mg_get_header(conn, "Content-Range");
  10436. r1 = r2 = 0;
  10437. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10438. conn->status_code = 206; /* Partial content */
  10439. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10440. mg_send_http_error(conn,
  10441. 500,
  10442. "Error: Internal error processing file %s",
  10443. path);
  10444. return;
  10445. }
  10446. }
  10447. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10448. /* forward_body_data failed.
  10449. * The error code has already been sent to the client,
  10450. * and conn->status_code is already set. */
  10451. (void)mg_fclose(&file.access);
  10452. return;
  10453. }
  10454. if (mg_fclose(&file.access) != 0) {
  10455. /* fclose failed. This might have different reasons, but a likely
  10456. * one is "no space on disk", http 507. */
  10457. conn->status_code = 507;
  10458. }
  10459. /* Create response (status_code has been set before) */
  10460. mg_response_header_start(conn, conn->status_code);
  10461. send_no_cache_header(conn);
  10462. send_additional_header(conn);
  10463. mg_response_header_add(conn, "Content-Length", "0", -1);
  10464. /* Send all headers - there is no body */
  10465. mg_response_header_send(conn);
  10466. }
  10467. static void
  10468. delete_file(struct mg_connection *conn, const char *path)
  10469. {
  10470. struct de de;
  10471. memset(&de.file, 0, sizeof(de.file));
  10472. if (!mg_stat(conn, path, &de.file)) {
  10473. /* mg_stat returns 0 if the file does not exist */
  10474. mg_send_http_error(conn,
  10475. 404,
  10476. "Error: Cannot delete file\nFile %s not found",
  10477. path);
  10478. return;
  10479. }
  10480. DEBUG_TRACE("delete %s", path);
  10481. if (de.file.is_directory) {
  10482. if (remove_directory(conn, path)) {
  10483. /* Delete is successful: Return 204 without content. */
  10484. mg_send_http_error(conn, 204, "%s", "");
  10485. } else {
  10486. /* Delete is not successful: Return 500 (Server error). */
  10487. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10488. }
  10489. return;
  10490. }
  10491. /* This is an existing file (not a directory).
  10492. * Check if write permission is granted. */
  10493. if (access(path, W_OK) != 0) {
  10494. /* File is read only */
  10495. mg_send_http_error(
  10496. conn,
  10497. 403,
  10498. "Error: Delete not possible\nDeleting %s is not allowed",
  10499. path);
  10500. return;
  10501. }
  10502. /* Try to delete it. */
  10503. if (mg_remove(conn, path) == 0) {
  10504. /* Delete was successful: Return 204 without content. */
  10505. mg_response_header_start(conn, 204);
  10506. send_no_cache_header(conn);
  10507. send_additional_header(conn);
  10508. mg_response_header_add(conn, "Content-Length", "0", -1);
  10509. mg_response_header_send(conn);
  10510. } else {
  10511. /* Delete not successful (file locked). */
  10512. mg_send_http_error(conn,
  10513. 423,
  10514. "Error: Cannot delete file\nremove(%s): %s",
  10515. path,
  10516. strerror(ERRNO));
  10517. }
  10518. }
  10519. #endif /* !NO_FILES */
  10520. #if !defined(NO_FILESYSTEMS)
  10521. static void
  10522. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10523. static void
  10524. do_ssi_include(struct mg_connection *conn,
  10525. const char *ssi,
  10526. char *tag,
  10527. int include_level)
  10528. {
  10529. char file_name[MG_BUF_LEN], path[512], *p;
  10530. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10531. size_t len;
  10532. int truncated = 0;
  10533. if (conn == NULL) {
  10534. return;
  10535. }
  10536. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10537. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10538. * always < MG_BUF_LEN. */
  10539. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10540. /* File name is relative to the webserver root */
  10541. file_name[511] = 0;
  10542. (void)mg_snprintf(conn,
  10543. &truncated,
  10544. path,
  10545. sizeof(path),
  10546. "%s/%s",
  10547. conn->dom_ctx->config[DOCUMENT_ROOT],
  10548. file_name);
  10549. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10550. /* File name is relative to the webserver working directory
  10551. * or it is absolute system path */
  10552. file_name[511] = 0;
  10553. (void)
  10554. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10555. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10556. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10557. /* File name is relative to the currect document */
  10558. file_name[511] = 0;
  10559. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10560. if (!truncated) {
  10561. if ((p = strrchr(path, '/')) != NULL) {
  10562. p[1] = '\0';
  10563. }
  10564. len = strlen(path);
  10565. (void)mg_snprintf(conn,
  10566. &truncated,
  10567. path + len,
  10568. sizeof(path) - len,
  10569. "%s",
  10570. file_name);
  10571. }
  10572. } else {
  10573. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10574. return;
  10575. }
  10576. if (truncated) {
  10577. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10578. return;
  10579. }
  10580. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10581. mg_cry_internal(conn,
  10582. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10583. tag,
  10584. path,
  10585. strerror(ERRNO));
  10586. } else {
  10587. fclose_on_exec(&file.access, conn);
  10588. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10589. > 0) {
  10590. send_ssi_file(conn, path, &file, include_level + 1);
  10591. } else {
  10592. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10593. }
  10594. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10595. }
  10596. }
  10597. #if !defined(NO_POPEN)
  10598. static void
  10599. do_ssi_exec(struct mg_connection *conn, char *tag)
  10600. {
  10601. char cmd[1024] = "";
  10602. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10603. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10604. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10605. } else {
  10606. cmd[1023] = 0;
  10607. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10608. mg_cry_internal(conn,
  10609. "Cannot SSI #exec: [%s]: %s",
  10610. cmd,
  10611. strerror(ERRNO));
  10612. } else {
  10613. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10614. pclose(file.access.fp);
  10615. }
  10616. }
  10617. }
  10618. #endif /* !NO_POPEN */
  10619. static int
  10620. mg_fgetc(struct mg_file *filep)
  10621. {
  10622. if (filep == NULL) {
  10623. return EOF;
  10624. }
  10625. if (filep->access.fp != NULL) {
  10626. return fgetc(filep->access.fp);
  10627. } else {
  10628. return EOF;
  10629. }
  10630. }
  10631. static void
  10632. send_ssi_file(struct mg_connection *conn,
  10633. const char *path,
  10634. struct mg_file *filep,
  10635. int include_level)
  10636. {
  10637. char buf[MG_BUF_LEN];
  10638. int ch, len, in_tag, in_ssi_tag;
  10639. if (include_level > 10) {
  10640. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10641. return;
  10642. }
  10643. in_tag = in_ssi_tag = len = 0;
  10644. /* Read file, byte by byte, and look for SSI include tags */
  10645. while ((ch = mg_fgetc(filep)) != EOF) {
  10646. if (in_tag) {
  10647. /* We are in a tag, either SSI tag or html tag */
  10648. if (ch == '>') {
  10649. /* Tag is closing */
  10650. buf[len++] = '>';
  10651. if (in_ssi_tag) {
  10652. /* Handle SSI tag */
  10653. buf[len] = 0;
  10654. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10655. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10656. #if !defined(NO_POPEN)
  10657. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10658. do_ssi_exec(conn, buf + 9);
  10659. #endif /* !NO_POPEN */
  10660. } else {
  10661. mg_cry_internal(conn,
  10662. "%s: unknown SSI "
  10663. "command: \"%s\"",
  10664. path,
  10665. buf);
  10666. }
  10667. len = 0;
  10668. in_ssi_tag = in_tag = 0;
  10669. } else {
  10670. /* Not an SSI tag */
  10671. /* Flush buffer */
  10672. (void)mg_write(conn, buf, (size_t)len);
  10673. len = 0;
  10674. in_tag = 0;
  10675. }
  10676. } else {
  10677. /* Tag is still open */
  10678. buf[len++] = (char)(ch & 0xff);
  10679. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10680. /* All SSI tags start with <!--# */
  10681. in_ssi_tag = 1;
  10682. }
  10683. if ((len + 2) > (int)sizeof(buf)) {
  10684. /* Tag to long for buffer */
  10685. mg_cry_internal(conn, "%s: tag is too large", path);
  10686. return;
  10687. }
  10688. }
  10689. } else {
  10690. /* We are not in a tag yet. */
  10691. if (ch == '<') {
  10692. /* Tag is opening */
  10693. in_tag = 1;
  10694. if (len > 0) {
  10695. /* Flush current buffer.
  10696. * Buffer is filled with "len" bytes. */
  10697. (void)mg_write(conn, buf, (size_t)len);
  10698. }
  10699. /* Store the < */
  10700. len = 1;
  10701. buf[0] = '<';
  10702. } else {
  10703. /* No Tag */
  10704. /* Add data to buffer */
  10705. buf[len++] = (char)(ch & 0xff);
  10706. /* Flush if buffer is full */
  10707. if (len == (int)sizeof(buf)) {
  10708. mg_write(conn, buf, (size_t)len);
  10709. len = 0;
  10710. }
  10711. }
  10712. }
  10713. }
  10714. /* Send the rest of buffered data */
  10715. if (len > 0) {
  10716. mg_write(conn, buf, (size_t)len);
  10717. }
  10718. }
  10719. static void
  10720. handle_ssi_file_request(struct mg_connection *conn,
  10721. const char *path,
  10722. struct mg_file *filep)
  10723. {
  10724. char date[64];
  10725. time_t curtime = time(NULL);
  10726. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10727. return;
  10728. }
  10729. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10730. /* File exists (precondition for calling this function),
  10731. * but can not be opened by the server. */
  10732. mg_send_http_error(conn,
  10733. 500,
  10734. "Error: Cannot read file\nfopen(%s): %s",
  10735. path,
  10736. strerror(ERRNO));
  10737. } else {
  10738. /* Set "must_close" for HTTP/1.x, since we do not know the
  10739. * content length */
  10740. conn->must_close = 1;
  10741. gmt_time_string(date, sizeof(date), &curtime);
  10742. fclose_on_exec(&filep->access, conn);
  10743. /* 200 OK response */
  10744. mg_response_header_start(conn, 200);
  10745. send_no_cache_header(conn);
  10746. send_additional_header(conn);
  10747. send_cors_header(conn);
  10748. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10749. mg_response_header_send(conn);
  10750. /* Header sent, now send body */
  10751. send_ssi_file(conn, path, filep, 0);
  10752. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10753. }
  10754. }
  10755. #endif /* NO_FILESYSTEMS */
  10756. #if !defined(NO_FILES)
  10757. static void
  10758. send_options(struct mg_connection *conn)
  10759. {
  10760. if (!conn || !all_methods) {
  10761. return;
  10762. }
  10763. /* We do not set a "Cache-Control" header here, but leave the default.
  10764. * Since browsers do not send an OPTIONS request, we can not test the
  10765. * effect anyway. */
  10766. mg_response_header_start(conn, 200);
  10767. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10768. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10769. /* Use the same as before */
  10770. mg_response_header_add(conn, "Allow", all_methods, -1);
  10771. mg_response_header_add(conn, "DAV", "1", -1);
  10772. } else {
  10773. /* TODO: Check this later for HTTP/2 */
  10774. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10775. }
  10776. send_additional_header(conn);
  10777. mg_response_header_send(conn);
  10778. }
  10779. /* Writes PROPFIND properties for a collection element */
  10780. static int
  10781. print_props(struct mg_connection *conn,
  10782. const char *uri,
  10783. const char *name,
  10784. struct mg_file_stat *filep)
  10785. {
  10786. size_t i;
  10787. char mtime[64];
  10788. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10789. char *link_concat;
  10790. size_t link_concat_len;
  10791. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10792. return 0;
  10793. }
  10794. link_concat_len = strlen(uri) + strlen(name) + 1;
  10795. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  10796. if (!link_concat) {
  10797. return 0;
  10798. }
  10799. strcpy(link_concat, uri);
  10800. strcat(link_concat, name);
  10801. /* Get full link used in request */
  10802. mg_construct_local_link(
  10803. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  10804. /*
  10805. OutputDebugStringA("print_props:\n uri: ");
  10806. OutputDebugStringA(uri);
  10807. OutputDebugStringA("\n name: ");
  10808. OutputDebugStringA(name);
  10809. OutputDebugStringA("\n link: ");
  10810. OutputDebugStringA(link_buf);
  10811. OutputDebugStringA("\n");
  10812. */
  10813. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10814. mg_printf(conn,
  10815. "<d:response>"
  10816. "<d:href>%s</d:href>"
  10817. "<d:propstat>"
  10818. "<d:prop>"
  10819. "<d:resourcetype>%s</d:resourcetype>"
  10820. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10821. "<d:getlastmodified>%s</d:getlastmodified>"
  10822. "<d:lockdiscovery>",
  10823. link_buf,
  10824. filep->is_directory ? "<d:collection/>" : "",
  10825. filep->size,
  10826. mtime);
  10827. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10828. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10829. if (!strcmp(dav_lock[i].path, link_buf)) {
  10830. mg_printf(conn,
  10831. "<d:activelock>"
  10832. "<d:locktype><d:write/></d:locktype>"
  10833. "<d:lockscope><d:exclusive/></d:lockscope>"
  10834. "<d:depth>0</d:depth>"
  10835. "<d:owner>%s</d:owner>"
  10836. "<d:timeout>Second-%u</d:timeout>"
  10837. "<d:locktoken>"
  10838. "<d:href>%s</d:href>"
  10839. "</d:locktoken>"
  10840. "</d:activelock>\n",
  10841. dav_lock[i].user,
  10842. (unsigned)LOCK_DURATION_S,
  10843. dav_lock[i].token);
  10844. }
  10845. }
  10846. mg_printf(conn,
  10847. "</d:lockdiscovery>"
  10848. "</d:prop>"
  10849. "<d:status>HTTP/1.1 200 OK</d:status>"
  10850. "</d:propstat>"
  10851. "</d:response>\n");
  10852. mg_free(link_concat);
  10853. return 1;
  10854. }
  10855. static int
  10856. print_dav_dir_entry(struct de *de, void *data)
  10857. {
  10858. struct mg_connection *conn = (struct mg_connection *)data;
  10859. if (!de || !conn
  10860. || !print_props(
  10861. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10862. /* stop scan */
  10863. return 1;
  10864. }
  10865. return 0;
  10866. }
  10867. static void
  10868. handle_propfind(struct mg_connection *conn,
  10869. const char *path,
  10870. struct mg_file_stat *filep)
  10871. {
  10872. const char *depth = mg_get_header(conn, "Depth");
  10873. if (!conn || !path || !filep || !conn->dom_ctx) {
  10874. return;
  10875. }
  10876. /* return 207 "Multi-Status" */
  10877. conn->must_close = 1;
  10878. mg_response_header_start(conn, 207);
  10879. send_static_cache_header(conn);
  10880. send_additional_header(conn);
  10881. mg_response_header_add(conn,
  10882. "Content-Type",
  10883. "application/xml; charset=utf-8",
  10884. -1);
  10885. mg_response_header_send(conn);
  10886. /* Content */
  10887. mg_printf(conn,
  10888. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10889. "<d:multistatus xmlns:d='DAV:'>\n");
  10890. /* Print properties for the requested resource itself */
  10891. print_props(conn, conn->request_info.local_uri, "", filep);
  10892. /* If it is a directory, print directory entries too if Depth is not 0
  10893. */
  10894. if (filep->is_directory
  10895. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10896. "yes")
  10897. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10898. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10899. }
  10900. mg_printf(conn, "%s\n", "</d:multistatus>");
  10901. }
  10902. static void
  10903. dav_lock_file(struct mg_connection *conn, const char *path)
  10904. {
  10905. /* internal function - therefore conn is assumed to be valid */
  10906. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10907. uint64_t new_locktime;
  10908. int lock_index = -1;
  10909. int i;
  10910. uint64_t LOCK_DURATION_NS =
  10911. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  10912. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10913. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  10914. return;
  10915. }
  10916. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10917. /* const char *refresh = mg_get_header(conn, "If"); */
  10918. /* Link refresh should have an "If" header:
  10919. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  10920. * But it seems Windows Explorer does not send them.
  10921. */
  10922. mg_lock_context(conn->phys_ctx);
  10923. new_locktime = mg_get_current_time_ns();
  10924. /* Find a slot for a lock */
  10925. while (lock_index < 0) {
  10926. /* find existing lock */
  10927. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10928. if (!strcmp(dav_lock[i].path, link_buf)) {
  10929. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  10930. /* locked by the same user */
  10931. dav_lock[i].locktime = new_locktime;
  10932. lock_index = i;
  10933. break;
  10934. } else {
  10935. /* already locked by someone else */
  10936. if (new_locktime
  10937. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  10938. /* Lock expired */
  10939. dav_lock[i].path[0] = 0;
  10940. } else {
  10941. /* Lock still valid */
  10942. mg_unlock_context(conn->phys_ctx);
  10943. mg_send_http_error(conn, 423, "%s", "Already locked");
  10944. return;
  10945. }
  10946. }
  10947. }
  10948. }
  10949. /* create new lock token */
  10950. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10951. if (dav_lock[i].path[0] == 0) {
  10952. char s[32];
  10953. dav_lock[i].locktime = mg_get_current_time_ns();
  10954. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  10955. mg_md5(dav_lock[i].token,
  10956. link_buf,
  10957. "\x01",
  10958. s,
  10959. "\x01",
  10960. conn->request_info.remote_user,
  10961. NULL);
  10962. strncpy(dav_lock[i].path,
  10963. link_buf,
  10964. sizeof(dav_lock[i].path) - 1);
  10965. strncpy(dav_lock[i].user,
  10966. conn->request_info.remote_user,
  10967. sizeof(dav_lock[i].user) - 1);
  10968. lock_index = i;
  10969. break;
  10970. }
  10971. }
  10972. if (lock_index < 0) {
  10973. /* too many locks. Find oldest lock */
  10974. uint64_t oldest_locktime = dav_lock[0].locktime;
  10975. lock_index = 0;
  10976. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  10977. if (dav_lock[i].locktime < oldest_locktime) {
  10978. oldest_locktime = dav_lock[i].locktime;
  10979. lock_index = i;
  10980. }
  10981. }
  10982. /* invalidate oldest lock */
  10983. dav_lock[lock_index].path[0] = 0;
  10984. }
  10985. }
  10986. mg_unlock_context(conn->phys_ctx);
  10987. /* return 200 "OK" */
  10988. conn->must_close = 1;
  10989. mg_response_header_start(conn, 200);
  10990. send_static_cache_header(conn);
  10991. send_additional_header(conn);
  10992. mg_response_header_add(conn,
  10993. "Content-Type",
  10994. "application/xml; charset=utf-8",
  10995. -1);
  10996. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  10997. mg_response_header_send(conn);
  10998. /* Content */
  10999. mg_printf(conn,
  11000. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11001. "<d:prop xmlns:d=\"DAV:\">\n"
  11002. " <d:lockdiscovery>\n"
  11003. " <d:activelock>\n"
  11004. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11005. " <d:locktype><d:write/></d:locktype>\n"
  11006. " <d:owner>\n"
  11007. " <d:href>%s</d:href>\n"
  11008. " </d:owner>\n"
  11009. " <d:timeout>Second-%u</d:timeout>\n"
  11010. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11011. " <d:lockroot>\n"
  11012. " <d:href>%s</d:href>\n"
  11013. " </d:lockroot>\n"
  11014. " </d:activelock>\n"
  11015. " </d:lockdiscovery>\n"
  11016. " </d:prop>\n",
  11017. dav_lock[lock_index].user,
  11018. (LOCK_DURATION_S),
  11019. dav_lock[lock_index].token,
  11020. dav_lock[lock_index].path);
  11021. }
  11022. static void
  11023. dav_unlock_file(struct mg_connection *conn, const char *path)
  11024. {
  11025. /* internal function - therefore conn is assumed to be valid */
  11026. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11027. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11028. int lock_index;
  11029. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11030. return;
  11031. }
  11032. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11033. mg_lock_context(conn->phys_ctx);
  11034. /* find existing lock */
  11035. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11036. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11037. /* Success: return 204 "No Content" */
  11038. mg_unlock_context(conn->phys_ctx);
  11039. conn->must_close = 1;
  11040. mg_response_header_start(conn, 204);
  11041. mg_response_header_send(conn);
  11042. return;
  11043. }
  11044. }
  11045. mg_unlock_context(conn->phys_ctx);
  11046. /* Error: Cannot unlock a resource that is not locked */
  11047. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11048. }
  11049. static void
  11050. dav_proppatch(struct mg_connection *conn, const char *path)
  11051. {
  11052. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11053. if (!conn || !path || !conn->dom_ctx) {
  11054. return;
  11055. }
  11056. /* return 207 "Multi-Status" */
  11057. conn->must_close = 1;
  11058. mg_response_header_start(conn, 207);
  11059. send_static_cache_header(conn);
  11060. send_additional_header(conn);
  11061. mg_response_header_add(conn,
  11062. "Content-Type",
  11063. "application/xml; charset=utf-8",
  11064. -1);
  11065. mg_response_header_send(conn);
  11066. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11067. /* Content */
  11068. mg_printf(conn,
  11069. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11070. "<d:multistatus xmlns:d='DAV:'>\n"
  11071. "<d:response>\n<d:href>%s</d:href>\n",
  11072. link_buf);
  11073. mg_printf(conn,
  11074. "<d:propstat><d:status>HTTP/1.1 403 "
  11075. "Forbidden</d:status></d:propstat>\n");
  11076. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11077. }
  11078. #endif
  11079. CIVETWEB_API void
  11080. mg_lock_connection(struct mg_connection *conn)
  11081. {
  11082. if (conn) {
  11083. (void)pthread_mutex_lock(&conn->mutex);
  11084. }
  11085. }
  11086. CIVETWEB_API void
  11087. mg_unlock_connection(struct mg_connection *conn)
  11088. {
  11089. if (conn) {
  11090. (void)pthread_mutex_unlock(&conn->mutex);
  11091. }
  11092. }
  11093. CIVETWEB_API void
  11094. mg_lock_context(struct mg_context *ctx)
  11095. {
  11096. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11097. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11098. }
  11099. }
  11100. CIVETWEB_API void
  11101. mg_unlock_context(struct mg_context *ctx)
  11102. {
  11103. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11104. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11105. }
  11106. }
  11107. #if defined(USE_LUA)
  11108. #include "mod_lua.inl"
  11109. #endif /* USE_LUA */
  11110. #if defined(USE_DUKTAPE)
  11111. #include "mod_duktape.inl"
  11112. #endif /* USE_DUKTAPE */
  11113. #if defined(USE_WEBSOCKET)
  11114. #if !defined(NO_SSL_DL)
  11115. #define SHA_API static
  11116. #include "sha1.inl"
  11117. #endif
  11118. static int
  11119. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11120. {
  11121. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11122. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11123. size_t dst_len = sizeof(b64_sha);
  11124. int truncated;
  11125. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11126. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11127. if (truncated) {
  11128. conn->must_close = 1;
  11129. return 0;
  11130. }
  11131. DEBUG_TRACE("%s", "Send websocket handshake");
  11132. EVP_Digest((unsigned char *)buf, (uint32_t)strlen(buf), (unsigned char *)sha,
  11133. NULL, EVP_get_digestbyname("sha1"), NULL);
  11134. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11135. mg_printf(conn,
  11136. "HTTP/1.1 101 Switching Protocols\r\n"
  11137. "Upgrade: websocket\r\n"
  11138. "Connection: Upgrade\r\n"
  11139. "Sec-WebSocket-Accept: %s\r\n",
  11140. b64_sha);
  11141. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11142. // Send negotiated compression extension parameters
  11143. websocket_deflate_response(conn);
  11144. #endif
  11145. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11146. mg_printf(conn,
  11147. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11148. conn->request_info.acceptedWebSocketSubprotocol);
  11149. } else {
  11150. mg_printf(conn, "%s", "\r\n");
  11151. }
  11152. return 1;
  11153. }
  11154. #if !defined(MG_MAX_UNANSWERED_PING)
  11155. /* Configuration of the maximum number of websocket PINGs that might
  11156. * stay unanswered before the connection is considered broken.
  11157. * Note: The name of this define may still change (until it is
  11158. * defined as a compile parameter in a documentation).
  11159. */
  11160. #define MG_MAX_UNANSWERED_PING (5)
  11161. #endif
  11162. static void
  11163. read_websocket(struct mg_connection *conn,
  11164. mg_websocket_data_handler ws_data_handler,
  11165. void *callback_data)
  11166. {
  11167. /* Pointer to the beginning of the portion of the incoming websocket
  11168. * message queue.
  11169. * The original websocket upgrade request is never removed, so the queue
  11170. * begins after it. */
  11171. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11172. int n, error, exit_by_callback;
  11173. int ret;
  11174. /* body_len is the length of the entire queue in bytes
  11175. * len is the length of the current message
  11176. * data_len is the length of the current message's data payload
  11177. * header_len is the length of the current message's header */
  11178. size_t i, len, mask_len = 0, header_len, body_len;
  11179. uint64_t data_len = 0;
  11180. /* "The masking key is a 32-bit value chosen at random by the client."
  11181. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11182. */
  11183. unsigned char mask[4];
  11184. /* data points to the place where the message is stored when passed to
  11185. * the websocket_data callback. This is either mem on the stack, or a
  11186. * dynamically allocated buffer if it is too large. */
  11187. unsigned char mem[4096];
  11188. unsigned char mop; /* mask flag and opcode */
  11189. /* Variables used for connection monitoring */
  11190. double timeout = -1.0;
  11191. int enable_ping_pong = 0;
  11192. int ping_count = 0;
  11193. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11194. enable_ping_pong =
  11195. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11196. "yes");
  11197. }
  11198. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11199. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11200. }
  11201. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11202. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11203. }
  11204. if (timeout <= 0.0) {
  11205. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11206. }
  11207. /* Enter data processing loop */
  11208. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11209. conn->request_info.remote_addr,
  11210. conn->request_info.remote_port);
  11211. conn->in_websocket_handling = 1;
  11212. mg_set_thread_name("wsock");
  11213. /* Loop continuously, reading messages from the socket, invoking the
  11214. * callback, and waiting repeatedly until an error occurs. */
  11215. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11216. && (!conn->must_close)) {
  11217. header_len = 0;
  11218. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11219. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11220. len = buf[1] & 127;
  11221. mask_len = (buf[1] & 128) ? 4 : 0;
  11222. if ((len < 126) && (body_len >= mask_len)) {
  11223. /* inline 7-bit length field */
  11224. data_len = len;
  11225. header_len = 2 + mask_len;
  11226. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11227. /* 16-bit length field */
  11228. header_len = 4 + mask_len;
  11229. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11230. } else if (body_len >= (10 + mask_len)) {
  11231. /* 64-bit length field */
  11232. uint32_t l1, l2;
  11233. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11234. memcpy(&l2, &buf[6], 4);
  11235. header_len = 10 + mask_len;
  11236. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11237. if (data_len > (uint64_t)0x7FFF0000ul) {
  11238. /* no can do */
  11239. mg_cry_internal(
  11240. conn,
  11241. "%s",
  11242. "websocket out of memory; closing connection");
  11243. break;
  11244. }
  11245. }
  11246. }
  11247. if ((header_len > 0) && (body_len >= header_len)) {
  11248. /* Allocate space to hold websocket payload */
  11249. unsigned char *data = mem;
  11250. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11251. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11252. conn->phys_ctx);
  11253. if (data == NULL) {
  11254. /* Allocation failed, exit the loop and then close the
  11255. * connection */
  11256. mg_cry_internal(
  11257. conn,
  11258. "%s",
  11259. "websocket out of memory; closing connection");
  11260. break;
  11261. }
  11262. }
  11263. /* Copy the mask before we shift the queue and destroy it */
  11264. if (mask_len > 0) {
  11265. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11266. } else {
  11267. memset(mask, 0, sizeof(mask));
  11268. }
  11269. /* Read frame payload from the first message in the queue into
  11270. * data and advance the queue by moving the memory in place. */
  11271. DEBUG_ASSERT(body_len >= header_len);
  11272. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11273. mop = buf[0]; /* current mask and opcode */
  11274. /* Overflow case */
  11275. len = body_len - header_len;
  11276. memcpy(data, buf + header_len, len);
  11277. error = 0;
  11278. while ((uint64_t)len < data_len) {
  11279. n = pull_inner(NULL,
  11280. conn,
  11281. (char *)(data + len),
  11282. (int)(data_len - len),
  11283. timeout);
  11284. if (n <= -2) {
  11285. error = 1;
  11286. break;
  11287. } else if (n > 0) {
  11288. len += (size_t)n;
  11289. } else {
  11290. /* Timeout: should retry */
  11291. /* TODO: retry condition */
  11292. }
  11293. }
  11294. if (error) {
  11295. mg_cry_internal(
  11296. conn,
  11297. "%s",
  11298. "Websocket pull failed; closing connection");
  11299. if (data != mem) {
  11300. mg_free(data);
  11301. }
  11302. break;
  11303. }
  11304. conn->data_len = conn->request_len;
  11305. } else {
  11306. mop = buf[0]; /* current mask and opcode, overwritten by
  11307. * memmove() */
  11308. /* Length of the message being read at the front of the
  11309. * queue. Cast to 31 bit is OK, since we limited
  11310. * data_len before. */
  11311. len = (size_t)data_len + header_len;
  11312. /* Copy the data payload into the data pointer for the
  11313. * callback. Cast to 31 bit is OK, since we
  11314. * limited data_len */
  11315. memcpy(data, buf + header_len, (size_t)data_len);
  11316. /* Move the queue forward len bytes */
  11317. memmove(buf, buf + len, body_len - len);
  11318. /* Mark the queue as advanced */
  11319. conn->data_len -= (int)len;
  11320. }
  11321. /* Apply mask if necessary */
  11322. if (mask_len > 0) {
  11323. for (i = 0; i < (size_t)data_len; i++) {
  11324. data[i] ^= mask[i & 3];
  11325. }
  11326. }
  11327. exit_by_callback = 0;
  11328. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11329. /* filter PONG messages */
  11330. DEBUG_TRACE("PONG from %s:%u",
  11331. conn->request_info.remote_addr,
  11332. conn->request_info.remote_port);
  11333. /* No unanwered PINGs left */
  11334. ping_count = 0;
  11335. } else if (enable_ping_pong
  11336. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11337. /* reply PING messages */
  11338. DEBUG_TRACE("Reply PING from %s:%u",
  11339. conn->request_info.remote_addr,
  11340. conn->request_info.remote_port);
  11341. ret = mg_websocket_write(conn,
  11342. MG_WEBSOCKET_OPCODE_PONG,
  11343. (char *)data,
  11344. (size_t)data_len);
  11345. if (ret <= 0) {
  11346. /* Error: send failed */
  11347. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11348. break;
  11349. }
  11350. } else {
  11351. /* Exit the loop if callback signals to exit (server side),
  11352. * or "connection close" opcode received (client side). */
  11353. if (ws_data_handler != NULL) {
  11354. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11355. if (mop & 0x40) {
  11356. /* Inflate the data received if bit RSV1 is set. */
  11357. if (!conn->websocket_deflate_initialized) {
  11358. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11359. exit_by_callback = 1;
  11360. }
  11361. if (!exit_by_callback) {
  11362. size_t inflate_buf_size_old = 0;
  11363. size_t inflate_buf_size =
  11364. data_len
  11365. * 4; // Initial guess of the inflated message
  11366. // size. We double the memory when needed.
  11367. Bytef *inflated = NULL;
  11368. Bytef *new_mem = NULL;
  11369. conn->websocket_inflate_state.avail_in =
  11370. (uInt)(data_len + 4);
  11371. conn->websocket_inflate_state.next_in = data;
  11372. // Add trailing 0x00 0x00 0xff 0xff bytes
  11373. data[data_len] = '\x00';
  11374. data[data_len + 1] = '\x00';
  11375. data[data_len + 2] = '\xff';
  11376. data[data_len + 3] = '\xff';
  11377. do {
  11378. if (inflate_buf_size_old == 0) {
  11379. new_mem =
  11380. (Bytef *)mg_calloc(inflate_buf_size,
  11381. sizeof(Bytef));
  11382. } else {
  11383. inflate_buf_size *= 2;
  11384. new_mem =
  11385. (Bytef *)mg_realloc(inflated,
  11386. inflate_buf_size);
  11387. }
  11388. if (new_mem == NULL) {
  11389. mg_cry_internal(
  11390. conn,
  11391. "Out of memory: Cannot allocate "
  11392. "inflate buffer of %lu bytes",
  11393. (unsigned long)inflate_buf_size);
  11394. exit_by_callback = 1;
  11395. break;
  11396. }
  11397. inflated = new_mem;
  11398. conn->websocket_inflate_state.avail_out =
  11399. (uInt)(inflate_buf_size
  11400. - inflate_buf_size_old);
  11401. conn->websocket_inflate_state.next_out =
  11402. inflated + inflate_buf_size_old;
  11403. ret = inflate(&conn->websocket_inflate_state,
  11404. Z_SYNC_FLUSH);
  11405. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11406. || ret == Z_MEM_ERROR) {
  11407. mg_cry_internal(
  11408. conn,
  11409. "ZLIB inflate error: %i %s",
  11410. ret,
  11411. (conn->websocket_inflate_state.msg
  11412. ? conn->websocket_inflate_state.msg
  11413. : "<no error message>"));
  11414. exit_by_callback = 1;
  11415. break;
  11416. }
  11417. inflate_buf_size_old = inflate_buf_size;
  11418. } while (conn->websocket_inflate_state.avail_out
  11419. == 0);
  11420. inflate_buf_size -=
  11421. conn->websocket_inflate_state.avail_out;
  11422. if (!ws_data_handler(conn,
  11423. mop,
  11424. (char *)inflated,
  11425. inflate_buf_size,
  11426. callback_data)) {
  11427. exit_by_callback = 1;
  11428. }
  11429. mg_free(inflated);
  11430. }
  11431. } else
  11432. #endif
  11433. if (!ws_data_handler(conn,
  11434. mop,
  11435. (char *)data,
  11436. (size_t)data_len,
  11437. callback_data)) {
  11438. exit_by_callback = 1;
  11439. }
  11440. }
  11441. }
  11442. /* It a buffer has been allocated, free it again */
  11443. if (data != mem) {
  11444. mg_free(data);
  11445. }
  11446. if (exit_by_callback) {
  11447. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11448. conn->request_info.remote_addr,
  11449. conn->request_info.remote_port);
  11450. break;
  11451. }
  11452. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11453. /* Opcode == 8, connection close */
  11454. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11455. conn->request_info.remote_addr,
  11456. conn->request_info.remote_port);
  11457. break;
  11458. }
  11459. /* Not breaking the loop, process next websocket frame. */
  11460. } else {
  11461. /* Read from the socket into the next available location in the
  11462. * message queue. */
  11463. n = pull_inner(NULL,
  11464. conn,
  11465. conn->buf + conn->data_len,
  11466. conn->buf_size - conn->data_len,
  11467. timeout);
  11468. if (n <= -2) {
  11469. /* Error, no bytes read */
  11470. DEBUG_TRACE("PULL from %s:%u failed",
  11471. conn->request_info.remote_addr,
  11472. conn->request_info.remote_port);
  11473. break;
  11474. }
  11475. if (n > 0) {
  11476. conn->data_len += n;
  11477. /* Reset open PING count */
  11478. ping_count = 0;
  11479. } else {
  11480. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11481. && (!conn->must_close)) {
  11482. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11483. /* Stop sending PING */
  11484. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11485. "- closing connection",
  11486. ping_count,
  11487. conn->request_info.remote_addr,
  11488. conn->request_info.remote_port);
  11489. break;
  11490. }
  11491. if (enable_ping_pong) {
  11492. /* Send Websocket PING message */
  11493. DEBUG_TRACE("PING to %s:%u",
  11494. conn->request_info.remote_addr,
  11495. conn->request_info.remote_port);
  11496. ret = mg_websocket_write(conn,
  11497. MG_WEBSOCKET_OPCODE_PING,
  11498. NULL,
  11499. 0);
  11500. if (ret <= 0) {
  11501. /* Error: send failed */
  11502. DEBUG_TRACE("Send PING failed (%i)", ret);
  11503. break;
  11504. }
  11505. ping_count++;
  11506. }
  11507. }
  11508. /* Timeout: should retry */
  11509. /* TODO: get timeout def */
  11510. }
  11511. }
  11512. }
  11513. /* Leave data processing loop */
  11514. mg_set_thread_name("worker");
  11515. conn->in_websocket_handling = 0;
  11516. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11517. conn->request_info.remote_addr,
  11518. conn->request_info.remote_port);
  11519. }
  11520. static int
  11521. mg_websocket_write_exec(struct mg_connection *conn,
  11522. int opcode,
  11523. const char *data,
  11524. size_t dataLen,
  11525. uint32_t masking_key)
  11526. {
  11527. unsigned char header[14];
  11528. size_t headerLen;
  11529. int retval;
  11530. #if defined(GCC_DIAGNOSTIC)
  11531. /* Disable spurious conversion warning for GCC */
  11532. #pragma GCC diagnostic push
  11533. #pragma GCC diagnostic ignored "-Wconversion"
  11534. #endif
  11535. /* Note that POSIX/Winsock's send() is threadsafe
  11536. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11537. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11538. * push(), although that is only a problem if the packet is large or
  11539. * outgoing buffer is full). */
  11540. /* TODO: Check if this lock should be moved to user land.
  11541. * Currently the server sets this lock for websockets, but
  11542. * not for any other connection. It must be set for every
  11543. * conn read/written by more than one thread, no matter if
  11544. * it is a websocket or regular connection. */
  11545. (void)mg_lock_connection(conn);
  11546. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11547. size_t deflated_size = 0;
  11548. Bytef *deflated = 0;
  11549. // Deflate websocket messages over 100kb
  11550. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11551. if (use_deflate) {
  11552. if (!conn->websocket_deflate_initialized) {
  11553. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11554. return 0;
  11555. }
  11556. // Deflating the message
  11557. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11558. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11559. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11560. deflated_size = (size_t)compressBound((uLong)dataLen);
  11561. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11562. if (deflated == NULL) {
  11563. mg_cry_internal(
  11564. conn,
  11565. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11566. (unsigned long)deflated_size);
  11567. mg_unlock_connection(conn);
  11568. return -1;
  11569. }
  11570. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11571. conn->websocket_deflate_state.next_out = deflated;
  11572. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11573. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11574. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11575. } else
  11576. #endif
  11577. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11578. #if defined(GCC_DIAGNOSTIC)
  11579. #pragma GCC diagnostic pop
  11580. #endif
  11581. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11582. if (dataLen < 126) {
  11583. /* inline 7-bit length field */
  11584. header[1] = (unsigned char)dataLen;
  11585. headerLen = 2;
  11586. } else if (dataLen <= 0xFFFF) {
  11587. /* 16-bit length field */
  11588. uint16_t len = htons((uint16_t)dataLen);
  11589. header[1] = 126;
  11590. memcpy(header + 2, &len, 2);
  11591. headerLen = 4;
  11592. } else {
  11593. /* 64-bit length field */
  11594. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11595. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11596. header[1] = 127;
  11597. memcpy(header + 2, &len1, 4);
  11598. memcpy(header + 6, &len2, 4);
  11599. headerLen = 10;
  11600. }
  11601. if (masking_key) {
  11602. /* add mask */
  11603. header[1] |= 0x80;
  11604. memcpy(header + headerLen, &masking_key, 4);
  11605. headerLen += 4;
  11606. }
  11607. retval = mg_write(conn, header, headerLen);
  11608. if (retval != (int)headerLen) {
  11609. /* Did not send complete header */
  11610. retval = -1;
  11611. } else {
  11612. if (dataLen > 0) {
  11613. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11614. if (use_deflate) {
  11615. retval = mg_write(conn, deflated, dataLen);
  11616. mg_free(deflated);
  11617. } else
  11618. #endif
  11619. retval = mg_write(conn, data, dataLen);
  11620. }
  11621. /* if dataLen == 0, the header length (2) is returned */
  11622. }
  11623. /* TODO: Remove this unlock as well, when lock is removed. */
  11624. mg_unlock_connection(conn);
  11625. return retval;
  11626. }
  11627. CIVETWEB_API int
  11628. mg_websocket_write(struct mg_connection *conn,
  11629. int opcode,
  11630. const char *data,
  11631. size_t dataLen)
  11632. {
  11633. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11634. }
  11635. static void
  11636. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11637. {
  11638. size_t i = 0;
  11639. i = 0;
  11640. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11641. /* Convert in 32 bit words, if data is 4 byte aligned */
  11642. while (i < (in_len - 3)) {
  11643. *(uint32_t *)(void *)(out + i) =
  11644. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11645. i += 4;
  11646. }
  11647. }
  11648. if (i != in_len) {
  11649. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11650. while (i < in_len) {
  11651. *(uint8_t *)(void *)(out + i) =
  11652. *(uint8_t *)(void *)(in + i)
  11653. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11654. i++;
  11655. }
  11656. }
  11657. }
  11658. CIVETWEB_API int
  11659. mg_websocket_client_write(struct mg_connection *conn,
  11660. int opcode,
  11661. const char *data,
  11662. size_t dataLen)
  11663. {
  11664. int retval = -1;
  11665. char *masked_data =
  11666. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11667. uint32_t masking_key = 0;
  11668. if (masked_data == NULL) {
  11669. /* Return -1 in an error case */
  11670. mg_cry_internal(conn,
  11671. "%s",
  11672. "Cannot allocate buffer for masked websocket response: "
  11673. "Out of memory");
  11674. return -1;
  11675. }
  11676. do {
  11677. /* Get a masking key - but not 0 */
  11678. masking_key = (uint32_t)get_random();
  11679. } while (masking_key == 0);
  11680. mask_data(data, dataLen, masking_key, masked_data);
  11681. retval = mg_websocket_write_exec(
  11682. conn, opcode, masked_data, dataLen, masking_key);
  11683. mg_free(masked_data);
  11684. return retval;
  11685. }
  11686. static void
  11687. handle_websocket_request(struct mg_connection *conn,
  11688. const char *path,
  11689. int is_callback_resource,
  11690. struct mg_websocket_subprotocols *subprotocols,
  11691. mg_websocket_connect_handler ws_connect_handler,
  11692. mg_websocket_ready_handler ws_ready_handler,
  11693. mg_websocket_data_handler ws_data_handler,
  11694. mg_websocket_close_handler ws_close_handler,
  11695. void *cbData)
  11696. {
  11697. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11698. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11699. ptrdiff_t lua_websock = 0;
  11700. #if !defined(USE_LUA)
  11701. (void)path;
  11702. #endif
  11703. /* Step 1: Check websocket protocol version. */
  11704. /* Step 1.1: Check Sec-WebSocket-Key. */
  11705. if (!websock_key) {
  11706. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11707. * requires a Sec-WebSocket-Key header.
  11708. */
  11709. /* It could be the hixie draft version
  11710. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11711. */
  11712. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11713. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11714. char key3[8];
  11715. if ((key1 != NULL) && (key2 != NULL)) {
  11716. /* This version uses 8 byte body data in a GET request */
  11717. conn->content_len = 8;
  11718. if (8 == mg_read(conn, key3, 8)) {
  11719. /* This is the hixie version */
  11720. mg_send_http_error(conn,
  11721. 426,
  11722. "%s",
  11723. "Protocol upgrade to RFC 6455 required");
  11724. return;
  11725. }
  11726. }
  11727. /* This is an unknown version */
  11728. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11729. return;
  11730. }
  11731. /* Step 1.2: Check websocket protocol version. */
  11732. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11733. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11734. /* Reject wrong versions */
  11735. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11736. return;
  11737. }
  11738. /* Step 1.3: Could check for "Host", but we do not really nead this
  11739. * value for anything, so just ignore it. */
  11740. /* Step 2: If a callback is responsible, call it. */
  11741. if (is_callback_resource) {
  11742. /* Step 2.1 check and select subprotocol */
  11743. const char *protocols[64]; // max 64 headers
  11744. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11745. "Sec-WebSocket-Protocol",
  11746. protocols,
  11747. 64);
  11748. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11749. int headerNo, idx;
  11750. size_t len;
  11751. const char *sep, *curSubProtocol,
  11752. *acceptedWebSocketSubprotocol = NULL;
  11753. /* look for matching subprotocol */
  11754. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11755. /* There might be multiple headers ... */
  11756. const char *protocol = protocols[headerNo];
  11757. curSubProtocol = protocol;
  11758. /* ... and in every header there might be a , separated list */
  11759. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11760. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11761. curSubProtocol++;
  11762. sep = strchr(curSubProtocol, ',');
  11763. if (sep) {
  11764. len = (size_t)(sep - curSubProtocol);
  11765. } else {
  11766. len = strlen(curSubProtocol);
  11767. }
  11768. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11769. // COMPARE: curSubProtocol ==
  11770. // subprotocols->subprotocols[idx]
  11771. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11772. && (strncmp(curSubProtocol,
  11773. subprotocols->subprotocols[idx],
  11774. len)
  11775. == 0)) {
  11776. acceptedWebSocketSubprotocol =
  11777. subprotocols->subprotocols[idx];
  11778. break;
  11779. }
  11780. }
  11781. curSubProtocol += len;
  11782. }
  11783. }
  11784. conn->request_info.acceptedWebSocketSubprotocol =
  11785. acceptedWebSocketSubprotocol;
  11786. }
  11787. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11788. websocket_deflate_negotiate(conn);
  11789. #endif
  11790. if ((ws_connect_handler != NULL)
  11791. && (ws_connect_handler(conn, cbData) != 0)) {
  11792. /* C callback has returned non-zero, do not proceed with
  11793. * handshake.
  11794. */
  11795. /* Note that C callbacks are no longer called when Lua is
  11796. * responsible, so C can no longer filter callbacks for Lua. */
  11797. return;
  11798. }
  11799. }
  11800. #if defined(USE_LUA)
  11801. /* Step 3: No callback. Check if Lua is responsible. */
  11802. else {
  11803. /* Step 3.1: Check if Lua is responsible. */
  11804. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11805. lua_websock = match_prefix_strlen(
  11806. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11807. }
  11808. if (lua_websock > 0) {
  11809. /* Step 3.2: Lua is responsible: call it. */
  11810. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11811. if (!conn->lua_websocket_state) {
  11812. /* Lua rejected the new client */
  11813. return;
  11814. }
  11815. }
  11816. }
  11817. #endif
  11818. /* Step 4: Check if there is a responsible websocket handler. */
  11819. if (!is_callback_resource && !lua_websock) {
  11820. /* There is no callback, and Lua is not responsible either. */
  11821. /* Reply with a 404 Not Found. We are still at a standard
  11822. * HTTP request here, before the websocket handshake, so
  11823. * we can still send standard HTTP error replies. */
  11824. mg_send_http_error(conn, 404, "%s", "Not found");
  11825. return;
  11826. }
  11827. /* Step 5: The websocket connection has been accepted */
  11828. if (!send_websocket_handshake(conn, websock_key)) {
  11829. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11830. return;
  11831. }
  11832. /* Step 6: Call the ready handler */
  11833. if (is_callback_resource) {
  11834. if (ws_ready_handler != NULL) {
  11835. ws_ready_handler(conn, cbData);
  11836. }
  11837. #if defined(USE_LUA)
  11838. } else if (lua_websock) {
  11839. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11840. /* the ready handler returned false */
  11841. return;
  11842. }
  11843. #endif
  11844. }
  11845. /* Step 7: Enter the read loop */
  11846. if (is_callback_resource) {
  11847. read_websocket(conn, ws_data_handler, cbData);
  11848. #if defined(USE_LUA)
  11849. } else if (lua_websock) {
  11850. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11851. #endif
  11852. }
  11853. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11854. /* Step 8: Close the deflate & inflate buffers */
  11855. if (conn->websocket_deflate_initialized) {
  11856. deflateEnd(&conn->websocket_deflate_state);
  11857. inflateEnd(&conn->websocket_inflate_state);
  11858. }
  11859. #endif
  11860. /* Step 9: Call the close handler */
  11861. if (ws_close_handler) {
  11862. ws_close_handler(conn, cbData);
  11863. }
  11864. }
  11865. #endif /* !USE_WEBSOCKET */
  11866. /* Is upgrade request:
  11867. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11868. * 1 = upgrade to websocket
  11869. * 2 = upgrade to HTTP/2
  11870. * -1 = upgrade to unknown protocol
  11871. */
  11872. static int
  11873. should_switch_to_protocol(const struct mg_connection *conn)
  11874. {
  11875. const char *upgrade, *connection;
  11876. /* A websocket protocoll has the following HTTP headers:
  11877. *
  11878. * Connection: Upgrade
  11879. * Upgrade: Websocket
  11880. */
  11881. connection = mg_get_header(conn, "Connection");
  11882. if (connection == NULL) {
  11883. return PROTOCOL_TYPE_HTTP1;
  11884. }
  11885. if (!mg_strcasestr(connection, "upgrade")) {
  11886. return PROTOCOL_TYPE_HTTP1;
  11887. }
  11888. upgrade = mg_get_header(conn, "Upgrade");
  11889. if (upgrade == NULL) {
  11890. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11891. return -1;
  11892. }
  11893. /* Upgrade to ... */
  11894. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11895. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11896. * "Sec-WebSocket-Version" are also required.
  11897. * Don't check them here, since even an unsupported websocket protocol
  11898. * request still IS a websocket request (in contrast to a standard HTTP
  11899. * request). It will fail later in handle_websocket_request.
  11900. */
  11901. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11902. }
  11903. if (0 != mg_strcasestr(upgrade, "h2")) {
  11904. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11905. }
  11906. /* Upgrade to another protocol */
  11907. return -1;
  11908. }
  11909. static int
  11910. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11911. {
  11912. int n;
  11913. unsigned int a, b, c, d, slash;
  11914. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  11915. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  11916. // integer value, but function will not report conversion
  11917. // errors; consider using 'strtol' instead
  11918. slash = 32;
  11919. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  11920. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  11921. // an integer value, but function will not report conversion
  11922. // errors; consider using 'strtol' instead
  11923. n = 0;
  11924. }
  11925. }
  11926. if ((n > 0) && ((size_t)n == vec->len)) {
  11927. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11928. /* IPv4 format */
  11929. if (sa->sa.sa_family == AF_INET) {
  11930. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  11931. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11932. | ((uint32_t)c << 8) | (uint32_t)d;
  11933. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11934. return (ip & mask) == net;
  11935. }
  11936. return 0;
  11937. }
  11938. }
  11939. #if defined(USE_IPV6)
  11940. else {
  11941. char ad[50];
  11942. const char *p;
  11943. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11944. slash = 128;
  11945. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11946. n = 0;
  11947. }
  11948. }
  11949. if ((n <= 0) && no_strict) {
  11950. /* no square brackets? */
  11951. p = strchr(vec->ptr, '/');
  11952. if (p && (p < (vec->ptr + vec->len))) {
  11953. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11954. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11955. n += (int)(p - vec->ptr);
  11956. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11957. } else {
  11958. n = 0;
  11959. }
  11960. } else if (vec->len < sizeof(ad)) {
  11961. n = (int)vec->len;
  11962. slash = 128;
  11963. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11964. }
  11965. }
  11966. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11967. p = ad;
  11968. c = 0;
  11969. /* zone indexes are unsupported, at least two colons are needed */
  11970. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11971. if (*(p++) == ':') {
  11972. c++;
  11973. }
  11974. }
  11975. if ((*p == '\0') && (c >= 2)) {
  11976. struct sockaddr_in6 sin6;
  11977. unsigned int i;
  11978. /* for strict validation, an actual IPv6 argument is needed */
  11979. if (sa->sa.sa_family != AF_INET6) {
  11980. return 0;
  11981. }
  11982. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11983. /* IPv6 format */
  11984. for (i = 0; i < 16; i++) {
  11985. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11986. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11987. uint8_t mask = 0;
  11988. if (8 * i + 8 < slash) {
  11989. mask = 0xFFu;
  11990. } else if (8 * i < slash) {
  11991. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11992. }
  11993. if ((ip & mask) != net) {
  11994. return 0;
  11995. }
  11996. }
  11997. return 1;
  11998. }
  11999. }
  12000. }
  12001. }
  12002. #else
  12003. (void)no_strict;
  12004. #endif
  12005. /* malformed */
  12006. return -1;
  12007. }
  12008. static int
  12009. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12010. {
  12011. int throttle = 0;
  12012. struct vec vec, val;
  12013. char mult;
  12014. double v;
  12015. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12016. mult = ',';
  12017. if ((val.ptr == NULL)
  12018. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12019. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12020. // to an integer value, but function will not report
  12021. // conversion errors; consider using 'strtol' instead
  12022. || (v < 0)
  12023. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12024. && (mult != ','))) {
  12025. continue;
  12026. }
  12027. v *= (lowercase(&mult) == 'k')
  12028. ? 1024
  12029. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12030. if (vec.len == 1 && vec.ptr[0] == '*') {
  12031. throttle = (int)v;
  12032. } else {
  12033. int matched = parse_match_net(&vec, rsa, 0);
  12034. if (matched >= 0) {
  12035. /* a valid IP subnet */
  12036. if (matched) {
  12037. throttle = (int)v;
  12038. }
  12039. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12040. throttle = (int)v;
  12041. }
  12042. }
  12043. }
  12044. return throttle;
  12045. }
  12046. /* The mg_upload function is superseeded by mg_handle_form_request. */
  12047. #include "handle_form.inl"
  12048. static int
  12049. get_first_ssl_listener_index(const struct mg_context *ctx)
  12050. {
  12051. unsigned int i;
  12052. int idx = -1;
  12053. if (ctx) {
  12054. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12055. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12056. }
  12057. }
  12058. return idx;
  12059. }
  12060. /* Return host (without port) */
  12061. static void
  12062. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12063. {
  12064. const char *host_header =
  12065. get_header(ri->http_headers, ri->num_headers, "Host");
  12066. host->ptr = NULL;
  12067. host->len = 0;
  12068. if (host_header != NULL) {
  12069. const char *pos;
  12070. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12071. * is found. */
  12072. if (*host_header == '[') {
  12073. pos = strchr(host_header, ']');
  12074. if (!pos) {
  12075. /* Malformed hostname starts with '[', but no ']' found */
  12076. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12077. return;
  12078. }
  12079. /* terminate after ']' */
  12080. host->ptr = host_header;
  12081. host->len = (size_t)(pos + 1 - host_header);
  12082. } else {
  12083. /* Otherwise, a ':' separates hostname and port number */
  12084. pos = strchr(host_header, ':');
  12085. if (pos != NULL) {
  12086. host->len = (size_t)(pos - host_header);
  12087. } else {
  12088. host->len = strlen(host_header);
  12089. }
  12090. host->ptr = host_header;
  12091. }
  12092. }
  12093. }
  12094. static int
  12095. switch_domain_context(struct mg_connection *conn)
  12096. {
  12097. struct vec host;
  12098. get_host_from_request_info(&host, &conn->request_info);
  12099. if (host.ptr) {
  12100. if (conn->ssl) {
  12101. /* This is a HTTPS connection, maybe we have a hostname
  12102. * from SNI (set in ssl_servername_callback). */
  12103. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12104. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12105. /* We are not using the default domain */
  12106. if ((strlen(sslhost) != host.len)
  12107. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12108. /* Mismatch between SNI domain and HTTP domain */
  12109. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12110. sslhost,
  12111. (int)host.len,
  12112. host.ptr);
  12113. return 0;
  12114. }
  12115. }
  12116. } else {
  12117. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12118. while (dom) {
  12119. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12120. size_t domNameLen = strlen(domName);
  12121. if ((domNameLen == host.len)
  12122. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12123. /* Found matching domain */
  12124. DEBUG_TRACE("HTTP domain %s found",
  12125. dom->config[AUTHENTICATION_DOMAIN]);
  12126. /* TODO: Check if this is a HTTP or HTTPS domain */
  12127. conn->dom_ctx = dom;
  12128. break;
  12129. }
  12130. mg_lock_context(conn->phys_ctx);
  12131. dom = dom->next;
  12132. mg_unlock_context(conn->phys_ctx);
  12133. }
  12134. }
  12135. DEBUG_TRACE("HTTP%s Host: %.*s",
  12136. conn->ssl ? "S" : "",
  12137. (int)host.len,
  12138. host.ptr);
  12139. } else {
  12140. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12141. return 1;
  12142. }
  12143. return 1;
  12144. }
  12145. static void
  12146. redirect_to_https_port(struct mg_connection *conn, int port)
  12147. {
  12148. char target_url[MG_BUF_LEN];
  12149. int truncated = 0;
  12150. const char *expect_proto =
  12151. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12152. /* Use "308 Permanent Redirect" */
  12153. int redirect_code = 308;
  12154. /* In any case, close the current connection */
  12155. conn->must_close = 1;
  12156. /* Send host, port, uri and (if it exists) ?query_string */
  12157. if (mg_construct_local_link(
  12158. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12159. < 0) {
  12160. truncated = 1;
  12161. } else if (conn->request_info.query_string != NULL) {
  12162. size_t slen1 = strlen(target_url);
  12163. size_t slen2 = strlen(conn->request_info.query_string);
  12164. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12165. target_url[slen1] = '?';
  12166. memcpy(target_url + slen1 + 1,
  12167. conn->request_info.query_string,
  12168. slen2);
  12169. target_url[slen1 + slen2 + 1] = 0;
  12170. } else {
  12171. truncated = 1;
  12172. }
  12173. }
  12174. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12175. * is used as buffer size) */
  12176. if (truncated) {
  12177. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12178. return;
  12179. }
  12180. /* Use redirect helper function */
  12181. mg_send_http_redirect(conn, target_url, redirect_code);
  12182. }
  12183. static void
  12184. mg_set_handler_type(struct mg_context *phys_ctx,
  12185. struct mg_domain_context *dom_ctx,
  12186. const char *uri,
  12187. int handler_type,
  12188. int is_delete_request,
  12189. mg_request_handler handler,
  12190. struct mg_websocket_subprotocols *subprotocols,
  12191. mg_websocket_connect_handler connect_handler,
  12192. mg_websocket_ready_handler ready_handler,
  12193. mg_websocket_data_handler data_handler,
  12194. mg_websocket_close_handler close_handler,
  12195. mg_authorization_handler auth_handler,
  12196. void *cbdata)
  12197. {
  12198. struct mg_handler_info *tmp_rh, **lastref;
  12199. size_t urilen = strlen(uri);
  12200. if (handler_type == WEBSOCKET_HANDLER) {
  12201. DEBUG_ASSERT(handler == NULL);
  12202. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12203. || ready_handler != NULL || data_handler != NULL
  12204. || close_handler != NULL);
  12205. DEBUG_ASSERT(auth_handler == NULL);
  12206. if (handler != NULL) {
  12207. return;
  12208. }
  12209. if (!is_delete_request && (connect_handler == NULL)
  12210. && (ready_handler == NULL) && (data_handler == NULL)
  12211. && (close_handler == NULL)) {
  12212. return;
  12213. }
  12214. if (auth_handler != NULL) {
  12215. return;
  12216. }
  12217. } else if (handler_type == REQUEST_HANDLER) {
  12218. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12219. && data_handler == NULL && close_handler == NULL);
  12220. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12221. DEBUG_ASSERT(auth_handler == NULL);
  12222. if ((connect_handler != NULL) || (ready_handler != NULL)
  12223. || (data_handler != NULL) || (close_handler != NULL)) {
  12224. return;
  12225. }
  12226. if (!is_delete_request && (handler == NULL)) {
  12227. return;
  12228. }
  12229. if (auth_handler != NULL) {
  12230. return;
  12231. }
  12232. } else if (handler_type == AUTH_HANDLER) {
  12233. DEBUG_ASSERT(handler == NULL);
  12234. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12235. && data_handler == NULL && close_handler == NULL);
  12236. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12237. if (handler != NULL) {
  12238. return;
  12239. }
  12240. if ((connect_handler != NULL) || (ready_handler != NULL)
  12241. || (data_handler != NULL) || (close_handler != NULL)) {
  12242. return;
  12243. }
  12244. if (!is_delete_request && (auth_handler == NULL)) {
  12245. return;
  12246. }
  12247. } else {
  12248. /* Unknown handler type. */
  12249. return;
  12250. }
  12251. if (!phys_ctx || !dom_ctx) {
  12252. /* no context available */
  12253. return;
  12254. }
  12255. mg_lock_context(phys_ctx);
  12256. /* first try to find an existing handler */
  12257. do {
  12258. lastref = &(dom_ctx->handlers);
  12259. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12260. tmp_rh = tmp_rh->next) {
  12261. if (tmp_rh->handler_type == handler_type
  12262. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12263. if (!is_delete_request) {
  12264. /* update existing handler */
  12265. if (handler_type == REQUEST_HANDLER) {
  12266. /* Wait for end of use before updating */
  12267. if (tmp_rh->refcount) {
  12268. mg_unlock_context(phys_ctx);
  12269. mg_sleep(1);
  12270. mg_lock_context(phys_ctx);
  12271. /* tmp_rh might have been freed, search again. */
  12272. break;
  12273. }
  12274. /* Ok, the handler is no more use -> Update it */
  12275. tmp_rh->handler = handler;
  12276. } else if (handler_type == WEBSOCKET_HANDLER) {
  12277. tmp_rh->subprotocols = subprotocols;
  12278. tmp_rh->connect_handler = connect_handler;
  12279. tmp_rh->ready_handler = ready_handler;
  12280. tmp_rh->data_handler = data_handler;
  12281. tmp_rh->close_handler = close_handler;
  12282. } else { /* AUTH_HANDLER */
  12283. tmp_rh->auth_handler = auth_handler;
  12284. }
  12285. tmp_rh->cbdata = cbdata;
  12286. } else {
  12287. /* remove existing handler */
  12288. if (handler_type == REQUEST_HANDLER) {
  12289. /* Wait for end of use before removing */
  12290. if (tmp_rh->refcount) {
  12291. tmp_rh->removing = 1;
  12292. mg_unlock_context(phys_ctx);
  12293. mg_sleep(1);
  12294. mg_lock_context(phys_ctx);
  12295. /* tmp_rh might have been freed, search again. */
  12296. break;
  12297. }
  12298. /* Ok, the handler is no more used */
  12299. }
  12300. *lastref = tmp_rh->next;
  12301. mg_free(tmp_rh->uri);
  12302. mg_free(tmp_rh);
  12303. }
  12304. mg_unlock_context(phys_ctx);
  12305. return;
  12306. }
  12307. lastref = &(tmp_rh->next);
  12308. }
  12309. } while (tmp_rh != NULL);
  12310. if (is_delete_request) {
  12311. /* no handler to set, this was a remove request to a non-existing
  12312. * handler */
  12313. mg_unlock_context(phys_ctx);
  12314. return;
  12315. }
  12316. tmp_rh =
  12317. (struct mg_handler_info *)mg_calloc_ctx(1,
  12318. sizeof(struct mg_handler_info),
  12319. phys_ctx);
  12320. if (tmp_rh == NULL) {
  12321. mg_unlock_context(phys_ctx);
  12322. mg_cry_ctx_internal(phys_ctx,
  12323. "%s",
  12324. "Cannot create new request handler struct, OOM");
  12325. return;
  12326. }
  12327. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12328. if (!tmp_rh->uri) {
  12329. mg_unlock_context(phys_ctx);
  12330. mg_free(tmp_rh);
  12331. mg_cry_ctx_internal(phys_ctx,
  12332. "%s",
  12333. "Cannot create new request handler struct, OOM");
  12334. return;
  12335. }
  12336. tmp_rh->uri_len = urilen;
  12337. if (handler_type == REQUEST_HANDLER) {
  12338. tmp_rh->refcount = 0;
  12339. tmp_rh->removing = 0;
  12340. tmp_rh->handler = handler;
  12341. } else if (handler_type == WEBSOCKET_HANDLER) {
  12342. tmp_rh->subprotocols = subprotocols;
  12343. tmp_rh->connect_handler = connect_handler;
  12344. tmp_rh->ready_handler = ready_handler;
  12345. tmp_rh->data_handler = data_handler;
  12346. tmp_rh->close_handler = close_handler;
  12347. } else { /* AUTH_HANDLER */
  12348. tmp_rh->auth_handler = auth_handler;
  12349. }
  12350. tmp_rh->cbdata = cbdata;
  12351. tmp_rh->handler_type = handler_type;
  12352. tmp_rh->next = NULL;
  12353. *lastref = tmp_rh;
  12354. mg_unlock_context(phys_ctx);
  12355. }
  12356. CIVETWEB_API void
  12357. mg_set_request_handler(struct mg_context *ctx,
  12358. const char *uri,
  12359. mg_request_handler handler,
  12360. void *cbdata)
  12361. {
  12362. mg_set_handler_type(ctx,
  12363. &(ctx->dd),
  12364. uri,
  12365. REQUEST_HANDLER,
  12366. handler == NULL,
  12367. handler,
  12368. NULL,
  12369. NULL,
  12370. NULL,
  12371. NULL,
  12372. NULL,
  12373. NULL,
  12374. cbdata);
  12375. }
  12376. CIVETWEB_API void
  12377. mg_set_websocket_handler(struct mg_context *ctx,
  12378. const char *uri,
  12379. mg_websocket_connect_handler connect_handler,
  12380. mg_websocket_ready_handler ready_handler,
  12381. mg_websocket_data_handler data_handler,
  12382. mg_websocket_close_handler close_handler,
  12383. void *cbdata)
  12384. {
  12385. mg_set_websocket_handler_with_subprotocols(ctx,
  12386. uri,
  12387. NULL,
  12388. connect_handler,
  12389. ready_handler,
  12390. data_handler,
  12391. close_handler,
  12392. cbdata);
  12393. }
  12394. CIVETWEB_API void
  12395. mg_set_websocket_handler_with_subprotocols(
  12396. struct mg_context *ctx,
  12397. const char *uri,
  12398. struct mg_websocket_subprotocols *subprotocols,
  12399. mg_websocket_connect_handler connect_handler,
  12400. mg_websocket_ready_handler ready_handler,
  12401. mg_websocket_data_handler data_handler,
  12402. mg_websocket_close_handler close_handler,
  12403. void *cbdata)
  12404. {
  12405. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12406. && (data_handler == NULL)
  12407. && (close_handler == NULL);
  12408. mg_set_handler_type(ctx,
  12409. &(ctx->dd),
  12410. uri,
  12411. WEBSOCKET_HANDLER,
  12412. is_delete_request,
  12413. NULL,
  12414. subprotocols,
  12415. connect_handler,
  12416. ready_handler,
  12417. data_handler,
  12418. close_handler,
  12419. NULL,
  12420. cbdata);
  12421. }
  12422. CIVETWEB_API void
  12423. mg_set_auth_handler(struct mg_context *ctx,
  12424. const char *uri,
  12425. mg_authorization_handler handler,
  12426. void *cbdata)
  12427. {
  12428. mg_set_handler_type(ctx,
  12429. &(ctx->dd),
  12430. uri,
  12431. AUTH_HANDLER,
  12432. handler == NULL,
  12433. NULL,
  12434. NULL,
  12435. NULL,
  12436. NULL,
  12437. NULL,
  12438. NULL,
  12439. handler,
  12440. cbdata);
  12441. }
  12442. static int
  12443. get_request_handler(struct mg_connection *conn,
  12444. int handler_type,
  12445. mg_request_handler *handler,
  12446. struct mg_websocket_subprotocols **subprotocols,
  12447. mg_websocket_connect_handler *connect_handler,
  12448. mg_websocket_ready_handler *ready_handler,
  12449. mg_websocket_data_handler *data_handler,
  12450. mg_websocket_close_handler *close_handler,
  12451. mg_authorization_handler *auth_handler,
  12452. void **cbdata,
  12453. struct mg_handler_info **handler_info)
  12454. {
  12455. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12456. if (request_info) {
  12457. const char *uri = request_info->local_uri;
  12458. size_t urilen = strlen(uri);
  12459. struct mg_handler_info *tmp_rh;
  12460. int step, matched;
  12461. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12462. return 0;
  12463. }
  12464. mg_lock_context(conn->phys_ctx);
  12465. for (step = 0; step < 3; step++) {
  12466. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12467. tmp_rh = tmp_rh->next) {
  12468. if (tmp_rh->handler_type != handler_type) {
  12469. continue;
  12470. }
  12471. if (step == 0) {
  12472. /* first try for an exact match */
  12473. matched = (tmp_rh->uri_len == urilen)
  12474. && (strcmp(tmp_rh->uri, uri) == 0);
  12475. } else if (step == 1) {
  12476. /* next try for a partial match, we will accept
  12477. uri/something */
  12478. matched =
  12479. (tmp_rh->uri_len < urilen)
  12480. && (uri[tmp_rh->uri_len] == '/')
  12481. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12482. } else {
  12483. /* finally try for pattern match */
  12484. matched =
  12485. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12486. }
  12487. if (matched) {
  12488. if (handler_type == WEBSOCKET_HANDLER) {
  12489. *subprotocols = tmp_rh->subprotocols;
  12490. *connect_handler = tmp_rh->connect_handler;
  12491. *ready_handler = tmp_rh->ready_handler;
  12492. *data_handler = tmp_rh->data_handler;
  12493. *close_handler = tmp_rh->close_handler;
  12494. } else if (handler_type == REQUEST_HANDLER) {
  12495. if (tmp_rh->removing) {
  12496. /* Treat as none found */
  12497. step = 2;
  12498. break;
  12499. }
  12500. *handler = tmp_rh->handler;
  12501. /* Acquire handler and give it back */
  12502. tmp_rh->refcount++;
  12503. *handler_info = tmp_rh;
  12504. } else { /* AUTH_HANDLER */
  12505. *auth_handler = tmp_rh->auth_handler;
  12506. }
  12507. *cbdata = tmp_rh->cbdata;
  12508. mg_unlock_context(conn->phys_ctx);
  12509. return 1;
  12510. }
  12511. }
  12512. }
  12513. mg_unlock_context(conn->phys_ctx);
  12514. }
  12515. return 0; /* none found */
  12516. }
  12517. /* Check if the script file is in a path, allowed for script files.
  12518. * This can be used if uploading files is possible not only for the server
  12519. * admin, and the upload mechanism does not check the file extension.
  12520. */
  12521. static int
  12522. is_in_script_path(const struct mg_connection *conn, const char *path)
  12523. {
  12524. /* TODO (Feature): Add config value for allowed script path.
  12525. * Default: All allowed. */
  12526. (void)conn;
  12527. (void)path;
  12528. return 1;
  12529. }
  12530. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12531. static int
  12532. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12533. int bits,
  12534. char *data,
  12535. size_t len,
  12536. void *cbdata)
  12537. {
  12538. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12539. if (pcallbacks->websocket_data) {
  12540. return pcallbacks->websocket_data(conn, bits, data, len);
  12541. }
  12542. /* No handler set - assume "OK" */
  12543. return 1;
  12544. }
  12545. static void
  12546. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12547. void *cbdata)
  12548. {
  12549. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12550. if (pcallbacks->connection_close) {
  12551. pcallbacks->connection_close(conn);
  12552. }
  12553. }
  12554. #endif
  12555. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12556. */
  12557. static void
  12558. release_handler_ref(struct mg_connection *conn,
  12559. struct mg_handler_info *handler_info)
  12560. {
  12561. if (handler_info != NULL) {
  12562. /* Use context lock for ref counter */
  12563. mg_lock_context(conn->phys_ctx);
  12564. handler_info->refcount--;
  12565. mg_unlock_context(conn->phys_ctx);
  12566. }
  12567. }
  12568. /* This is the heart of the Civetweb's logic.
  12569. * This function is called when the request is read, parsed and validated,
  12570. * and Civetweb must decide what action to take: serve a file, or
  12571. * a directory, or call embedded function, etcetera. */
  12572. static void
  12573. handle_request(struct mg_connection *conn)
  12574. {
  12575. struct mg_request_info *ri = &conn->request_info;
  12576. char path[UTF8_PATH_MAX];
  12577. int uri_len, ssl_index;
  12578. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12579. is_put_or_delete_request = 0, is_callback_resource = 0,
  12580. is_template_text_file = 0, is_webdav_request = 0;
  12581. int i;
  12582. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12583. mg_request_handler callback_handler = NULL;
  12584. struct mg_handler_info *handler_info = NULL;
  12585. struct mg_websocket_subprotocols *subprotocols;
  12586. mg_websocket_connect_handler ws_connect_handler = NULL;
  12587. mg_websocket_ready_handler ws_ready_handler = NULL;
  12588. mg_websocket_data_handler ws_data_handler = NULL;
  12589. mg_websocket_close_handler ws_close_handler = NULL;
  12590. void *callback_data = NULL;
  12591. mg_authorization_handler auth_handler = NULL;
  12592. void *auth_callback_data = NULL;
  12593. int handler_type;
  12594. time_t curtime = time(NULL);
  12595. char date[64];
  12596. char *tmp;
  12597. path[0] = 0;
  12598. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12599. conn->request_state = 0;
  12600. /* 1. get the request url */
  12601. /* 1.1. split into url and query string */
  12602. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12603. != NULL) {
  12604. *((char *)conn->request_info.query_string++) = '\0';
  12605. }
  12606. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12607. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12608. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12609. if (ssl_index >= 0) {
  12610. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12611. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12612. redirect_to_https_port(conn, port);
  12613. } else {
  12614. /* A http to https forward port has been specified,
  12615. * but no https port to forward to. */
  12616. mg_send_http_error(conn,
  12617. 503,
  12618. "%s",
  12619. "Error: SSL forward not configured properly");
  12620. mg_cry_internal(conn,
  12621. "%s",
  12622. "Can not redirect to SSL, no SSL port available");
  12623. }
  12624. return;
  12625. }
  12626. uri_len = (int)strlen(ri->local_uri);
  12627. /* 1.3. decode url (if config says so) */
  12628. if (should_decode_url(conn)) {
  12629. url_decode_in_place((char *)ri->local_uri);
  12630. }
  12631. /* URL decode the query-string only if explicity set in the configuration */
  12632. if (conn->request_info.query_string) {
  12633. if (should_decode_query_string(conn)) {
  12634. url_decode_in_place((char *)conn->request_info.query_string);
  12635. }
  12636. }
  12637. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12638. * possible. The fact that we cleaned the URI is stored in that the
  12639. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12640. * ri->local_uri_raw still points to memory allocated in
  12641. * worker_thread_run(). ri->local_uri is private to the request so we
  12642. * don't have to use preallocated memory here. */
  12643. tmp = mg_strdup(ri->local_uri_raw);
  12644. if (!tmp) {
  12645. /* Out of memory. We cannot do anything reasonable here. */
  12646. return;
  12647. }
  12648. remove_dot_segments(tmp);
  12649. ri->local_uri = tmp;
  12650. /* step 1. completed, the url is known now */
  12651. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12652. /* 2. if this ip has limited speed, set it for this connection */
  12653. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12654. &conn->client.rsa,
  12655. ri->local_uri);
  12656. /* 3. call a "handle everything" callback, if registered */
  12657. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12658. /* Note that since V1.7 the "begin_request" function is called
  12659. * before an authorization check. If an authorization check is
  12660. * required, use a request_handler instead. */
  12661. i = conn->phys_ctx->callbacks.begin_request(conn);
  12662. if (i > 0) {
  12663. /* callback already processed the request. Store the
  12664. return value as a status code for the access log. */
  12665. conn->status_code = i;
  12666. if (!conn->must_close) {
  12667. discard_unread_request_data(conn);
  12668. }
  12669. DEBUG_TRACE("%s", "begin_request handled request");
  12670. return;
  12671. } else if (i == 0) {
  12672. /* civetweb should process the request */
  12673. } else {
  12674. /* unspecified - may change with the next version */
  12675. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12676. return;
  12677. }
  12678. }
  12679. /* request not yet handled by a handler or redirect, so the request
  12680. * is processed here */
  12681. /* 4. Check for CORS preflight requests and handle them (if configured).
  12682. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12683. */
  12684. if (!strcmp(ri->request_method, "OPTIONS")) {
  12685. /* Send a response to CORS preflights only if
  12686. * access_control_allow_methods is not NULL and not an empty string.
  12687. * In this case, scripts can still handle CORS. */
  12688. const char *cors_meth_cfg =
  12689. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12690. const char *cors_orig_cfg =
  12691. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12692. const char *cors_origin =
  12693. get_header(ri->http_headers, ri->num_headers, "Origin");
  12694. const char *cors_acrm = get_header(ri->http_headers,
  12695. ri->num_headers,
  12696. "Access-Control-Request-Method");
  12697. /* Todo: check if cors_origin is in cors_orig_cfg.
  12698. * Or, let the client check this. */
  12699. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12700. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12701. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12702. /* This is a valid CORS preflight, and the server is configured
  12703. * to handle it automatically. */
  12704. const char *cors_acrh =
  12705. get_header(ri->http_headers,
  12706. ri->num_headers,
  12707. "Access-Control-Request-Headers");
  12708. gmt_time_string(date, sizeof(date), &curtime);
  12709. mg_printf(conn,
  12710. "HTTP/1.1 200 OK\r\n"
  12711. "Date: %s\r\n"
  12712. "Access-Control-Allow-Origin: %s\r\n"
  12713. "Access-Control-Allow-Methods: %s\r\n"
  12714. "Content-Length: 0\r\n"
  12715. "Connection: %s\r\n",
  12716. date,
  12717. cors_orig_cfg,
  12718. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12719. suggest_connection_header(conn));
  12720. if (cors_acrh != NULL) {
  12721. /* CORS request is asking for additional headers */
  12722. const char *cors_hdr_cfg =
  12723. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12724. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12725. /* Allow only if access_control_allow_headers is
  12726. * not NULL and not an empty string. If this
  12727. * configuration is set to *, allow everything.
  12728. * Otherwise this configuration must be a list
  12729. * of allowed HTTP header names. */
  12730. mg_printf(conn,
  12731. "Access-Control-Allow-Headers: %s\r\n",
  12732. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12733. : cors_hdr_cfg));
  12734. }
  12735. }
  12736. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12737. mg_printf(conn, "\r\n");
  12738. DEBUG_TRACE("%s", "OPTIONS done");
  12739. return;
  12740. }
  12741. }
  12742. /* 5. interpret the url to find out how the request must be handled
  12743. */
  12744. /* 5.1. first test, if the request targets the regular http(s)://
  12745. * protocol namespace or the websocket ws(s):// protocol namespace.
  12746. */
  12747. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12748. #if defined(USE_WEBSOCKET)
  12749. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12750. #else
  12751. handler_type = REQUEST_HANDLER;
  12752. #endif /* defined(USE_WEBSOCKET) */
  12753. if (is_websocket_request) {
  12754. HTTP1_only;
  12755. }
  12756. /* 5.2. check if the request will be handled by a callback */
  12757. if (get_request_handler(conn,
  12758. handler_type,
  12759. &callback_handler,
  12760. &subprotocols,
  12761. &ws_connect_handler,
  12762. &ws_ready_handler,
  12763. &ws_data_handler,
  12764. &ws_close_handler,
  12765. NULL,
  12766. &callback_data,
  12767. &handler_info)) {
  12768. /* 5.2.1. A callback will handle this request. All requests
  12769. * handled by a callback have to be considered as requests
  12770. * to a script resource. */
  12771. is_callback_resource = 1;
  12772. is_script_resource = 1;
  12773. is_put_or_delete_request = is_put_or_delete_method(conn);
  12774. /* Never handle a C callback according to File WebDav rules,
  12775. * even if it is a webdav method */
  12776. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12777. } else {
  12778. no_callback_resource:
  12779. /* 5.2.2. No callback is responsible for this request. The URI
  12780. * addresses a file based resource (static content or Lua/cgi
  12781. * scripts in the file system). */
  12782. is_callback_resource = 0;
  12783. interpret_uri(conn,
  12784. path,
  12785. sizeof(path),
  12786. &file.stat,
  12787. &is_found,
  12788. &is_script_resource,
  12789. &is_websocket_request,
  12790. &is_put_or_delete_request,
  12791. &is_webdav_request,
  12792. &is_template_text_file);
  12793. }
  12794. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12795. if (is_webdav_request) {
  12796. /* TODO: Do we need a config option? */
  12797. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  12798. if (webdav_enable[0] != 'y') {
  12799. mg_send_http_error(conn,
  12800. 405,
  12801. "%s method not allowed",
  12802. conn->request_info.request_method);
  12803. DEBUG_TRACE("%s", "webdav rejected");
  12804. return;
  12805. }
  12806. }
  12807. /* 6. authorization check */
  12808. /* 6.1. a custom authorization handler is installed */
  12809. if (get_request_handler(conn,
  12810. AUTH_HANDLER,
  12811. NULL,
  12812. NULL,
  12813. NULL,
  12814. NULL,
  12815. NULL,
  12816. NULL,
  12817. &auth_handler,
  12818. &auth_callback_data,
  12819. NULL)) {
  12820. if (!auth_handler(conn, auth_callback_data)) {
  12821. /* Callback handler will not be used anymore. Release it */
  12822. release_handler_ref(conn, handler_info);
  12823. DEBUG_TRACE("%s", "auth handler rejected request");
  12824. return;
  12825. }
  12826. } else if (is_put_or_delete_request && !is_script_resource
  12827. && !is_callback_resource) {
  12828. HTTP1_only;
  12829. /* 6.2. this request is a PUT/DELETE to a real file */
  12830. /* 6.2.1. thus, the server must have real files */
  12831. #if defined(NO_FILES)
  12832. if (1) {
  12833. #else
  12834. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12835. #endif
  12836. /* This code path will not be called for request handlers */
  12837. DEBUG_ASSERT(handler_info == NULL);
  12838. /* This server does not have any real files, thus the
  12839. * PUT/DELETE methods are not valid. */
  12840. mg_send_http_error(conn,
  12841. 405,
  12842. "%s method not allowed",
  12843. conn->request_info.request_method);
  12844. DEBUG_TRACE("%s", "all file based requests rejected");
  12845. return;
  12846. }
  12847. #if !defined(NO_FILES)
  12848. /* 6.2.2. Check if put authorization for static files is
  12849. * available.
  12850. */
  12851. if (!is_authorized_for_put(conn)) {
  12852. send_authorization_request(conn, NULL);
  12853. DEBUG_TRACE("%s", "file write needs authorization");
  12854. return;
  12855. }
  12856. #endif
  12857. } else {
  12858. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12859. * or it is a PUT or DELETE request to a resource that does not
  12860. * correspond to a file. Check authorization. */
  12861. if (!check_authorization(conn, path)) {
  12862. send_authorization_request(conn, NULL);
  12863. /* Callback handler will not be used anymore. Release it */
  12864. release_handler_ref(conn, handler_info);
  12865. DEBUG_TRACE("%s", "access authorization required");
  12866. return;
  12867. }
  12868. }
  12869. /* request is authorized or does not need authorization */
  12870. /* 7. check if there are request handlers for this uri */
  12871. if (is_callback_resource) {
  12872. HTTP1_only;
  12873. if (!is_websocket_request) {
  12874. i = callback_handler(conn, callback_data);
  12875. /* Callback handler will not be used anymore. Release it */
  12876. release_handler_ref(conn, handler_info);
  12877. if (i > 0) {
  12878. /* Do nothing, callback has served the request. Store
  12879. * then return value as status code for the log and discard
  12880. * all data from the client not used by the callback. */
  12881. conn->status_code = i;
  12882. if (!conn->must_close) {
  12883. discard_unread_request_data(conn);
  12884. }
  12885. } else {
  12886. /* The handler did NOT handle the request. */
  12887. /* Some proper reactions would be:
  12888. * a) close the connections without sending anything
  12889. * b) send a 404 not found
  12890. * c) try if there is a file matching the URI
  12891. * It would be possible to do a, b or c in the callback
  12892. * implementation, and return 1 - we cannot do anything
  12893. * here, that is not possible in the callback.
  12894. *
  12895. * TODO: What would be the best reaction here?
  12896. * (Note: The reaction may change, if there is a better
  12897. * idea.)
  12898. */
  12899. /* For the moment, use option c: We look for a proper file,
  12900. * but since a file request is not always a script resource,
  12901. * the authorization check might be different. */
  12902. callback_handler = NULL;
  12903. /* Here we are at a dead end:
  12904. * According to URI matching, a callback should be
  12905. * responsible for handling the request,
  12906. * we called it, but the callback declared itself
  12907. * not responsible.
  12908. * We use a goto here, to get out of this dead end,
  12909. * and continue with the default handling.
  12910. * A goto here is simpler and better to understand
  12911. * than some curious loop. */
  12912. goto no_callback_resource;
  12913. }
  12914. } else {
  12915. #if defined(USE_WEBSOCKET)
  12916. handle_websocket_request(conn,
  12917. path,
  12918. is_callback_resource,
  12919. subprotocols,
  12920. ws_connect_handler,
  12921. ws_ready_handler,
  12922. ws_data_handler,
  12923. ws_close_handler,
  12924. callback_data);
  12925. #endif
  12926. }
  12927. DEBUG_TRACE("%s", "websocket handling done");
  12928. return;
  12929. }
  12930. /* 8. handle websocket requests */
  12931. #if defined(USE_WEBSOCKET)
  12932. if (is_websocket_request) {
  12933. HTTP1_only;
  12934. if (is_script_resource) {
  12935. if (is_in_script_path(conn, path)) {
  12936. /* Websocket Lua script */
  12937. handle_websocket_request(conn,
  12938. path,
  12939. 0 /* Lua Script */,
  12940. NULL,
  12941. NULL,
  12942. NULL,
  12943. NULL,
  12944. NULL,
  12945. conn->phys_ctx->user_data);
  12946. } else {
  12947. /* Script was in an illegal path */
  12948. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12949. }
  12950. } else {
  12951. mg_send_http_error(conn, 404, "%s", "Not found");
  12952. }
  12953. DEBUG_TRACE("%s", "websocket script done");
  12954. return;
  12955. } else
  12956. #endif
  12957. #if defined(NO_FILES)
  12958. /* 9a. In case the server uses only callbacks, this uri is
  12959. * unknown.
  12960. * Then, all request handling ends here. */
  12961. mg_send_http_error(conn, 404, "%s", "Not Found");
  12962. #else
  12963. /* 9b. This request is either for a static file or resource handled
  12964. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12965. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12966. mg_send_http_error(conn, 404, "%s", "Not Found");
  12967. DEBUG_TRACE("%s", "no document root available");
  12968. return;
  12969. }
  12970. /* 10. Request is handled by a script */
  12971. if (is_script_resource) {
  12972. HTTP1_only;
  12973. handle_file_based_request(conn, path, &file);
  12974. DEBUG_TRACE("%s", "script handling done");
  12975. return;
  12976. }
  12977. /* Request was not handled by a callback or script. It will be
  12978. * handled by a server internal method. */
  12979. /* 11. Handle put/delete/mkcol requests */
  12980. if (is_put_or_delete_request) {
  12981. HTTP1_only;
  12982. /* 11.1. PUT method */
  12983. if (!strcmp(ri->request_method, "PUT")) {
  12984. put_file(conn, path);
  12985. DEBUG_TRACE("handling %s request to %s done",
  12986. ri->request_method,
  12987. path);
  12988. return;
  12989. }
  12990. /* 11.2. DELETE method */
  12991. if (!strcmp(ri->request_method, "DELETE")) {
  12992. delete_file(conn, path);
  12993. DEBUG_TRACE("handling %s request to %s done",
  12994. ri->request_method,
  12995. path);
  12996. return;
  12997. }
  12998. /* 11.3. MKCOL method */
  12999. if (!strcmp(ri->request_method, "MKCOL")) {
  13000. dav_mkcol(conn, path);
  13001. DEBUG_TRACE("handling %s request to %s done",
  13002. ri->request_method,
  13003. path);
  13004. return;
  13005. }
  13006. /* 11.4. MOVE method */
  13007. if (!strcmp(ri->request_method, "MOVE")) {
  13008. dav_move_file(conn, path, 0);
  13009. DEBUG_TRACE("handling %s request to %s done",
  13010. ri->request_method,
  13011. path);
  13012. return;
  13013. }
  13014. if (!strcmp(ri->request_method, "COPY")) {
  13015. dav_move_file(conn, path, 1);
  13016. DEBUG_TRACE("handling %s request to %s done",
  13017. ri->request_method,
  13018. path);
  13019. return;
  13020. }
  13021. /* 11.5. LOCK method */
  13022. if (!strcmp(ri->request_method, "LOCK")) {
  13023. dav_lock_file(conn, path);
  13024. DEBUG_TRACE("handling %s request to %s done",
  13025. ri->request_method,
  13026. path);
  13027. return;
  13028. }
  13029. /* 11.6. UNLOCK method */
  13030. if (!strcmp(ri->request_method, "UNLOCK")) {
  13031. dav_unlock_file(conn, path);
  13032. DEBUG_TRACE("handling %s request to %s done",
  13033. ri->request_method,
  13034. path);
  13035. return;
  13036. }
  13037. /* 11.7. PROPPATCH method */
  13038. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13039. dav_proppatch(conn, path);
  13040. DEBUG_TRACE("handling %s request to %s done",
  13041. ri->request_method,
  13042. path);
  13043. return;
  13044. }
  13045. /* 11.8. Other methods, e.g.: PATCH
  13046. * This method is not supported for static resources,
  13047. * only for scripts (Lua, CGI) and callbacks. */
  13048. mg_send_http_error(conn,
  13049. 405,
  13050. "%s method not allowed",
  13051. conn->request_info.request_method);
  13052. DEBUG_TRACE("method %s on %s is not supported",
  13053. ri->request_method,
  13054. path);
  13055. return;
  13056. }
  13057. /* 11. File does not exist, or it was configured that it should be
  13058. * hidden */
  13059. if (!is_found || (must_hide_file(conn, path))) {
  13060. mg_send_http_error(conn, 404, "%s", "Not found");
  13061. DEBUG_TRACE("handling %s request to %s: file not found",
  13062. ri->request_method,
  13063. path);
  13064. return;
  13065. }
  13066. /* 12. Directory uris should end with a slash */
  13067. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13068. && (ri->local_uri[uri_len - 1] != '/')) {
  13069. /* Path + server root */
  13070. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13071. char *new_path;
  13072. if (ri->query_string) {
  13073. buflen += strlen(ri->query_string);
  13074. }
  13075. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13076. if (!new_path) {
  13077. mg_send_http_error(conn, 500, "out or memory");
  13078. } else {
  13079. mg_get_request_link(conn, new_path, buflen - 1);
  13080. strcat(new_path, "/");
  13081. if (ri->query_string) {
  13082. /* Append ? and query string */
  13083. strcat(new_path, "?");
  13084. strcat(new_path, ri->query_string);
  13085. }
  13086. mg_send_http_redirect(conn, new_path, 301);
  13087. mg_free(new_path);
  13088. }
  13089. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13090. ri->request_method,
  13091. path);
  13092. return;
  13093. }
  13094. /* 13. Handle other methods than GET/HEAD */
  13095. /* 13.1. Handle PROPFIND */
  13096. if (!strcmp(ri->request_method, "PROPFIND")) {
  13097. handle_propfind(conn, path, &file.stat);
  13098. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13099. return;
  13100. }
  13101. /* 13.2. Handle OPTIONS for files */
  13102. if (!strcmp(ri->request_method, "OPTIONS")) {
  13103. /* This standard handler is only used for real files.
  13104. * Scripts should support the OPTIONS method themselves, to allow a
  13105. * maximum flexibility.
  13106. * Lua and CGI scripts may fully support CORS this way (including
  13107. * preflights). */
  13108. send_options(conn);
  13109. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13110. return;
  13111. }
  13112. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13113. if ((0 != strcmp(ri->request_method, "GET"))
  13114. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13115. mg_send_http_error(conn,
  13116. 405,
  13117. "%s method not allowed",
  13118. conn->request_info.request_method);
  13119. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13120. return;
  13121. }
  13122. /* 14. directories */
  13123. if (file.stat.is_directory) {
  13124. /* Substitute files have already been handled above. */
  13125. /* Here we can either generate and send a directory listing,
  13126. * or send an "access denied" error. */
  13127. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13128. "yes")) {
  13129. handle_directory_request(conn, path);
  13130. } else {
  13131. mg_send_http_error(conn,
  13132. 403,
  13133. "%s",
  13134. "Error: Directory listing denied");
  13135. }
  13136. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13137. return;
  13138. }
  13139. /* 15. Files with search/replace patterns: LSP and SSI */
  13140. if (is_template_text_file) {
  13141. HTTP1_only;
  13142. handle_file_based_request(conn, path, &file);
  13143. DEBUG_TRACE("handling %s request to %s done (template)",
  13144. ri->request_method,
  13145. path);
  13146. return;
  13147. }
  13148. /* 16. Static file - maybe cached */
  13149. #if !defined(NO_CACHING)
  13150. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13151. /* Send 304 "Not Modified" - this must not send any body data */
  13152. handle_not_modified_static_file_request(conn, &file);
  13153. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13154. ri->request_method,
  13155. path);
  13156. return;
  13157. }
  13158. #endif /* !NO_CACHING */
  13159. /* 17. Static file - not cached */
  13160. handle_static_file_request(conn, path, &file, NULL, NULL);
  13161. DEBUG_TRACE("handling %s request to %s done (static)",
  13162. ri->request_method,
  13163. path);
  13164. #endif /* !defined(NO_FILES) */
  13165. }
  13166. #if !defined(NO_FILESYSTEMS)
  13167. static void
  13168. handle_file_based_request(struct mg_connection *conn,
  13169. const char *path,
  13170. struct mg_file *file)
  13171. {
  13172. #if !defined(NO_CGI)
  13173. unsigned char cgi_config_idx, inc, max;
  13174. #endif
  13175. if (!conn || !conn->dom_ctx) {
  13176. return;
  13177. }
  13178. #if defined(USE_LUA)
  13179. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13180. path)
  13181. > 0) {
  13182. if (is_in_script_path(conn, path)) {
  13183. /* Lua server page: an SSI like page containing mostly plain
  13184. * html code plus some tags with server generated contents. */
  13185. handle_lsp_request(conn, path, file, NULL);
  13186. } else {
  13187. /* Script was in an illegal path */
  13188. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13189. }
  13190. return;
  13191. }
  13192. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13193. > 0) {
  13194. if (is_in_script_path(conn, path)) {
  13195. /* Lua in-server module script: a CGI like script used to
  13196. * generate the entire reply. */
  13197. mg_exec_lua_script(conn, path, NULL);
  13198. } else {
  13199. /* Script was in an illegal path */
  13200. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13201. }
  13202. return;
  13203. }
  13204. #endif
  13205. #if defined(USE_DUKTAPE)
  13206. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13207. path)
  13208. > 0) {
  13209. if (is_in_script_path(conn, path)) {
  13210. /* Call duktape to generate the page */
  13211. mg_exec_duktape_script(conn, path);
  13212. } else {
  13213. /* Script was in an illegal path */
  13214. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13215. }
  13216. return;
  13217. }
  13218. #endif
  13219. #if !defined(NO_CGI)
  13220. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13221. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13222. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13223. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13224. if (match_prefix_strlen(
  13225. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13226. path)
  13227. > 0) {
  13228. if (is_in_script_path(conn, path)) {
  13229. /* CGI scripts may support all HTTP methods */
  13230. handle_cgi_request(conn, path, cgi_config_idx);
  13231. } else {
  13232. /* Script was in an illegal path */
  13233. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13234. }
  13235. return;
  13236. }
  13237. }
  13238. }
  13239. #endif /* !NO_CGI */
  13240. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13241. if (is_in_script_path(conn, path)) {
  13242. handle_ssi_file_request(conn, path, file);
  13243. } else {
  13244. /* Script was in an illegal path */
  13245. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13246. }
  13247. return;
  13248. }
  13249. #if !defined(NO_CACHING)
  13250. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13251. /* Send 304 "Not Modified" - this must not send any body data */
  13252. handle_not_modified_static_file_request(conn, file);
  13253. return;
  13254. }
  13255. #endif /* !NO_CACHING */
  13256. handle_static_file_request(conn, path, file, NULL, NULL);
  13257. }
  13258. #endif /* NO_FILESYSTEMS */
  13259. static void
  13260. close_all_listening_sockets(struct mg_context *ctx)
  13261. {
  13262. unsigned int i;
  13263. if (!ctx) {
  13264. return;
  13265. }
  13266. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13267. closesocket(ctx->listening_sockets[i].sock);
  13268. #if defined(USE_X_DOM_SOCKET)
  13269. /* For unix domain sockets, the socket name represents a file that has
  13270. * to be deleted. */
  13271. /* See
  13272. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13273. */
  13274. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13275. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13276. IGNORE_UNUSED_RESULT(
  13277. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13278. }
  13279. #endif
  13280. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13281. }
  13282. mg_free(ctx->listening_sockets);
  13283. ctx->listening_sockets = NULL;
  13284. mg_free(ctx->listening_socket_fds);
  13285. ctx->listening_socket_fds = NULL;
  13286. }
  13287. /* Valid listening port specification is: [ip_address:]port[s]
  13288. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13289. * Examples for IPv6: [::]:80, [::1]:80,
  13290. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13291. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13292. * In order to bind to both, IPv4 and IPv6, you can either add
  13293. * both ports using 8080,[::]:8080, or the short form +8080.
  13294. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13295. * one only accepting IPv4 the other only IPv6. +8080 creates
  13296. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13297. * environment, they might work differently, or might not work
  13298. * at all - it must be tested what options work best in the
  13299. * relevant network environment.
  13300. */
  13301. static int
  13302. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13303. {
  13304. unsigned int a, b, c, d;
  13305. unsigned port;
  13306. unsigned long portUL;
  13307. int ch, len;
  13308. const char *cb;
  13309. char *endptr;
  13310. #if defined(USE_IPV6)
  13311. char buf[100] = {0};
  13312. #endif
  13313. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13314. * Also, all-zeroes in the socket address means binding to all addresses
  13315. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13316. memset(so, 0, sizeof(*so));
  13317. so->lsa.sin.sin_family = AF_INET;
  13318. *ip_version = 0;
  13319. /* Initialize len as invalid. */
  13320. port = 0;
  13321. len = 0;
  13322. /* Test for different ways to format this string */
  13323. if (sscanf(vec->ptr,
  13324. "%u.%u.%u.%u:%u%n",
  13325. &a,
  13326. &b,
  13327. &c,
  13328. &d,
  13329. &port,
  13330. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13331. // to an integer value, but function will not report
  13332. // conversion errors; consider using 'strtol' instead
  13333. == 5) {
  13334. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13335. so->lsa.sin.sin_addr.s_addr =
  13336. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13337. so->lsa.sin.sin_port = htons((uint16_t)port);
  13338. *ip_version = 4;
  13339. #if defined(USE_IPV6)
  13340. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13341. && ((size_t)len <= vec->len)
  13342. && mg_inet_pton(
  13343. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13344. /* IPv6 address, examples: see above */
  13345. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13346. */
  13347. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13348. *ip_version = 6;
  13349. #endif
  13350. } else if ((vec->ptr[0] == '+')
  13351. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13352. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13353. // string to an integer value, but function will not
  13354. // report conversion errors; consider using 'strtol'
  13355. // instead
  13356. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13357. /* Add 1 to len for the + character we skipped before */
  13358. len++;
  13359. #if defined(USE_IPV6)
  13360. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13361. so->lsa.sin6.sin6_family = AF_INET6;
  13362. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13363. *ip_version = 4 + 6;
  13364. #else
  13365. /* Bind to IPv4 only, since IPv6 is not built in. */
  13366. so->lsa.sin.sin_port = htons((uint16_t)port);
  13367. *ip_version = 4;
  13368. #endif
  13369. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13370. && (vec->ptr != endptr)) {
  13371. len = (int)(endptr - vec->ptr);
  13372. port = (uint16_t)portUL;
  13373. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13374. so->lsa.sin.sin_port = htons((uint16_t)port);
  13375. *ip_version = 4;
  13376. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13377. /* String could be a hostname. This check algotithm
  13378. * will only work for RFC 952 compliant hostnames,
  13379. * starting with a letter, containing only letters,
  13380. * digits and hyphen ('-'). Newer specs may allow
  13381. * more, but this is not guaranteed here, since it
  13382. * may interfere with rules for port option lists. */
  13383. /* According to RFC 1035, hostnames are restricted to 255 characters
  13384. * in total (63 between two dots). */
  13385. char hostname[256];
  13386. size_t hostnlen = (size_t)(cb - vec->ptr);
  13387. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13388. /* This would be invalid in any case */
  13389. *ip_version = 0;
  13390. return 0;
  13391. }
  13392. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13393. if (mg_inet_pton(
  13394. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13395. if (sscanf(cb + 1, "%u%n", &port, &len)
  13396. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13397. // string to an integer value, but function will not
  13398. // report conversion errors; consider using 'strtol'
  13399. // instead
  13400. *ip_version = 4;
  13401. so->lsa.sin.sin_port = htons((uint16_t)port);
  13402. len += (int)(hostnlen + 1);
  13403. } else {
  13404. len = 0;
  13405. }
  13406. #if defined(USE_IPV6)
  13407. } else if (mg_inet_pton(AF_INET6,
  13408. hostname,
  13409. &so->lsa.sin6,
  13410. sizeof(so->lsa.sin6),
  13411. 1)) {
  13412. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13413. *ip_version = 6;
  13414. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13415. len += (int)(hostnlen + 1);
  13416. } else {
  13417. len = 0;
  13418. }
  13419. #endif
  13420. } else {
  13421. len = 0;
  13422. }
  13423. #if defined(USE_X_DOM_SOCKET)
  13424. } else if (vec->ptr[0] == 'x') {
  13425. /* unix (linux) domain socket */
  13426. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13427. len = vec->len;
  13428. so->lsa.sun.sun_family = AF_UNIX;
  13429. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13430. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13431. port = 0;
  13432. *ip_version = 99;
  13433. } else {
  13434. /* String too long */
  13435. len = 0;
  13436. }
  13437. #endif
  13438. } else {
  13439. /* Parsing failure. */
  13440. len = 0;
  13441. }
  13442. /* sscanf and the option splitting code ensure the following condition
  13443. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13444. if ((len > 0) && is_valid_port(port)
  13445. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13446. /* Next character after the port number */
  13447. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13448. so->is_ssl = (ch == 's');
  13449. so->ssl_redir = (ch == 'r');
  13450. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13451. return 1;
  13452. }
  13453. }
  13454. /* Reset ip_version to 0 if there is an error */
  13455. *ip_version = 0;
  13456. return 0;
  13457. }
  13458. /* Is there any SSL port in use? */
  13459. static int
  13460. is_ssl_port_used(const char *ports)
  13461. {
  13462. if (ports) {
  13463. /* There are several different allowed syntax variants:
  13464. * - "80" for a single port using every network interface
  13465. * - "localhost:80" for a single port using only localhost
  13466. * - "80,localhost:8080" for two ports, one bound to localhost
  13467. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13468. * to IPv4 localhost, one to IPv6 localhost
  13469. * - "+80" use port 80 for IPv4 and IPv6
  13470. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13471. * for both: IPv4 and IPv4
  13472. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13473. * additionally port 8080 bound to localhost connections
  13474. *
  13475. * If we just look for 's' anywhere in the string, "localhost:80"
  13476. * will be detected as SSL (false positive).
  13477. * Looking for 's' after a digit may cause false positives in
  13478. * "my24service:8080".
  13479. * Looking from 's' backward if there are only ':' and numbers
  13480. * before will not work for "24service:8080" (non SSL, port 8080)
  13481. * or "24s" (SSL, port 24).
  13482. *
  13483. * Remark: Initially hostnames were not allowed to start with a
  13484. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13485. * Section 2.1).
  13486. *
  13487. * To get this correct, the entire string must be parsed as a whole,
  13488. * reading it as a list element for element and parsing with an
  13489. * algorithm equivalent to parse_port_string.
  13490. *
  13491. * In fact, we use local interface names here, not arbitrary
  13492. * hostnames, so in most cases the only name will be "localhost".
  13493. *
  13494. * So, for now, we use this simple algorithm, that may still return
  13495. * a false positive in bizarre cases.
  13496. */
  13497. int i;
  13498. int portslen = (int)strlen(ports);
  13499. char prevIsNumber = 0;
  13500. for (i = 0; i < portslen; i++) {
  13501. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13502. return 1;
  13503. }
  13504. if (ports[i] >= '0' && ports[i] <= '9') {
  13505. prevIsNumber = 1;
  13506. } else {
  13507. prevIsNumber = 0;
  13508. }
  13509. }
  13510. }
  13511. return 0;
  13512. }
  13513. static int
  13514. set_ports_option(struct mg_context *phys_ctx)
  13515. {
  13516. const char *list;
  13517. int on = 1;
  13518. #if defined(USE_IPV6)
  13519. int off = 0;
  13520. #endif
  13521. struct vec vec;
  13522. struct socket so, *ptr;
  13523. struct mg_pollfd *pfd;
  13524. union usa usa;
  13525. socklen_t len;
  13526. int ip_version;
  13527. int portsTotal = 0;
  13528. int portsOk = 0;
  13529. const char *opt_txt;
  13530. long opt_listen_backlog;
  13531. if (!phys_ctx) {
  13532. return 0;
  13533. }
  13534. memset(&so, 0, sizeof(so));
  13535. memset(&usa, 0, sizeof(usa));
  13536. len = sizeof(usa);
  13537. list = phys_ctx->dd.config[LISTENING_PORTS];
  13538. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13539. portsTotal++;
  13540. if (!parse_port_string(&vec, &so, &ip_version)) {
  13541. mg_cry_ctx_internal(
  13542. phys_ctx,
  13543. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13544. (int)vec.len,
  13545. vec.ptr,
  13546. portsTotal,
  13547. "[IP_ADDRESS:]PORT[s|r]");
  13548. continue;
  13549. }
  13550. #if !defined(NO_SSL)
  13551. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13552. mg_cry_ctx_internal(phys_ctx,
  13553. "Cannot add SSL socket (entry %i)",
  13554. portsTotal);
  13555. continue;
  13556. }
  13557. #endif
  13558. /* Create socket. */
  13559. /* For a list of protocol numbers (e.g., TCP==6) see:
  13560. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13561. */
  13562. if ((so.sock =
  13563. socket(so.lsa.sa.sa_family,
  13564. SOCK_STREAM,
  13565. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13566. == INVALID_SOCKET) {
  13567. mg_cry_ctx_internal(phys_ctx,
  13568. "cannot create socket (entry %i)",
  13569. portsTotal);
  13570. continue;
  13571. }
  13572. #if defined(_WIN32)
  13573. /* Windows SO_REUSEADDR lets many procs binds to a
  13574. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13575. * if someone already has the socket -- DTL */
  13576. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13577. * Windows might need a few seconds before
  13578. * the same port can be used again in the
  13579. * same process, so a short Sleep may be
  13580. * required between mg_stop and mg_start.
  13581. */
  13582. if (setsockopt(so.sock,
  13583. SOL_SOCKET,
  13584. SO_EXCLUSIVEADDRUSE,
  13585. (SOCK_OPT_TYPE)&on,
  13586. sizeof(on))
  13587. != 0) {
  13588. /* Set reuse option, but don't abort on errors. */
  13589. mg_cry_ctx_internal(
  13590. phys_ctx,
  13591. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13592. portsTotal);
  13593. }
  13594. #else
  13595. if (setsockopt(so.sock,
  13596. SOL_SOCKET,
  13597. SO_REUSEADDR,
  13598. (SOCK_OPT_TYPE)&on,
  13599. sizeof(on))
  13600. != 0) {
  13601. /* Set reuse option, but don't abort on errors. */
  13602. mg_cry_ctx_internal(
  13603. phys_ctx,
  13604. "cannot set socket option SO_REUSEADDR (entry %i)",
  13605. portsTotal);
  13606. }
  13607. #endif
  13608. #if defined(USE_X_DOM_SOCKET)
  13609. if (ip_version == 99) {
  13610. /* Unix domain socket */
  13611. } else
  13612. #endif
  13613. if (ip_version > 4) {
  13614. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13615. #if defined(USE_IPV6)
  13616. if (ip_version > 6) {
  13617. if (so.lsa.sa.sa_family == AF_INET6
  13618. && setsockopt(so.sock,
  13619. IPPROTO_IPV6,
  13620. IPV6_V6ONLY,
  13621. (void *)&off,
  13622. sizeof(off))
  13623. != 0) {
  13624. /* Set IPv6 only option, but don't abort on errors. */
  13625. mg_cry_ctx_internal(phys_ctx,
  13626. "cannot set socket option "
  13627. "IPV6_V6ONLY=off (entry %i)",
  13628. portsTotal);
  13629. }
  13630. } else {
  13631. if (so.lsa.sa.sa_family == AF_INET6
  13632. && setsockopt(so.sock,
  13633. IPPROTO_IPV6,
  13634. IPV6_V6ONLY,
  13635. (void *)&on,
  13636. sizeof(on))
  13637. != 0) {
  13638. /* Set IPv6 only option, but don't abort on errors. */
  13639. mg_cry_ctx_internal(phys_ctx,
  13640. "cannot set socket option "
  13641. "IPV6_V6ONLY=on (entry %i)",
  13642. portsTotal);
  13643. }
  13644. }
  13645. #else
  13646. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13647. closesocket(so.sock);
  13648. so.sock = INVALID_SOCKET;
  13649. continue;
  13650. #endif
  13651. }
  13652. if (so.lsa.sa.sa_family == AF_INET) {
  13653. len = sizeof(so.lsa.sin);
  13654. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13655. mg_cry_ctx_internal(phys_ctx,
  13656. "cannot bind to %.*s: %d (%s)",
  13657. (int)vec.len,
  13658. vec.ptr,
  13659. (int)ERRNO,
  13660. strerror(errno));
  13661. closesocket(so.sock);
  13662. so.sock = INVALID_SOCKET;
  13663. continue;
  13664. }
  13665. }
  13666. #if defined(USE_IPV6)
  13667. else if (so.lsa.sa.sa_family == AF_INET6) {
  13668. len = sizeof(so.lsa.sin6);
  13669. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13670. mg_cry_ctx_internal(phys_ctx,
  13671. "cannot bind to IPv6 %.*s: %d (%s)",
  13672. (int)vec.len,
  13673. vec.ptr,
  13674. (int)ERRNO,
  13675. strerror(errno));
  13676. closesocket(so.sock);
  13677. so.sock = INVALID_SOCKET;
  13678. continue;
  13679. }
  13680. }
  13681. #endif
  13682. #if defined(USE_X_DOM_SOCKET)
  13683. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13684. len = sizeof(so.lsa.sun);
  13685. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13686. mg_cry_ctx_internal(phys_ctx,
  13687. "cannot bind to unix socket %s: %d (%s)",
  13688. so.lsa.sun.sun_path,
  13689. (int)ERRNO,
  13690. strerror(errno));
  13691. closesocket(so.sock);
  13692. so.sock = INVALID_SOCKET;
  13693. continue;
  13694. }
  13695. }
  13696. #endif
  13697. else {
  13698. mg_cry_ctx_internal(
  13699. phys_ctx,
  13700. "cannot bind: address family not supported (entry %i)",
  13701. portsTotal);
  13702. closesocket(so.sock);
  13703. so.sock = INVALID_SOCKET;
  13704. continue;
  13705. }
  13706. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13707. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13708. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13709. mg_cry_ctx_internal(phys_ctx,
  13710. "%s value \"%s\" is invalid",
  13711. config_options[LISTEN_BACKLOG_SIZE].name,
  13712. opt_txt);
  13713. closesocket(so.sock);
  13714. so.sock = INVALID_SOCKET;
  13715. continue;
  13716. }
  13717. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13718. mg_cry_ctx_internal(phys_ctx,
  13719. "cannot listen to %.*s: %d (%s)",
  13720. (int)vec.len,
  13721. vec.ptr,
  13722. (int)ERRNO,
  13723. strerror(errno));
  13724. closesocket(so.sock);
  13725. so.sock = INVALID_SOCKET;
  13726. continue;
  13727. }
  13728. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13729. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13730. int err = (int)ERRNO;
  13731. mg_cry_ctx_internal(phys_ctx,
  13732. "call to getsockname failed %.*s: %d (%s)",
  13733. (int)vec.len,
  13734. vec.ptr,
  13735. err,
  13736. strerror(errno));
  13737. closesocket(so.sock);
  13738. so.sock = INVALID_SOCKET;
  13739. continue;
  13740. }
  13741. /* Update lsa port in case of random free ports */
  13742. #if defined(USE_IPV6)
  13743. if (so.lsa.sa.sa_family == AF_INET6) {
  13744. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13745. } else
  13746. #endif
  13747. {
  13748. so.lsa.sin.sin_port = usa.sin.sin_port;
  13749. }
  13750. if ((ptr = (struct socket *)
  13751. mg_realloc_ctx(phys_ctx->listening_sockets,
  13752. (phys_ctx->num_listening_sockets + 1)
  13753. * sizeof(phys_ctx->listening_sockets[0]),
  13754. phys_ctx))
  13755. == NULL) {
  13756. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13757. closesocket(so.sock);
  13758. so.sock = INVALID_SOCKET;
  13759. continue;
  13760. }
  13761. if ((pfd = (struct mg_pollfd *)
  13762. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13763. (phys_ctx->num_listening_sockets + 1)
  13764. * sizeof(phys_ctx->listening_socket_fds[0]),
  13765. phys_ctx))
  13766. == NULL) {
  13767. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13768. closesocket(so.sock);
  13769. so.sock = INVALID_SOCKET;
  13770. mg_free(ptr);
  13771. continue;
  13772. }
  13773. set_close_on_exec(so.sock, NULL, phys_ctx);
  13774. phys_ctx->listening_sockets = ptr;
  13775. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13776. phys_ctx->listening_socket_fds = pfd;
  13777. phys_ctx->num_listening_sockets++;
  13778. portsOk++;
  13779. }
  13780. if (portsOk != portsTotal) {
  13781. close_all_listening_sockets(phys_ctx);
  13782. portsOk = 0;
  13783. }
  13784. return portsOk;
  13785. }
  13786. static const char *
  13787. header_val(const struct mg_connection *conn, const char *header)
  13788. {
  13789. const char *header_value;
  13790. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13791. return "-";
  13792. } else {
  13793. return header_value;
  13794. }
  13795. }
  13796. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13797. #include "external_log_access.inl"
  13798. #elif !defined(NO_FILESYSTEMS)
  13799. static void
  13800. log_access(const struct mg_connection *conn)
  13801. {
  13802. const struct mg_request_info *ri;
  13803. struct mg_file fi;
  13804. char date[64], src_addr[IP_ADDR_STR_LEN];
  13805. #if defined(REENTRANT_TIME)
  13806. struct tm _tm;
  13807. struct tm *tm = &_tm;
  13808. #else
  13809. struct tm *tm;
  13810. #endif
  13811. const char *referer;
  13812. const char *user_agent;
  13813. char log_buf[4096];
  13814. if (!conn || !conn->dom_ctx) {
  13815. return;
  13816. }
  13817. /* Set log message to "empty" */
  13818. log_buf[0] = 0;
  13819. #if defined(USE_LUA)
  13820. if (conn->phys_ctx->lua_bg_log_available) {
  13821. int ret;
  13822. struct mg_context *ctx = conn->phys_ctx;
  13823. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13824. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13825. /* call "log()" in Lua */
  13826. lua_getglobal(lstate, "log");
  13827. prepare_lua_request_info_inner(conn, lstate);
  13828. push_lua_response_log_data(conn, lstate);
  13829. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13830. if (ret == 0) {
  13831. int t = lua_type(lstate, -1);
  13832. if (t == LUA_TBOOLEAN) {
  13833. if (lua_toboolean(lstate, -1) == 0) {
  13834. /* log() returned false: do not log */
  13835. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13836. return;
  13837. }
  13838. /* log returned true: continue logging */
  13839. } else if (t == LUA_TSTRING) {
  13840. size_t len;
  13841. const char *txt = lua_tolstring(lstate, -1, &len);
  13842. if ((len == 0) || (*txt == 0)) {
  13843. /* log() returned empty string: do not log */
  13844. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13845. return;
  13846. }
  13847. /* Copy test from Lua into log_buf */
  13848. if (len >= sizeof(log_buf)) {
  13849. len = sizeof(log_buf) - 1;
  13850. }
  13851. memcpy(log_buf, txt, len);
  13852. log_buf[len] = 0;
  13853. }
  13854. } else {
  13855. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13856. }
  13857. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13858. }
  13859. #endif
  13860. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13861. if (mg_fopen(conn,
  13862. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13863. MG_FOPEN_MODE_APPEND,
  13864. &fi)
  13865. == 0) {
  13866. fi.access.fp = NULL;
  13867. }
  13868. } else {
  13869. fi.access.fp = NULL;
  13870. }
  13871. /* Log is written to a file and/or a callback. If both are not set,
  13872. * executing the rest of the function is pointless. */
  13873. if ((fi.access.fp == NULL)
  13874. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13875. return;
  13876. }
  13877. /* If we did not get a log message from Lua, create it here. */
  13878. if (!log_buf[0]) {
  13879. #if defined(REENTRANT_TIME)
  13880. localtime_r(&conn->conn_birth_time, tm);
  13881. #else
  13882. tm = localtime(&conn->conn_birth_time);
  13883. #endif
  13884. if (tm != NULL) {
  13885. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13886. } else {
  13887. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13888. date[sizeof(date) - 1] = '\0';
  13889. }
  13890. ri = &conn->request_info;
  13891. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13892. referer = header_val(conn, "Referer");
  13893. user_agent = header_val(conn, "User-Agent");
  13894. mg_snprintf(conn,
  13895. NULL, /* Ignore truncation in access log */
  13896. log_buf,
  13897. sizeof(log_buf),
  13898. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13899. " %s %s",
  13900. src_addr,
  13901. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13902. date,
  13903. ri->request_method ? ri->request_method : "-",
  13904. ri->request_uri ? ri->request_uri : "-",
  13905. ri->query_string ? "?" : "",
  13906. ri->query_string ? ri->query_string : "",
  13907. ri->http_version,
  13908. conn->status_code,
  13909. conn->num_bytes_sent,
  13910. referer,
  13911. user_agent);
  13912. }
  13913. /* Here we have a log message in log_buf. Call the callback */
  13914. if (conn->phys_ctx->callbacks.log_access) {
  13915. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13916. /* do not log if callack returns non-zero */
  13917. if (fi.access.fp) {
  13918. mg_fclose(&fi.access);
  13919. }
  13920. return;
  13921. }
  13922. }
  13923. /* Store in file */
  13924. if (fi.access.fp) {
  13925. int ok = 1;
  13926. flockfile(fi.access.fp);
  13927. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13928. ok = 0;
  13929. }
  13930. if (fflush(fi.access.fp) != 0) {
  13931. ok = 0;
  13932. }
  13933. funlockfile(fi.access.fp);
  13934. if (mg_fclose(&fi.access) != 0) {
  13935. ok = 0;
  13936. }
  13937. if (!ok) {
  13938. mg_cry_internal(conn,
  13939. "Error writing log file %s",
  13940. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13941. }
  13942. }
  13943. }
  13944. #else
  13945. #error "Either enable filesystems or provide a custom log_access implementation"
  13946. #endif /* Externally provided function */
  13947. /* Verify given socket address against the ACL.
  13948. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13949. */
  13950. static int
  13951. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13952. {
  13953. int allowed, flag, matched;
  13954. struct vec vec;
  13955. if (phys_ctx) {
  13956. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13957. /* If any ACL is set, deny by default */
  13958. allowed = (list == NULL) ? '+' : '-';
  13959. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13960. flag = vec.ptr[0];
  13961. matched = -1;
  13962. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13963. vec.ptr++;
  13964. vec.len--;
  13965. matched = parse_match_net(&vec, sa, 1);
  13966. }
  13967. if (matched < 0) {
  13968. mg_cry_ctx_internal(phys_ctx,
  13969. "%s: subnet must be [+|-]IP-addr[/x]",
  13970. __func__);
  13971. return -1;
  13972. }
  13973. if (matched) {
  13974. allowed = flag;
  13975. }
  13976. }
  13977. return allowed == '+';
  13978. }
  13979. return -1;
  13980. }
  13981. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13982. static int
  13983. set_uid_option(struct mg_context *phys_ctx)
  13984. {
  13985. int success = 0;
  13986. if (phys_ctx) {
  13987. /* We are currently running as curr_uid. */
  13988. const uid_t curr_uid = getuid();
  13989. /* If set, we want to run as run_as_user. */
  13990. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13991. const struct passwd *to_pw = NULL;
  13992. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13993. /* run_as_user does not exist on the system. We can't proceed
  13994. * further. */
  13995. mg_cry_ctx_internal(phys_ctx,
  13996. "%s: unknown user [%s]",
  13997. __func__,
  13998. run_as_user);
  13999. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14000. /* There was either no request to change user, or we're already
  14001. * running as run_as_user. Nothing else to do.
  14002. */
  14003. success = 1;
  14004. } else {
  14005. /* Valid change request. */
  14006. if (setgid(to_pw->pw_gid) == -1) {
  14007. mg_cry_ctx_internal(phys_ctx,
  14008. "%s: setgid(%s): %s",
  14009. __func__,
  14010. run_as_user,
  14011. strerror(errno));
  14012. } else if (setgroups(0, NULL) == -1) {
  14013. mg_cry_ctx_internal(phys_ctx,
  14014. "%s: setgroups(): %s",
  14015. __func__,
  14016. strerror(errno));
  14017. } else if (setuid(to_pw->pw_uid) == -1) {
  14018. mg_cry_ctx_internal(phys_ctx,
  14019. "%s: setuid(%s): %s",
  14020. __func__,
  14021. run_as_user,
  14022. strerror(errno));
  14023. } else {
  14024. success = 1;
  14025. }
  14026. }
  14027. }
  14028. return success;
  14029. }
  14030. #endif /* !_WIN32 */
  14031. static void
  14032. tls_dtor(void *key)
  14033. {
  14034. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14035. /* key == pthread_getspecific(sTlsKey); */
  14036. if (tls) {
  14037. if (tls->is_master == 2) {
  14038. tls->is_master = -3; /* Mark memory as dead */
  14039. mg_free(tls);
  14040. }
  14041. }
  14042. pthread_setspecific(sTlsKey, NULL);
  14043. }
  14044. #if defined(USE_MBEDTLS)
  14045. /* Check if SSL is required.
  14046. * If so, set up ctx->ssl_ctx pointer. */
  14047. static int
  14048. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14049. {
  14050. if (!phys_ctx) {
  14051. return 0;
  14052. }
  14053. if (!dom_ctx) {
  14054. dom_ctx = &(phys_ctx->dd);
  14055. }
  14056. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14057. /* No SSL port is set. No need to setup SSL. */
  14058. return 1;
  14059. }
  14060. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14061. if (dom_ctx->ssl_ctx == NULL) {
  14062. fprintf(stderr, "ssl_ctx malloc failed\n");
  14063. return 0;
  14064. }
  14065. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14066. == 0
  14067. ? 1
  14068. : 0;
  14069. }
  14070. #elif !defined(NO_SSL)
  14071. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14072. struct mg_domain_context *dom_ctx,
  14073. const char *pem,
  14074. const char *chain);
  14075. static const char *ssl_error(void);
  14076. static int
  14077. refresh_trust(struct mg_connection *conn)
  14078. {
  14079. struct stat cert_buf;
  14080. int64_t t = 0;
  14081. const char *pem;
  14082. const char *chain;
  14083. int should_verify_peer;
  14084. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14085. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14086. * refresh_trust still can not work. */
  14087. return 0;
  14088. }
  14089. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14090. if (chain == NULL) {
  14091. /* pem is not NULL here */
  14092. chain = pem;
  14093. }
  14094. if (*chain == 0) {
  14095. chain = NULL;
  14096. }
  14097. if (stat(pem, &cert_buf) != -1) {
  14098. t = (int64_t)cert_buf.st_mtime;
  14099. }
  14100. mg_lock_context(conn->phys_ctx);
  14101. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14102. conn->dom_ctx->ssl_cert_last_mtime = t;
  14103. should_verify_peer = 0;
  14104. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14105. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14106. == 0) {
  14107. should_verify_peer = 1;
  14108. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14109. "optional")
  14110. == 0) {
  14111. should_verify_peer = 1;
  14112. }
  14113. }
  14114. if (should_verify_peer) {
  14115. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14116. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14117. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14118. ca_file,
  14119. ca_path)
  14120. != 1) {
  14121. mg_unlock_context(conn->phys_ctx);
  14122. mg_cry_ctx_internal(
  14123. conn->phys_ctx,
  14124. "SSL_CTX_load_verify_locations error: %s "
  14125. "ssl_verify_peer requires setting "
  14126. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14127. "present in "
  14128. "the .conf file?",
  14129. ssl_error());
  14130. return 0;
  14131. }
  14132. }
  14133. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14134. mg_unlock_context(conn->phys_ctx);
  14135. return 0;
  14136. }
  14137. }
  14138. mg_unlock_context(conn->phys_ctx);
  14139. return 1;
  14140. }
  14141. #if defined(OPENSSL_API_1_1)
  14142. #else
  14143. static pthread_mutex_t *ssl_mutexes;
  14144. #endif /* OPENSSL_API_1_1 */
  14145. static int
  14146. sslize(struct mg_connection *conn,
  14147. int (*func)(SSL *),
  14148. const struct mg_client_options *client_options)
  14149. {
  14150. int ret, err;
  14151. int short_trust;
  14152. unsigned timeout = 1024;
  14153. unsigned i;
  14154. if (!conn) {
  14155. return 0;
  14156. }
  14157. short_trust =
  14158. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14159. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14160. if (short_trust) {
  14161. int trust_ret = refresh_trust(conn);
  14162. if (!trust_ret) {
  14163. return trust_ret;
  14164. }
  14165. }
  14166. mg_lock_context(conn->phys_ctx);
  14167. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14168. mg_unlock_context(conn->phys_ctx);
  14169. if (conn->ssl == NULL) {
  14170. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14171. OPENSSL_REMOVE_THREAD_STATE();
  14172. return 0;
  14173. }
  14174. SSL_set_app_data(conn->ssl, (char *)conn);
  14175. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14176. if (ret != 1) {
  14177. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14178. SSL_free(conn->ssl);
  14179. conn->ssl = NULL;
  14180. OPENSSL_REMOVE_THREAD_STATE();
  14181. return 0;
  14182. }
  14183. if (client_options) {
  14184. if (client_options->host_name) {
  14185. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14186. }
  14187. }
  14188. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14189. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14190. /* NOTE: The loop below acts as a back-off, so we can end
  14191. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14192. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14193. if (to >= 0) {
  14194. timeout = (unsigned)to;
  14195. }
  14196. }
  14197. /* SSL functions may fail and require to be called again:
  14198. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14199. * Here "func" could be SSL_connect or SSL_accept. */
  14200. for (i = 0; i <= timeout; i += 50) {
  14201. ERR_clear_error();
  14202. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14203. ret = func(conn->ssl);
  14204. if (ret != 1) {
  14205. err = SSL_get_error(conn->ssl, ret);
  14206. if ((err == SSL_ERROR_WANT_CONNECT)
  14207. || (err == SSL_ERROR_WANT_ACCEPT)
  14208. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14209. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14210. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14211. /* Don't wait if the server is going to be stopped. */
  14212. break;
  14213. }
  14214. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14215. /* Simply retry the function call. */
  14216. mg_sleep(50);
  14217. } else {
  14218. /* Need to retry the function call "later".
  14219. * See https://linux.die.net/man/3/ssl_get_error
  14220. * This is typical for non-blocking sockets. */
  14221. struct mg_pollfd pfd;
  14222. int pollres;
  14223. pfd.fd = conn->client.sock;
  14224. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14225. || (err == SSL_ERROR_WANT_WRITE))
  14226. ? POLLOUT
  14227. : POLLIN;
  14228. pollres =
  14229. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14230. if (pollres < 0) {
  14231. /* Break if error occured (-1)
  14232. * or server shutdown (-2) */
  14233. break;
  14234. }
  14235. }
  14236. } else if (err == SSL_ERROR_SYSCALL) {
  14237. /* This is an IO error. Look at errno. */
  14238. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14239. break;
  14240. } else {
  14241. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14242. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14243. break;
  14244. }
  14245. } else {
  14246. /* success */
  14247. break;
  14248. }
  14249. }
  14250. ERR_clear_error();
  14251. if (ret != 1) {
  14252. SSL_free(conn->ssl);
  14253. conn->ssl = NULL;
  14254. OPENSSL_REMOVE_THREAD_STATE();
  14255. return 0;
  14256. }
  14257. return 1;
  14258. }
  14259. /* Return OpenSSL error message (from CRYPTO lib) */
  14260. static const char *
  14261. ssl_error(void)
  14262. {
  14263. unsigned long err;
  14264. err = ERR_get_error();
  14265. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14266. }
  14267. static int
  14268. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14269. {
  14270. int i;
  14271. const char hexdigit[] = "0123456789abcdef";
  14272. if ((memlen <= 0) || (buflen <= 0)) {
  14273. return 0;
  14274. }
  14275. if (buflen < (3 * memlen)) {
  14276. return 0;
  14277. }
  14278. for (i = 0; i < memlen; i++) {
  14279. if (i > 0) {
  14280. buf[3 * i - 1] = ' ';
  14281. }
  14282. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14283. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14284. }
  14285. buf[3 * memlen - 1] = 0;
  14286. return 1;
  14287. }
  14288. static int
  14289. ssl_get_client_cert_info(const struct mg_connection *conn,
  14290. struct mg_client_cert *client_cert)
  14291. {
  14292. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14293. if (cert) {
  14294. char str_buf[1024];
  14295. unsigned char buf[256];
  14296. char *str_serial = NULL;
  14297. unsigned int ulen;
  14298. int ilen;
  14299. unsigned char *tmp_buf;
  14300. unsigned char *tmp_p;
  14301. /* Handle to algorithm used for fingerprint */
  14302. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14303. /* Get Subject and issuer */
  14304. X509_NAME *subj = X509_get_subject_name(cert);
  14305. X509_NAME *iss = X509_get_issuer_name(cert);
  14306. /* Get serial number */
  14307. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14308. /* Translate serial number to a hex string */
  14309. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14310. if (serial_bn) {
  14311. str_serial = BN_bn2hex(serial_bn);
  14312. BN_free(serial_bn);
  14313. }
  14314. client_cert->serial =
  14315. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14316. /* Translate subject and issuer to a string */
  14317. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14318. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14319. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14320. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14321. /* Calculate SHA1 fingerprint and store as a hex string */
  14322. ulen = 0;
  14323. /* ASN1_digest is deprecated. Do the calculation manually,
  14324. * using EVP_Digest. */
  14325. ilen = i2d_X509(cert, NULL);
  14326. tmp_buf = (ilen > 0)
  14327. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14328. conn->phys_ctx)
  14329. : NULL;
  14330. if (tmp_buf) {
  14331. tmp_p = tmp_buf;
  14332. (void)i2d_X509(cert, &tmp_p);
  14333. if (!EVP_Digest(
  14334. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14335. ulen = 0;
  14336. }
  14337. mg_free(tmp_buf);
  14338. }
  14339. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14340. *str_buf = 0;
  14341. }
  14342. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14343. client_cert->peer_cert = (void *)cert;
  14344. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14345. * see https://linux.die.net/man/3/bn_bn2hex */
  14346. OPENSSL_free(str_serial);
  14347. return 1;
  14348. }
  14349. return 0;
  14350. }
  14351. #if defined(OPENSSL_API_1_1)
  14352. #else
  14353. static void
  14354. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14355. {
  14356. (void)line;
  14357. (void)file;
  14358. if (mode & 1) {
  14359. /* 1 is CRYPTO_LOCK */
  14360. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14361. } else {
  14362. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14363. }
  14364. }
  14365. #endif /* OPENSSL_API_1_1 */
  14366. #if !defined(NO_SSL_DL)
  14367. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14368. static void *
  14369. load_tls_dll(char *ebuf,
  14370. size_t ebuf_len,
  14371. const char *dll_name,
  14372. struct ssl_func *sw,
  14373. int *feature_missing)
  14374. {
  14375. union {
  14376. void *p;
  14377. void (*fp)(void);
  14378. } u;
  14379. void *dll_handle;
  14380. struct ssl_func *fp;
  14381. int ok;
  14382. int truncated = 0;
  14383. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14384. mg_snprintf(NULL,
  14385. NULL, /* No truncation check for ebuf */
  14386. ebuf,
  14387. ebuf_len,
  14388. "%s: cannot load %s",
  14389. __func__,
  14390. dll_name);
  14391. return NULL;
  14392. }
  14393. ok = 1;
  14394. for (fp = sw; fp->name != NULL; fp++) {
  14395. #if defined(_WIN32)
  14396. /* GetProcAddress() returns pointer to function */
  14397. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14398. #else
  14399. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14400. * pointers to function pointers. We need to use a union to make a
  14401. * cast. */
  14402. u.p = dlsym(dll_handle, fp->name);
  14403. #endif /* _WIN32 */
  14404. /* Set pointer (might be NULL) */
  14405. fp->ptr = u.fp;
  14406. if (u.fp == NULL) {
  14407. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14408. if (feature_missing) {
  14409. feature_missing[fp->required]++;
  14410. }
  14411. if (fp->required == TLS_Mandatory) {
  14412. /* Mandatory function is missing */
  14413. if (ok) {
  14414. /* This is the first missing function.
  14415. * Create a new error message. */
  14416. mg_snprintf(NULL,
  14417. &truncated,
  14418. ebuf,
  14419. ebuf_len,
  14420. "%s: %s: cannot find %s",
  14421. __func__,
  14422. dll_name,
  14423. fp->name);
  14424. ok = 0;
  14425. } else {
  14426. /* This is yet anothermissing function.
  14427. * Append existing error message. */
  14428. size_t cur_len = strlen(ebuf);
  14429. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14430. mg_snprintf(NULL,
  14431. &truncated,
  14432. ebuf + cur_len,
  14433. ebuf_len - cur_len - 3,
  14434. ", %s",
  14435. fp->name);
  14436. if (truncated) {
  14437. /* If truncated, add "..." */
  14438. strcat(ebuf, "...");
  14439. }
  14440. }
  14441. }
  14442. }
  14443. }
  14444. }
  14445. if (!ok) {
  14446. (void)dlclose(dll_handle);
  14447. return NULL;
  14448. }
  14449. return dll_handle;
  14450. }
  14451. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14452. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14453. #endif /* NO_SSL_DL */
  14454. #if defined(SSL_ALREADY_INITIALIZED)
  14455. static volatile ptrdiff_t cryptolib_users =
  14456. 1; /* Reference counter for crypto library. */
  14457. #else
  14458. static volatile ptrdiff_t cryptolib_users =
  14459. 0; /* Reference counter for crypto library. */
  14460. #endif
  14461. static int
  14462. initialize_openssl(char *ebuf, size_t ebuf_len)
  14463. {
  14464. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14465. int i, num_locks;
  14466. size_t size;
  14467. #endif
  14468. if (ebuf_len > 0) {
  14469. ebuf[0] = 0;
  14470. }
  14471. #if !defined(NO_SSL_DL)
  14472. if (!cryptolib_dll_handle) {
  14473. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14474. cryptolib_dll_handle = load_tls_dll(
  14475. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14476. if (!cryptolib_dll_handle) {
  14477. mg_snprintf(NULL,
  14478. NULL, /* No truncation check for ebuf */
  14479. ebuf,
  14480. ebuf_len,
  14481. "%s: error loading library %s",
  14482. __func__,
  14483. CRYPTO_LIB);
  14484. DEBUG_TRACE("%s", ebuf);
  14485. return 0;
  14486. }
  14487. }
  14488. #endif /* NO_SSL_DL */
  14489. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14490. return 1;
  14491. }
  14492. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14493. /* Initialize locking callbacks, needed for thread safety.
  14494. * http://www.openssl.org/support/faq.html#PROG1
  14495. */
  14496. num_locks = CRYPTO_num_locks();
  14497. if (num_locks < 0) {
  14498. num_locks = 0;
  14499. }
  14500. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14501. /* allocate mutex array, if required */
  14502. if (num_locks == 0) {
  14503. /* No mutex array required */
  14504. ssl_mutexes = NULL;
  14505. } else {
  14506. /* Mutex array required - allocate it */
  14507. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14508. /* Check OOM */
  14509. if (ssl_mutexes == NULL) {
  14510. mg_snprintf(NULL,
  14511. NULL, /* No truncation check for ebuf */
  14512. ebuf,
  14513. ebuf_len,
  14514. "%s: cannot allocate mutexes: %s",
  14515. __func__,
  14516. ssl_error());
  14517. DEBUG_TRACE("%s", ebuf);
  14518. return 0;
  14519. }
  14520. /* initialize mutex array */
  14521. for (i = 0; i < num_locks; i++) {
  14522. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14523. mg_snprintf(NULL,
  14524. NULL, /* No truncation check for ebuf */
  14525. ebuf,
  14526. ebuf_len,
  14527. "%s: error initializing mutex %i of %i",
  14528. __func__,
  14529. i,
  14530. num_locks);
  14531. DEBUG_TRACE("%s", ebuf);
  14532. mg_free(ssl_mutexes);
  14533. return 0;
  14534. }
  14535. }
  14536. }
  14537. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14538. CRYPTO_set_id_callback(&mg_current_thread_id);
  14539. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14540. #if !defined(NO_SSL_DL)
  14541. if (!ssllib_dll_handle) {
  14542. ssllib_dll_handle =
  14543. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14544. if (!ssllib_dll_handle) {
  14545. #if !defined(OPENSSL_API_1_1)
  14546. mg_free(ssl_mutexes);
  14547. #endif
  14548. DEBUG_TRACE("%s", ebuf);
  14549. return 0;
  14550. }
  14551. }
  14552. #endif /* NO_SSL_DL */
  14553. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14554. && !defined(NO_SSL_DL)
  14555. /* Initialize SSL library */
  14556. OPENSSL_init_ssl(0, NULL);
  14557. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14558. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14559. NULL);
  14560. #else
  14561. /* Initialize SSL library */
  14562. SSL_library_init();
  14563. SSL_load_error_strings();
  14564. #endif
  14565. return 1;
  14566. }
  14567. static int
  14568. ssl_use_pem_file(struct mg_context *phys_ctx,
  14569. struct mg_domain_context *dom_ctx,
  14570. const char *pem,
  14571. const char *chain)
  14572. {
  14573. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14574. mg_cry_ctx_internal(phys_ctx,
  14575. "%s: cannot open certificate file %s: %s",
  14576. __func__,
  14577. pem,
  14578. ssl_error());
  14579. return 0;
  14580. }
  14581. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14582. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14583. mg_cry_ctx_internal(phys_ctx,
  14584. "%s: cannot open private key file %s: %s",
  14585. __func__,
  14586. pem,
  14587. ssl_error());
  14588. return 0;
  14589. }
  14590. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14591. mg_cry_ctx_internal(phys_ctx,
  14592. "%s: certificate and private key do not match: %s",
  14593. __func__,
  14594. pem);
  14595. return 0;
  14596. }
  14597. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14598. * chain files that contain private keys and certificates in
  14599. * SSL_CTX_use_certificate_chain_file.
  14600. * The CivetWeb-Server used pem-Files that contained both information.
  14601. * In order to make wolfSSL work, it is split in two files.
  14602. * One file that contains key and certificate used by the server and
  14603. * an optional chain file for the ssl stack.
  14604. */
  14605. if (chain) {
  14606. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14607. mg_cry_ctx_internal(phys_ctx,
  14608. "%s: cannot use certificate chain file %s: %s",
  14609. __func__,
  14610. chain,
  14611. ssl_error());
  14612. return 0;
  14613. }
  14614. }
  14615. return 1;
  14616. }
  14617. #if defined(OPENSSL_API_1_1)
  14618. static unsigned long
  14619. ssl_get_protocol(int version_id)
  14620. {
  14621. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14622. if (version_id > 0)
  14623. ret |= SSL_OP_NO_SSLv2;
  14624. if (version_id > 1)
  14625. ret |= SSL_OP_NO_SSLv3;
  14626. if (version_id > 2)
  14627. ret |= SSL_OP_NO_TLSv1;
  14628. if (version_id > 3)
  14629. ret |= SSL_OP_NO_TLSv1_1;
  14630. if (version_id > 4)
  14631. ret |= SSL_OP_NO_TLSv1_2;
  14632. #if defined(SSL_OP_NO_TLSv1_3)
  14633. if (version_id > 5)
  14634. ret |= SSL_OP_NO_TLSv1_3;
  14635. #endif
  14636. return ret;
  14637. }
  14638. #else
  14639. static long
  14640. ssl_get_protocol(int version_id)
  14641. {
  14642. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14643. if (version_id > 0)
  14644. ret |= SSL_OP_NO_SSLv2;
  14645. if (version_id > 1)
  14646. ret |= SSL_OP_NO_SSLv3;
  14647. if (version_id > 2)
  14648. ret |= SSL_OP_NO_TLSv1;
  14649. if (version_id > 3)
  14650. ret |= SSL_OP_NO_TLSv1_1;
  14651. if (version_id > 4)
  14652. ret |= SSL_OP_NO_TLSv1_2;
  14653. #if defined(SSL_OP_NO_TLSv1_3)
  14654. if (version_id > 5)
  14655. ret |= SSL_OP_NO_TLSv1_3;
  14656. #endif
  14657. return (long)ret;
  14658. }
  14659. #endif /* OPENSSL_API_1_1 */
  14660. /* SSL callback documentation:
  14661. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14662. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14663. * https://linux.die.net/man/3/ssl_set_info_callback */
  14664. /* Note: There is no "const" for the first argument in the documentation
  14665. * examples, however some (maybe most, but not all) headers of OpenSSL
  14666. * versions / OpenSSL compatibility layers have it. Having a different
  14667. * definition will cause a warning in C and an error in C++. Use "const SSL
  14668. * *", while automatical conversion from "SSL *" works for all compilers,
  14669. * but not other way around */
  14670. static void
  14671. ssl_info_callback(const SSL *ssl, int what, int ret)
  14672. {
  14673. (void)ret;
  14674. if (what & SSL_CB_HANDSHAKE_START) {
  14675. SSL_get_app_data(ssl);
  14676. }
  14677. if (what & SSL_CB_HANDSHAKE_DONE) {
  14678. /* TODO: check for openSSL 1.1 */
  14679. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14680. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14681. }
  14682. }
  14683. static int
  14684. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14685. {
  14686. #if defined(GCC_DIAGNOSTIC)
  14687. #pragma GCC diagnostic push
  14688. #pragma GCC diagnostic ignored "-Wcast-align"
  14689. #endif /* defined(GCC_DIAGNOSTIC) */
  14690. /* We used an aligned pointer in SSL_set_app_data */
  14691. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14692. #if defined(GCC_DIAGNOSTIC)
  14693. #pragma GCC diagnostic pop
  14694. #endif /* defined(GCC_DIAGNOSTIC) */
  14695. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14696. (void)ad;
  14697. (void)arg;
  14698. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14699. DEBUG_ASSERT(0);
  14700. return SSL_TLSEXT_ERR_NOACK;
  14701. }
  14702. conn->dom_ctx = &(conn->phys_ctx->dd);
  14703. /* Old clients (Win XP) will not support SNI. Then, there
  14704. * is no server name available in the request - we can
  14705. * only work with the default certificate.
  14706. * Multiple HTTPS hosts on one IP+port are only possible
  14707. * with a certificate containing all alternative names.
  14708. */
  14709. if ((servername == NULL) || (*servername == 0)) {
  14710. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14711. mg_lock_context(conn->phys_ctx);
  14712. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14713. mg_unlock_context(conn->phys_ctx);
  14714. return SSL_TLSEXT_ERR_NOACK;
  14715. }
  14716. DEBUG_TRACE("TLS connection to host %s", servername);
  14717. while (conn->dom_ctx) {
  14718. if (!mg_strcasecmp(servername,
  14719. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14720. /* Found matching domain */
  14721. DEBUG_TRACE("TLS domain %s found",
  14722. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14723. break;
  14724. }
  14725. mg_lock_context(conn->phys_ctx);
  14726. conn->dom_ctx = conn->dom_ctx->next;
  14727. mg_unlock_context(conn->phys_ctx);
  14728. }
  14729. if (conn->dom_ctx == NULL) {
  14730. /* Default domain */
  14731. DEBUG_TRACE("TLS default domain %s used",
  14732. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14733. conn->dom_ctx = &(conn->phys_ctx->dd);
  14734. }
  14735. mg_lock_context(conn->phys_ctx);
  14736. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14737. mg_unlock_context(conn->phys_ctx);
  14738. return SSL_TLSEXT_ERR_OK;
  14739. }
  14740. #if defined(USE_ALPN)
  14741. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14742. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14743. alpn_proto_list + 3 + 8,
  14744. NULL};
  14745. #if defined(USE_HTTP2)
  14746. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14747. alpn_proto_list + 3,
  14748. alpn_proto_list + 3 + 8,
  14749. NULL};
  14750. #endif
  14751. static int
  14752. alpn_select_cb(SSL *ssl,
  14753. const unsigned char **out,
  14754. unsigned char *outlen,
  14755. const unsigned char *in,
  14756. unsigned int inlen,
  14757. void *arg)
  14758. {
  14759. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14760. unsigned int i, j, enable_http2 = 0;
  14761. const char **alpn_proto_order = alpn_proto_order_http1;
  14762. struct mg_workerTLS *tls =
  14763. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14764. (void)ssl;
  14765. if (tls == NULL) {
  14766. /* Need to store protocol in Thread Local Storage */
  14767. /* If there is no Thread Local Storage, don't use ALPN */
  14768. return SSL_TLSEXT_ERR_NOACK;
  14769. }
  14770. #if defined(USE_HTTP2)
  14771. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14772. if (enable_http2) {
  14773. alpn_proto_order = alpn_proto_order_http2;
  14774. }
  14775. #endif
  14776. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14777. /* check all accepted protocols in this order */
  14778. const char *alpn_proto = alpn_proto_order[j];
  14779. /* search input for matching protocol */
  14780. for (i = 0; i < inlen; i++) {
  14781. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14782. *out = in + i + 1;
  14783. *outlen = in[i];
  14784. tls->alpn_proto = alpn_proto;
  14785. return SSL_TLSEXT_ERR_OK;
  14786. }
  14787. }
  14788. }
  14789. /* Nothing found */
  14790. return SSL_TLSEXT_ERR_NOACK;
  14791. }
  14792. static int
  14793. next_protos_advertised_cb(SSL *ssl,
  14794. const unsigned char **data,
  14795. unsigned int *len,
  14796. void *arg)
  14797. {
  14798. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14799. *data = (const unsigned char *)alpn_proto_list;
  14800. *len = (unsigned int)strlen((const char *)data);
  14801. (void)ssl;
  14802. (void)dom_ctx;
  14803. return SSL_TLSEXT_ERR_OK;
  14804. }
  14805. static int
  14806. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14807. {
  14808. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14809. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14810. (const unsigned char *)alpn_proto_list,
  14811. alpn_len);
  14812. if (ret != 0) {
  14813. mg_cry_ctx_internal(phys_ctx,
  14814. "SSL_CTX_set_alpn_protos error: %s",
  14815. ssl_error());
  14816. }
  14817. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14818. alpn_select_cb,
  14819. (void *)dom_ctx);
  14820. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14821. next_protos_advertised_cb,
  14822. (void *)dom_ctx);
  14823. return ret;
  14824. }
  14825. #endif
  14826. /* Setup SSL CTX as required by CivetWeb */
  14827. static int
  14828. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14829. struct mg_domain_context *dom_ctx,
  14830. const char *pem,
  14831. const char *chain)
  14832. {
  14833. int callback_ret;
  14834. int should_verify_peer;
  14835. int peer_certificate_optional;
  14836. const char *ca_path;
  14837. const char *ca_file;
  14838. int use_default_verify_paths;
  14839. int verify_depth;
  14840. struct timespec now_mt;
  14841. md5_byte_t ssl_context_id[16];
  14842. md5_state_t md5state;
  14843. int protocol_ver;
  14844. int ssl_cache_timeout;
  14845. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14846. && !defined(NO_SSL_DL)
  14847. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14848. mg_cry_ctx_internal(phys_ctx,
  14849. "SSL_CTX_new (server) error: %s",
  14850. ssl_error());
  14851. return 0;
  14852. }
  14853. #else
  14854. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14855. mg_cry_ctx_internal(phys_ctx,
  14856. "SSL_CTX_new (server) error: %s",
  14857. ssl_error());
  14858. return 0;
  14859. }
  14860. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14861. #if defined(SSL_OP_NO_TLSv1_3)
  14862. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14863. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14864. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14865. | SSL_OP_NO_TLSv1_3);
  14866. #else
  14867. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14868. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14869. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14870. #endif
  14871. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14872. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14873. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14874. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14875. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14876. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14877. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14878. #if defined(SSL_OP_NO_RENEGOTIATION)
  14879. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14880. #endif
  14881. #if !defined(NO_SSL_DL)
  14882. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14883. #endif /* NO_SSL_DL */
  14884. /* In SSL documentation examples callback defined without const
  14885. * specifier 'void (*)(SSL *, int, int)' See:
  14886. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14887. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14888. * But in the source code const SSL is used:
  14889. * 'void (*)(const SSL *, int, int)' See:
  14890. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14891. * Problem about wrong documentation described, but not resolved:
  14892. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14893. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14894. * But when compiled with modern C++ compiler, correct const should be
  14895. * provided
  14896. */
  14897. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14898. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14899. ssl_servername_callback);
  14900. /* If a callback has been specified, call it. */
  14901. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14902. ? 0
  14903. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14904. phys_ctx->user_data));
  14905. /* If callback returns 0, civetweb sets up the SSL certificate.
  14906. * If it returns 1, civetweb assumes the calback already did this.
  14907. * If it returns -1, initializing ssl fails. */
  14908. if (callback_ret < 0) {
  14909. mg_cry_ctx_internal(phys_ctx,
  14910. "SSL callback returned error: %i",
  14911. callback_ret);
  14912. return 0;
  14913. }
  14914. if (callback_ret > 0) {
  14915. /* Callback did everything. */
  14916. return 1;
  14917. }
  14918. /* If a domain callback has been specified, call it. */
  14919. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14920. ? 0
  14921. : (phys_ctx->callbacks.init_ssl_domain(
  14922. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14923. dom_ctx->ssl_ctx,
  14924. phys_ctx->user_data));
  14925. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14926. * If it returns 1, civetweb assumes the calback already did this.
  14927. * If it returns -1, initializing ssl fails. */
  14928. if (callback_ret < 0) {
  14929. mg_cry_ctx_internal(phys_ctx,
  14930. "Domain SSL callback returned error: %i",
  14931. callback_ret);
  14932. return 0;
  14933. }
  14934. if (callback_ret > 0) {
  14935. /* Domain callback did everything. */
  14936. return 1;
  14937. }
  14938. /* Use some combination of start time, domain and port as a SSL
  14939. * context ID. This should be unique on the current machine. */
  14940. md5_init(&md5state);
  14941. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14942. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14943. md5_append(&md5state,
  14944. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14945. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14946. md5_append(&md5state,
  14947. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14948. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14949. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14950. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14951. md5_finish(&md5state, ssl_context_id);
  14952. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14953. (unsigned char *)ssl_context_id,
  14954. sizeof(ssl_context_id));
  14955. if (pem != NULL) {
  14956. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14957. return 0;
  14958. }
  14959. }
  14960. /* Should we support client certificates? */
  14961. /* Default is "no". */
  14962. should_verify_peer = 0;
  14963. peer_certificate_optional = 0;
  14964. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14965. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14966. /* Yes, they are mandatory */
  14967. should_verify_peer = 1;
  14968. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14969. "optional")
  14970. == 0) {
  14971. /* Yes, they are optional */
  14972. should_verify_peer = 1;
  14973. peer_certificate_optional = 1;
  14974. }
  14975. }
  14976. use_default_verify_paths =
  14977. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14978. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14979. == 0);
  14980. if (should_verify_peer) {
  14981. ca_path = dom_ctx->config[SSL_CA_PATH];
  14982. ca_file = dom_ctx->config[SSL_CA_FILE];
  14983. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14984. != 1) {
  14985. mg_cry_ctx_internal(phys_ctx,
  14986. "SSL_CTX_load_verify_locations error: %s "
  14987. "ssl_verify_peer requires setting "
  14988. "either ssl_ca_path or ssl_ca_file. "
  14989. "Is any of them present in the "
  14990. ".conf file?",
  14991. ssl_error());
  14992. return 0;
  14993. }
  14994. if (peer_certificate_optional) {
  14995. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14996. } else {
  14997. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14998. SSL_VERIFY_PEER
  14999. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15000. NULL);
  15001. }
  15002. if (use_default_verify_paths
  15003. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15004. mg_cry_ctx_internal(phys_ctx,
  15005. "SSL_CTX_set_default_verify_paths error: %s",
  15006. ssl_error());
  15007. return 0;
  15008. }
  15009. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15010. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15011. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15012. }
  15013. }
  15014. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15015. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15016. dom_ctx->config[SSL_CIPHER_LIST])
  15017. != 1) {
  15018. mg_cry_ctx_internal(phys_ctx,
  15019. "SSL_CTX_set_cipher_list error: %s",
  15020. ssl_error());
  15021. }
  15022. }
  15023. /* SSL session caching */
  15024. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15025. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15026. : 0);
  15027. if (ssl_cache_timeout > 0) {
  15028. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15029. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15030. * default */
  15031. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15032. }
  15033. #if defined(USE_ALPN)
  15034. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15035. #if !defined(NO_SSL_DL)
  15036. if (!tls_feature_missing[TLS_ALPN])
  15037. #endif
  15038. {
  15039. init_alpn(phys_ctx, dom_ctx);
  15040. }
  15041. #endif
  15042. return 1;
  15043. }
  15044. /* Check if SSL is required.
  15045. * If so, dynamically load SSL library
  15046. * and set up ctx->ssl_ctx pointer. */
  15047. static int
  15048. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15049. {
  15050. void *ssl_ctx = 0;
  15051. int callback_ret;
  15052. const char *pem;
  15053. const char *chain;
  15054. char ebuf[128];
  15055. if (!phys_ctx) {
  15056. return 0;
  15057. }
  15058. if (!dom_ctx) {
  15059. dom_ctx = &(phys_ctx->dd);
  15060. }
  15061. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15062. /* No SSL port is set. No need to setup SSL. */
  15063. return 1;
  15064. }
  15065. /* Check for external SSL_CTX */
  15066. callback_ret =
  15067. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15068. ? 0
  15069. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15070. phys_ctx->user_data));
  15071. if (callback_ret < 0) {
  15072. /* Callback exists and returns <0: Initializing failed. */
  15073. mg_cry_ctx_internal(phys_ctx,
  15074. "external_ssl_ctx callback returned error: %i",
  15075. callback_ret);
  15076. return 0;
  15077. } else if (callback_ret > 0) {
  15078. /* Callback exists and returns >0: Initializing complete,
  15079. * civetweb should not modify the SSL context. */
  15080. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15081. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15082. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15083. return 0;
  15084. }
  15085. return 1;
  15086. }
  15087. /* If the callback does not exist or return 0, civetweb must initialize
  15088. * the SSL context. Handle "domain" callback next. */
  15089. /* Check for external domain SSL_CTX callback. */
  15090. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15091. ? 0
  15092. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15093. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15094. &ssl_ctx,
  15095. phys_ctx->user_data));
  15096. if (callback_ret < 0) {
  15097. /* Callback < 0: Error. Abort init. */
  15098. mg_cry_ctx_internal(
  15099. phys_ctx,
  15100. "external_ssl_ctx_domain callback returned error: %i",
  15101. callback_ret);
  15102. return 0;
  15103. } else if (callback_ret > 0) {
  15104. /* Callback > 0: Consider init done. */
  15105. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15106. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15107. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15108. return 0;
  15109. }
  15110. return 1;
  15111. }
  15112. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15113. * 0, CivetWeb should continue initializing SSL */
  15114. /* If PEM file is not specified and the init_ssl callbacks
  15115. * are not specified, setup will fail. */
  15116. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15117. && (phys_ctx->callbacks.init_ssl == NULL)
  15118. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15119. /* No certificate and no init_ssl callbacks:
  15120. * Essential data to set up TLS is missing.
  15121. */
  15122. mg_cry_ctx_internal(phys_ctx,
  15123. "Initializing SSL failed: -%s is not set",
  15124. config_options[SSL_CERTIFICATE].name);
  15125. return 0;
  15126. }
  15127. /* If a certificate chain is configured, use it. */
  15128. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15129. if (chain == NULL) {
  15130. /* Default: certificate chain in PEM file */
  15131. chain = pem;
  15132. }
  15133. if ((chain != NULL) && (*chain == 0)) {
  15134. /* If the chain is an empty string, don't use it. */
  15135. chain = NULL;
  15136. }
  15137. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15138. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15139. return 0;
  15140. }
  15141. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15142. }
  15143. static void
  15144. uninitialize_openssl(void)
  15145. {
  15146. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15147. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15148. /* Shutdown according to
  15149. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15150. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15151. */
  15152. CONF_modules_unload(1);
  15153. #else
  15154. int i;
  15155. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15156. /* Shutdown according to
  15157. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15158. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15159. */
  15160. CRYPTO_set_locking_callback(NULL);
  15161. CRYPTO_set_id_callback(NULL);
  15162. ENGINE_cleanup();
  15163. CONF_modules_unload(1);
  15164. ERR_free_strings();
  15165. EVP_cleanup();
  15166. CRYPTO_cleanup_all_ex_data();
  15167. OPENSSL_REMOVE_THREAD_STATE();
  15168. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15169. pthread_mutex_destroy(&ssl_mutexes[i]);
  15170. }
  15171. mg_free(ssl_mutexes);
  15172. ssl_mutexes = NULL;
  15173. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15174. }
  15175. }
  15176. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15177. #if !defined(NO_FILESYSTEMS)
  15178. static int
  15179. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15180. {
  15181. if (phys_ctx) {
  15182. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15183. const char *path;
  15184. struct mg_connection fc;
  15185. if (!dom_ctx) {
  15186. dom_ctx = &(phys_ctx->dd);
  15187. }
  15188. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15189. if ((path != NULL)
  15190. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15191. mg_cry_ctx_internal(phys_ctx,
  15192. "Cannot open %s: %s",
  15193. path,
  15194. strerror(ERRNO));
  15195. return 0;
  15196. }
  15197. return 1;
  15198. }
  15199. return 0;
  15200. }
  15201. #endif /* NO_FILESYSTEMS */
  15202. static int
  15203. set_acl_option(struct mg_context *phys_ctx)
  15204. {
  15205. union usa sa;
  15206. memset(&sa, 0, sizeof(sa));
  15207. #if defined(USE_IPV6)
  15208. sa.sin6.sin6_family = AF_INET6;
  15209. #else
  15210. sa.sin.sin_family = AF_INET;
  15211. #endif
  15212. return check_acl(phys_ctx, &sa) != -1;
  15213. }
  15214. static void
  15215. reset_per_request_attributes(struct mg_connection *conn)
  15216. {
  15217. if (!conn) {
  15218. return;
  15219. }
  15220. conn->num_bytes_sent = conn->consumed_content = 0;
  15221. conn->path_info = NULL;
  15222. conn->status_code = -1;
  15223. conn->content_len = -1;
  15224. conn->is_chunked = 0;
  15225. conn->must_close = 0;
  15226. conn->request_len = 0;
  15227. conn->request_state = 0;
  15228. conn->throttle = 0;
  15229. conn->accept_gzip = 0;
  15230. conn->response_info.content_length = conn->request_info.content_length = -1;
  15231. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15232. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15233. conn->response_info.status_text = NULL;
  15234. conn->response_info.status_code = 0;
  15235. conn->request_info.remote_user = NULL;
  15236. conn->request_info.request_method = NULL;
  15237. conn->request_info.request_uri = NULL;
  15238. /* Free cleaned local URI (if any) */
  15239. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15240. mg_free((void *)conn->request_info.local_uri);
  15241. conn->request_info.local_uri = NULL;
  15242. }
  15243. conn->request_info.local_uri = NULL;
  15244. #if defined(USE_SERVER_STATS)
  15245. conn->processing_time = 0;
  15246. #endif
  15247. }
  15248. static int
  15249. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15250. {
  15251. if ((so->lsa.sa.sa_family == AF_INET)
  15252. || (so->lsa.sa.sa_family == AF_INET6)) {
  15253. /* Only for TCP sockets */
  15254. if (setsockopt(so->sock,
  15255. IPPROTO_TCP,
  15256. TCP_NODELAY,
  15257. (SOCK_OPT_TYPE)&nodelay_on,
  15258. sizeof(nodelay_on))
  15259. != 0) {
  15260. /* Error */
  15261. return 1;
  15262. }
  15263. }
  15264. /* OK */
  15265. return 0;
  15266. }
  15267. #if !defined(__ZEPHYR__)
  15268. static void
  15269. close_socket_gracefully(struct mg_connection *conn)
  15270. {
  15271. #if defined(_WIN32)
  15272. char buf[MG_BUF_LEN];
  15273. int n;
  15274. #endif
  15275. struct linger linger;
  15276. int error_code = 0;
  15277. int linger_timeout = -2;
  15278. socklen_t opt_len = sizeof(error_code);
  15279. if (!conn) {
  15280. return;
  15281. }
  15282. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15283. * "Note that enabling a nonzero timeout on a nonblocking socket
  15284. * is not recommended.", so set it to blocking now */
  15285. set_blocking_mode(conn->client.sock);
  15286. /* Send FIN to the client */
  15287. shutdown(conn->client.sock, SHUTDOWN_WR);
  15288. #if defined(_WIN32)
  15289. /* Read and discard pending incoming data. If we do not do that and
  15290. * close
  15291. * the socket, the data in the send buffer may be discarded. This
  15292. * behaviour is seen on Windows, when client keeps sending data
  15293. * when server decides to close the connection; then when client
  15294. * does recv() it gets no data back. */
  15295. do {
  15296. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15297. } while (n > 0);
  15298. #endif
  15299. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15300. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15301. }
  15302. /* Set linger option according to configuration */
  15303. if (linger_timeout >= 0) {
  15304. /* Set linger option to avoid socket hanging out after close. This
  15305. * prevent ephemeral port exhaust problem under high QPS. */
  15306. linger.l_onoff = 1;
  15307. #if defined(_MSC_VER)
  15308. #pragma warning(push)
  15309. #pragma warning(disable : 4244)
  15310. #endif
  15311. #if defined(GCC_DIAGNOSTIC)
  15312. #pragma GCC diagnostic push
  15313. #pragma GCC diagnostic ignored "-Wconversion"
  15314. #endif
  15315. /* Data type of linger structure elements may differ,
  15316. * so we don't know what cast we need here.
  15317. * Disable type conversion warnings. */
  15318. linger.l_linger = (linger_timeout + 999) / 1000;
  15319. #if defined(GCC_DIAGNOSTIC)
  15320. #pragma GCC diagnostic pop
  15321. #endif
  15322. #if defined(_MSC_VER)
  15323. #pragma warning(pop)
  15324. #endif
  15325. } else {
  15326. linger.l_onoff = 0;
  15327. linger.l_linger = 0;
  15328. }
  15329. if (linger_timeout < -1) {
  15330. /* Default: don't configure any linger */
  15331. } else if (getsockopt(conn->client.sock,
  15332. SOL_SOCKET,
  15333. SO_ERROR,
  15334. #if defined(_WIN32) /* WinSock uses different data type here */
  15335. (char *)&error_code,
  15336. #else
  15337. &error_code,
  15338. #endif
  15339. &opt_len)
  15340. != 0) {
  15341. /* Cannot determine if socket is already closed. This should
  15342. * not occur and never did in a test. Log an error message
  15343. * and continue. */
  15344. mg_cry_internal(conn,
  15345. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15346. __func__,
  15347. strerror(ERRNO));
  15348. #if defined(_WIN32)
  15349. } else if (error_code == WSAECONNRESET) {
  15350. #else
  15351. } else if (error_code == ECONNRESET) {
  15352. #endif
  15353. /* Socket already closed by client/peer, close socket without linger
  15354. */
  15355. } else {
  15356. /* Set linger timeout */
  15357. if (setsockopt(conn->client.sock,
  15358. SOL_SOCKET,
  15359. SO_LINGER,
  15360. (char *)&linger,
  15361. sizeof(linger))
  15362. != 0) {
  15363. mg_cry_internal(
  15364. conn,
  15365. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15366. __func__,
  15367. linger.l_onoff,
  15368. linger.l_linger,
  15369. strerror(ERRNO));
  15370. }
  15371. }
  15372. /* Now we know that our FIN is ACK-ed, safe to close */
  15373. closesocket(conn->client.sock);
  15374. conn->client.sock = INVALID_SOCKET;
  15375. }
  15376. #endif
  15377. static void
  15378. close_connection(struct mg_connection *conn)
  15379. {
  15380. #if defined(USE_SERVER_STATS)
  15381. conn->conn_state = 6; /* to close */
  15382. #endif
  15383. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15384. if (conn->lua_websocket_state) {
  15385. lua_websocket_close(conn, conn->lua_websocket_state);
  15386. conn->lua_websocket_state = NULL;
  15387. }
  15388. #endif
  15389. mg_lock_connection(conn);
  15390. /* Set close flag, so keep-alive loops will stop */
  15391. conn->must_close = 1;
  15392. /* call the connection_close callback if assigned */
  15393. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15394. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15395. conn->phys_ctx->callbacks.connection_close(conn);
  15396. }
  15397. }
  15398. /* Reset user data, after close callback is called.
  15399. * Do not reuse it. If the user needs a destructor,
  15400. * it must be done in the connection_close callback. */
  15401. mg_set_user_connection_data(conn, NULL);
  15402. #if defined(USE_SERVER_STATS)
  15403. conn->conn_state = 7; /* closing */
  15404. #endif
  15405. #if defined(USE_MBEDTLS)
  15406. if (conn->ssl != NULL) {
  15407. mbed_ssl_close(conn->ssl);
  15408. conn->ssl = NULL;
  15409. }
  15410. #elif !defined(NO_SSL)
  15411. if (conn->ssl != NULL) {
  15412. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15413. */
  15414. SSL_shutdown(conn->ssl);
  15415. SSL_free(conn->ssl);
  15416. OPENSSL_REMOVE_THREAD_STATE();
  15417. conn->ssl = NULL;
  15418. }
  15419. #endif
  15420. if (conn->client.sock != INVALID_SOCKET) {
  15421. #if defined(__ZEPHYR__)
  15422. closesocket(conn->client.sock);
  15423. #else
  15424. close_socket_gracefully(conn);
  15425. #endif
  15426. conn->client.sock = INVALID_SOCKET;
  15427. }
  15428. /* call the connection_closed callback if assigned */
  15429. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15430. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15431. conn->phys_ctx->callbacks.connection_closed(conn);
  15432. }
  15433. }
  15434. mg_unlock_connection(conn);
  15435. #if defined(USE_SERVER_STATS)
  15436. conn->conn_state = 8; /* closed */
  15437. #endif
  15438. }
  15439. CIVETWEB_API void
  15440. mg_close_connection(struct mg_connection *conn)
  15441. {
  15442. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15443. return;
  15444. }
  15445. #if defined(USE_WEBSOCKET)
  15446. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15447. if (conn->in_websocket_handling) {
  15448. /* Set close flag, so the server thread can exit. */
  15449. conn->must_close = 1;
  15450. return;
  15451. }
  15452. }
  15453. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15454. unsigned int i;
  15455. /* client context: loops must end */
  15456. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15457. conn->must_close = 1;
  15458. /* We need to get the client thread out of the select/recv call
  15459. * here. */
  15460. /* Since we use a sleep quantum of some seconds to check for recv
  15461. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15462. /* join worker thread */
  15463. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15464. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15465. }
  15466. }
  15467. #endif /* defined(USE_WEBSOCKET) */
  15468. close_connection(conn);
  15469. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15470. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15471. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15472. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15473. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15474. }
  15475. #endif
  15476. #if defined(USE_WEBSOCKET)
  15477. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15478. mg_free(conn->phys_ctx->worker_threadids);
  15479. (void)pthread_mutex_destroy(&conn->mutex);
  15480. mg_free(conn);
  15481. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15482. (void)pthread_mutex_destroy(&conn->mutex);
  15483. mg_free(conn);
  15484. }
  15485. #else
  15486. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15487. (void)pthread_mutex_destroy(&conn->mutex);
  15488. mg_free(conn);
  15489. }
  15490. #endif /* defined(USE_WEBSOCKET) */
  15491. }
  15492. static struct mg_connection *
  15493. mg_connect_client_impl(const struct mg_client_options *client_options,
  15494. int use_ssl,
  15495. struct mg_init_data *init,
  15496. struct mg_error_data *error)
  15497. {
  15498. struct mg_connection *conn = NULL;
  15499. SOCKET sock;
  15500. union usa sa;
  15501. struct sockaddr *psa;
  15502. socklen_t len;
  15503. unsigned max_req_size =
  15504. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15505. /* Size of structures, aligned to 8 bytes */
  15506. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15507. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15508. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15509. (void)init; /* TODO: Implement required options */
  15510. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15511. if (error != NULL) {
  15512. error->code = MG_ERROR_DATA_CODE_OK;
  15513. error->code_sub = 0;
  15514. if (error->text_buffer_size > 0) {
  15515. error->text[0] = 0;
  15516. }
  15517. }
  15518. if (conn == NULL) {
  15519. if (error != NULL) {
  15520. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15521. error->code_sub = (unsigned)alloc_size;
  15522. mg_snprintf(NULL,
  15523. NULL, /* No truncation check for ebuf */
  15524. error->text,
  15525. error->text_buffer_size,
  15526. "calloc(): %s",
  15527. strerror(ERRNO));
  15528. }
  15529. return NULL;
  15530. }
  15531. #if defined(GCC_DIAGNOSTIC)
  15532. #pragma GCC diagnostic push
  15533. #pragma GCC diagnostic ignored "-Wcast-align"
  15534. #endif /* defined(GCC_DIAGNOSTIC) */
  15535. /* conn_size is aligned to 8 bytes */
  15536. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15537. #if defined(GCC_DIAGNOSTIC)
  15538. #pragma GCC diagnostic pop
  15539. #endif /* defined(GCC_DIAGNOSTIC) */
  15540. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15541. conn->buf_size = (int)max_req_size;
  15542. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15543. conn->dom_ctx = &(conn->phys_ctx->dd);
  15544. if (!connect_socket(conn->phys_ctx,
  15545. client_options->host,
  15546. client_options->port,
  15547. use_ssl,
  15548. error,
  15549. &sock,
  15550. &sa)) {
  15551. /* "error" will be set by connect_socket. */
  15552. /* free all memory and return NULL; */
  15553. mg_free(conn);
  15554. return NULL;
  15555. }
  15556. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15557. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15558. && !defined(NO_SSL_DL)
  15559. if (use_ssl
  15560. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15561. == NULL) {
  15562. if (error != NULL) {
  15563. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15564. mg_snprintf(NULL,
  15565. NULL, /* No truncation check for ebuf */
  15566. error->text,
  15567. error->text_buffer_size,
  15568. "SSL_CTX_new error: %s",
  15569. ssl_error());
  15570. }
  15571. closesocket(sock);
  15572. mg_free(conn);
  15573. return NULL;
  15574. }
  15575. #else
  15576. if (use_ssl
  15577. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15578. == NULL) {
  15579. if (error != NULL) {
  15580. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15581. mg_snprintf(NULL,
  15582. NULL, /* No truncation check for ebuf */
  15583. error->text,
  15584. error->text_buffer_size,
  15585. "SSL_CTX_new error: %s",
  15586. ssl_error());
  15587. }
  15588. closesocket(sock);
  15589. mg_free(conn);
  15590. return NULL;
  15591. }
  15592. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15593. #endif /* NO_SSL */
  15594. #if defined(USE_IPV6)
  15595. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15596. : sizeof(conn->client.rsa.sin6);
  15597. psa = (sa.sa.sa_family == AF_INET)
  15598. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15599. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15600. #else
  15601. len = sizeof(conn->client.rsa.sin);
  15602. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15603. #endif
  15604. conn->client.sock = sock;
  15605. conn->client.lsa = sa;
  15606. if (getsockname(sock, psa, &len) != 0) {
  15607. mg_cry_internal(conn,
  15608. "%s: getsockname() failed: %s",
  15609. __func__,
  15610. strerror(ERRNO));
  15611. }
  15612. conn->client.is_ssl = use_ssl ? 1 : 0;
  15613. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15614. if (error != NULL) {
  15615. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15616. error->code_sub = (unsigned)ERRNO;
  15617. mg_snprintf(NULL,
  15618. NULL, /* No truncation check for ebuf */
  15619. error->text,
  15620. error->text_buffer_size,
  15621. "Can not create mutex");
  15622. }
  15623. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15624. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15625. #endif
  15626. closesocket(sock);
  15627. mg_free(conn);
  15628. return NULL;
  15629. }
  15630. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15631. if (use_ssl) {
  15632. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15633. * SSL_CTX_set_verify call is needed to switch off server
  15634. * certificate checking, which is off by default in OpenSSL and
  15635. * on in yaSSL. */
  15636. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15637. * SSL_VERIFY_PEER, verify_ssl_server); */
  15638. if (client_options->client_cert) {
  15639. if (!ssl_use_pem_file(conn->phys_ctx,
  15640. conn->dom_ctx,
  15641. client_options->client_cert,
  15642. NULL)) {
  15643. if (error != NULL) {
  15644. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15645. mg_snprintf(NULL,
  15646. NULL, /* No truncation check for ebuf */
  15647. error->text,
  15648. error->text_buffer_size,
  15649. "Can not use SSL client certificate");
  15650. }
  15651. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15652. closesocket(sock);
  15653. mg_free(conn);
  15654. return NULL;
  15655. }
  15656. }
  15657. if (client_options->server_cert) {
  15658. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15659. client_options->server_cert,
  15660. NULL)
  15661. != 1) {
  15662. if (error != NULL) {
  15663. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15664. mg_snprintf(NULL,
  15665. NULL, /* No truncation check for ebuf */
  15666. error->text,
  15667. error->text_buffer_size,
  15668. "SSL_CTX_load_verify_locations error: %s",
  15669. ssl_error());
  15670. }
  15671. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15672. closesocket(sock);
  15673. mg_free(conn);
  15674. return NULL;
  15675. }
  15676. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15677. } else {
  15678. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15679. }
  15680. if (!sslize(conn, SSL_connect, client_options)) {
  15681. if (error != NULL) {
  15682. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15683. mg_snprintf(NULL,
  15684. NULL, /* No truncation check for ebuf */
  15685. error->text,
  15686. error->text_buffer_size,
  15687. "SSL connection error");
  15688. }
  15689. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15690. closesocket(sock);
  15691. mg_free(conn);
  15692. return NULL;
  15693. }
  15694. }
  15695. #endif
  15696. return conn;
  15697. }
  15698. CIVETWEB_API struct mg_connection *
  15699. mg_connect_client_secure(const struct mg_client_options *client_options,
  15700. char *error_buffer,
  15701. size_t error_buffer_size)
  15702. {
  15703. struct mg_init_data init;
  15704. struct mg_error_data error;
  15705. memset(&init, 0, sizeof(init));
  15706. memset(&error, 0, sizeof(error));
  15707. error.text_buffer_size = error_buffer_size;
  15708. error.text = error_buffer;
  15709. return mg_connect_client_impl(client_options, 1, &init, &error);
  15710. }
  15711. CIVETWEB_API struct mg_connection *
  15712. mg_connect_client(const char *host,
  15713. int port,
  15714. int use_ssl,
  15715. char *error_buffer,
  15716. size_t error_buffer_size)
  15717. {
  15718. struct mg_client_options opts;
  15719. struct mg_init_data init;
  15720. struct mg_error_data error;
  15721. memset(&init, 0, sizeof(init));
  15722. memset(&error, 0, sizeof(error));
  15723. error.text_buffer_size = error_buffer_size;
  15724. error.text = error_buffer;
  15725. memset(&opts, 0, sizeof(opts));
  15726. opts.host = host;
  15727. opts.port = port;
  15728. if (use_ssl) {
  15729. opts.host_name = host;
  15730. }
  15731. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  15732. }
  15733. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15734. CIVETWEB_API struct mg_connection *
  15735. mg_connect_client2(const char *host,
  15736. const char *protocol,
  15737. int port,
  15738. const char *path,
  15739. struct mg_init_data *init,
  15740. struct mg_error_data *error)
  15741. {
  15742. (void)path;
  15743. int is_ssl, is_ws;
  15744. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15745. if (error != NULL) {
  15746. error->code = MG_ERROR_DATA_CODE_OK;
  15747. error->code_sub = 0;
  15748. if (error->text_buffer_size > 0) {
  15749. *error->text = 0;
  15750. }
  15751. }
  15752. if ((host == NULL) || (protocol == NULL)) {
  15753. if (error != NULL) {
  15754. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15755. mg_snprintf(NULL,
  15756. NULL, /* No truncation check for error buffers */
  15757. error->text,
  15758. error->text_buffer_size,
  15759. "%s",
  15760. "Invalid parameters");
  15761. }
  15762. return NULL;
  15763. }
  15764. /* check all known protocolls */
  15765. if (!mg_strcasecmp(protocol, "http")) {
  15766. is_ssl = 0;
  15767. is_ws = 0;
  15768. } else if (!mg_strcasecmp(protocol, "https")) {
  15769. is_ssl = 1;
  15770. is_ws = 0;
  15771. #if defined(USE_WEBSOCKET)
  15772. } else if (!mg_strcasecmp(protocol, "ws")) {
  15773. is_ssl = 0;
  15774. is_ws = 1;
  15775. } else if (!mg_strcasecmp(protocol, "wss")) {
  15776. is_ssl = 1;
  15777. is_ws = 1;
  15778. #endif
  15779. } else {
  15780. if (error != NULL) {
  15781. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15782. mg_snprintf(NULL,
  15783. NULL, /* No truncation check for error buffers */
  15784. error->text,
  15785. error->text_buffer_size,
  15786. "Protocol %s not supported",
  15787. protocol);
  15788. }
  15789. return NULL;
  15790. }
  15791. /* TODO: The current implementation here just calls the old
  15792. * implementations, without using any new options. This is just a first
  15793. * step to test the new interfaces. */
  15794. #if defined(USE_WEBSOCKET)
  15795. if (is_ws) {
  15796. /* TODO: implement all options */
  15797. return mg_connect_websocket_client(
  15798. host,
  15799. port,
  15800. is_ssl,
  15801. ((error != NULL) ? error->text : NULL),
  15802. ((error != NULL) ? error->text_buffer_size : 0),
  15803. (path ? path : ""),
  15804. NULL /* TODO: origin */,
  15805. experimental_websocket_client_data_wrapper,
  15806. experimental_websocket_client_close_wrapper,
  15807. (void *)init->callbacks);
  15808. }
  15809. #else
  15810. (void)is_ws;
  15811. #endif
  15812. /* TODO: all additional options */
  15813. struct mg_client_options opts;
  15814. memset(&opts, 0, sizeof(opts));
  15815. opts.host = host;
  15816. opts.port = port;
  15817. return mg_connect_client_impl(&opts, is_ssl, init, error);
  15818. }
  15819. #endif
  15820. static const struct {
  15821. const char *proto;
  15822. size_t proto_len;
  15823. unsigned default_port;
  15824. } abs_uri_protocols[] = {{"http://", 7, 80},
  15825. {"https://", 8, 443},
  15826. {"ws://", 5, 80},
  15827. {"wss://", 6, 443},
  15828. {NULL, 0, 0}};
  15829. /* Check if the uri is valid.
  15830. * return 0 for invalid uri,
  15831. * return 1 for *,
  15832. * return 2 for relative uri,
  15833. * return 3 for absolute uri without port,
  15834. * return 4 for absolute uri with port */
  15835. static int
  15836. get_uri_type(const char *uri)
  15837. {
  15838. int i;
  15839. const char *hostend, *portbegin;
  15840. char *portend;
  15841. unsigned long port;
  15842. /* According to the HTTP standard
  15843. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15844. * URI can be an asterisk (*) or should start with slash (relative uri),
  15845. * or it should start with the protocol (absolute uri). */
  15846. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15847. /* asterisk */
  15848. return 1;
  15849. }
  15850. /* Valid URIs according to RFC 3986
  15851. * (https://www.ietf.org/rfc/rfc3986.txt)
  15852. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15853. * and unreserved characters A-Z a-z 0-9 and -._~
  15854. * and % encoded symbols.
  15855. */
  15856. for (i = 0; uri[i] != 0; i++) {
  15857. if (uri[i] < 33) {
  15858. /* control characters and spaces are invalid */
  15859. return 0;
  15860. }
  15861. /* Allow everything else here (See #894) */
  15862. }
  15863. /* A relative uri starts with a / character */
  15864. if (uri[0] == '/') {
  15865. /* relative uri */
  15866. return 2;
  15867. }
  15868. /* It could be an absolute uri: */
  15869. /* This function only checks if the uri is valid, not if it is
  15870. * addressing the current server. So civetweb can also be used
  15871. * as a proxy server. */
  15872. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15873. if (mg_strncasecmp(uri,
  15874. abs_uri_protocols[i].proto,
  15875. abs_uri_protocols[i].proto_len)
  15876. == 0) {
  15877. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15878. if (!hostend) {
  15879. return 0;
  15880. }
  15881. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15882. if (!portbegin) {
  15883. return 3;
  15884. }
  15885. port = strtoul(portbegin + 1, &portend, 10);
  15886. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15887. return 0;
  15888. }
  15889. return 4;
  15890. }
  15891. }
  15892. return 0;
  15893. }
  15894. /* Return NULL or the relative uri at the current server */
  15895. static const char *
  15896. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15897. {
  15898. const char *server_domain;
  15899. size_t server_domain_len;
  15900. size_t request_domain_len = 0;
  15901. unsigned long port = 0;
  15902. int i, auth_domain_check_enabled;
  15903. const char *hostbegin = NULL;
  15904. const char *hostend = NULL;
  15905. const char *portbegin;
  15906. char *portend;
  15907. auth_domain_check_enabled =
  15908. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15909. /* DNS is case insensitive, so use case insensitive string compare here
  15910. */
  15911. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15912. if (mg_strncasecmp(uri,
  15913. abs_uri_protocols[i].proto,
  15914. abs_uri_protocols[i].proto_len)
  15915. == 0) {
  15916. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15917. hostend = strchr(hostbegin, '/');
  15918. if (!hostend) {
  15919. return 0;
  15920. }
  15921. portbegin = strchr(hostbegin, ':');
  15922. if ((!portbegin) || (portbegin > hostend)) {
  15923. port = abs_uri_protocols[i].default_port;
  15924. request_domain_len = (size_t)(hostend - hostbegin);
  15925. } else {
  15926. port = strtoul(portbegin + 1, &portend, 10);
  15927. if ((portend != hostend) || (port <= 0)
  15928. || !is_valid_port(port)) {
  15929. return 0;
  15930. }
  15931. request_domain_len = (size_t)(portbegin - hostbegin);
  15932. }
  15933. /* protocol found, port set */
  15934. break;
  15935. }
  15936. }
  15937. if (!port) {
  15938. /* port remains 0 if the protocol is not found */
  15939. return 0;
  15940. }
  15941. /* Check if the request is directed to a different server. */
  15942. /* First check if the port is the same. */
  15943. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15944. /* Request is directed to a different port */
  15945. return 0;
  15946. }
  15947. /* Finally check if the server corresponds to the authentication
  15948. * domain of the server (the server domain).
  15949. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15950. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15951. * but do not allow substrings (like
  15952. * http://notmydomain.com/path/file.ext
  15953. * or http://mydomain.com.fake/path/file.ext).
  15954. */
  15955. if (auth_domain_check_enabled) {
  15956. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15957. server_domain_len = strlen(server_domain);
  15958. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15959. return 0;
  15960. }
  15961. if ((request_domain_len == server_domain_len)
  15962. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15963. /* Request is directed to this server - full name match. */
  15964. } else {
  15965. if (request_domain_len < (server_domain_len + 2)) {
  15966. /* Request is directed to another server: The server name
  15967. * is longer than the request name.
  15968. * Drop this case here to avoid overflows in the
  15969. * following checks. */
  15970. return 0;
  15971. }
  15972. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15973. /* Request is directed to another server: It could be a
  15974. * substring
  15975. * like notmyserver.com */
  15976. return 0;
  15977. }
  15978. if (0
  15979. != memcmp(server_domain,
  15980. hostbegin + request_domain_len - server_domain_len,
  15981. server_domain_len)) {
  15982. /* Request is directed to another server:
  15983. * The server name is different. */
  15984. return 0;
  15985. }
  15986. }
  15987. }
  15988. return hostend;
  15989. }
  15990. static int
  15991. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15992. {
  15993. if (ebuf_len > 0) {
  15994. ebuf[0] = '\0';
  15995. }
  15996. *err = 0;
  15997. reset_per_request_attributes(conn);
  15998. if (!conn) {
  15999. mg_snprintf(conn,
  16000. NULL, /* No truncation check for ebuf */
  16001. ebuf,
  16002. ebuf_len,
  16003. "%s",
  16004. "Internal error");
  16005. *err = 500;
  16006. return 0;
  16007. }
  16008. /* Set the time the request was received. This value should be used for
  16009. * timeouts. */
  16010. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16011. conn->request_len =
  16012. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16013. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16014. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16015. mg_snprintf(conn,
  16016. NULL, /* No truncation check for ebuf */
  16017. ebuf,
  16018. ebuf_len,
  16019. "%s",
  16020. "Invalid message size");
  16021. *err = 500;
  16022. return 0;
  16023. }
  16024. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16025. mg_snprintf(conn,
  16026. NULL, /* No truncation check for ebuf */
  16027. ebuf,
  16028. ebuf_len,
  16029. "%s",
  16030. "Message too large");
  16031. *err = 413;
  16032. return 0;
  16033. }
  16034. if (conn->request_len <= 0) {
  16035. if (conn->data_len > 0) {
  16036. mg_snprintf(conn,
  16037. NULL, /* No truncation check for ebuf */
  16038. ebuf,
  16039. ebuf_len,
  16040. "%s",
  16041. "Malformed message");
  16042. *err = 400;
  16043. } else {
  16044. /* Server did not recv anything -> just close the connection */
  16045. conn->must_close = 1;
  16046. mg_snprintf(conn,
  16047. NULL, /* No truncation check for ebuf */
  16048. ebuf,
  16049. ebuf_len,
  16050. "%s",
  16051. "No data received");
  16052. *err = 0;
  16053. }
  16054. return 0;
  16055. }
  16056. return 1;
  16057. }
  16058. static int
  16059. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16060. {
  16061. const char *cl;
  16062. conn->connection_type =
  16063. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16064. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16065. return 0;
  16066. }
  16067. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16068. <= 0) {
  16069. mg_snprintf(conn,
  16070. NULL, /* No truncation check for ebuf */
  16071. ebuf,
  16072. ebuf_len,
  16073. "%s",
  16074. "Bad request");
  16075. *err = 400;
  16076. return 0;
  16077. }
  16078. /* Message is a valid request */
  16079. if (!switch_domain_context(conn)) {
  16080. mg_snprintf(conn,
  16081. NULL, /* No truncation check for ebuf */
  16082. ebuf,
  16083. ebuf_len,
  16084. "%s",
  16085. "Bad request: Host mismatch");
  16086. *err = 400;
  16087. return 0;
  16088. }
  16089. #if USE_ZLIB
  16090. if (((cl = get_header(conn->request_info.http_headers,
  16091. conn->request_info.num_headers,
  16092. "Accept-Encoding"))
  16093. != NULL)
  16094. && strstr(cl, "gzip")) {
  16095. conn->accept_gzip = 1;
  16096. }
  16097. #endif
  16098. if (((cl = get_header(conn->request_info.http_headers,
  16099. conn->request_info.num_headers,
  16100. "Transfer-Encoding"))
  16101. != NULL)
  16102. && mg_strcasecmp(cl, "identity")) {
  16103. if (mg_strcasecmp(cl, "chunked")) {
  16104. mg_snprintf(conn,
  16105. NULL, /* No truncation check for ebuf */
  16106. ebuf,
  16107. ebuf_len,
  16108. "%s",
  16109. "Bad request");
  16110. *err = 400;
  16111. return 0;
  16112. }
  16113. conn->is_chunked = 1;
  16114. conn->content_len = 0; /* not yet read */
  16115. } else if ((cl = get_header(conn->request_info.http_headers,
  16116. conn->request_info.num_headers,
  16117. "Content-Length"))
  16118. != NULL) {
  16119. /* Request has content length set */
  16120. char *endptr = NULL;
  16121. conn->content_len = strtoll(cl, &endptr, 10);
  16122. if ((endptr == cl) || (conn->content_len < 0)) {
  16123. mg_snprintf(conn,
  16124. NULL, /* No truncation check for ebuf */
  16125. ebuf,
  16126. ebuf_len,
  16127. "%s",
  16128. "Bad request");
  16129. *err = 411;
  16130. return 0;
  16131. }
  16132. /* Publish the content length back to the request info. */
  16133. conn->request_info.content_length = conn->content_len;
  16134. } else {
  16135. /* There is no exception, see RFC7230. */
  16136. conn->content_len = 0;
  16137. }
  16138. return 1;
  16139. }
  16140. /* conn is assumed to be valid in this internal function */
  16141. static int
  16142. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16143. {
  16144. const char *cl;
  16145. conn->connection_type =
  16146. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16147. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16148. return 0;
  16149. }
  16150. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16151. <= 0) {
  16152. mg_snprintf(conn,
  16153. NULL, /* No truncation check for ebuf */
  16154. ebuf,
  16155. ebuf_len,
  16156. "%s",
  16157. "Bad response");
  16158. *err = 400;
  16159. return 0;
  16160. }
  16161. /* Message is a valid response */
  16162. if (((cl = get_header(conn->response_info.http_headers,
  16163. conn->response_info.num_headers,
  16164. "Transfer-Encoding"))
  16165. != NULL)
  16166. && mg_strcasecmp(cl, "identity")) {
  16167. if (mg_strcasecmp(cl, "chunked")) {
  16168. mg_snprintf(conn,
  16169. NULL, /* No truncation check for ebuf */
  16170. ebuf,
  16171. ebuf_len,
  16172. "%s",
  16173. "Bad request");
  16174. *err = 400;
  16175. return 0;
  16176. }
  16177. conn->is_chunked = 1;
  16178. conn->content_len = 0; /* not yet read */
  16179. } else if ((cl = get_header(conn->response_info.http_headers,
  16180. conn->response_info.num_headers,
  16181. "Content-Length"))
  16182. != NULL) {
  16183. char *endptr = NULL;
  16184. conn->content_len = strtoll(cl, &endptr, 10);
  16185. if ((endptr == cl) || (conn->content_len < 0)) {
  16186. mg_snprintf(conn,
  16187. NULL, /* No truncation check for ebuf */
  16188. ebuf,
  16189. ebuf_len,
  16190. "%s",
  16191. "Bad request");
  16192. *err = 411;
  16193. return 0;
  16194. }
  16195. /* Publish the content length back to the response info. */
  16196. conn->response_info.content_length = conn->content_len;
  16197. /* TODO: check if it is still used in response_info */
  16198. conn->request_info.content_length = conn->content_len;
  16199. /* TODO: we should also consider HEAD method */
  16200. if (conn->response_info.status_code == 304) {
  16201. conn->content_len = 0;
  16202. }
  16203. } else {
  16204. /* TODO: we should also consider HEAD method */
  16205. if (((conn->response_info.status_code >= 100)
  16206. && (conn->response_info.status_code <= 199))
  16207. || (conn->response_info.status_code == 204)
  16208. || (conn->response_info.status_code == 304)) {
  16209. conn->content_len = 0;
  16210. } else {
  16211. conn->content_len = -1; /* unknown content length */
  16212. }
  16213. }
  16214. return 1;
  16215. }
  16216. CIVETWEB_API int
  16217. mg_get_response(struct mg_connection *conn,
  16218. char *ebuf,
  16219. size_t ebuf_len,
  16220. int timeout)
  16221. {
  16222. int err, ret;
  16223. char txt[32]; /* will not overflow */
  16224. char *save_timeout;
  16225. char *new_timeout;
  16226. if (ebuf_len > 0) {
  16227. ebuf[0] = '\0';
  16228. }
  16229. if (!conn) {
  16230. mg_snprintf(conn,
  16231. NULL, /* No truncation check for ebuf */
  16232. ebuf,
  16233. ebuf_len,
  16234. "%s",
  16235. "Parameter error");
  16236. return -1;
  16237. }
  16238. /* Reset the previous responses */
  16239. conn->data_len = 0;
  16240. /* Implementation of API function for HTTP clients */
  16241. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16242. if (timeout >= 0) {
  16243. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16244. new_timeout = txt;
  16245. } else {
  16246. new_timeout = NULL;
  16247. }
  16248. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16249. ret = get_response(conn, ebuf, ebuf_len, &err);
  16250. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16251. /* TODO: here, the URI is the http response code */
  16252. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16253. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16254. /* TODO (mid): Define proper return values - maybe return length?
  16255. * For the first test use <0 for error and >0 for OK */
  16256. return (ret == 0) ? -1 : +1;
  16257. }
  16258. CIVETWEB_API struct mg_connection *
  16259. mg_download(const char *host,
  16260. int port,
  16261. int use_ssl,
  16262. char *ebuf,
  16263. size_t ebuf_len,
  16264. const char *fmt,
  16265. ...)
  16266. {
  16267. struct mg_connection *conn;
  16268. va_list ap;
  16269. int i;
  16270. int reqerr;
  16271. if (ebuf_len > 0) {
  16272. ebuf[0] = '\0';
  16273. }
  16274. va_start(ap, fmt);
  16275. /* open a connection */
  16276. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16277. if (conn != NULL) {
  16278. i = mg_vprintf(conn, fmt, ap);
  16279. if (i <= 0) {
  16280. mg_snprintf(conn,
  16281. NULL, /* No truncation check for ebuf */
  16282. ebuf,
  16283. ebuf_len,
  16284. "%s",
  16285. "Error sending request");
  16286. } else {
  16287. /* make sure the buffer is clear */
  16288. conn->data_len = 0;
  16289. get_response(conn, ebuf, ebuf_len, &reqerr);
  16290. /* TODO: here, the URI is the http response code */
  16291. conn->request_info.local_uri = conn->request_info.request_uri;
  16292. }
  16293. }
  16294. /* if an error occurred, close the connection */
  16295. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16296. mg_close_connection(conn);
  16297. conn = NULL;
  16298. }
  16299. va_end(ap);
  16300. return conn;
  16301. }
  16302. struct websocket_client_thread_data {
  16303. struct mg_connection *conn;
  16304. mg_websocket_data_handler data_handler;
  16305. mg_websocket_close_handler close_handler;
  16306. void *callback_data;
  16307. };
  16308. #if defined(USE_WEBSOCKET)
  16309. #if defined(_WIN32)
  16310. static unsigned __stdcall websocket_client_thread(void *data)
  16311. #else
  16312. static void *
  16313. websocket_client_thread(void *data)
  16314. #endif
  16315. {
  16316. struct websocket_client_thread_data *cdata =
  16317. (struct websocket_client_thread_data *)data;
  16318. void *user_thread_ptr = NULL;
  16319. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16320. struct sigaction sa;
  16321. /* Ignore SIGPIPE */
  16322. memset(&sa, 0, sizeof(sa));
  16323. sa.sa_handler = SIG_IGN;
  16324. sigaction(SIGPIPE, &sa, NULL);
  16325. #endif
  16326. mg_set_thread_name("ws-clnt");
  16327. if (cdata->conn->phys_ctx) {
  16328. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16329. /* 3 indicates a websocket client thread */
  16330. /* TODO: check if conn->phys_ctx can be set */
  16331. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16332. cdata->conn->phys_ctx, 3);
  16333. }
  16334. }
  16335. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16336. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16337. if (cdata->close_handler != NULL) {
  16338. cdata->close_handler(cdata->conn, cdata->callback_data);
  16339. }
  16340. /* The websocket_client context has only this thread. If it runs out,
  16341. set the stop_flag to 2 (= "stopped"). */
  16342. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16343. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16344. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16345. 3,
  16346. user_thread_ptr);
  16347. }
  16348. mg_free((void *)cdata);
  16349. #if defined(_WIN32)
  16350. return 0;
  16351. #else
  16352. return NULL;
  16353. #endif
  16354. }
  16355. #endif
  16356. static struct mg_connection *
  16357. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16358. int use_ssl,
  16359. char *error_buffer,
  16360. size_t error_buffer_size,
  16361. const char *path,
  16362. const char *origin,
  16363. const char *extensions,
  16364. mg_websocket_data_handler data_func,
  16365. mg_websocket_close_handler close_func,
  16366. void *user_data)
  16367. {
  16368. struct mg_connection *conn = NULL;
  16369. #if defined(USE_WEBSOCKET)
  16370. struct websocket_client_thread_data *thread_data;
  16371. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16372. const char *host = client_options->host;
  16373. int i;
  16374. struct mg_init_data init;
  16375. struct mg_error_data error;
  16376. memset(&init, 0, sizeof(init));
  16377. memset(&error, 0, sizeof(error));
  16378. error.text_buffer_size = error_buffer_size;
  16379. error.text = error_buffer;
  16380. #if defined(__clang__)
  16381. #pragma clang diagnostic push
  16382. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16383. #endif
  16384. /* Establish the client connection and request upgrade */
  16385. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16386. /* Connection object will be null if something goes wrong */
  16387. if (conn == NULL) {
  16388. /* error_buffer should be already filled ... */
  16389. if (!error_buffer[0]) {
  16390. /* ... if not add an error message */
  16391. mg_snprintf(conn,
  16392. NULL, /* No truncation check for ebuf */
  16393. error_buffer,
  16394. error_buffer_size,
  16395. "Unexpected error");
  16396. }
  16397. return NULL;
  16398. }
  16399. if (origin != NULL) {
  16400. if (extensions != NULL) {
  16401. i = mg_printf(conn,
  16402. "GET %s HTTP/1.1\r\n"
  16403. "Host: %s\r\n"
  16404. "Upgrade: websocket\r\n"
  16405. "Connection: Upgrade\r\n"
  16406. "Sec-WebSocket-Key: %s\r\n"
  16407. "Sec-WebSocket-Version: 13\r\n"
  16408. "Sec-WebSocket-Extensions: %s\r\n"
  16409. "Origin: %s\r\n"
  16410. "\r\n",
  16411. path,
  16412. host,
  16413. magic,
  16414. extensions,
  16415. origin);
  16416. } else {
  16417. i = mg_printf(conn,
  16418. "GET %s HTTP/1.1\r\n"
  16419. "Host: %s\r\n"
  16420. "Upgrade: websocket\r\n"
  16421. "Connection: Upgrade\r\n"
  16422. "Sec-WebSocket-Key: %s\r\n"
  16423. "Sec-WebSocket-Version: 13\r\n"
  16424. "Origin: %s\r\n"
  16425. "\r\n",
  16426. path,
  16427. host,
  16428. magic,
  16429. origin);
  16430. }
  16431. } else {
  16432. if (extensions != NULL) {
  16433. i = mg_printf(conn,
  16434. "GET %s HTTP/1.1\r\n"
  16435. "Host: %s\r\n"
  16436. "Upgrade: websocket\r\n"
  16437. "Connection: Upgrade\r\n"
  16438. "Sec-WebSocket-Key: %s\r\n"
  16439. "Sec-WebSocket-Version: 13\r\n"
  16440. "Sec-WebSocket-Extensions: %s\r\n"
  16441. "\r\n",
  16442. path,
  16443. host,
  16444. magic,
  16445. extensions);
  16446. } else {
  16447. i = mg_printf(conn,
  16448. "GET %s HTTP/1.1\r\n"
  16449. "Host: %s\r\n"
  16450. "Upgrade: websocket\r\n"
  16451. "Connection: Upgrade\r\n"
  16452. "Sec-WebSocket-Key: %s\r\n"
  16453. "Sec-WebSocket-Version: 13\r\n"
  16454. "\r\n",
  16455. path,
  16456. host,
  16457. magic);
  16458. }
  16459. }
  16460. if (i <= 0) {
  16461. mg_snprintf(conn,
  16462. NULL, /* No truncation check for ebuf */
  16463. error_buffer,
  16464. error_buffer_size,
  16465. "%s",
  16466. "Error sending request");
  16467. mg_close_connection(conn);
  16468. return NULL;
  16469. }
  16470. conn->data_len = 0;
  16471. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16472. mg_close_connection(conn);
  16473. return NULL;
  16474. }
  16475. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16476. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16477. #if defined(__clang__)
  16478. #pragma clang diagnostic pop
  16479. #endif
  16480. if (conn->response_info.status_code != 101) {
  16481. /* We sent an "upgrade" request. For a correct websocket
  16482. * protocol handshake, we expect a "101 Continue" response.
  16483. * Otherwise it is a protocol violation. Maybe the HTTP
  16484. * Server does not know websockets. */
  16485. if (!*error_buffer) {
  16486. /* set an error, if not yet set */
  16487. mg_snprintf(conn,
  16488. NULL, /* No truncation check for ebuf */
  16489. error_buffer,
  16490. error_buffer_size,
  16491. "Unexpected server reply");
  16492. }
  16493. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16494. mg_close_connection(conn);
  16495. return NULL;
  16496. }
  16497. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16498. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16499. if (!thread_data) {
  16500. DEBUG_TRACE("%s\r\n", "Out of memory");
  16501. mg_close_connection(conn);
  16502. return NULL;
  16503. }
  16504. thread_data->conn = conn;
  16505. thread_data->data_handler = data_func;
  16506. thread_data->close_handler = close_func;
  16507. thread_data->callback_data = user_data;
  16508. conn->phys_ctx->worker_threadids =
  16509. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16510. if (!conn->phys_ctx->worker_threadids) {
  16511. DEBUG_TRACE("%s\r\n", "Out of memory");
  16512. mg_free(thread_data);
  16513. mg_close_connection(conn);
  16514. return NULL;
  16515. }
  16516. /* Now upgrade to ws/wss client context */
  16517. conn->phys_ctx->user_data = user_data;
  16518. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16519. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16520. /* Start a thread to read the websocket client connection
  16521. * This thread will automatically stop when mg_disconnect is
  16522. * called on the client connection */
  16523. if (mg_start_thread_with_id(websocket_client_thread,
  16524. thread_data,
  16525. conn->phys_ctx->worker_threadids)
  16526. != 0) {
  16527. conn->phys_ctx->cfg_worker_threads = 0;
  16528. mg_free(thread_data);
  16529. mg_close_connection(conn);
  16530. conn = NULL;
  16531. DEBUG_TRACE("%s",
  16532. "Websocket client connect thread could not be started\r\n");
  16533. }
  16534. #else
  16535. /* Appease "unused parameter" warnings */
  16536. (void)client_options;
  16537. (void)use_ssl;
  16538. (void)error_buffer;
  16539. (void)error_buffer_size;
  16540. (void)path;
  16541. (void)origin;
  16542. (void)extensions;
  16543. (void)user_data;
  16544. (void)data_func;
  16545. (void)close_func;
  16546. #endif
  16547. return conn;
  16548. }
  16549. CIVETWEB_API struct mg_connection *
  16550. mg_connect_websocket_client(const char *host,
  16551. int port,
  16552. int use_ssl,
  16553. char *error_buffer,
  16554. size_t error_buffer_size,
  16555. const char *path,
  16556. const char *origin,
  16557. mg_websocket_data_handler data_func,
  16558. mg_websocket_close_handler close_func,
  16559. void *user_data)
  16560. {
  16561. struct mg_client_options client_options;
  16562. memset(&client_options, 0, sizeof(client_options));
  16563. client_options.host = host;
  16564. client_options.port = port;
  16565. return mg_connect_websocket_client_impl(&client_options,
  16566. use_ssl,
  16567. error_buffer,
  16568. error_buffer_size,
  16569. path,
  16570. origin,
  16571. NULL,
  16572. data_func,
  16573. close_func,
  16574. user_data);
  16575. }
  16576. CIVETWEB_API struct mg_connection *
  16577. mg_connect_websocket_client_secure(
  16578. const struct mg_client_options *client_options,
  16579. char *error_buffer,
  16580. size_t error_buffer_size,
  16581. const char *path,
  16582. const char *origin,
  16583. mg_websocket_data_handler data_func,
  16584. mg_websocket_close_handler close_func,
  16585. void *user_data)
  16586. {
  16587. if (!client_options) {
  16588. return NULL;
  16589. }
  16590. return mg_connect_websocket_client_impl(client_options,
  16591. 1,
  16592. error_buffer,
  16593. error_buffer_size,
  16594. path,
  16595. origin,
  16596. NULL,
  16597. data_func,
  16598. close_func,
  16599. user_data);
  16600. }
  16601. CIVETWEB_API struct mg_connection *
  16602. mg_connect_websocket_client_extensions(const char *host,
  16603. int port,
  16604. int use_ssl,
  16605. char *error_buffer,
  16606. size_t error_buffer_size,
  16607. const char *path,
  16608. const char *origin,
  16609. const char *extensions,
  16610. mg_websocket_data_handler data_func,
  16611. mg_websocket_close_handler close_func,
  16612. void *user_data)
  16613. {
  16614. struct mg_client_options client_options;
  16615. memset(&client_options, 0, sizeof(client_options));
  16616. client_options.host = host;
  16617. client_options.port = port;
  16618. return mg_connect_websocket_client_impl(&client_options,
  16619. use_ssl,
  16620. error_buffer,
  16621. error_buffer_size,
  16622. path,
  16623. origin,
  16624. extensions,
  16625. data_func,
  16626. close_func,
  16627. user_data);
  16628. }
  16629. CIVETWEB_API struct mg_connection *
  16630. mg_connect_websocket_client_secure_extensions(
  16631. const struct mg_client_options *client_options,
  16632. char *error_buffer,
  16633. size_t error_buffer_size,
  16634. const char *path,
  16635. const char *origin,
  16636. const char *extensions,
  16637. mg_websocket_data_handler data_func,
  16638. mg_websocket_close_handler close_func,
  16639. void *user_data)
  16640. {
  16641. if (!client_options) {
  16642. return NULL;
  16643. }
  16644. return mg_connect_websocket_client_impl(client_options,
  16645. 1,
  16646. error_buffer,
  16647. error_buffer_size,
  16648. path,
  16649. origin,
  16650. extensions,
  16651. data_func,
  16652. close_func,
  16653. user_data);
  16654. }
  16655. /* Prepare connection data structure */
  16656. static void
  16657. init_connection(struct mg_connection *conn)
  16658. {
  16659. /* Is keep alive allowed by the server */
  16660. int keep_alive_enabled =
  16661. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16662. if (!keep_alive_enabled) {
  16663. conn->must_close = 1;
  16664. }
  16665. /* Important: on new connection, reset the receiving buffer. Credit
  16666. * goes to crule42. */
  16667. conn->data_len = 0;
  16668. conn->handled_requests = 0;
  16669. conn->connection_type = CONNECTION_TYPE_INVALID;
  16670. mg_set_user_connection_data(conn, NULL);
  16671. #if defined(USE_SERVER_STATS)
  16672. conn->conn_state = 2; /* init */
  16673. #endif
  16674. /* call the init_connection callback if assigned */
  16675. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16676. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16677. void *conn_data = NULL;
  16678. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16679. mg_set_user_connection_data(conn, conn_data);
  16680. }
  16681. }
  16682. }
  16683. /* Process a connection - may handle multiple requests
  16684. * using the same connection.
  16685. * Must be called with a valid connection (conn and
  16686. * conn->phys_ctx must be valid).
  16687. */
  16688. static void
  16689. process_new_connection(struct mg_connection *conn)
  16690. {
  16691. struct mg_request_info *ri = &conn->request_info;
  16692. int keep_alive, discard_len;
  16693. char ebuf[100];
  16694. const char *hostend;
  16695. int reqerr, uri_type;
  16696. #if defined(USE_SERVER_STATS)
  16697. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16698. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16699. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16700. #endif
  16701. DEBUG_TRACE("Start processing connection from %s",
  16702. conn->request_info.remote_addr);
  16703. /* Loop over multiple requests sent using the same connection
  16704. * (while "keep alive"). */
  16705. do {
  16706. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16707. conn->handled_requests + 1);
  16708. #if defined(USE_SERVER_STATS)
  16709. conn->conn_state = 3; /* ready */
  16710. #endif
  16711. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16712. /* The request sent by the client could not be understood by
  16713. * the server, or it was incomplete or a timeout. Send an
  16714. * error message and close the connection. */
  16715. if (reqerr > 0) {
  16716. DEBUG_ASSERT(ebuf[0] != '\0');
  16717. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16718. }
  16719. } else if (strcmp(ri->http_version, "1.0")
  16720. && strcmp(ri->http_version, "1.1")) {
  16721. /* HTTP/2 is not allowed here */
  16722. mg_snprintf(conn,
  16723. NULL, /* No truncation check for ebuf */
  16724. ebuf,
  16725. sizeof(ebuf),
  16726. "Bad HTTP version: [%s]",
  16727. ri->http_version);
  16728. mg_send_http_error(conn, 505, "%s", ebuf);
  16729. }
  16730. if (ebuf[0] == '\0') {
  16731. uri_type = get_uri_type(conn->request_info.request_uri);
  16732. switch (uri_type) {
  16733. case 1:
  16734. /* Asterisk */
  16735. conn->request_info.local_uri_raw = 0;
  16736. /* TODO: Deal with '*'. */
  16737. break;
  16738. case 2:
  16739. /* relative uri */
  16740. conn->request_info.local_uri_raw =
  16741. conn->request_info.request_uri;
  16742. break;
  16743. case 3:
  16744. case 4:
  16745. /* absolute uri (with/without port) */
  16746. hostend = get_rel_url_at_current_server(
  16747. conn->request_info.request_uri, conn);
  16748. if (hostend) {
  16749. conn->request_info.local_uri_raw = hostend;
  16750. } else {
  16751. conn->request_info.local_uri_raw = NULL;
  16752. }
  16753. break;
  16754. default:
  16755. mg_snprintf(conn,
  16756. NULL, /* No truncation check for ebuf */
  16757. ebuf,
  16758. sizeof(ebuf),
  16759. "Invalid URI");
  16760. mg_send_http_error(conn, 400, "%s", ebuf);
  16761. conn->request_info.local_uri_raw = NULL;
  16762. break;
  16763. }
  16764. conn->request_info.local_uri =
  16765. (char *)conn->request_info.local_uri_raw;
  16766. }
  16767. if (ebuf[0] != '\0') {
  16768. conn->protocol_type = -1;
  16769. } else {
  16770. /* HTTP/1 allows protocol upgrade */
  16771. conn->protocol_type = should_switch_to_protocol(conn);
  16772. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16773. /* This will occur, if a HTTP/1.1 request should be upgraded
  16774. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16775. * Since most (all?) major browsers only support HTTP/2 using
  16776. * ALPN, this is hard to test and very low priority.
  16777. * Deactivate it (at least for now).
  16778. */
  16779. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16780. }
  16781. }
  16782. DEBUG_TRACE("http: %s, error: %s",
  16783. (ri->http_version ? ri->http_version : "none"),
  16784. (ebuf[0] ? ebuf : "none"));
  16785. if (ebuf[0] == '\0') {
  16786. if (conn->request_info.local_uri) {
  16787. /* handle request to local server */
  16788. handle_request_stat_log(conn);
  16789. } else {
  16790. /* TODO: handle non-local request (PROXY) */
  16791. conn->must_close = 1;
  16792. }
  16793. } else {
  16794. conn->must_close = 1;
  16795. }
  16796. /* Response complete. Free header buffer */
  16797. free_buffered_response_header_list(conn);
  16798. if (ri->remote_user != NULL) {
  16799. mg_free((void *)ri->remote_user);
  16800. /* Important! When having connections with and without auth
  16801. * would cause double free and then crash */
  16802. ri->remote_user = NULL;
  16803. }
  16804. /* NOTE(lsm): order is important here. should_keep_alive() call
  16805. * is using parsed request, which will be invalid after
  16806. * memmove's below.
  16807. * Therefore, memorize should_keep_alive() result now for later
  16808. * use in loop exit condition. */
  16809. /* Enable it only if this request is completely discardable. */
  16810. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16811. && should_keep_alive(conn) && (conn->content_len >= 0)
  16812. && (conn->request_len > 0)
  16813. && ((conn->is_chunked == 4)
  16814. || (!conn->is_chunked
  16815. && ((conn->consumed_content == conn->content_len)
  16816. || ((conn->request_len + conn->content_len)
  16817. <= conn->data_len))))
  16818. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16819. if (keep_alive) {
  16820. /* Discard all buffered data for this request */
  16821. discard_len =
  16822. ((conn->request_len + conn->content_len) < conn->data_len)
  16823. ? (int)(conn->request_len + conn->content_len)
  16824. : conn->data_len;
  16825. conn->data_len -= discard_len;
  16826. if (conn->data_len > 0) {
  16827. DEBUG_TRACE("discard_len = %d", discard_len);
  16828. memmove(conn->buf,
  16829. conn->buf + discard_len,
  16830. (size_t)conn->data_len);
  16831. }
  16832. }
  16833. DEBUG_ASSERT(conn->data_len >= 0);
  16834. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16835. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16836. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16837. (long int)conn->data_len,
  16838. (long int)conn->buf_size);
  16839. break;
  16840. }
  16841. conn->handled_requests++;
  16842. } while (keep_alive);
  16843. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16844. conn->request_info.remote_addr,
  16845. difftime(time(NULL), conn->conn_birth_time));
  16846. close_connection(conn);
  16847. #if defined(USE_SERVER_STATS)
  16848. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16849. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16850. #endif
  16851. }
  16852. #if defined(ALTERNATIVE_QUEUE)
  16853. static void
  16854. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16855. {
  16856. unsigned int i;
  16857. while (!ctx->stop_flag) {
  16858. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16859. /* find a free worker slot and signal it */
  16860. if (ctx->client_socks[i].in_use == 2) {
  16861. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16862. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16863. ctx->client_socks[i] = *sp;
  16864. ctx->client_socks[i].in_use = 1;
  16865. /* socket has been moved to the consumer */
  16866. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16867. (void)event_signal(ctx->client_wait_events[i]);
  16868. return;
  16869. }
  16870. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16871. }
  16872. }
  16873. /* queue is full */
  16874. mg_sleep(1);
  16875. }
  16876. /* must consume */
  16877. set_blocking_mode(sp->sock);
  16878. closesocket(sp->sock);
  16879. }
  16880. static int
  16881. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16882. {
  16883. DEBUG_TRACE("%s", "going idle");
  16884. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16885. ctx->client_socks[thread_index].in_use = 2;
  16886. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16887. event_wait(ctx->client_wait_events[thread_index]);
  16888. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16889. *sp = ctx->client_socks[thread_index];
  16890. if (ctx->stop_flag) {
  16891. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16892. if (sp->in_use == 1) {
  16893. /* must consume */
  16894. set_blocking_mode(sp->sock);
  16895. closesocket(sp->sock);
  16896. }
  16897. return 0;
  16898. }
  16899. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16900. if (sp->in_use == 1) {
  16901. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16902. return 1;
  16903. }
  16904. /* must not reach here */
  16905. DEBUG_ASSERT(0);
  16906. return 0;
  16907. }
  16908. #else /* ALTERNATIVE_QUEUE */
  16909. /* Worker threads take accepted socket from the queue */
  16910. static int
  16911. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16912. {
  16913. (void)thread_index;
  16914. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16915. DEBUG_TRACE("%s", "going idle");
  16916. /* If the queue is empty, wait. We're idle at this point. */
  16917. while ((ctx->sq_head == ctx->sq_tail)
  16918. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16919. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16920. }
  16921. /* If we're stopping, sq_head may be equal to sq_tail. */
  16922. if (ctx->sq_head > ctx->sq_tail) {
  16923. /* Copy socket from the queue and increment tail */
  16924. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16925. ctx->sq_tail++;
  16926. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16927. /* Wrap pointers if needed */
  16928. while (ctx->sq_tail > ctx->sq_size) {
  16929. ctx->sq_tail -= ctx->sq_size;
  16930. ctx->sq_head -= ctx->sq_size;
  16931. }
  16932. }
  16933. (void)pthread_cond_signal(&ctx->sq_empty);
  16934. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16935. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16936. }
  16937. /* Master thread adds accepted socket to a queue */
  16938. static void
  16939. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16940. {
  16941. int queue_filled;
  16942. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16943. queue_filled = ctx->sq_head - ctx->sq_tail;
  16944. /* If the queue is full, wait */
  16945. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16946. && (queue_filled >= ctx->sq_size)) {
  16947. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16948. #if defined(USE_SERVER_STATS)
  16949. if (queue_filled > ctx->sq_max_fill) {
  16950. ctx->sq_max_fill = queue_filled;
  16951. }
  16952. #endif
  16953. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16954. ctx->sq_blocked = 0; /* Not blocked now */
  16955. queue_filled = ctx->sq_head - ctx->sq_tail;
  16956. }
  16957. if (queue_filled < ctx->sq_size) {
  16958. /* Copy socket to the queue and increment head */
  16959. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16960. ctx->sq_head++;
  16961. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16962. }
  16963. queue_filled = ctx->sq_head - ctx->sq_tail;
  16964. #if defined(USE_SERVER_STATS)
  16965. if (queue_filled > ctx->sq_max_fill) {
  16966. ctx->sq_max_fill = queue_filled;
  16967. }
  16968. #endif
  16969. (void)pthread_cond_signal(&ctx->sq_full);
  16970. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16971. }
  16972. #endif /* ALTERNATIVE_QUEUE */
  16973. static void
  16974. worker_thread_run(struct mg_connection *conn)
  16975. {
  16976. struct mg_context *ctx = conn->phys_ctx;
  16977. int thread_index;
  16978. struct mg_workerTLS tls;
  16979. mg_set_thread_name("worker");
  16980. tls.is_master = 0;
  16981. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16982. #if defined(_WIN32)
  16983. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16984. #endif
  16985. /* Initialize thread local storage before calling any callback */
  16986. pthread_setspecific(sTlsKey, &tls);
  16987. /* Check if there is a user callback */
  16988. if (ctx->callbacks.init_thread) {
  16989. /* call init_thread for a worker thread (type 1), and store the
  16990. * return value */
  16991. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16992. } else {
  16993. /* No callback: set user pointer to NULL */
  16994. tls.user_ptr = NULL;
  16995. }
  16996. /* Connection structure has been pre-allocated */
  16997. thread_index = (int)(conn - ctx->worker_connections);
  16998. if ((thread_index < 0)
  16999. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  17000. mg_cry_ctx_internal(ctx,
  17001. "Internal error: Invalid worker index %i",
  17002. thread_index);
  17003. return;
  17004. }
  17005. /* Request buffers are not pre-allocated. They are private to the
  17006. * request and do not contain any state information that might be
  17007. * of interest to anyone observing a server status. */
  17008. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17009. if (conn->buf == NULL) {
  17010. mg_cry_ctx_internal(
  17011. ctx,
  17012. "Out of memory: Cannot allocate buffer for worker %i",
  17013. thread_index);
  17014. return;
  17015. }
  17016. conn->buf_size = (int)ctx->max_request_size;
  17017. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17018. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17019. conn->request_info.user_data = ctx->user_data;
  17020. /* Allocate a mutex for this connection to allow communication both
  17021. * within the request handler and from elsewhere in the application
  17022. */
  17023. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17024. mg_free(conn->buf);
  17025. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17026. return;
  17027. }
  17028. #if defined(USE_SERVER_STATS)
  17029. conn->conn_state = 1; /* not consumed */
  17030. #endif
  17031. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17032. * signal sq_empty condvar to wake up the master waiting in
  17033. * produce_socket() */
  17034. while (consume_socket(ctx, &conn->client, thread_index)) {
  17035. /* New connections must start with new protocol negotiation */
  17036. tls.alpn_proto = NULL;
  17037. #if defined(USE_SERVER_STATS)
  17038. conn->conn_close_time = 0;
  17039. #endif
  17040. conn->conn_birth_time = time(NULL);
  17041. /* Fill in IP, port info early so even if SSL setup below fails,
  17042. * error handler would have the corresponding info.
  17043. * Thanks to Johannes Winkelmann for the patch.
  17044. */
  17045. conn->request_info.remote_port =
  17046. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17047. conn->request_info.server_port =
  17048. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17049. sockaddr_to_string(conn->request_info.remote_addr,
  17050. sizeof(conn->request_info.remote_addr),
  17051. &conn->client.rsa);
  17052. DEBUG_TRACE("Incomming %sconnection from %s",
  17053. (conn->client.is_ssl ? "SSL " : ""),
  17054. conn->request_info.remote_addr);
  17055. conn->request_info.is_ssl = conn->client.is_ssl;
  17056. if (conn->client.is_ssl) {
  17057. #if defined(USE_MBEDTLS)
  17058. /* HTTPS connection */
  17059. if (mbed_ssl_accept(&(conn->ssl),
  17060. conn->dom_ctx->ssl_ctx,
  17061. (int *)&(conn->client.sock),
  17062. conn->phys_ctx)
  17063. == 0) {
  17064. /* conn->dom_ctx is set in get_request */
  17065. /* process HTTPS connection */
  17066. init_connection(conn);
  17067. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17068. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17069. process_new_connection(conn);
  17070. } else {
  17071. /* make sure the connection is cleaned up on SSL failure */
  17072. close_connection(conn);
  17073. }
  17074. #elif !defined(NO_SSL)
  17075. /* HTTPS connection */
  17076. if (sslize(conn, SSL_accept, NULL)) {
  17077. /* conn->dom_ctx is set in get_request */
  17078. /* Get SSL client certificate information (if set) */
  17079. struct mg_client_cert client_cert;
  17080. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17081. conn->request_info.client_cert = &client_cert;
  17082. }
  17083. /* process HTTPS connection */
  17084. #if defined(USE_HTTP2)
  17085. if ((tls.alpn_proto != NULL)
  17086. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17087. /* process HTTPS/2 connection */
  17088. init_connection(conn);
  17089. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17090. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17091. conn->content_len =
  17092. -1; /* content length is not predefined */
  17093. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17094. process_new_http2_connection(conn);
  17095. } else
  17096. #endif
  17097. {
  17098. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17099. init_connection(conn);
  17100. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17101. /* Start with HTTP, WS will be an "upgrade" request later */
  17102. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17103. process_new_connection(conn);
  17104. }
  17105. /* Free client certificate info */
  17106. if (conn->request_info.client_cert) {
  17107. mg_free((void *)(conn->request_info.client_cert->subject));
  17108. mg_free((void *)(conn->request_info.client_cert->issuer));
  17109. mg_free((void *)(conn->request_info.client_cert->serial));
  17110. mg_free((void *)(conn->request_info.client_cert->finger));
  17111. /* Free certificate memory */
  17112. X509_free(
  17113. (X509 *)conn->request_info.client_cert->peer_cert);
  17114. conn->request_info.client_cert->peer_cert = 0;
  17115. conn->request_info.client_cert->subject = 0;
  17116. conn->request_info.client_cert->issuer = 0;
  17117. conn->request_info.client_cert->serial = 0;
  17118. conn->request_info.client_cert->finger = 0;
  17119. conn->request_info.client_cert = 0;
  17120. }
  17121. } else {
  17122. /* make sure the connection is cleaned up on SSL failure */
  17123. close_connection(conn);
  17124. }
  17125. #endif
  17126. } else {
  17127. /* process HTTP connection */
  17128. init_connection(conn);
  17129. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17130. /* Start with HTTP, WS will be an "upgrade" request later */
  17131. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17132. process_new_connection(conn);
  17133. }
  17134. DEBUG_TRACE("%s", "Connection closed");
  17135. #if defined(USE_SERVER_STATS)
  17136. conn->conn_close_time = time(NULL);
  17137. #endif
  17138. }
  17139. /* Call exit thread user callback */
  17140. if (ctx->callbacks.exit_thread) {
  17141. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17142. }
  17143. /* delete thread local storage objects */
  17144. pthread_setspecific(sTlsKey, NULL);
  17145. #if defined(_WIN32)
  17146. CloseHandle(tls.pthread_cond_helper_mutex);
  17147. #endif
  17148. pthread_mutex_destroy(&conn->mutex);
  17149. /* Free the request buffer. */
  17150. conn->buf_size = 0;
  17151. mg_free(conn->buf);
  17152. conn->buf = NULL;
  17153. /* Free cleaned URI (if any) */
  17154. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17155. mg_free((void *)conn->request_info.local_uri);
  17156. conn->request_info.local_uri = NULL;
  17157. }
  17158. #if defined(USE_SERVER_STATS)
  17159. conn->conn_state = 9; /* done */
  17160. #endif
  17161. DEBUG_TRACE("%s", "exiting");
  17162. }
  17163. /* Threads have different return types on Windows and Unix. */
  17164. #if defined(_WIN32)
  17165. static unsigned __stdcall worker_thread(void *thread_func_param)
  17166. {
  17167. worker_thread_run((struct mg_connection *)thread_func_param);
  17168. return 0;
  17169. }
  17170. #else
  17171. static void *
  17172. worker_thread(void *thread_func_param)
  17173. {
  17174. #if !defined(__ZEPHYR__)
  17175. struct sigaction sa;
  17176. /* Ignore SIGPIPE */
  17177. memset(&sa, 0, sizeof(sa));
  17178. sa.sa_handler = SIG_IGN;
  17179. sigaction(SIGPIPE, &sa, NULL);
  17180. #endif
  17181. worker_thread_run((struct mg_connection *)thread_func_param);
  17182. return NULL;
  17183. }
  17184. #endif /* _WIN32 */
  17185. /* This is an internal function, thus all arguments are expected to be
  17186. * valid - a NULL check is not required. */
  17187. static void
  17188. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17189. {
  17190. struct socket so;
  17191. char src_addr[IP_ADDR_STR_LEN];
  17192. socklen_t len = sizeof(so.rsa);
  17193. #if !defined(__ZEPHYR__)
  17194. int on = 1;
  17195. #endif
  17196. memset(&so, 0, sizeof(so));
  17197. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17198. == INVALID_SOCKET) {
  17199. } else if (check_acl(ctx, &so.rsa) != 1) {
  17200. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17201. mg_cry_ctx_internal(ctx,
  17202. "%s: %s is not allowed to connect",
  17203. __func__,
  17204. src_addr);
  17205. closesocket(so.sock);
  17206. } else {
  17207. /* Put so socket structure into the queue */
  17208. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17209. set_close_on_exec(so.sock, NULL, ctx);
  17210. so.is_ssl = listener->is_ssl;
  17211. so.ssl_redir = listener->ssl_redir;
  17212. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17213. mg_cry_ctx_internal(ctx,
  17214. "%s: getsockname() failed: %s",
  17215. __func__,
  17216. strerror(ERRNO));
  17217. }
  17218. #if !defined(__ZEPHYR__)
  17219. if ((so.lsa.sa.sa_family == AF_INET)
  17220. || (so.lsa.sa.sa_family == AF_INET6)) {
  17221. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17222. * This is needed because if HTTP-level keep-alive
  17223. * is enabled, and client resets the connection, server won't get
  17224. * TCP FIN or RST and will keep the connection open forever. With
  17225. * TCP keep-alive, next keep-alive handshake will figure out that
  17226. * the client is down and will close the server end.
  17227. * Thanks to Igor Klopov who suggested the patch. */
  17228. if (setsockopt(so.sock,
  17229. SOL_SOCKET,
  17230. SO_KEEPALIVE,
  17231. (SOCK_OPT_TYPE)&on,
  17232. sizeof(on))
  17233. != 0) {
  17234. mg_cry_ctx_internal(
  17235. ctx,
  17236. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17237. __func__,
  17238. strerror(ERRNO));
  17239. }
  17240. }
  17241. #endif
  17242. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17243. * to effectively fill up the underlying IP packet payload and
  17244. * reduce the overhead of sending lots of small buffers. However
  17245. * this hurts the server's throughput (ie. operations per second)
  17246. * when HTTP 1.1 persistent connections are used and the responses
  17247. * are relatively small (eg. less than 1400 bytes).
  17248. */
  17249. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17250. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17251. if (set_tcp_nodelay(&so, 1) != 0) {
  17252. mg_cry_ctx_internal(
  17253. ctx,
  17254. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17255. __func__,
  17256. strerror(ERRNO));
  17257. }
  17258. }
  17259. /* The "non blocking" property should already be
  17260. * inherited from the parent socket. Set it for
  17261. * non-compliant socket implementations. */
  17262. set_non_blocking_mode(so.sock);
  17263. so.in_use = 0;
  17264. produce_socket(ctx, &so);
  17265. }
  17266. }
  17267. static void
  17268. master_thread_run(struct mg_context *ctx)
  17269. {
  17270. struct mg_workerTLS tls;
  17271. struct mg_pollfd *pfd;
  17272. unsigned int i;
  17273. unsigned int workerthreadcount;
  17274. if (!ctx) {
  17275. return;
  17276. }
  17277. mg_set_thread_name("master");
  17278. /* Increase priority of the master thread */
  17279. #if defined(_WIN32)
  17280. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17281. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17282. int min_prio = sched_get_priority_min(SCHED_RR);
  17283. int max_prio = sched_get_priority_max(SCHED_RR);
  17284. if ((min_prio >= 0) && (max_prio >= 0)
  17285. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17286. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17287. struct sched_param sched_param = {0};
  17288. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17289. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17290. }
  17291. #endif
  17292. /* Initialize thread local storage */
  17293. #if defined(_WIN32)
  17294. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17295. #endif
  17296. tls.is_master = 1;
  17297. pthread_setspecific(sTlsKey, &tls);
  17298. if (ctx->callbacks.init_thread) {
  17299. /* Callback for the master thread (type 0) */
  17300. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17301. } else {
  17302. tls.user_ptr = NULL;
  17303. }
  17304. /* Lua background script "start" event */
  17305. #if defined(USE_LUA)
  17306. if (ctx->lua_background_state) {
  17307. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17308. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17309. /* call "start()" in Lua */
  17310. lua_getglobal(lstate, "start");
  17311. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17312. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17313. if (ret != 0) {
  17314. struct mg_connection fc;
  17315. lua_cry(fake_connection(&fc, ctx),
  17316. ret,
  17317. lstate,
  17318. "lua_background_script",
  17319. "start");
  17320. }
  17321. } else {
  17322. lua_pop(lstate, 1);
  17323. }
  17324. /* determine if there is a "log()" function in Lua background script */
  17325. lua_getglobal(lstate, "log");
  17326. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17327. ctx->lua_bg_log_available = 1;
  17328. }
  17329. lua_pop(lstate, 1);
  17330. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17331. }
  17332. #endif
  17333. /* Server starts *now* */
  17334. ctx->start_time = time(NULL);
  17335. /* Server accept loop */
  17336. pfd = ctx->listening_socket_fds;
  17337. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17338. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17339. pfd[i].fd = ctx->listening_sockets[i].sock;
  17340. pfd[i].events = POLLIN;
  17341. }
  17342. if (mg_poll(pfd,
  17343. ctx->num_listening_sockets,
  17344. SOCKET_TIMEOUT_QUANTUM,
  17345. &(ctx->stop_flag))
  17346. > 0) {
  17347. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17348. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17349. * successful poll, and POLLIN is defined as
  17350. * (POLLRDNORM | POLLRDBAND)
  17351. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17352. * pfd[i].revents == POLLIN. */
  17353. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17354. && (pfd[i].revents & POLLIN)) {
  17355. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17356. }
  17357. }
  17358. }
  17359. }
  17360. /* Here stop_flag is 1 - Initiate shutdown. */
  17361. DEBUG_TRACE("%s", "stopping workers");
  17362. /* Stop signal received: somebody called mg_stop. Quit. */
  17363. close_all_listening_sockets(ctx);
  17364. /* Wakeup workers that are waiting for connections to handle. */
  17365. #if defined(ALTERNATIVE_QUEUE)
  17366. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17367. event_signal(ctx->client_wait_events[i]);
  17368. }
  17369. #else
  17370. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17371. pthread_cond_broadcast(&ctx->sq_full);
  17372. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17373. #endif
  17374. /* Join all worker threads to avoid leaking threads. */
  17375. workerthreadcount = ctx->cfg_worker_threads;
  17376. for (i = 0; i < workerthreadcount; i++) {
  17377. if (ctx->worker_threadids[i] != 0) {
  17378. mg_join_thread(ctx->worker_threadids[i]);
  17379. }
  17380. }
  17381. #if defined(USE_LUA)
  17382. /* Free Lua state of lua background task */
  17383. if (ctx->lua_background_state) {
  17384. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17385. ctx->lua_bg_log_available = 0;
  17386. /* call "stop()" in Lua */
  17387. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17388. lua_getglobal(lstate, "stop");
  17389. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17390. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17391. if (ret != 0) {
  17392. struct mg_connection fc;
  17393. lua_cry(fake_connection(&fc, ctx),
  17394. ret,
  17395. lstate,
  17396. "lua_background_script",
  17397. "stop");
  17398. }
  17399. }
  17400. lua_close(lstate);
  17401. ctx->lua_background_state = 0;
  17402. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17403. }
  17404. #endif
  17405. DEBUG_TRACE("%s", "exiting");
  17406. /* call exit thread callback */
  17407. if (ctx->callbacks.exit_thread) {
  17408. /* Callback for the master thread (type 0) */
  17409. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17410. }
  17411. #if defined(_WIN32)
  17412. CloseHandle(tls.pthread_cond_helper_mutex);
  17413. #endif
  17414. pthread_setspecific(sTlsKey, NULL);
  17415. /* Signal mg_stop() that we're done.
  17416. * WARNING: This must be the very last thing this
  17417. * thread does, as ctx becomes invalid after this line. */
  17418. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17419. }
  17420. /* Threads have different return types on Windows and Unix. */
  17421. #if defined(_WIN32)
  17422. static unsigned __stdcall master_thread(void *thread_func_param)
  17423. {
  17424. master_thread_run((struct mg_context *)thread_func_param);
  17425. return 0;
  17426. }
  17427. #else
  17428. static void *
  17429. master_thread(void *thread_func_param)
  17430. {
  17431. #if !defined(__ZEPHYR__)
  17432. struct sigaction sa;
  17433. /* Ignore SIGPIPE */
  17434. memset(&sa, 0, sizeof(sa));
  17435. sa.sa_handler = SIG_IGN;
  17436. sigaction(SIGPIPE, &sa, NULL);
  17437. #endif
  17438. master_thread_run((struct mg_context *)thread_func_param);
  17439. return NULL;
  17440. }
  17441. #endif /* _WIN32 */
  17442. static void
  17443. free_context(struct mg_context *ctx)
  17444. {
  17445. int i;
  17446. struct mg_handler_info *tmp_rh;
  17447. if (ctx == NULL) {
  17448. return;
  17449. }
  17450. /* Call user callback */
  17451. if (ctx->callbacks.exit_context) {
  17452. ctx->callbacks.exit_context(ctx);
  17453. }
  17454. /* All threads exited, no sync is needed. Destroy thread mutex and
  17455. * condvars
  17456. */
  17457. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17458. #if defined(ALTERNATIVE_QUEUE)
  17459. mg_free(ctx->client_socks);
  17460. if (ctx->client_wait_events != NULL) {
  17461. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17462. event_destroy(ctx->client_wait_events[i]);
  17463. }
  17464. mg_free(ctx->client_wait_events);
  17465. }
  17466. #else
  17467. (void)pthread_cond_destroy(&ctx->sq_empty);
  17468. (void)pthread_cond_destroy(&ctx->sq_full);
  17469. mg_free(ctx->squeue);
  17470. #endif
  17471. /* Destroy other context global data structures mutex */
  17472. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17473. #if defined(USE_LUA)
  17474. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17475. #endif
  17476. /* Deallocate config parameters */
  17477. for (i = 0; i < NUM_OPTIONS; i++) {
  17478. if (ctx->dd.config[i] != NULL) {
  17479. #if defined(_MSC_VER)
  17480. #pragma warning(suppress : 6001)
  17481. #endif
  17482. mg_free(ctx->dd.config[i]);
  17483. }
  17484. }
  17485. /* Deallocate request handlers */
  17486. while (ctx->dd.handlers) {
  17487. tmp_rh = ctx->dd.handlers;
  17488. ctx->dd.handlers = tmp_rh->next;
  17489. mg_free(tmp_rh->uri);
  17490. mg_free(tmp_rh);
  17491. }
  17492. #if defined(USE_MBEDTLS)
  17493. if (ctx->dd.ssl_ctx != NULL) {
  17494. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17495. mg_free(ctx->dd.ssl_ctx);
  17496. ctx->dd.ssl_ctx = NULL;
  17497. }
  17498. #elif !defined(NO_SSL)
  17499. /* Deallocate SSL context */
  17500. if (ctx->dd.ssl_ctx != NULL) {
  17501. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17502. int callback_ret =
  17503. (ctx->callbacks.external_ssl_ctx == NULL)
  17504. ? 0
  17505. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17506. if (callback_ret == 0) {
  17507. SSL_CTX_free(ctx->dd.ssl_ctx);
  17508. }
  17509. /* else: ignore error and ommit SSL_CTX_free in case
  17510. * callback_ret is 1 */
  17511. }
  17512. #endif /* !NO_SSL */
  17513. /* Deallocate worker thread ID array */
  17514. mg_free(ctx->worker_threadids);
  17515. /* Deallocate worker thread ID array */
  17516. mg_free(ctx->worker_connections);
  17517. /* deallocate system name string */
  17518. mg_free(ctx->systemName);
  17519. /* Deallocate context itself */
  17520. mg_free(ctx);
  17521. }
  17522. CIVETWEB_API void
  17523. mg_stop(struct mg_context *ctx)
  17524. {
  17525. pthread_t mt;
  17526. if (!ctx) {
  17527. return;
  17528. }
  17529. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17530. * two threads is not allowed. */
  17531. mt = ctx->masterthreadid;
  17532. if (mt == 0) {
  17533. return;
  17534. }
  17535. ctx->masterthreadid = 0;
  17536. /* Set stop flag, so all threads know they have to exit. */
  17537. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17538. /* Join timer thread */
  17539. #if defined(USE_TIMERS)
  17540. timers_exit(ctx);
  17541. #endif
  17542. /* Wait until everything has stopped. */
  17543. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17544. (void)mg_sleep(10);
  17545. }
  17546. /* Wait to stop master thread */
  17547. mg_join_thread(mt);
  17548. /* Close remaining Lua states */
  17549. #if defined(USE_LUA)
  17550. lua_ctx_exit(ctx);
  17551. #endif
  17552. /* Free memory */
  17553. free_context(ctx);
  17554. }
  17555. static void
  17556. get_system_name(char **sysName)
  17557. {
  17558. #if defined(_WIN32)
  17559. char name[128];
  17560. DWORD dwVersion = 0;
  17561. DWORD dwMajorVersion = 0;
  17562. DWORD dwMinorVersion = 0;
  17563. DWORD dwBuild = 0;
  17564. BOOL wowRet, isWoW = FALSE;
  17565. #if defined(_MSC_VER)
  17566. #pragma warning(push)
  17567. /* GetVersion was declared deprecated */
  17568. #pragma warning(disable : 4996)
  17569. #endif
  17570. dwVersion = GetVersion();
  17571. #if defined(_MSC_VER)
  17572. #pragma warning(pop)
  17573. #endif
  17574. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17575. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17576. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17577. (void)dwBuild;
  17578. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17579. sprintf(name,
  17580. "Windows %u.%u%s",
  17581. (unsigned)dwMajorVersion,
  17582. (unsigned)dwMinorVersion,
  17583. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17584. *sysName = mg_strdup(name);
  17585. #elif defined(__ZEPHYR__)
  17586. *sysName = mg_strdup("Zephyr OS");
  17587. #else
  17588. struct utsname name;
  17589. memset(&name, 0, sizeof(name));
  17590. uname(&name);
  17591. *sysName = mg_strdup(name.sysname);
  17592. #endif
  17593. }
  17594. static void
  17595. legacy_init(const char **options)
  17596. {
  17597. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17598. if (options) {
  17599. const char **run_options = options;
  17600. const char *optname = config_options[LISTENING_PORTS].name;
  17601. /* Try to find the "listening_ports" option */
  17602. while (*run_options) {
  17603. if (!strcmp(*run_options, optname)) {
  17604. ports_option = run_options[1];
  17605. }
  17606. run_options += 2;
  17607. }
  17608. }
  17609. if (is_ssl_port_used(ports_option)) {
  17610. /* Initialize with SSL support */
  17611. mg_init_library(MG_FEATURES_TLS);
  17612. } else {
  17613. /* Initialize without SSL support */
  17614. mg_init_library(MG_FEATURES_DEFAULT);
  17615. }
  17616. }
  17617. CIVETWEB_API struct mg_context *
  17618. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17619. {
  17620. struct mg_context *ctx;
  17621. const char *name, *value, *default_value;
  17622. int idx, ok, workerthreadcount;
  17623. unsigned int i;
  17624. int itmp;
  17625. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17626. const char **options =
  17627. ((init != NULL) ? (init->configuration_options) : (NULL));
  17628. struct mg_workerTLS tls;
  17629. if (error != NULL) {
  17630. error->code = MG_ERROR_DATA_CODE_OK;
  17631. error->code_sub = 0;
  17632. if (error->text_buffer_size > 0) {
  17633. *error->text = 0;
  17634. }
  17635. }
  17636. if (mg_init_library_called == 0) {
  17637. /* Legacy INIT, if mg_start is called without mg_init_library.
  17638. * Note: This will cause a memory leak when unloading the library.
  17639. */
  17640. legacy_init(options);
  17641. }
  17642. if (mg_init_library_called == 0) {
  17643. if (error != NULL) {
  17644. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  17645. mg_snprintf(NULL,
  17646. NULL, /* No truncation check for error buffers */
  17647. error->text,
  17648. error->text_buffer_size,
  17649. "%s",
  17650. "Library uninitialized");
  17651. }
  17652. return NULL;
  17653. }
  17654. /* Allocate context and initialize reasonable general case defaults. */
  17655. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  17656. if (ctx == NULL) {
  17657. if (error != NULL) {
  17658. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17659. error->code_sub = (unsigned)sizeof(*ctx);
  17660. mg_snprintf(NULL,
  17661. NULL, /* No truncation check for error buffers */
  17662. error->text,
  17663. error->text_buffer_size,
  17664. "%s",
  17665. "Out of memory");
  17666. }
  17667. return NULL;
  17668. }
  17669. /* Random number generator will initialize at the first call */
  17670. ctx->dd.auth_nonce_mask =
  17671. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17672. /* Save started thread index to reuse in other external API calls
  17673. * For the sake of thread synchronization all non-civetweb threads
  17674. * can be considered as single external thread */
  17675. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17676. tls.is_master = -1; /* Thread calling mg_start */
  17677. tls.thread_idx = ctx->starter_thread_idx;
  17678. #if defined(_WIN32)
  17679. tls.pthread_cond_helper_mutex = NULL;
  17680. #endif
  17681. pthread_setspecific(sTlsKey, &tls);
  17682. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17683. #if !defined(ALTERNATIVE_QUEUE)
  17684. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17685. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17686. ctx->sq_blocked = 0;
  17687. #endif
  17688. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17689. #if defined(USE_LUA)
  17690. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17691. #endif
  17692. if (!ok) {
  17693. unsigned error_id = (unsigned)ERRNO;
  17694. const char *err_msg =
  17695. "Cannot initialize thread synchronization objects";
  17696. /* Fatal error - abort start. However, this situation should never
  17697. * occur in practice. */
  17698. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17699. if (error != NULL) {
  17700. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  17701. error->code_sub = error_id;
  17702. mg_snprintf(NULL,
  17703. NULL, /* No truncation check for error buffers */
  17704. error->text,
  17705. error->text_buffer_size,
  17706. "%s",
  17707. err_msg);
  17708. }
  17709. mg_free(ctx);
  17710. pthread_setspecific(sTlsKey, NULL);
  17711. return NULL;
  17712. }
  17713. if ((init != NULL) && (init->callbacks != NULL)) {
  17714. /* Set all callbacks except exit_context. */
  17715. ctx->callbacks = *init->callbacks;
  17716. exit_callback = init->callbacks->exit_context;
  17717. /* The exit callback is activated once the context is successfully
  17718. * created. It should not be called, if an incomplete context object
  17719. * is deleted during a failed initialization. */
  17720. ctx->callbacks.exit_context = 0;
  17721. }
  17722. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17723. ctx->dd.handlers = NULL;
  17724. ctx->dd.next = NULL;
  17725. #if defined(USE_LUA)
  17726. lua_ctx_init(ctx);
  17727. #endif
  17728. /* Store options */
  17729. while (options && (name = *options++) != NULL) {
  17730. idx = get_option_index(name);
  17731. if (idx == -1) {
  17732. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17733. if (error != NULL) {
  17734. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17735. error->code_sub = (unsigned)-1;
  17736. mg_snprintf(NULL,
  17737. NULL, /* No truncation check for error buffers */
  17738. error->text,
  17739. error->text_buffer_size,
  17740. "Invalid configuration option: %s",
  17741. name);
  17742. }
  17743. free_context(ctx);
  17744. pthread_setspecific(sTlsKey, NULL);
  17745. return NULL;
  17746. } else if ((value = *options++) == NULL) {
  17747. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17748. if (error != NULL) {
  17749. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17750. error->code_sub = (unsigned)idx;
  17751. mg_snprintf(NULL,
  17752. NULL, /* No truncation check for error buffers */
  17753. error->text,
  17754. error->text_buffer_size,
  17755. "Invalid configuration option value: %s",
  17756. name);
  17757. }
  17758. free_context(ctx);
  17759. pthread_setspecific(sTlsKey, NULL);
  17760. return NULL;
  17761. }
  17762. if (ctx->dd.config[idx] != NULL) {
  17763. /* A duplicate configuration option is not an error - the last
  17764. * option value will be used. */
  17765. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17766. mg_free(ctx->dd.config[idx]);
  17767. }
  17768. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17769. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17770. }
  17771. /* Set default value if needed */
  17772. for (i = 0; config_options[i].name != NULL; i++) {
  17773. default_value = config_options[i].default_value;
  17774. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17775. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17776. }
  17777. }
  17778. /* Request size option */
  17779. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17780. if (itmp < 1024) {
  17781. mg_cry_ctx_internal(ctx,
  17782. "%s too small",
  17783. config_options[MAX_REQUEST_SIZE].name);
  17784. if (error != NULL) {
  17785. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17786. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  17787. mg_snprintf(NULL,
  17788. NULL, /* No truncation check for error buffers */
  17789. error->text,
  17790. error->text_buffer_size,
  17791. "Invalid configuration option value: %s",
  17792. config_options[MAX_REQUEST_SIZE].name);
  17793. }
  17794. free_context(ctx);
  17795. pthread_setspecific(sTlsKey, NULL);
  17796. return NULL;
  17797. }
  17798. ctx->max_request_size = (unsigned)itmp;
  17799. /* Queue length */
  17800. #if !defined(ALTERNATIVE_QUEUE)
  17801. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17802. if (itmp < 1) {
  17803. mg_cry_ctx_internal(ctx,
  17804. "%s too small",
  17805. config_options[CONNECTION_QUEUE_SIZE].name);
  17806. if (error != NULL) {
  17807. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17808. error->code_sub = CONNECTION_QUEUE_SIZE;
  17809. mg_snprintf(NULL,
  17810. NULL, /* No truncation check for error buffers */
  17811. error->text,
  17812. error->text_buffer_size,
  17813. "Invalid configuration option value: %s",
  17814. config_options[CONNECTION_QUEUE_SIZE].name);
  17815. }
  17816. free_context(ctx);
  17817. pthread_setspecific(sTlsKey, NULL);
  17818. return NULL;
  17819. }
  17820. ctx->squeue =
  17821. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17822. if (ctx->squeue == NULL) {
  17823. mg_cry_ctx_internal(ctx,
  17824. "Out of memory: Cannot allocate %s",
  17825. config_options[CONNECTION_QUEUE_SIZE].name);
  17826. if (error != NULL) {
  17827. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17828. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  17829. mg_snprintf(NULL,
  17830. NULL, /* No truncation check for error buffers */
  17831. error->text,
  17832. error->text_buffer_size,
  17833. "Out of memory: Cannot allocate %s",
  17834. config_options[CONNECTION_QUEUE_SIZE].name);
  17835. }
  17836. free_context(ctx);
  17837. pthread_setspecific(sTlsKey, NULL);
  17838. return NULL;
  17839. }
  17840. ctx->sq_size = itmp;
  17841. #endif
  17842. /* Worker thread count option */
  17843. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17844. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17845. if (workerthreadcount <= 0) {
  17846. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17847. } else {
  17848. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17849. }
  17850. if (error != NULL) {
  17851. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17852. error->code_sub = NUM_THREADS;
  17853. mg_snprintf(NULL,
  17854. NULL, /* No truncation check for error buffers */
  17855. error->text,
  17856. error->text_buffer_size,
  17857. "Invalid configuration option value: %s",
  17858. config_options[NUM_THREADS].name);
  17859. }
  17860. free_context(ctx);
  17861. pthread_setspecific(sTlsKey, NULL);
  17862. return NULL;
  17863. }
  17864. /* Document root */
  17865. #if defined(NO_FILES)
  17866. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17867. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17868. if (error != NULL) {
  17869. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17870. error->code_sub = (unsigned)DOCUMENT_ROOT;
  17871. mg_snprintf(NULL,
  17872. NULL, /* No truncation check for error buffers */
  17873. error->text,
  17874. error->text_buffer_size,
  17875. "Invalid configuration option value: %s",
  17876. config_options[DOCUMENT_ROOT].name);
  17877. }
  17878. free_context(ctx);
  17879. pthread_setspecific(sTlsKey, NULL);
  17880. return NULL;
  17881. }
  17882. #endif
  17883. get_system_name(&ctx->systemName);
  17884. #if defined(USE_LUA)
  17885. /* If a Lua background script has been configured, start it. */
  17886. ctx->lua_bg_log_available = 0;
  17887. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17888. char ebuf[256];
  17889. struct vec opt_vec;
  17890. struct vec eq_vec;
  17891. const char *sparams;
  17892. memset(ebuf, 0, sizeof(ebuf));
  17893. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17894. /* Create a Lua state, load all standard libraries and the mg table */
  17895. lua_State *state = mg_lua_context_script_prepare(
  17896. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17897. if (!state) {
  17898. mg_cry_ctx_internal(ctx,
  17899. "lua_background_script load error: %s",
  17900. ebuf);
  17901. if (error != NULL) {
  17902. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  17903. mg_snprintf(NULL,
  17904. NULL, /* No truncation check for error buffers */
  17905. error->text,
  17906. error->text_buffer_size,
  17907. "Error in script %s: %s",
  17908. config_options[LUA_BACKGROUND_SCRIPT].name,
  17909. ebuf);
  17910. }
  17911. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17912. free_context(ctx);
  17913. pthread_setspecific(sTlsKey, NULL);
  17914. return NULL;
  17915. }
  17916. /* Add a table with parameters into mg.params */
  17917. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17918. if (sparams && sparams[0]) {
  17919. lua_getglobal(state, "mg");
  17920. lua_pushstring(state, "params");
  17921. lua_newtable(state);
  17922. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17923. != NULL) {
  17924. reg_llstring(
  17925. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17926. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17927. break;
  17928. }
  17929. lua_rawset(state, -3);
  17930. lua_pop(state, 1);
  17931. }
  17932. /* Call script */
  17933. state = mg_lua_context_script_run(state,
  17934. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17935. ctx,
  17936. ebuf,
  17937. sizeof(ebuf));
  17938. if (!state) {
  17939. mg_cry_ctx_internal(ctx,
  17940. "lua_background_script start error: %s",
  17941. ebuf);
  17942. if (error != NULL) {
  17943. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  17944. mg_snprintf(NULL,
  17945. NULL, /* No truncation check for error buffers */
  17946. error->text,
  17947. error->text_buffer_size,
  17948. "Error in script %s: %s",
  17949. config_options[DOCUMENT_ROOT].name,
  17950. ebuf);
  17951. }
  17952. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17953. free_context(ctx);
  17954. pthread_setspecific(sTlsKey, NULL);
  17955. return NULL;
  17956. }
  17957. /* state remains valid */
  17958. ctx->lua_background_state = (void *)state;
  17959. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17960. } else {
  17961. ctx->lua_background_state = 0;
  17962. }
  17963. #endif
  17964. /* Step by step initialization of ctx - depending on build options */
  17965. #if !defined(NO_FILESYSTEMS)
  17966. if (!set_gpass_option(ctx, NULL)) {
  17967. const char *err_msg = "Invalid global password file";
  17968. /* Fatal error - abort start. */
  17969. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17970. if (error != NULL) {
  17971. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  17972. mg_snprintf(NULL,
  17973. NULL, /* No truncation check for error buffers */
  17974. error->text,
  17975. error->text_buffer_size,
  17976. "%s",
  17977. err_msg);
  17978. }
  17979. free_context(ctx);
  17980. pthread_setspecific(sTlsKey, NULL);
  17981. return NULL;
  17982. }
  17983. #endif
  17984. #if defined(USE_MBEDTLS)
  17985. if (!mg_sslctx_init(ctx, NULL)) {
  17986. const char *err_msg = "Error initializing SSL context";
  17987. /* Fatal error - abort start. */
  17988. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17989. if (error != NULL) {
  17990. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  17991. mg_snprintf(NULL,
  17992. NULL, /* No truncation check for error buffers */
  17993. error->text,
  17994. error->text_buffer_size,
  17995. "%s",
  17996. err_msg);
  17997. }
  17998. free_context(ctx);
  17999. pthread_setspecific(sTlsKey, NULL);
  18000. return NULL;
  18001. }
  18002. #elif !defined(NO_SSL)
  18003. if (!init_ssl_ctx(ctx, NULL)) {
  18004. const char *err_msg = "Error initializing SSL context";
  18005. /* Fatal error - abort start. */
  18006. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18007. if (error != NULL) {
  18008. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18009. mg_snprintf(NULL,
  18010. NULL, /* No truncation check for error buffers */
  18011. error->text,
  18012. error->text_buffer_size,
  18013. "%s",
  18014. err_msg);
  18015. }
  18016. free_context(ctx);
  18017. pthread_setspecific(sTlsKey, NULL);
  18018. return NULL;
  18019. }
  18020. #endif
  18021. if (!set_ports_option(ctx)) {
  18022. const char *err_msg = "Failed to setup server ports";
  18023. /* Fatal error - abort start. */
  18024. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18025. if (error != NULL) {
  18026. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18027. mg_snprintf(NULL,
  18028. NULL, /* No truncation check for error buffers */
  18029. error->text,
  18030. error->text_buffer_size,
  18031. "%s",
  18032. err_msg);
  18033. }
  18034. free_context(ctx);
  18035. pthread_setspecific(sTlsKey, NULL);
  18036. return NULL;
  18037. }
  18038. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18039. if (!set_uid_option(ctx)) {
  18040. const char *err_msg = "Failed to run as configured user";
  18041. /* Fatal error - abort start. */
  18042. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18043. if (error != NULL) {
  18044. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18045. mg_snprintf(NULL,
  18046. NULL, /* No truncation check for error buffers */
  18047. error->text,
  18048. error->text_buffer_size,
  18049. "%s",
  18050. err_msg);
  18051. }
  18052. free_context(ctx);
  18053. pthread_setspecific(sTlsKey, NULL);
  18054. return NULL;
  18055. }
  18056. #endif
  18057. if (!set_acl_option(ctx)) {
  18058. const char *err_msg = "Failed to setup access control list";
  18059. /* Fatal error - abort start. */
  18060. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18061. if (error != NULL) {
  18062. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18063. mg_snprintf(NULL,
  18064. NULL, /* No truncation check for error buffers */
  18065. error->text,
  18066. error->text_buffer_size,
  18067. "%s",
  18068. err_msg);
  18069. }
  18070. free_context(ctx);
  18071. pthread_setspecific(sTlsKey, NULL);
  18072. return NULL;
  18073. }
  18074. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  18075. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18076. sizeof(pthread_t),
  18077. ctx);
  18078. if (ctx->worker_threadids == NULL) {
  18079. const char *err_msg = "Not enough memory for worker thread ID array";
  18080. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18081. if (error != NULL) {
  18082. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18083. error->code_sub =
  18084. (unsigned)ctx->cfg_worker_threads * (unsigned)sizeof(pthread_t);
  18085. mg_snprintf(NULL,
  18086. NULL, /* No truncation check for error buffers */
  18087. error->text,
  18088. error->text_buffer_size,
  18089. "%s",
  18090. err_msg);
  18091. }
  18092. free_context(ctx);
  18093. pthread_setspecific(sTlsKey, NULL);
  18094. return NULL;
  18095. }
  18096. ctx->worker_connections =
  18097. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18098. sizeof(struct mg_connection),
  18099. ctx);
  18100. if (ctx->worker_connections == NULL) {
  18101. const char *err_msg =
  18102. "Not enough memory for worker thread connection array";
  18103. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18104. if (error != NULL) {
  18105. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18106. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18107. * (unsigned)sizeof(struct mg_connection);
  18108. mg_snprintf(NULL,
  18109. NULL, /* No truncation check for error buffers */
  18110. error->text,
  18111. error->text_buffer_size,
  18112. "%s",
  18113. err_msg);
  18114. }
  18115. free_context(ctx);
  18116. pthread_setspecific(sTlsKey, NULL);
  18117. return NULL;
  18118. }
  18119. #if defined(ALTERNATIVE_QUEUE)
  18120. ctx->client_wait_events =
  18121. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  18122. sizeof(ctx->client_wait_events[0]),
  18123. ctx);
  18124. if (ctx->client_wait_events == NULL) {
  18125. const char *err_msg = "Not enough memory for worker event array";
  18126. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18127. mg_free(ctx->worker_threadids);
  18128. if (error != NULL) {
  18129. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18130. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18131. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18132. mg_snprintf(NULL,
  18133. NULL, /* No truncation check for error buffers */
  18134. error->text,
  18135. error->text_buffer_size,
  18136. "%s",
  18137. err_msg);
  18138. }
  18139. free_context(ctx);
  18140. pthread_setspecific(sTlsKey, NULL);
  18141. return NULL;
  18142. }
  18143. ctx->client_socks =
  18144. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18145. sizeof(ctx->client_socks[0]),
  18146. ctx);
  18147. if (ctx->client_socks == NULL) {
  18148. const char *err_msg = "Not enough memory for worker socket array";
  18149. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18150. mg_free(ctx->client_wait_events);
  18151. mg_free(ctx->worker_threadids);
  18152. if (error != NULL) {
  18153. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18154. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18155. * (unsigned)sizeof(ctx->client_socks[0]);
  18156. mg_snprintf(NULL,
  18157. NULL, /* No truncation check for error buffers */
  18158. error->text,
  18159. error->text_buffer_size,
  18160. "%s",
  18161. err_msg);
  18162. }
  18163. free_context(ctx);
  18164. pthread_setspecific(sTlsKey, NULL);
  18165. return NULL;
  18166. }
  18167. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  18168. ctx->client_wait_events[i] = event_create();
  18169. if (ctx->client_wait_events[i] == 0) {
  18170. const char *err_msg = "Error creating worker event %i";
  18171. mg_cry_ctx_internal(ctx, err_msg, i);
  18172. while (i > 0) {
  18173. i--;
  18174. event_destroy(ctx->client_wait_events[i]);
  18175. }
  18176. mg_free(ctx->client_socks);
  18177. mg_free(ctx->client_wait_events);
  18178. mg_free(ctx->worker_threadids);
  18179. if (error != NULL) {
  18180. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18181. error->code_sub = ERRNO;
  18182. mg_snprintf(NULL,
  18183. NULL, /* No truncation check for error buffers */
  18184. error->text,
  18185. error->text_buffer_size,
  18186. err_msg,
  18187. i);
  18188. }
  18189. free_context(ctx);
  18190. pthread_setspecific(sTlsKey, NULL);
  18191. return NULL;
  18192. }
  18193. }
  18194. #endif
  18195. #if defined(USE_TIMERS)
  18196. if (timers_init(ctx) != 0) {
  18197. const char *err_msg = "Error creating timers";
  18198. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18199. if (error != NULL) {
  18200. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18201. error->code_sub = ERRNO;
  18202. mg_snprintf(NULL,
  18203. NULL, /* No truncation check for error buffers */
  18204. error->text,
  18205. error->text_buffer_size,
  18206. "%s",
  18207. err_msg);
  18208. }
  18209. free_context(ctx);
  18210. pthread_setspecific(sTlsKey, NULL);
  18211. return NULL;
  18212. }
  18213. #endif
  18214. /* Context has been created - init user libraries */
  18215. if (ctx->callbacks.init_context) {
  18216. ctx->callbacks.init_context(ctx);
  18217. }
  18218. /* From now, the context is successfully created.
  18219. * When it is destroyed, the exit callback should be called. */
  18220. ctx->callbacks.exit_context = exit_callback;
  18221. ctx->context_type = CONTEXT_SERVER; /* server context */
  18222. /* Start worker threads */
  18223. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  18224. /* worker_thread sets up the other fields */
  18225. ctx->worker_connections[i].phys_ctx = ctx;
  18226. if (mg_start_thread_with_id(worker_thread,
  18227. &ctx->worker_connections[i],
  18228. &ctx->worker_threadids[i])
  18229. != 0) {
  18230. long error_no = (long)ERRNO;
  18231. /* thread was not created */
  18232. if (i > 0) {
  18233. /* If the second, third, ... thread cannot be created, set a
  18234. * warning, but keep running. */
  18235. mg_cry_ctx_internal(ctx,
  18236. "Cannot start worker thread %i: error %ld",
  18237. i + 1,
  18238. error_no);
  18239. /* If the server initialization should stop here, all
  18240. * threads that have already been created must be stopped
  18241. * first, before any free_context(ctx) call.
  18242. */
  18243. } else {
  18244. /* If the first worker thread cannot be created, stop
  18245. * initialization and free the entire server context. */
  18246. mg_cry_ctx_internal(ctx,
  18247. "Cannot create threads: error %ld",
  18248. error_no);
  18249. if (error != NULL) {
  18250. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18251. error->code_sub = (unsigned)error_no;
  18252. mg_snprintf(
  18253. NULL,
  18254. NULL, /* No truncation check for error buffers */
  18255. error->text,
  18256. error->text_buffer_size,
  18257. "Cannot create first worker thread: error %ld",
  18258. error_no);
  18259. }
  18260. free_context(ctx);
  18261. pthread_setspecific(sTlsKey, NULL);
  18262. return NULL;
  18263. }
  18264. break;
  18265. }
  18266. }
  18267. /* Start master (listening) thread */
  18268. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18269. pthread_setspecific(sTlsKey, NULL);
  18270. return ctx;
  18271. }
  18272. CIVETWEB_API struct mg_context *
  18273. mg_start(const struct mg_callbacks *callbacks,
  18274. void *user_data,
  18275. const char **options)
  18276. {
  18277. struct mg_init_data init = {0};
  18278. init.callbacks = callbacks;
  18279. init.user_data = user_data;
  18280. init.configuration_options = options;
  18281. return mg_start2(&init, NULL);
  18282. }
  18283. /* Add an additional domain to an already running web server. */
  18284. CIVETWEB_API int
  18285. mg_start_domain2(struct mg_context *ctx,
  18286. const char **options,
  18287. struct mg_error_data *error)
  18288. {
  18289. const char *name;
  18290. const char *value;
  18291. const char *default_value;
  18292. struct mg_domain_context *new_dom;
  18293. struct mg_domain_context *dom;
  18294. int idx, i;
  18295. if (error != NULL) {
  18296. error->code = MG_ERROR_DATA_CODE_OK;
  18297. error->code_sub = 0;
  18298. if (error->text_buffer_size > 0) {
  18299. *error->text = 0;
  18300. }
  18301. }
  18302. if ((ctx == NULL) || (options == NULL)) {
  18303. if (error != NULL) {
  18304. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18305. mg_snprintf(NULL,
  18306. NULL, /* No truncation check for error buffers */
  18307. error->text,
  18308. error->text_buffer_size,
  18309. "%s",
  18310. "Invalid parameters");
  18311. }
  18312. return -1;
  18313. }
  18314. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18315. if (error != NULL) {
  18316. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18317. mg_snprintf(NULL,
  18318. NULL, /* No truncation check for error buffers */
  18319. error->text,
  18320. error->text_buffer_size,
  18321. "%s",
  18322. "Server already stopped");
  18323. }
  18324. return -7;
  18325. }
  18326. new_dom = (struct mg_domain_context *)
  18327. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18328. if (!new_dom) {
  18329. /* Out of memory */
  18330. if (error != NULL) {
  18331. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18332. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18333. mg_snprintf(NULL,
  18334. NULL, /* No truncation check for error buffers */
  18335. error->text,
  18336. error->text_buffer_size,
  18337. "%s",
  18338. "Out or memory");
  18339. }
  18340. return -6;
  18341. }
  18342. /* Store options - TODO: unite duplicate code */
  18343. while (options && (name = *options++) != NULL) {
  18344. idx = get_option_index(name);
  18345. if (idx == -1) {
  18346. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18347. if (error != NULL) {
  18348. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18349. error->code_sub = (unsigned)-1;
  18350. mg_snprintf(NULL,
  18351. NULL, /* No truncation check for error buffers */
  18352. error->text,
  18353. error->text_buffer_size,
  18354. "Invalid option: %s",
  18355. name);
  18356. }
  18357. mg_free(new_dom);
  18358. return -2;
  18359. } else if ((value = *options++) == NULL) {
  18360. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18361. if (error != NULL) {
  18362. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18363. error->code_sub = idx;
  18364. mg_snprintf(NULL,
  18365. NULL, /* No truncation check for error buffers */
  18366. error->text,
  18367. error->text_buffer_size,
  18368. "Invalid option value: %s",
  18369. name);
  18370. }
  18371. mg_free(new_dom);
  18372. return -2;
  18373. }
  18374. if (new_dom->config[idx] != NULL) {
  18375. /* Duplicate option: Later values overwrite earlier ones. */
  18376. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18377. mg_free(new_dom->config[idx]);
  18378. }
  18379. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18380. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18381. }
  18382. /* Authentication domain is mandatory */
  18383. /* TODO: Maybe use a new option hostname? */
  18384. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18385. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18386. if (error != NULL) {
  18387. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18388. error->code_sub = AUTHENTICATION_DOMAIN;
  18389. mg_snprintf(NULL,
  18390. NULL, /* No truncation check for error buffers */
  18391. error->text,
  18392. error->text_buffer_size,
  18393. "Mandatory option %s missing",
  18394. config_options[AUTHENTICATION_DOMAIN].name);
  18395. }
  18396. mg_free(new_dom);
  18397. return -4;
  18398. }
  18399. /* Set default value if needed. Take the config value from
  18400. * ctx as a default value. */
  18401. for (i = 0; config_options[i].name != NULL; i++) {
  18402. default_value = ctx->dd.config[i];
  18403. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18404. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18405. }
  18406. }
  18407. new_dom->handlers = NULL;
  18408. new_dom->next = NULL;
  18409. new_dom->nonce_count = 0;
  18410. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18411. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18412. new_dom->shared_lua_websockets = NULL;
  18413. #endif
  18414. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18415. if (!init_ssl_ctx(ctx, new_dom)) {
  18416. /* Init SSL failed */
  18417. if (error != NULL) {
  18418. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18419. mg_snprintf(NULL,
  18420. NULL, /* No truncation check for error buffers */
  18421. error->text,
  18422. error->text_buffer_size,
  18423. "%s",
  18424. "Initializing SSL context failed");
  18425. }
  18426. mg_free(new_dom);
  18427. return -3;
  18428. }
  18429. #endif
  18430. /* Add element to linked list. */
  18431. mg_lock_context(ctx);
  18432. idx = 0;
  18433. dom = &(ctx->dd);
  18434. for (;;) {
  18435. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18436. dom->config[AUTHENTICATION_DOMAIN])) {
  18437. /* Domain collision */
  18438. mg_cry_ctx_internal(ctx,
  18439. "domain %s already in use",
  18440. new_dom->config[AUTHENTICATION_DOMAIN]);
  18441. if (error != NULL) {
  18442. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18443. mg_snprintf(NULL,
  18444. NULL, /* No truncation check for error buffers */
  18445. error->text,
  18446. error->text_buffer_size,
  18447. "Domain %s specified by %s is already in use",
  18448. new_dom->config[AUTHENTICATION_DOMAIN],
  18449. config_options[AUTHENTICATION_DOMAIN].name);
  18450. }
  18451. mg_free(new_dom);
  18452. mg_unlock_context(ctx);
  18453. return -5;
  18454. }
  18455. /* Count number of domains */
  18456. idx++;
  18457. if (dom->next == NULL) {
  18458. dom->next = new_dom;
  18459. break;
  18460. }
  18461. dom = dom->next;
  18462. }
  18463. mg_unlock_context(ctx);
  18464. /* Return domain number */
  18465. return idx;
  18466. }
  18467. CIVETWEB_API int
  18468. mg_start_domain(struct mg_context *ctx, const char **options)
  18469. {
  18470. return mg_start_domain2(ctx, options, NULL);
  18471. }
  18472. /* Feature check API function */
  18473. CIVETWEB_API unsigned
  18474. mg_check_feature(unsigned feature)
  18475. {
  18476. static const unsigned feature_set = 0
  18477. /* Set bits for available features according to API documentation.
  18478. * This bit mask is created at compile time, according to the active
  18479. * preprocessor defines. It is a single const value at runtime. */
  18480. #if !defined(NO_FILES)
  18481. | MG_FEATURES_FILES
  18482. #endif
  18483. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18484. | MG_FEATURES_SSL
  18485. #endif
  18486. #if !defined(NO_CGI)
  18487. | MG_FEATURES_CGI
  18488. #endif
  18489. #if defined(USE_IPV6)
  18490. | MG_FEATURES_IPV6
  18491. #endif
  18492. #if defined(USE_WEBSOCKET)
  18493. | MG_FEATURES_WEBSOCKET
  18494. #endif
  18495. #if defined(USE_LUA)
  18496. | MG_FEATURES_LUA
  18497. #endif
  18498. #if defined(USE_DUKTAPE)
  18499. | MG_FEATURES_SSJS
  18500. #endif
  18501. #if !defined(NO_CACHING)
  18502. | MG_FEATURES_CACHE
  18503. #endif
  18504. #if defined(USE_SERVER_STATS)
  18505. | MG_FEATURES_STATS
  18506. #endif
  18507. #if defined(USE_ZLIB)
  18508. | MG_FEATURES_COMPRESSION
  18509. #endif
  18510. #if defined(USE_HTTP2)
  18511. | MG_FEATURES_HTTP2
  18512. #endif
  18513. #if defined(USE_X_DOM_SOCKET)
  18514. | MG_FEATURES_X_DOMAIN_SOCKET
  18515. #endif
  18516. /* Set some extra bits not defined in the API documentation.
  18517. * These bits may change without further notice. */
  18518. #if defined(MG_LEGACY_INTERFACE)
  18519. | 0x80000000u
  18520. #endif
  18521. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18522. | 0x40000000u
  18523. #endif
  18524. #if !defined(NO_RESPONSE_BUFFERING)
  18525. | 0x20000000u
  18526. #endif
  18527. #if defined(MEMORY_DEBUGGING)
  18528. | 0x10000000u
  18529. #endif
  18530. ;
  18531. return (feature & feature_set);
  18532. }
  18533. static size_t
  18534. mg_str_append(char **dst, char *end, const char *src)
  18535. {
  18536. size_t len = strlen(src);
  18537. if (*dst != end) {
  18538. /* Append src if enough space, or close dst. */
  18539. if ((size_t)(end - *dst) > len) {
  18540. strcpy(*dst, src);
  18541. *dst += len;
  18542. } else {
  18543. *dst = end;
  18544. }
  18545. }
  18546. return len;
  18547. }
  18548. /* Get system information. It can be printed or stored by the caller.
  18549. * Return the size of available information. */
  18550. CIVETWEB_API int
  18551. mg_get_system_info(char *buffer, int buflen)
  18552. {
  18553. char *end, *append_eoobj = NULL, block[256];
  18554. size_t system_info_length = 0;
  18555. #if defined(_WIN32)
  18556. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18557. #else
  18558. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18559. #endif
  18560. if ((buffer == NULL) || (buflen < 1)) {
  18561. buflen = 0;
  18562. end = buffer;
  18563. } else {
  18564. *buffer = 0;
  18565. end = buffer + buflen;
  18566. }
  18567. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18568. /* has enough space to append eoobj */
  18569. append_eoobj = buffer;
  18570. if (end) {
  18571. end -= sizeof(eoobj) - 1;
  18572. }
  18573. }
  18574. system_info_length += mg_str_append(&buffer, end, "{");
  18575. /* Server version */
  18576. {
  18577. const char *version = mg_version();
  18578. mg_snprintf(NULL,
  18579. NULL,
  18580. block,
  18581. sizeof(block),
  18582. "%s\"version\" : \"%s\"",
  18583. eol,
  18584. version);
  18585. system_info_length += mg_str_append(&buffer, end, block);
  18586. }
  18587. /* System info */
  18588. {
  18589. #if defined(_WIN32)
  18590. DWORD dwVersion = 0;
  18591. DWORD dwMajorVersion = 0;
  18592. DWORD dwMinorVersion = 0;
  18593. SYSTEM_INFO si;
  18594. GetSystemInfo(&si);
  18595. #if defined(_MSC_VER)
  18596. #pragma warning(push)
  18597. /* GetVersion was declared deprecated */
  18598. #pragma warning(disable : 4996)
  18599. #endif
  18600. dwVersion = GetVersion();
  18601. #if defined(_MSC_VER)
  18602. #pragma warning(pop)
  18603. #endif
  18604. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18605. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18606. mg_snprintf(NULL,
  18607. NULL,
  18608. block,
  18609. sizeof(block),
  18610. ",%s\"os\" : \"Windows %u.%u\"",
  18611. eol,
  18612. (unsigned)dwMajorVersion,
  18613. (unsigned)dwMinorVersion);
  18614. system_info_length += mg_str_append(&buffer, end, block);
  18615. mg_snprintf(NULL,
  18616. NULL,
  18617. block,
  18618. sizeof(block),
  18619. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18620. eol,
  18621. (unsigned)si.wProcessorArchitecture,
  18622. (unsigned)si.dwNumberOfProcessors,
  18623. (unsigned)si.dwActiveProcessorMask);
  18624. system_info_length += mg_str_append(&buffer, end, block);
  18625. #elif defined(__ZEPHYR__)
  18626. mg_snprintf(NULL,
  18627. NULL,
  18628. block,
  18629. sizeof(block),
  18630. ",%s\"os\" : \"%s %s\"",
  18631. eol,
  18632. "Zephyr OS",
  18633. ZEPHYR_VERSION);
  18634. system_info_length += mg_str_append(&buffer, end, block);
  18635. #else
  18636. struct utsname name;
  18637. memset(&name, 0, sizeof(name));
  18638. uname(&name);
  18639. mg_snprintf(NULL,
  18640. NULL,
  18641. block,
  18642. sizeof(block),
  18643. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18644. eol,
  18645. name.sysname,
  18646. name.version,
  18647. name.release,
  18648. name.machine);
  18649. system_info_length += mg_str_append(&buffer, end, block);
  18650. #endif
  18651. }
  18652. /* Features */
  18653. {
  18654. mg_snprintf(NULL,
  18655. NULL,
  18656. block,
  18657. sizeof(block),
  18658. ",%s\"features\" : %lu"
  18659. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18660. eol,
  18661. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18662. eol,
  18663. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18664. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18665. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18666. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18667. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18668. : "",
  18669. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18670. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18671. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18672. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18673. system_info_length += mg_str_append(&buffer, end, block);
  18674. #if defined(USE_LUA)
  18675. mg_snprintf(NULL,
  18676. NULL,
  18677. block,
  18678. sizeof(block),
  18679. ",%s\"lua_version\" : \"%u (%s)\"",
  18680. eol,
  18681. (unsigned)LUA_VERSION_NUM,
  18682. LUA_RELEASE);
  18683. system_info_length += mg_str_append(&buffer, end, block);
  18684. #endif
  18685. #if defined(USE_DUKTAPE)
  18686. mg_snprintf(NULL,
  18687. NULL,
  18688. block,
  18689. sizeof(block),
  18690. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18691. eol,
  18692. (unsigned)DUK_VERSION / 10000,
  18693. ((unsigned)DUK_VERSION / 100) % 100,
  18694. (unsigned)DUK_VERSION % 100);
  18695. system_info_length += mg_str_append(&buffer, end, block);
  18696. #endif
  18697. }
  18698. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18699. {
  18700. #if defined(BUILD_DATE)
  18701. const char *bd = BUILD_DATE;
  18702. #else
  18703. #if defined(GCC_DIAGNOSTIC)
  18704. #if GCC_VERSION >= 40900
  18705. #pragma GCC diagnostic push
  18706. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18707. * does not work in some versions. If "BUILD_DATE" is defined to some
  18708. * string, it is used instead of __DATE__. */
  18709. #pragma GCC diagnostic ignored "-Wdate-time"
  18710. #endif
  18711. #endif
  18712. const char *bd = __DATE__;
  18713. #if defined(GCC_DIAGNOSTIC)
  18714. #if GCC_VERSION >= 40900
  18715. #pragma GCC diagnostic pop
  18716. #endif
  18717. #endif
  18718. #endif
  18719. mg_snprintf(
  18720. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18721. system_info_length += mg_str_append(&buffer, end, block);
  18722. }
  18723. /* Compiler information */
  18724. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18725. {
  18726. #if defined(_MSC_VER)
  18727. mg_snprintf(NULL,
  18728. NULL,
  18729. block,
  18730. sizeof(block),
  18731. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18732. eol,
  18733. (unsigned)_MSC_VER,
  18734. (unsigned)_MSC_FULL_VER);
  18735. system_info_length += mg_str_append(&buffer, end, block);
  18736. #elif defined(__MINGW64__)
  18737. mg_snprintf(NULL,
  18738. NULL,
  18739. block,
  18740. sizeof(block),
  18741. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18742. eol,
  18743. (unsigned)__MINGW64_VERSION_MAJOR,
  18744. (unsigned)__MINGW64_VERSION_MINOR);
  18745. system_info_length += mg_str_append(&buffer, end, block);
  18746. mg_snprintf(NULL,
  18747. NULL,
  18748. block,
  18749. sizeof(block),
  18750. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18751. eol,
  18752. (unsigned)__MINGW32_MAJOR_VERSION,
  18753. (unsigned)__MINGW32_MINOR_VERSION);
  18754. system_info_length += mg_str_append(&buffer, end, block);
  18755. #elif defined(__MINGW32__)
  18756. mg_snprintf(NULL,
  18757. NULL,
  18758. block,
  18759. sizeof(block),
  18760. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18761. eol,
  18762. (unsigned)__MINGW32_MAJOR_VERSION,
  18763. (unsigned)__MINGW32_MINOR_VERSION);
  18764. system_info_length += mg_str_append(&buffer, end, block);
  18765. #elif defined(__clang__)
  18766. mg_snprintf(NULL,
  18767. NULL,
  18768. block,
  18769. sizeof(block),
  18770. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18771. eol,
  18772. __clang_major__,
  18773. __clang_minor__,
  18774. __clang_patchlevel__,
  18775. __clang_version__);
  18776. system_info_length += mg_str_append(&buffer, end, block);
  18777. #elif defined(__GNUC__)
  18778. mg_snprintf(NULL,
  18779. NULL,
  18780. block,
  18781. sizeof(block),
  18782. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18783. eol,
  18784. (unsigned)__GNUC__,
  18785. (unsigned)__GNUC_MINOR__,
  18786. (unsigned)__GNUC_PATCHLEVEL__);
  18787. system_info_length += mg_str_append(&buffer, end, block);
  18788. #elif defined(__INTEL_COMPILER)
  18789. mg_snprintf(NULL,
  18790. NULL,
  18791. block,
  18792. sizeof(block),
  18793. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18794. eol,
  18795. (unsigned)__INTEL_COMPILER);
  18796. system_info_length += mg_str_append(&buffer, end, block);
  18797. #elif defined(__BORLANDC__)
  18798. mg_snprintf(NULL,
  18799. NULL,
  18800. block,
  18801. sizeof(block),
  18802. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18803. eol,
  18804. (unsigned)__BORLANDC__);
  18805. system_info_length += mg_str_append(&buffer, end, block);
  18806. #elif defined(__SUNPRO_C)
  18807. mg_snprintf(NULL,
  18808. NULL,
  18809. block,
  18810. sizeof(block),
  18811. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18812. eol,
  18813. (unsigned)__SUNPRO_C);
  18814. system_info_length += mg_str_append(&buffer, end, block);
  18815. #else
  18816. mg_snprintf(NULL,
  18817. NULL,
  18818. block,
  18819. sizeof(block),
  18820. ",%s\"compiler\" : \"other\"",
  18821. eol);
  18822. system_info_length += mg_str_append(&buffer, end, block);
  18823. #endif
  18824. }
  18825. /* Determine 32/64 bit data mode.
  18826. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18827. {
  18828. mg_snprintf(NULL,
  18829. NULL,
  18830. block,
  18831. sizeof(block),
  18832. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18833. "char:%u/%u, "
  18834. "ptr:%u, size:%u, time:%u\"",
  18835. eol,
  18836. (unsigned)sizeof(short),
  18837. (unsigned)sizeof(int),
  18838. (unsigned)sizeof(long),
  18839. (unsigned)sizeof(long long),
  18840. (unsigned)sizeof(float),
  18841. (unsigned)sizeof(double),
  18842. (unsigned)sizeof(long double),
  18843. (unsigned)sizeof(char),
  18844. (unsigned)sizeof(wchar_t),
  18845. (unsigned)sizeof(void *),
  18846. (unsigned)sizeof(size_t),
  18847. (unsigned)sizeof(time_t));
  18848. system_info_length += mg_str_append(&buffer, end, block);
  18849. }
  18850. /* Terminate string */
  18851. if (append_eoobj) {
  18852. strcat(append_eoobj, eoobj);
  18853. }
  18854. system_info_length += sizeof(eoobj) - 1;
  18855. return (int)system_info_length;
  18856. }
  18857. /* Get context information. It can be printed or stored by the caller.
  18858. * Return the size of available information. */
  18859. CIVETWEB_API int
  18860. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18861. {
  18862. #if defined(USE_SERVER_STATS)
  18863. char *end, *append_eoobj = NULL, block[256];
  18864. size_t context_info_length = 0;
  18865. #if defined(_WIN32)
  18866. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18867. #else
  18868. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18869. #endif
  18870. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18871. if ((buffer == NULL) || (buflen < 1)) {
  18872. buflen = 0;
  18873. end = buffer;
  18874. } else {
  18875. *buffer = 0;
  18876. end = buffer + buflen;
  18877. }
  18878. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18879. /* has enough space to append eoobj */
  18880. append_eoobj = buffer;
  18881. end -= sizeof(eoobj) - 1;
  18882. }
  18883. context_info_length += mg_str_append(&buffer, end, "{");
  18884. if (ms) { /* <-- should be always true */
  18885. /* Memory information */
  18886. int blockCount = (int)ms->blockCount;
  18887. int64_t totalMemUsed = ms->totalMemUsed;
  18888. int64_t maxMemUsed = ms->maxMemUsed;
  18889. if (totalMemUsed > maxMemUsed) {
  18890. maxMemUsed = totalMemUsed;
  18891. }
  18892. mg_snprintf(NULL,
  18893. NULL,
  18894. block,
  18895. sizeof(block),
  18896. "%s\"memory\" : {%s"
  18897. "\"blocks\" : %i,%s"
  18898. "\"used\" : %" INT64_FMT ",%s"
  18899. "\"maxUsed\" : %" INT64_FMT "%s"
  18900. "}",
  18901. eol,
  18902. eol,
  18903. blockCount,
  18904. eol,
  18905. totalMemUsed,
  18906. eol,
  18907. maxMemUsed,
  18908. eol);
  18909. context_info_length += mg_str_append(&buffer, end, block);
  18910. }
  18911. if (ctx) {
  18912. /* Declare all variables at begin of the block, to comply
  18913. * with old C standards. */
  18914. char start_time_str[64] = {0};
  18915. char now_str[64] = {0};
  18916. time_t start_time = ctx->start_time;
  18917. time_t now = time(NULL);
  18918. int64_t total_data_read, total_data_written;
  18919. int active_connections = (int)ctx->active_connections;
  18920. int max_active_connections = (int)ctx->max_active_connections;
  18921. int total_connections = (int)ctx->total_connections;
  18922. if (active_connections > max_active_connections) {
  18923. max_active_connections = active_connections;
  18924. }
  18925. if (active_connections > total_connections) {
  18926. total_connections = active_connections;
  18927. }
  18928. /* Connections information */
  18929. mg_snprintf(NULL,
  18930. NULL,
  18931. block,
  18932. sizeof(block),
  18933. ",%s\"connections\" : {%s"
  18934. "\"active\" : %i,%s"
  18935. "\"maxActive\" : %i,%s"
  18936. "\"total\" : %i%s"
  18937. "}",
  18938. eol,
  18939. eol,
  18940. active_connections,
  18941. eol,
  18942. max_active_connections,
  18943. eol,
  18944. total_connections,
  18945. eol);
  18946. context_info_length += mg_str_append(&buffer, end, block);
  18947. /* Queue information */
  18948. #if !defined(ALTERNATIVE_QUEUE)
  18949. mg_snprintf(NULL,
  18950. NULL,
  18951. block,
  18952. sizeof(block),
  18953. ",%s\"queue\" : {%s"
  18954. "\"length\" : %i,%s"
  18955. "\"filled\" : %i,%s"
  18956. "\"maxFilled\" : %i,%s"
  18957. "\"full\" : %s%s"
  18958. "}",
  18959. eol,
  18960. eol,
  18961. ctx->sq_size,
  18962. eol,
  18963. ctx->sq_head - ctx->sq_tail,
  18964. eol,
  18965. ctx->sq_max_fill,
  18966. eol,
  18967. (ctx->sq_blocked ? "true" : "false"),
  18968. eol);
  18969. context_info_length += mg_str_append(&buffer, end, block);
  18970. #endif
  18971. /* Requests information */
  18972. mg_snprintf(NULL,
  18973. NULL,
  18974. block,
  18975. sizeof(block),
  18976. ",%s\"requests\" : {%s"
  18977. "\"total\" : %lu%s"
  18978. "}",
  18979. eol,
  18980. eol,
  18981. (unsigned long)ctx->total_requests,
  18982. eol);
  18983. context_info_length += mg_str_append(&buffer, end, block);
  18984. /* Data information */
  18985. total_data_read =
  18986. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18987. total_data_written =
  18988. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18989. mg_snprintf(NULL,
  18990. NULL,
  18991. block,
  18992. sizeof(block),
  18993. ",%s\"data\" : {%s"
  18994. "\"read\" : %" INT64_FMT ",%s"
  18995. "\"written\" : %" INT64_FMT "%s"
  18996. "}",
  18997. eol,
  18998. eol,
  18999. total_data_read,
  19000. eol,
  19001. total_data_written,
  19002. eol);
  19003. context_info_length += mg_str_append(&buffer, end, block);
  19004. /* Execution time information */
  19005. gmt_time_string(start_time_str,
  19006. sizeof(start_time_str) - 1,
  19007. &start_time);
  19008. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19009. mg_snprintf(NULL,
  19010. NULL,
  19011. block,
  19012. sizeof(block),
  19013. ",%s\"time\" : {%s"
  19014. "\"uptime\" : %.0f,%s"
  19015. "\"start\" : \"%s\",%s"
  19016. "\"now\" : \"%s\"%s"
  19017. "}",
  19018. eol,
  19019. eol,
  19020. difftime(now, start_time),
  19021. eol,
  19022. start_time_str,
  19023. eol,
  19024. now_str,
  19025. eol);
  19026. context_info_length += mg_str_append(&buffer, end, block);
  19027. }
  19028. /* Terminate string */
  19029. if (append_eoobj) {
  19030. strcat(append_eoobj, eoobj);
  19031. }
  19032. context_info_length += sizeof(eoobj) - 1;
  19033. return (int)context_info_length;
  19034. #else
  19035. (void)ctx;
  19036. if ((buffer != NULL) && (buflen > 0)) {
  19037. *buffer = 0;
  19038. }
  19039. return 0;
  19040. #endif
  19041. }
  19042. CIVETWEB_API void
  19043. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19044. {
  19045. /* https://github.com/civetweb/civetweb/issues/727 */
  19046. if (conn != NULL) {
  19047. conn->must_close = 1;
  19048. }
  19049. }
  19050. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19051. /* Get connection information. It can be printed or stored by the caller.
  19052. * Return the size of available information. */
  19053. CIVETWEB_API int
  19054. mg_get_connection_info(const struct mg_context *ctx,
  19055. int idx,
  19056. char *buffer,
  19057. int buflen)
  19058. {
  19059. const struct mg_connection *conn;
  19060. const struct mg_request_info *ri;
  19061. char *end, *append_eoobj = NULL, block[256];
  19062. size_t connection_info_length = 0;
  19063. int state = 0;
  19064. const char *state_str = "unknown";
  19065. #if defined(_WIN32)
  19066. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19067. #else
  19068. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19069. #endif
  19070. if ((buffer == NULL) || (buflen < 1)) {
  19071. buflen = 0;
  19072. end = buffer;
  19073. } else {
  19074. *buffer = 0;
  19075. end = buffer + buflen;
  19076. }
  19077. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19078. /* has enough space to append eoobj */
  19079. append_eoobj = buffer;
  19080. end -= sizeof(eoobj) - 1;
  19081. }
  19082. if ((ctx == NULL) || (idx < 0)) {
  19083. /* Parameter error */
  19084. return 0;
  19085. }
  19086. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  19087. /* Out of range */
  19088. return 0;
  19089. }
  19090. /* Take connection [idx]. This connection is not locked in
  19091. * any way, so some other thread might use it. */
  19092. conn = (ctx->worker_connections) + idx;
  19093. /* Initialize output string */
  19094. connection_info_length += mg_str_append(&buffer, end, "{");
  19095. /* Init variables */
  19096. ri = &(conn->request_info);
  19097. #if defined(USE_SERVER_STATS)
  19098. state = conn->conn_state;
  19099. /* State as string */
  19100. switch (state) {
  19101. case 0:
  19102. state_str = "undefined";
  19103. break;
  19104. case 1:
  19105. state_str = "not used";
  19106. break;
  19107. case 2:
  19108. state_str = "init";
  19109. break;
  19110. case 3:
  19111. state_str = "ready";
  19112. break;
  19113. case 4:
  19114. state_str = "processing";
  19115. break;
  19116. case 5:
  19117. state_str = "processed";
  19118. break;
  19119. case 6:
  19120. state_str = "to close";
  19121. break;
  19122. case 7:
  19123. state_str = "closing";
  19124. break;
  19125. case 8:
  19126. state_str = "closed";
  19127. break;
  19128. case 9:
  19129. state_str = "done";
  19130. break;
  19131. }
  19132. #endif
  19133. /* Connection info */
  19134. if ((state >= 3) && (state < 9)) {
  19135. mg_snprintf(NULL,
  19136. NULL,
  19137. block,
  19138. sizeof(block),
  19139. "%s\"connection\" : {%s"
  19140. "\"remote\" : {%s"
  19141. "\"protocol\" : \"%s\",%s"
  19142. "\"addr\" : \"%s\",%s"
  19143. "\"port\" : %u%s"
  19144. "},%s"
  19145. "\"handled_requests\" : %u%s"
  19146. "}",
  19147. eol,
  19148. eol,
  19149. eol,
  19150. get_proto_name(conn),
  19151. eol,
  19152. ri->remote_addr,
  19153. eol,
  19154. ri->remote_port,
  19155. eol,
  19156. eol,
  19157. conn->handled_requests,
  19158. eol);
  19159. connection_info_length += mg_str_append(&buffer, end, block);
  19160. }
  19161. /* Request info */
  19162. if ((state >= 4) && (state < 6)) {
  19163. mg_snprintf(NULL,
  19164. NULL,
  19165. block,
  19166. sizeof(block),
  19167. "%s%s\"request_info\" : {%s"
  19168. "\"method\" : \"%s\",%s"
  19169. "\"uri\" : \"%s\",%s"
  19170. "\"query\" : %s%s%s%s"
  19171. "}",
  19172. (connection_info_length > 1 ? "," : ""),
  19173. eol,
  19174. eol,
  19175. ri->request_method,
  19176. eol,
  19177. ri->request_uri,
  19178. eol,
  19179. ri->query_string ? "\"" : "",
  19180. ri->query_string ? ri->query_string : "null",
  19181. ri->query_string ? "\"" : "",
  19182. eol);
  19183. connection_info_length += mg_str_append(&buffer, end, block);
  19184. }
  19185. /* Execution time information */
  19186. if ((state >= 2) && (state < 9)) {
  19187. char start_time_str[64] = {0};
  19188. char close_time_str[64] = {0};
  19189. time_t start_time = conn->conn_birth_time;
  19190. time_t close_time = 0;
  19191. double time_diff;
  19192. gmt_time_string(start_time_str,
  19193. sizeof(start_time_str) - 1,
  19194. &start_time);
  19195. #if defined(USE_SERVER_STATS)
  19196. close_time = conn->conn_close_time;
  19197. #endif
  19198. if (close_time != 0) {
  19199. time_diff = difftime(close_time, start_time);
  19200. gmt_time_string(close_time_str,
  19201. sizeof(close_time_str) - 1,
  19202. &close_time);
  19203. } else {
  19204. time_t now = time(NULL);
  19205. time_diff = difftime(now, start_time);
  19206. close_time_str[0] = 0; /* or use "now" ? */
  19207. }
  19208. mg_snprintf(NULL,
  19209. NULL,
  19210. block,
  19211. sizeof(block),
  19212. "%s%s\"time\" : {%s"
  19213. "\"uptime\" : %.0f,%s"
  19214. "\"start\" : \"%s\",%s"
  19215. "\"closed\" : \"%s\"%s"
  19216. "}",
  19217. (connection_info_length > 1 ? "," : ""),
  19218. eol,
  19219. eol,
  19220. time_diff,
  19221. eol,
  19222. start_time_str,
  19223. eol,
  19224. close_time_str,
  19225. eol);
  19226. connection_info_length += mg_str_append(&buffer, end, block);
  19227. }
  19228. /* Remote user name */
  19229. if ((ri->remote_user) && (state < 9)) {
  19230. mg_snprintf(NULL,
  19231. NULL,
  19232. block,
  19233. sizeof(block),
  19234. "%s%s\"user\" : {%s"
  19235. "\"name\" : \"%s\",%s"
  19236. "}",
  19237. (connection_info_length > 1 ? "," : ""),
  19238. eol,
  19239. eol,
  19240. ri->remote_user,
  19241. eol);
  19242. connection_info_length += mg_str_append(&buffer, end, block);
  19243. }
  19244. /* Data block */
  19245. if (state >= 3) {
  19246. mg_snprintf(NULL,
  19247. NULL,
  19248. block,
  19249. sizeof(block),
  19250. "%s%s\"data\" : {%s"
  19251. "\"read\" : %" INT64_FMT ",%s"
  19252. "\"written\" : %" INT64_FMT "%s"
  19253. "}",
  19254. (connection_info_length > 1 ? "," : ""),
  19255. eol,
  19256. eol,
  19257. conn->consumed_content,
  19258. eol,
  19259. conn->num_bytes_sent,
  19260. eol);
  19261. connection_info_length += mg_str_append(&buffer, end, block);
  19262. }
  19263. /* State */
  19264. mg_snprintf(NULL,
  19265. NULL,
  19266. block,
  19267. sizeof(block),
  19268. "%s%s\"state\" : \"%s\"",
  19269. (connection_info_length > 1 ? "," : ""),
  19270. eol,
  19271. state_str);
  19272. connection_info_length += mg_str_append(&buffer, end, block);
  19273. /* Terminate string */
  19274. if (append_eoobj) {
  19275. strcat(append_eoobj, eoobj);
  19276. }
  19277. connection_info_length += sizeof(eoobj) - 1;
  19278. return (int)connection_info_length;
  19279. }
  19280. #if 0
  19281. /* Get handler information. It can be printed or stored by the caller.
  19282. * Return the size of available information. */
  19283. CIVETWEB_API int
  19284. mg_get_handler_info(struct mg_context *ctx,
  19285. char *buffer,
  19286. int buflen)
  19287. {
  19288. int handler_info_len = 0;
  19289. struct mg_handler_info *tmp_rh;
  19290. mg_lock_context(ctx);
  19291. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19292. if (buflen > handler_info_len+ tmp_rh->uri_len) {
  19293. memcpy(buffer+handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19294. }
  19295. handler_info_len += tmp_rh->uri_len;
  19296. switch (tmp_rh->handler_type) {
  19297. case REQUEST_HANDLER:
  19298. (void)tmp_rh->handler;
  19299. break;
  19300. case WEBSOCKET_HANDLER:
  19301. (void)tmp_rh->connect_handler;
  19302. (void) tmp_rh->ready_handler;
  19303. (void) tmp_rh->data_handler;
  19304. (void) tmp_rh->close_handler;
  19305. break;
  19306. case AUTH_HANDLER:
  19307. (void) tmp_rh->auth_handler;
  19308. break;
  19309. }
  19310. (void)cbdata;
  19311. }
  19312. mg_unlock_context(ctx);
  19313. return handler_info_len;
  19314. }
  19315. #endif
  19316. #endif
  19317. /* Initialize this library. This function does not need to be thread safe.
  19318. */
  19319. CIVETWEB_API unsigned
  19320. mg_init_library(unsigned features)
  19321. {
  19322. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19323. unsigned features_inited = features_to_init;
  19324. if (mg_init_library_called <= 0) {
  19325. /* Not initialized yet */
  19326. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19327. return 0;
  19328. }
  19329. }
  19330. mg_global_lock();
  19331. if (mg_init_library_called <= 0) {
  19332. int i, len;
  19333. #if defined(_WIN32)
  19334. int file_mutex_init = 1;
  19335. int wsa = 1;
  19336. #else
  19337. int mutexattr_init = 1;
  19338. #endif
  19339. int failed = 1;
  19340. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19341. if (key_create == 0) {
  19342. #if defined(_WIN32)
  19343. file_mutex_init =
  19344. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19345. if (file_mutex_init == 0) {
  19346. /* Start WinSock */
  19347. WSADATA data;
  19348. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19349. }
  19350. #else
  19351. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19352. if (mutexattr_init == 0) {
  19353. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19354. PTHREAD_MUTEX_RECURSIVE);
  19355. }
  19356. #endif
  19357. }
  19358. if (failed) {
  19359. #if defined(_WIN32)
  19360. if (wsa == 0) {
  19361. (void)WSACleanup();
  19362. }
  19363. if (file_mutex_init == 0) {
  19364. (void)pthread_mutex_destroy(&global_log_file_lock);
  19365. }
  19366. #else
  19367. if (mutexattr_init == 0) {
  19368. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19369. }
  19370. #endif
  19371. if (key_create == 0) {
  19372. (void)pthread_key_delete(sTlsKey);
  19373. }
  19374. mg_global_unlock();
  19375. (void)pthread_mutex_destroy(&global_lock_mutex);
  19376. return 0;
  19377. }
  19378. #if defined(USE_LUA)
  19379. lua_init_optional_libraries();
  19380. #endif
  19381. len = 1;
  19382. for (i = 0; http_methods[i].name != NULL; i++) {
  19383. size_t sl = strlen(http_methods[i].name);
  19384. len += (int)sl;
  19385. if (i > 0) {
  19386. len += 2;
  19387. }
  19388. }
  19389. all_methods = mg_malloc(len);
  19390. if (!all_methods) {
  19391. /* Must never happen */
  19392. return 0;
  19393. }
  19394. all_methods[0] = 0;
  19395. for (i = 0; http_methods[i].name != NULL; i++) {
  19396. if (i > 0) {
  19397. strcat(all_methods, ", ");
  19398. strcat(all_methods, http_methods[i].name);
  19399. } else {
  19400. strcpy(all_methods, http_methods[i].name);
  19401. }
  19402. }
  19403. }
  19404. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19405. || defined(OPENSSL_API_3_0)) \
  19406. && !defined(NO_SSL)
  19407. if (features_to_init & MG_FEATURES_SSL) {
  19408. if (!mg_openssl_initialized) {
  19409. char ebuf[128];
  19410. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19411. mg_openssl_initialized = 1;
  19412. } else {
  19413. (void)ebuf;
  19414. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19415. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19416. }
  19417. } else {
  19418. /* ssl already initialized */
  19419. }
  19420. }
  19421. #endif
  19422. if (mg_init_library_called <= 0) {
  19423. mg_init_library_called = 1;
  19424. } else {
  19425. mg_init_library_called++;
  19426. }
  19427. mg_global_unlock();
  19428. return features_inited;
  19429. }
  19430. /* Un-initialize this library. */
  19431. CIVETWEB_API unsigned
  19432. mg_exit_library(void)
  19433. {
  19434. if (mg_init_library_called <= 0) {
  19435. return 0;
  19436. }
  19437. mg_global_lock();
  19438. mg_init_library_called--;
  19439. if (mg_init_library_called == 0) {
  19440. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19441. if (mg_openssl_initialized) {
  19442. uninitialize_openssl();
  19443. mg_openssl_initialized = 0;
  19444. }
  19445. #endif
  19446. #if defined(_WIN32)
  19447. (void)WSACleanup();
  19448. (void)pthread_mutex_destroy(&global_log_file_lock);
  19449. #else
  19450. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19451. #endif
  19452. (void)pthread_key_delete(sTlsKey);
  19453. #if defined(USE_LUA)
  19454. lua_exit_optional_libraries();
  19455. #endif
  19456. mg_free(all_methods);
  19457. all_methods = NULL;
  19458. mg_global_unlock();
  19459. (void)pthread_mutex_destroy(&global_lock_mutex);
  19460. return 1;
  19461. }
  19462. mg_global_unlock();
  19463. return 1;
  19464. }
  19465. /* End of civetweb.c */