civetweb.c 597 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454
  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__) && defined(__APPLE__) /* 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 macros */
  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__) && defined(__APPLE__)
  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_#_# or USE_MBEDTLS"
  1306. #endif
  1307. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1308. #error "Multiple OPENSSL_API versions defined"
  1309. #endif
  1310. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1311. #error "Multiple OPENSSL_API versions defined"
  1312. #endif
  1313. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1314. #error "Multiple OPENSSL_API versions defined"
  1315. #endif
  1316. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1317. || defined(OPENSSL_API_3_0)) \
  1318. && defined(USE_MBEDTLS)
  1319. #error "Multiple SSL libraries defined"
  1320. #endif
  1321. #endif
  1322. static pthread_key_t sTlsKey; /* Thread local storage index */
  1323. static volatile ptrdiff_t thread_idx_max = 0;
  1324. #if defined(MG_LEGACY_INTERFACE)
  1325. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1326. #endif
  1327. struct mg_workerTLS {
  1328. int is_master;
  1329. unsigned long thread_idx;
  1330. void *user_ptr;
  1331. #if defined(_WIN32)
  1332. HANDLE pthread_cond_helper_mutex;
  1333. struct mg_workerTLS *next_waiting_thread;
  1334. #endif
  1335. const char *alpn_proto;
  1336. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1337. char txtbuf[4];
  1338. #endif
  1339. };
  1340. #if defined(GCC_DIAGNOSTIC)
  1341. /* Show no warning in case system functions are not used. */
  1342. #pragma GCC diagnostic push
  1343. #pragma GCC diagnostic ignored "-Wunused-function"
  1344. #endif /* defined(GCC_DIAGNOSTIC) */
  1345. #if defined(__clang__)
  1346. /* Show no warning in case system functions are not used. */
  1347. #pragma clang diagnostic push
  1348. #pragma clang diagnostic ignored "-Wunused-function"
  1349. #endif
  1350. /* Get a unique thread ID as unsigned long, independent from the data type
  1351. * of thread IDs defined by the operating system API.
  1352. * If two calls to mg_current_thread_id return the same value, they calls
  1353. * are done from the same thread. If they return different values, they are
  1354. * done from different threads. (Provided this function is used in the same
  1355. * process context and threads are not repeatedly created and deleted, but
  1356. * CivetWeb does not do that).
  1357. * This function must match the signature required for SSL id callbacks:
  1358. * CRYPTO_set_id_callback
  1359. */
  1360. FUNCTION_MAY_BE_UNUSED
  1361. static unsigned long
  1362. mg_current_thread_id(void)
  1363. {
  1364. #if defined(_WIN32)
  1365. return GetCurrentThreadId();
  1366. #else
  1367. #if defined(__clang__)
  1368. #pragma clang diagnostic push
  1369. #pragma clang diagnostic ignored "-Wunreachable-code"
  1370. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1371. * or not, so one of the two conditions will be unreachable by construction.
  1372. * Unfortunately the C standard does not define a way to check this at
  1373. * compile time, since the #if preprocessor conditions can not use the
  1374. * sizeof operator as an argument. */
  1375. #endif
  1376. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1377. /* This is the problematic case for CRYPTO_set_id_callback:
  1378. * The OS pthread_t can not be cast to unsigned long. */
  1379. struct mg_workerTLS *tls =
  1380. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1381. if (tls == NULL) {
  1382. /* SSL called from an unknown thread: Create some thread index.
  1383. */
  1384. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1385. tls->is_master = -2; /* -2 means "3rd party thread" */
  1386. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1387. pthread_setspecific(sTlsKey, tls);
  1388. }
  1389. return tls->thread_idx;
  1390. } else {
  1391. /* pthread_t may be any data type, so a simple cast to unsigned long
  1392. * can rise a warning/error, depending on the platform.
  1393. * Here memcpy is used as an anything-to-anything cast. */
  1394. unsigned long ret = 0;
  1395. pthread_t t = pthread_self();
  1396. memcpy(&ret, &t, sizeof(pthread_t));
  1397. return ret;
  1398. }
  1399. #if defined(__clang__)
  1400. #pragma clang diagnostic pop
  1401. #endif
  1402. #endif
  1403. }
  1404. FUNCTION_MAY_BE_UNUSED
  1405. static uint64_t
  1406. mg_get_current_time_ns(void)
  1407. {
  1408. struct timespec tsnow;
  1409. clock_gettime(CLOCK_REALTIME, &tsnow);
  1410. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1411. }
  1412. #if defined(GCC_DIAGNOSTIC)
  1413. /* Show no warning in case system functions are not used. */
  1414. #pragma GCC diagnostic pop
  1415. #endif /* defined(GCC_DIAGNOSTIC) */
  1416. #if defined(__clang__)
  1417. /* Show no warning in case system functions are not used. */
  1418. #pragma clang diagnostic pop
  1419. #endif
  1420. #if defined(NEED_DEBUG_TRACE_FUNC)
  1421. static void
  1422. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1423. {
  1424. va_list args;
  1425. struct timespec tsnow;
  1426. /* Get some operating system independent thread id */
  1427. unsigned long thread_id = mg_current_thread_id();
  1428. clock_gettime(CLOCK_REALTIME, &tsnow);
  1429. flockfile(DEBUG_TRACE_STREAM);
  1430. fprintf(DEBUG_TRACE_STREAM,
  1431. "*** %lu.%09lu %lu %s:%u: ",
  1432. (unsigned long)tsnow.tv_sec,
  1433. (unsigned long)tsnow.tv_nsec,
  1434. thread_id,
  1435. func,
  1436. line);
  1437. va_start(args, fmt);
  1438. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1439. va_end(args);
  1440. putc('\n', DEBUG_TRACE_STREAM);
  1441. fflush(DEBUG_TRACE_STREAM);
  1442. funlockfile(DEBUG_TRACE_STREAM);
  1443. }
  1444. #endif /* NEED_DEBUG_TRACE_FUNC */
  1445. #define MD5_STATIC static
  1446. #include "md5.inl"
  1447. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1448. #if defined(NO_SOCKLEN_T)
  1449. typedef int socklen_t;
  1450. #endif /* NO_SOCKLEN_T */
  1451. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1452. #if !defined(MSG_NOSIGNAL)
  1453. #define MSG_NOSIGNAL (0)
  1454. #endif
  1455. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1456. #if defined(USE_MBEDTLS)
  1457. /* mbedTLS */
  1458. #include "mod_mbedtls.inl"
  1459. #elif defined(NO_SSL)
  1460. /* no SSL */
  1461. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1462. typedef struct SSL_CTX SSL_CTX;
  1463. #elif defined(NO_SSL_DL)
  1464. /* OpenSSL without dynamic loading */
  1465. #include <openssl/bn.h>
  1466. #include <openssl/conf.h>
  1467. #include <openssl/crypto.h>
  1468. #include <openssl/dh.h>
  1469. #include <openssl/engine.h>
  1470. #include <openssl/err.h>
  1471. #include <openssl/opensslv.h>
  1472. #include <openssl/pem.h>
  1473. #include <openssl/ssl.h>
  1474. #include <openssl/tls1.h>
  1475. #include <openssl/x509.h>
  1476. #if defined(WOLFSSL_VERSION)
  1477. /* Additional defines for WolfSSL, see
  1478. * https://github.com/civetweb/civetweb/issues/583 */
  1479. #include "wolfssl_extras.inl"
  1480. #endif
  1481. #if defined(OPENSSL_IS_BORINGSSL)
  1482. /* From boringssl/src/include/openssl/mem.h:
  1483. *
  1484. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1485. * However, that was written in a time before Valgrind and ASAN. Since we now
  1486. * have those tools, the OpenSSL allocation functions are simply macros around
  1487. * the standard memory functions.
  1488. *
  1489. * #define OPENSSL_free free */
  1490. #define free free
  1491. // disable for boringssl
  1492. #define CONF_modules_unload(a) ((void)0)
  1493. #define ENGINE_cleanup() ((void)0)
  1494. #endif
  1495. /* If OpenSSL headers are included, automatically select the API version */
  1496. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1497. #if !defined(OPENSSL_API_3_0)
  1498. #define OPENSSL_API_3_0
  1499. #endif
  1500. #define OPENSSL_REMOVE_THREAD_STATE()
  1501. #else
  1502. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1503. #if !defined(OPENSSL_API_1_1)
  1504. #define OPENSSL_API_1_1
  1505. #endif
  1506. #define OPENSSL_REMOVE_THREAD_STATE()
  1507. #else
  1508. #if !defined(OPENSSL_API_1_0)
  1509. #define OPENSSL_API_1_0
  1510. #endif
  1511. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1512. #endif
  1513. #endif
  1514. #else
  1515. /* SSL loaded dynamically from DLL / shared object */
  1516. /* Add all prototypes here, to be independent from OpenSSL source
  1517. * installation. */
  1518. #include "openssl_dl.inl"
  1519. #endif /* Various SSL bindings */
  1520. #if !defined(NO_CACHING)
  1521. static const char month_names[][4] = {"Jan",
  1522. "Feb",
  1523. "Mar",
  1524. "Apr",
  1525. "May",
  1526. "Jun",
  1527. "Jul",
  1528. "Aug",
  1529. "Sep",
  1530. "Oct",
  1531. "Nov",
  1532. "Dec"};
  1533. #endif /* !NO_CACHING */
  1534. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1535. * the union u. */
  1536. union usa {
  1537. struct sockaddr sa;
  1538. struct sockaddr_in sin;
  1539. #if defined(USE_IPV6)
  1540. struct sockaddr_in6 sin6;
  1541. #endif
  1542. #if defined(USE_X_DOM_SOCKET)
  1543. struct sockaddr_un sun;
  1544. #endif
  1545. };
  1546. #if defined(USE_X_DOM_SOCKET)
  1547. static unsigned short
  1548. USA_IN_PORT_UNSAFE(union usa *s)
  1549. {
  1550. if (s->sa.sa_family == AF_INET)
  1551. return s->sin.sin_port;
  1552. #if defined(USE_IPV6)
  1553. if (s->sa.sa_family == AF_INET6)
  1554. return s->sin6.sin6_port;
  1555. #endif
  1556. return 0;
  1557. }
  1558. #endif
  1559. #if defined(USE_IPV6)
  1560. #define USA_IN_PORT_UNSAFE(s) \
  1561. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1562. #else
  1563. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1564. #endif
  1565. /* Describes a string (chunk of memory). */
  1566. struct vec {
  1567. const char *ptr;
  1568. size_t len;
  1569. };
  1570. struct mg_file_stat {
  1571. /* File properties filled by mg_stat: */
  1572. uint64_t size;
  1573. time_t last_modified;
  1574. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1575. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1576. * case we need a "Content-Eencoding: gzip" header */
  1577. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1578. };
  1579. struct mg_file_access {
  1580. /* File properties filled by mg_fopen: */
  1581. FILE *fp;
  1582. };
  1583. struct mg_file {
  1584. struct mg_file_stat stat;
  1585. struct mg_file_access access;
  1586. };
  1587. #define STRUCT_FILE_INITIALIZER \
  1588. { \
  1589. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1590. { \
  1591. (FILE *)NULL \
  1592. } \
  1593. }
  1594. /* Describes listening socket, or socket which was accept()-ed by the master
  1595. * thread and queued for future handling by the worker thread. */
  1596. struct socket {
  1597. SOCKET sock; /* Listening socket */
  1598. union usa lsa; /* Local socket address */
  1599. union usa rsa; /* Remote socket address */
  1600. unsigned char is_ssl; /* Is port SSL-ed */
  1601. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1602. * port */
  1603. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1604. };
  1605. /* Enum const for all options must be in sync with
  1606. * static struct mg_option config_options[]
  1607. * This is tested in the unit test (test/private.c)
  1608. * "Private Config Options"
  1609. */
  1610. enum {
  1611. /* Once for each server */
  1612. LISTENING_PORTS,
  1613. NUM_THREADS,
  1614. RUN_AS_USER,
  1615. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1616. * socket option typedef TCP_NODELAY. */
  1617. MAX_REQUEST_SIZE,
  1618. LINGER_TIMEOUT,
  1619. CONNECTION_QUEUE_SIZE,
  1620. LISTEN_BACKLOG_SIZE,
  1621. #if defined(__linux__)
  1622. ALLOW_SENDFILE_CALL,
  1623. #endif
  1624. #if defined(_WIN32)
  1625. CASE_SENSITIVE_FILES,
  1626. #endif
  1627. THROTTLE,
  1628. ENABLE_KEEP_ALIVE,
  1629. REQUEST_TIMEOUT,
  1630. KEEP_ALIVE_TIMEOUT,
  1631. #if defined(USE_WEBSOCKET)
  1632. WEBSOCKET_TIMEOUT,
  1633. ENABLE_WEBSOCKET_PING_PONG,
  1634. #endif
  1635. DECODE_URL,
  1636. DECODE_QUERY_STRING,
  1637. #if defined(USE_LUA)
  1638. LUA_BACKGROUND_SCRIPT,
  1639. LUA_BACKGROUND_SCRIPT_PARAMS,
  1640. #endif
  1641. #if defined(USE_HTTP2)
  1642. ENABLE_HTTP2,
  1643. #endif
  1644. /* Once for each domain */
  1645. DOCUMENT_ROOT,
  1646. ACCESS_LOG_FILE,
  1647. ERROR_LOG_FILE,
  1648. CGI_EXTENSIONS,
  1649. CGI_ENVIRONMENT,
  1650. CGI_INTERPRETER,
  1651. CGI_INTERPRETER_ARGS,
  1652. #if defined(USE_TIMERS)
  1653. CGI_TIMEOUT,
  1654. #endif
  1655. CGI_BUFFERING,
  1656. CGI2_EXTENSIONS,
  1657. CGI2_ENVIRONMENT,
  1658. CGI2_INTERPRETER,
  1659. CGI2_INTERPRETER_ARGS,
  1660. #if defined(USE_TIMERS)
  1661. CGI2_TIMEOUT,
  1662. #endif
  1663. CGI2_BUFFERING,
  1664. #if defined(USE_4_CGI)
  1665. CGI3_EXTENSIONS,
  1666. CGI3_ENVIRONMENT,
  1667. CGI3_INTERPRETER,
  1668. CGI3_INTERPRETER_ARGS,
  1669. #if defined(USE_TIMERS)
  1670. CGI3_TIMEOUT,
  1671. #endif
  1672. CGI3_BUFFERING,
  1673. CGI4_EXTENSIONS,
  1674. CGI4_ENVIRONMENT,
  1675. CGI4_INTERPRETER,
  1676. CGI4_INTERPRETER_ARGS,
  1677. #if defined(USE_TIMERS)
  1678. CGI4_TIMEOUT,
  1679. #endif
  1680. CGI4_BUFFERING,
  1681. #endif
  1682. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1683. PROTECT_URI,
  1684. AUTHENTICATION_DOMAIN,
  1685. ENABLE_AUTH_DOMAIN_CHECK,
  1686. SSI_EXTENSIONS,
  1687. ENABLE_DIRECTORY_LISTING,
  1688. ENABLE_WEBDAV,
  1689. GLOBAL_PASSWORDS_FILE,
  1690. INDEX_FILES,
  1691. ACCESS_CONTROL_LIST,
  1692. EXTRA_MIME_TYPES,
  1693. SSL_CERTIFICATE,
  1694. SSL_CERTIFICATE_CHAIN,
  1695. URL_REWRITE_PATTERN,
  1696. HIDE_FILES,
  1697. SSL_DO_VERIFY_PEER,
  1698. SSL_CACHE_TIMEOUT,
  1699. SSL_CA_PATH,
  1700. SSL_CA_FILE,
  1701. SSL_VERIFY_DEPTH,
  1702. SSL_DEFAULT_VERIFY_PATHS,
  1703. SSL_CIPHER_LIST,
  1704. SSL_PROTOCOL_VERSION,
  1705. SSL_SHORT_TRUST,
  1706. #if defined(USE_LUA)
  1707. LUA_PRELOAD_FILE,
  1708. LUA_SCRIPT_EXTENSIONS,
  1709. LUA_SERVER_PAGE_EXTENSIONS,
  1710. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1711. LUA_DEBUG_PARAMS,
  1712. #endif
  1713. #endif
  1714. #if defined(USE_DUKTAPE)
  1715. DUKTAPE_SCRIPT_EXTENSIONS,
  1716. #endif
  1717. #if defined(USE_WEBSOCKET)
  1718. WEBSOCKET_ROOT,
  1719. #endif
  1720. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1721. LUA_WEBSOCKET_EXTENSIONS,
  1722. #endif
  1723. ACCESS_CONTROL_ALLOW_ORIGIN,
  1724. ACCESS_CONTROL_ALLOW_METHODS,
  1725. ACCESS_CONTROL_ALLOW_HEADERS,
  1726. ERROR_PAGES,
  1727. #if !defined(NO_CACHING)
  1728. STATIC_FILE_MAX_AGE,
  1729. STATIC_FILE_CACHE_CONTROL,
  1730. #endif
  1731. #if !defined(NO_SSL)
  1732. STRICT_HTTPS_MAX_AGE,
  1733. #endif
  1734. ADDITIONAL_HEADER,
  1735. ALLOW_INDEX_SCRIPT_SUB_RES,
  1736. NUM_OPTIONS
  1737. };
  1738. /* Config option name, config types, default value.
  1739. * Must be in the same order as the enum const above.
  1740. */
  1741. static const struct mg_option config_options[] = {
  1742. /* Once for each server */
  1743. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1744. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1745. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1746. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1747. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1748. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1749. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1750. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1751. #if defined(__linux__)
  1752. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1753. #endif
  1754. #if defined(_WIN32)
  1755. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1756. #endif
  1757. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1758. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1759. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1760. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1761. #if defined(USE_WEBSOCKET)
  1762. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1763. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1764. #endif
  1765. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1766. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1767. #if defined(USE_LUA)
  1768. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1769. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1770. #endif
  1771. #if defined(USE_HTTP2)
  1772. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1773. #endif
  1774. /* Once for each domain */
  1775. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1776. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1777. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1778. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1779. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1780. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1781. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1782. #if defined(USE_TIMERS)
  1783. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1784. #endif
  1785. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1786. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1787. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1788. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1789. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1790. #if defined(USE_TIMERS)
  1791. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1792. #endif
  1793. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1794. #if defined(USE_4_CGI)
  1795. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1796. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1797. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1798. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1799. #if defined(USE_TIMERS)
  1800. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1801. #endif
  1802. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1803. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1804. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1805. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1806. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1807. #if defined(USE_TIMERS)
  1808. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1809. #endif
  1810. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1811. #endif
  1812. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1813. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1814. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1815. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1816. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1817. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1818. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1819. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1820. {"index_files",
  1821. MG_CONFIG_TYPE_STRING_LIST,
  1822. #if defined(USE_LUA)
  1823. "index.xhtml,index.html,index.htm,"
  1824. "index.lp,index.lsp,index.lua,index.cgi,"
  1825. "index.shtml,index.php"},
  1826. #else
  1827. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1828. #endif
  1829. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1830. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1831. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1832. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1833. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1834. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1835. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1836. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1837. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1838. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1839. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1840. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1841. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1842. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1843. * as a minimum in 2020 */
  1844. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1845. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1846. #if defined(USE_LUA)
  1847. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1848. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1849. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1850. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1851. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1852. #endif
  1853. #endif
  1854. #if defined(USE_DUKTAPE)
  1855. /* The support for duktape is still in alpha version state.
  1856. * The name of this config option might change. */
  1857. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1858. #endif
  1859. #if defined(USE_WEBSOCKET)
  1860. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1861. #endif
  1862. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1863. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1864. #endif
  1865. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1866. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1867. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1868. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1869. #if !defined(NO_CACHING)
  1870. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1871. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1872. #endif
  1873. #if !defined(NO_SSL)
  1874. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1875. #endif
  1876. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1877. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1878. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1879. /* Check if the config_options and the corresponding enum have compatible
  1880. * sizes. */
  1881. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1882. == (NUM_OPTIONS + 1),
  1883. "config_options and enum not sync");
  1884. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1885. struct mg_handler_info {
  1886. /* Name/Pattern of the URI. */
  1887. char *uri;
  1888. size_t uri_len;
  1889. /* handler type */
  1890. int handler_type;
  1891. /* Handler for http/https or requests. */
  1892. mg_request_handler handler;
  1893. unsigned int refcount;
  1894. int removing;
  1895. /* Handler for ws/wss (websocket) requests. */
  1896. mg_websocket_connect_handler connect_handler;
  1897. mg_websocket_ready_handler ready_handler;
  1898. mg_websocket_data_handler data_handler;
  1899. mg_websocket_close_handler close_handler;
  1900. /* accepted subprotocols for ws/wss requests. */
  1901. struct mg_websocket_subprotocols *subprotocols;
  1902. /* Handler for authorization requests */
  1903. mg_authorization_handler auth_handler;
  1904. /* User supplied argument for the handler function. */
  1905. void *cbdata;
  1906. /* next handler in a linked list */
  1907. struct mg_handler_info *next;
  1908. };
  1909. enum {
  1910. CONTEXT_INVALID,
  1911. CONTEXT_SERVER,
  1912. CONTEXT_HTTP_CLIENT,
  1913. CONTEXT_WS_CLIENT
  1914. };
  1915. struct mg_domain_context {
  1916. SSL_CTX *ssl_ctx; /* SSL context */
  1917. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1918. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1919. int64_t ssl_cert_last_mtime;
  1920. /* Server nonce */
  1921. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1922. unsigned long nonce_count; /* Used nonces, used for authentication */
  1923. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1924. /* linked list of shared lua websockets */
  1925. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1926. #endif
  1927. /* Linked list of domains */
  1928. struct mg_domain_context *next;
  1929. };
  1930. /* Stop flag can be "volatile" or require a lock.
  1931. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1932. * states a read operation for int is always atomic. */
  1933. #if defined(STOP_FLAG_NEEDS_LOCK)
  1934. typedef ptrdiff_t volatile stop_flag_t;
  1935. static int
  1936. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1937. {
  1938. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1939. return (sf == 0);
  1940. }
  1941. static int
  1942. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1943. {
  1944. stop_flag_t sf = mg_atomic_add(f, 0);
  1945. return (sf == 2);
  1946. }
  1947. static void
  1948. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1949. {
  1950. stop_flag_t sf;
  1951. do {
  1952. sf = mg_atomic_compare_and_swap(f, *f, v);
  1953. } while (sf != v);
  1954. }
  1955. #else /* STOP_FLAG_NEEDS_LOCK */
  1956. typedef int volatile stop_flag_t;
  1957. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1958. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1959. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1960. #endif /* STOP_FLAG_NEEDS_LOCK */
  1961. #if !defined(NUM_WEBDAV_LOCKS)
  1962. #define NUM_WEBDAV_LOCKS 10
  1963. #endif
  1964. #if !defined(LOCK_DURATION_S)
  1965. #define LOCK_DURATION_S 60
  1966. #endif
  1967. struct twebdav_lock {
  1968. uint64_t locktime;
  1969. char token[33];
  1970. char path[UTF8_PATH_MAX * 2];
  1971. char user[UTF8_PATH_MAX * 2];
  1972. };
  1973. struct mg_context {
  1974. /* Part 1 - Physical context:
  1975. * This holds threads, ports, timeouts, ...
  1976. * set for the entire server, independent from the
  1977. * addressed hostname.
  1978. */
  1979. /* Connection related */
  1980. int context_type; /* See CONTEXT_* above */
  1981. struct socket *listening_sockets;
  1982. struct mg_pollfd *listening_socket_fds;
  1983. unsigned int num_listening_sockets;
  1984. struct mg_connection *worker_connections; /* The connection struct, pre-
  1985. * allocated for each worker */
  1986. #if defined(USE_SERVER_STATS)
  1987. volatile ptrdiff_t active_connections;
  1988. volatile ptrdiff_t max_active_connections;
  1989. volatile ptrdiff_t total_connections;
  1990. volatile ptrdiff_t total_requests;
  1991. volatile int64_t total_data_read;
  1992. volatile int64_t total_data_written;
  1993. #endif
  1994. /* Thread related */
  1995. stop_flag_t stop_flag; /* Should we stop event loop */
  1996. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  1997. pthread_t masterthreadid; /* The master thread ID */
  1998. unsigned int
  1999. cfg_worker_threads; /* The number of configured worker threads. */
  2000. pthread_t *worker_threadids; /* The worker thread IDs */
  2001. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2002. /* Connection to thread dispatching */
  2003. #if defined(ALTERNATIVE_QUEUE)
  2004. struct socket *client_socks;
  2005. void **client_wait_events;
  2006. #else
  2007. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2008. worker thread */
  2009. volatile int sq_head; /* Head of the socket queue */
  2010. volatile int sq_tail; /* Tail of the socket queue */
  2011. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2012. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2013. volatile int sq_blocked; /* Status information: sq is full */
  2014. int sq_size; /* No of elements in socket queue */
  2015. #if defined(USE_SERVER_STATS)
  2016. int sq_max_fill;
  2017. #endif /* USE_SERVER_STATS */
  2018. #endif /* ALTERNATIVE_QUEUE */
  2019. /* Memory related */
  2020. unsigned int max_request_size; /* The max request size */
  2021. #if defined(USE_SERVER_STATS)
  2022. struct mg_memory_stat ctx_memory;
  2023. #endif
  2024. /* WebDAV lock structures */
  2025. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2026. /* Operating system related */
  2027. char *systemName; /* What operating system is running */
  2028. time_t start_time; /* Server start time, used for authentication
  2029. * and for diagnstics. */
  2030. #if defined(USE_TIMERS)
  2031. struct ttimers *timers;
  2032. #endif
  2033. /* Lua specific: Background operations and shared websockets */
  2034. #if defined(USE_LUA)
  2035. void *lua_background_state; /* lua_State (here as void *) */
  2036. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2037. int lua_bg_log_available; /* Use Lua background state for access log */
  2038. #endif
  2039. /* Server nonce */
  2040. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2041. * ssl_cert_last_mtime, nonce_count, and
  2042. * next (linked list) */
  2043. /* Server callbacks */
  2044. struct mg_callbacks callbacks; /* User-defined callback function */
  2045. void *user_data; /* User-defined data */
  2046. /* Part 2 - Logical domain:
  2047. * This holds hostname, TLS certificate, document root, ...
  2048. * set for a domain hosted at the server.
  2049. * There may be multiple domains hosted at one physical server.
  2050. * The default domain "dd" is the first element of a list of
  2051. * domains.
  2052. */
  2053. struct mg_domain_context dd; /* default domain */
  2054. };
  2055. #if defined(USE_SERVER_STATS)
  2056. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2057. static struct mg_memory_stat *
  2058. get_memory_stat(struct mg_context *ctx)
  2059. {
  2060. if (ctx) {
  2061. return &(ctx->ctx_memory);
  2062. }
  2063. return &mg_common_memory;
  2064. }
  2065. #endif
  2066. enum {
  2067. CONNECTION_TYPE_INVALID = 0,
  2068. CONNECTION_TYPE_REQUEST = 1,
  2069. CONNECTION_TYPE_RESPONSE = 2
  2070. };
  2071. enum {
  2072. PROTOCOL_TYPE_HTTP1 = 0,
  2073. PROTOCOL_TYPE_WEBSOCKET = 1,
  2074. PROTOCOL_TYPE_HTTP2 = 2
  2075. };
  2076. #if defined(USE_HTTP2)
  2077. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2078. #define HTTP2_DYN_TABLE_SIZE (256)
  2079. #endif
  2080. struct mg_http2_connection {
  2081. uint32_t stream_id;
  2082. uint32_t dyn_table_size;
  2083. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2084. };
  2085. #endif
  2086. struct mg_connection {
  2087. int connection_type; /* see CONNECTION_TYPE_* above */
  2088. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2089. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2090. fully sent */
  2091. #if defined(USE_HTTP2)
  2092. struct mg_http2_connection http2;
  2093. #endif
  2094. struct mg_request_info request_info;
  2095. struct mg_response_info response_info;
  2096. struct mg_context *phys_ctx;
  2097. struct mg_domain_context *dom_ctx;
  2098. #if defined(USE_SERVER_STATS)
  2099. int conn_state; /* 0 = undef, numerical value may change in different
  2100. * versions. For the current definition, see
  2101. * mg_get_connection_info_impl */
  2102. #endif
  2103. SSL *ssl; /* SSL descriptor */
  2104. struct socket client; /* Connected client */
  2105. time_t conn_birth_time; /* Time (wall clock) when connection was
  2106. * established */
  2107. #if defined(USE_SERVER_STATS)
  2108. time_t conn_close_time; /* Time (wall clock) when connection was
  2109. * closed (or 0 if still open) */
  2110. double processing_time; /* Processing time for one request. */
  2111. #endif
  2112. struct timespec req_time; /* Time (since system start) when the request
  2113. * was received */
  2114. int64_t num_bytes_sent; /* Total bytes sent to client */
  2115. int64_t content_len; /* How many bytes of content can be read
  2116. * !is_chunked: Content-Length header value
  2117. * or -1 (until connection closed,
  2118. * not allowed for a request)
  2119. * is_chunked: >= 0, appended gradually
  2120. */
  2121. int64_t consumed_content; /* How many bytes of content have been read */
  2122. int is_chunked; /* Transfer-Encoding is chunked:
  2123. * 0 = not chunked,
  2124. * 1 = chunked, not yet, or some data read,
  2125. * 2 = chunked, has error,
  2126. * 3 = chunked, all data read except trailer,
  2127. * 4 = chunked, all data read
  2128. */
  2129. char *buf; /* Buffer for received data */
  2130. char *path_info; /* PATH_INFO part of the URL */
  2131. int must_close; /* 1 if connection must be closed */
  2132. int accept_gzip; /* 1 if gzip encoding is accepted */
  2133. int in_error_handler; /* 1 if in handler for user defined error
  2134. * pages */
  2135. #if defined(USE_WEBSOCKET)
  2136. int in_websocket_handling; /* 1 if in read_websocket */
  2137. #endif
  2138. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2139. && defined(MG_EXPERIMENTAL_INTERFACES)
  2140. /* Parameters for websocket data compression according to rfc7692 */
  2141. int websocket_deflate_server_max_windows_bits;
  2142. int websocket_deflate_client_max_windows_bits;
  2143. int websocket_deflate_server_no_context_takeover;
  2144. int websocket_deflate_client_no_context_takeover;
  2145. int websocket_deflate_initialized;
  2146. int websocket_deflate_flush;
  2147. z_stream websocket_deflate_state;
  2148. z_stream websocket_inflate_state;
  2149. #endif
  2150. int handled_requests; /* Number of requests handled by this connection
  2151. */
  2152. int buf_size; /* Buffer size */
  2153. int request_len; /* Size of the request + headers in a buffer */
  2154. int data_len; /* Total size of data in a buffer */
  2155. int status_code; /* HTTP reply status code, e.g. 200 */
  2156. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2157. * throttle */
  2158. time_t last_throttle_time; /* Last time throttled data was sent */
  2159. int last_throttle_bytes; /* Bytes sent this second */
  2160. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2161. * atomic transmissions for websockets */
  2162. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2163. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2164. #endif
  2165. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2166. * for quick access */
  2167. };
  2168. /* Directory entry */
  2169. struct de {
  2170. char *file_name;
  2171. struct mg_file_stat file;
  2172. };
  2173. #define mg_cry_internal(conn, fmt, ...) \
  2174. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2175. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2176. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2177. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2178. struct mg_context *ctx,
  2179. const char *func,
  2180. unsigned line,
  2181. const char *fmt,
  2182. ...) PRINTF_ARGS(5, 6);
  2183. #if !defined(NO_THREAD_NAME)
  2184. #if defined(_WIN32) && defined(_MSC_VER)
  2185. /* Set the thread name for debugging purposes in Visual Studio
  2186. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2187. */
  2188. #pragma pack(push, 8)
  2189. typedef struct tagTHREADNAME_INFO {
  2190. DWORD dwType; /* Must be 0x1000. */
  2191. LPCSTR szName; /* Pointer to name (in user addr space). */
  2192. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2193. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2194. } THREADNAME_INFO;
  2195. #pragma pack(pop)
  2196. #elif defined(__linux__)
  2197. #include <sys/prctl.h>
  2198. #include <sys/sendfile.h>
  2199. #if defined(ALTERNATIVE_QUEUE)
  2200. #include <sys/eventfd.h>
  2201. #endif /* ALTERNATIVE_QUEUE */
  2202. #if defined(ALTERNATIVE_QUEUE)
  2203. static void *
  2204. event_create(void)
  2205. {
  2206. int evhdl = eventfd(0, EFD_CLOEXEC);
  2207. int *ret;
  2208. if (evhdl == -1) {
  2209. /* Linux uses -1 on error, Windows NULL. */
  2210. /* However, Linux does not return 0 on success either. */
  2211. return 0;
  2212. }
  2213. ret = (int *)mg_malloc(sizeof(int));
  2214. if (ret) {
  2215. *ret = evhdl;
  2216. } else {
  2217. (void)close(evhdl);
  2218. }
  2219. return (void *)ret;
  2220. }
  2221. static int
  2222. event_wait(void *eventhdl)
  2223. {
  2224. uint64_t u;
  2225. int evhdl, s;
  2226. if (!eventhdl) {
  2227. /* error */
  2228. return 0;
  2229. }
  2230. evhdl = *(int *)eventhdl;
  2231. s = (int)read(evhdl, &u, sizeof(u));
  2232. if (s != sizeof(u)) {
  2233. /* error */
  2234. return 0;
  2235. }
  2236. (void)u; /* the value is not required */
  2237. return 1;
  2238. }
  2239. static int
  2240. event_signal(void *eventhdl)
  2241. {
  2242. uint64_t u = 1;
  2243. int evhdl, s;
  2244. if (!eventhdl) {
  2245. /* error */
  2246. return 0;
  2247. }
  2248. evhdl = *(int *)eventhdl;
  2249. s = (int)write(evhdl, &u, sizeof(u));
  2250. if (s != sizeof(u)) {
  2251. /* error */
  2252. return 0;
  2253. }
  2254. return 1;
  2255. }
  2256. static void
  2257. event_destroy(void *eventhdl)
  2258. {
  2259. int evhdl;
  2260. if (!eventhdl) {
  2261. /* error */
  2262. return;
  2263. }
  2264. evhdl = *(int *)eventhdl;
  2265. close(evhdl);
  2266. mg_free(eventhdl);
  2267. }
  2268. #endif
  2269. #endif
  2270. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2271. struct posix_event {
  2272. pthread_mutex_t mutex;
  2273. pthread_cond_t cond;
  2274. int signaled;
  2275. };
  2276. static void *
  2277. event_create(void)
  2278. {
  2279. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2280. if (ret == 0) {
  2281. /* out of memory */
  2282. return 0;
  2283. }
  2284. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2285. /* pthread mutex not available */
  2286. mg_free(ret);
  2287. return 0;
  2288. }
  2289. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2290. /* pthread cond not available */
  2291. pthread_mutex_destroy(&(ret->mutex));
  2292. mg_free(ret);
  2293. return 0;
  2294. }
  2295. ret->signaled = 0;
  2296. return (void *)ret;
  2297. }
  2298. static int
  2299. event_wait(void *eventhdl)
  2300. {
  2301. struct posix_event *ev = (struct posix_event *)eventhdl;
  2302. pthread_mutex_lock(&(ev->mutex));
  2303. while (!ev->signaled) {
  2304. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2305. }
  2306. ev->signaled = 0;
  2307. pthread_mutex_unlock(&(ev->mutex));
  2308. return 1;
  2309. }
  2310. static int
  2311. event_signal(void *eventhdl)
  2312. {
  2313. struct posix_event *ev = (struct posix_event *)eventhdl;
  2314. pthread_mutex_lock(&(ev->mutex));
  2315. pthread_cond_signal(&(ev->cond));
  2316. ev->signaled = 1;
  2317. pthread_mutex_unlock(&(ev->mutex));
  2318. return 1;
  2319. }
  2320. static void
  2321. event_destroy(void *eventhdl)
  2322. {
  2323. struct posix_event *ev = (struct posix_event *)eventhdl;
  2324. pthread_cond_destroy(&(ev->cond));
  2325. pthread_mutex_destroy(&(ev->mutex));
  2326. mg_free(ev);
  2327. }
  2328. #endif
  2329. static void
  2330. mg_set_thread_name(const char *name)
  2331. {
  2332. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2333. mg_snprintf(
  2334. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2335. #if defined(_WIN32)
  2336. #if defined(_MSC_VER)
  2337. /* Windows and Visual Studio Compiler */
  2338. __try {
  2339. THREADNAME_INFO info;
  2340. info.dwType = 0x1000;
  2341. info.szName = threadName;
  2342. info.dwThreadID = ~0U;
  2343. info.dwFlags = 0;
  2344. RaiseException(0x406D1388,
  2345. 0,
  2346. sizeof(info) / sizeof(ULONG_PTR),
  2347. (ULONG_PTR *)&info);
  2348. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2349. }
  2350. #elif defined(__MINGW32__)
  2351. /* No option known to set thread name for MinGW known */
  2352. #endif
  2353. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2354. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2355. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2356. #if defined(__MACH__) && defined(__APPLE__)
  2357. /* OS X only current thread name can be changed */
  2358. (void)pthread_setname_np(threadName);
  2359. #else
  2360. (void)pthread_setname_np(pthread_self(), threadName);
  2361. #endif
  2362. #elif defined(__linux__)
  2363. /* On Linux we can use the prctl function.
  2364. * When building for Linux Standard Base (LSB) use
  2365. * NO_THREAD_NAME. However, thread names are a big
  2366. * help for debugging, so the stadard is to set them.
  2367. */
  2368. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2369. #endif
  2370. }
  2371. #else /* !defined(NO_THREAD_NAME) */
  2372. static void
  2373. mg_set_thread_name(const char *threadName)
  2374. {
  2375. }
  2376. #endif
  2377. CIVETWEB_API const struct mg_option *
  2378. mg_get_valid_options(void)
  2379. {
  2380. return config_options;
  2381. }
  2382. /* Do not open file (unused) */
  2383. #define MG_FOPEN_MODE_NONE (0)
  2384. /* Open file for read only access */
  2385. #define MG_FOPEN_MODE_READ (1)
  2386. /* Open file for writing, create and overwrite */
  2387. #define MG_FOPEN_MODE_WRITE (2)
  2388. /* Open file for writing, create and append */
  2389. #define MG_FOPEN_MODE_APPEND (4)
  2390. static int
  2391. is_file_opened(const struct mg_file_access *fileacc)
  2392. {
  2393. if (!fileacc) {
  2394. return 0;
  2395. }
  2396. return (fileacc->fp != NULL);
  2397. }
  2398. #if !defined(NO_FILESYSTEMS)
  2399. static int mg_stat(const struct mg_connection *conn,
  2400. const char *path,
  2401. struct mg_file_stat *filep);
  2402. /* Reject files with special characters (for Windows) */
  2403. static int
  2404. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2405. {
  2406. const uint8_t *c = (const uint8_t *)path;
  2407. (void)conn; /* not used */
  2408. if ((c == NULL) || (c[0] == 0)) {
  2409. /* Null pointer or empty path --> suspicious */
  2410. return 1;
  2411. }
  2412. #if defined(_WIN32)
  2413. while (*c) {
  2414. if (*c < 32) {
  2415. /* Control character */
  2416. return 1;
  2417. }
  2418. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2419. /* stdin/stdout redirection character */
  2420. return 1;
  2421. }
  2422. if ((*c == '*') || (*c == '?')) {
  2423. /* Wildcard character */
  2424. return 1;
  2425. }
  2426. if (*c == '"') {
  2427. /* Windows quotation */
  2428. return 1;
  2429. }
  2430. c++;
  2431. }
  2432. #endif
  2433. /* Nothing suspicious found */
  2434. return 0;
  2435. }
  2436. /* mg_fopen will open a file either in memory or on the disk.
  2437. * The input parameter path is a string in UTF-8 encoding.
  2438. * The input parameter mode is MG_FOPEN_MODE_*
  2439. * On success, fp will be set in the output struct mg_file.
  2440. * All status members will also be set.
  2441. * The function returns 1 on success, 0 on error. */
  2442. static int
  2443. mg_fopen(const struct mg_connection *conn,
  2444. const char *path,
  2445. int mode,
  2446. struct mg_file *filep)
  2447. {
  2448. int found;
  2449. if (!filep) {
  2450. return 0;
  2451. }
  2452. filep->access.fp = NULL;
  2453. if (mg_path_suspicious(conn, path)) {
  2454. return 0;
  2455. }
  2456. /* filep is initialized in mg_stat: all fields with memset to,
  2457. * some fields like size and modification date with values */
  2458. found = mg_stat(conn, path, &(filep->stat));
  2459. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2460. /* file does not exist and will not be created */
  2461. return 0;
  2462. }
  2463. #if defined(_WIN32)
  2464. {
  2465. wchar_t wbuf[UTF16_PATH_MAX];
  2466. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2467. switch (mode) {
  2468. case MG_FOPEN_MODE_READ:
  2469. filep->access.fp = _wfopen(wbuf, L"rb");
  2470. break;
  2471. case MG_FOPEN_MODE_WRITE:
  2472. filep->access.fp = _wfopen(wbuf, L"wb");
  2473. break;
  2474. case MG_FOPEN_MODE_APPEND:
  2475. filep->access.fp = _wfopen(wbuf, L"ab");
  2476. break;
  2477. }
  2478. }
  2479. #else
  2480. /* Linux et al already use unicode. No need to convert. */
  2481. switch (mode) {
  2482. case MG_FOPEN_MODE_READ:
  2483. filep->access.fp = fopen(path, "r");
  2484. break;
  2485. case MG_FOPEN_MODE_WRITE:
  2486. filep->access.fp = fopen(path, "w");
  2487. break;
  2488. case MG_FOPEN_MODE_APPEND:
  2489. filep->access.fp = fopen(path, "a");
  2490. break;
  2491. }
  2492. #endif
  2493. if (!found) {
  2494. /* File did not exist before fopen was called.
  2495. * Maybe it has been created now. Get stat info
  2496. * like creation time now. */
  2497. found = mg_stat(conn, path, &(filep->stat));
  2498. (void)found;
  2499. }
  2500. /* return OK if file is opened */
  2501. return (filep->access.fp != NULL);
  2502. }
  2503. /* return 0 on success, just like fclose */
  2504. static int
  2505. mg_fclose(struct mg_file_access *fileacc)
  2506. {
  2507. int ret = -1;
  2508. if (fileacc != NULL) {
  2509. if (fileacc->fp != NULL) {
  2510. ret = fclose(fileacc->fp);
  2511. }
  2512. /* reset all members of fileacc */
  2513. memset(fileacc, 0, sizeof(*fileacc));
  2514. }
  2515. return ret;
  2516. }
  2517. #endif /* NO_FILESYSTEMS */
  2518. static void
  2519. mg_strlcpy(char *dst, const char *src, size_t n)
  2520. {
  2521. for (; *src != '\0' && n > 1; n--) {
  2522. *dst++ = *src++;
  2523. }
  2524. *dst = '\0';
  2525. }
  2526. static int
  2527. lowercase(const char *s)
  2528. {
  2529. return tolower((unsigned char)*s);
  2530. }
  2531. CIVETWEB_API int
  2532. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2533. {
  2534. int diff = 0;
  2535. if (len > 0) {
  2536. do {
  2537. diff = lowercase(s1++) - lowercase(s2++);
  2538. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2539. }
  2540. return diff;
  2541. }
  2542. CIVETWEB_API int
  2543. mg_strcasecmp(const char *s1, const char *s2)
  2544. {
  2545. int diff;
  2546. do {
  2547. diff = lowercase(s1++) - lowercase(s2++);
  2548. } while (diff == 0 && s1[-1] != '\0');
  2549. return diff;
  2550. }
  2551. static char *
  2552. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2553. {
  2554. char *p;
  2555. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2556. * defined */
  2557. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2558. mg_strlcpy(p, ptr, len + 1);
  2559. }
  2560. return p;
  2561. }
  2562. static char *
  2563. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2564. {
  2565. return mg_strndup_ctx(str, strlen(str), ctx);
  2566. }
  2567. static char *
  2568. mg_strdup(const char *str)
  2569. {
  2570. return mg_strndup_ctx(str, strlen(str), NULL);
  2571. }
  2572. static const char *
  2573. mg_strcasestr(const char *big_str, const char *small_str)
  2574. {
  2575. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2576. if (big_len >= small_len) {
  2577. for (i = 0; i <= (big_len - small_len); i++) {
  2578. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2579. return big_str + i;
  2580. }
  2581. }
  2582. }
  2583. return NULL;
  2584. }
  2585. /* Return null terminated string of given maximum length.
  2586. * Report errors if length is exceeded. */
  2587. static void
  2588. mg_vsnprintf(const struct mg_connection *conn,
  2589. int *truncated,
  2590. char *buf,
  2591. size_t buflen,
  2592. const char *fmt,
  2593. va_list ap)
  2594. {
  2595. int n, ok;
  2596. if (buflen == 0) {
  2597. if (truncated) {
  2598. *truncated = 1;
  2599. }
  2600. return;
  2601. }
  2602. #if defined(__clang__)
  2603. #pragma clang diagnostic push
  2604. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2605. /* Using fmt as a non-literal is intended here, since it is mostly called
  2606. * indirectly by mg_snprintf */
  2607. #endif
  2608. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2609. ok = (n >= 0) && ((size_t)n < buflen);
  2610. #if defined(__clang__)
  2611. #pragma clang diagnostic pop
  2612. #endif
  2613. if (ok) {
  2614. if (truncated) {
  2615. *truncated = 0;
  2616. }
  2617. } else {
  2618. if (truncated) {
  2619. *truncated = 1;
  2620. }
  2621. mg_cry_internal(conn,
  2622. "truncating vsnprintf buffer: [%.*s]",
  2623. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2624. buf);
  2625. n = (int)buflen - 1;
  2626. }
  2627. buf[n] = '\0';
  2628. }
  2629. static void
  2630. mg_snprintf(const struct mg_connection *conn,
  2631. int *truncated,
  2632. char *buf,
  2633. size_t buflen,
  2634. const char *fmt,
  2635. ...)
  2636. {
  2637. va_list ap;
  2638. va_start(ap, fmt);
  2639. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2640. va_end(ap);
  2641. }
  2642. static int
  2643. get_option_index(const char *name)
  2644. {
  2645. int i;
  2646. for (i = 0; config_options[i].name != NULL; i++) {
  2647. if (strcmp(config_options[i].name, name) == 0) {
  2648. return i;
  2649. }
  2650. }
  2651. return -1;
  2652. }
  2653. CIVETWEB_API const char *
  2654. mg_get_option(const struct mg_context *ctx, const char *name)
  2655. {
  2656. int i;
  2657. if ((i = get_option_index(name)) == -1) {
  2658. return NULL;
  2659. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2660. return "";
  2661. } else {
  2662. return ctx->dd.config[i];
  2663. }
  2664. }
  2665. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2666. CIVETWEB_API struct mg_context *
  2667. mg_get_context(const struct mg_connection *conn)
  2668. {
  2669. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2670. }
  2671. CIVETWEB_API void *
  2672. mg_get_user_data(const struct mg_context *ctx)
  2673. {
  2674. return (ctx == NULL) ? NULL : ctx->user_data;
  2675. }
  2676. CIVETWEB_API void *
  2677. mg_get_user_context_data(const struct mg_connection *conn)
  2678. {
  2679. return mg_get_user_data(mg_get_context(conn));
  2680. }
  2681. CIVETWEB_API void *
  2682. mg_get_thread_pointer(const struct mg_connection *conn)
  2683. {
  2684. /* both methods should return the same pointer */
  2685. if (conn) {
  2686. /* quick access, in case conn is known */
  2687. return conn->tls_user_ptr;
  2688. } else {
  2689. /* otherwise get pointer from thread local storage (TLS) */
  2690. struct mg_workerTLS *tls =
  2691. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2692. return tls->user_ptr;
  2693. }
  2694. }
  2695. CIVETWEB_API void
  2696. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2697. {
  2698. if (const_conn != NULL) {
  2699. /* Const cast, since "const struct mg_connection *" does not mean
  2700. * the connection object is not modified. Here "const" is used,
  2701. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2702. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2703. conn->request_info.conn_data = data;
  2704. }
  2705. }
  2706. CIVETWEB_API void *
  2707. mg_get_user_connection_data(const struct mg_connection *conn)
  2708. {
  2709. if (conn != NULL) {
  2710. return conn->request_info.conn_data;
  2711. }
  2712. return NULL;
  2713. }
  2714. CIVETWEB_API int
  2715. mg_get_server_ports(const struct mg_context *ctx,
  2716. int size,
  2717. struct mg_server_port *ports)
  2718. {
  2719. int i, cnt = 0;
  2720. if (size <= 0) {
  2721. return -1;
  2722. }
  2723. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2724. if (!ctx) {
  2725. return -1;
  2726. }
  2727. if (!ctx->listening_sockets) {
  2728. return -1;
  2729. }
  2730. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2731. ports[cnt].port =
  2732. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2733. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2734. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2735. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2736. /* IPv4 */
  2737. ports[cnt].protocol = 1;
  2738. cnt++;
  2739. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2740. /* IPv6 */
  2741. ports[cnt].protocol = 3;
  2742. cnt++;
  2743. }
  2744. }
  2745. return cnt;
  2746. }
  2747. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2748. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2749. #endif
  2750. static void
  2751. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2752. {
  2753. buf[0] = '\0';
  2754. if (!usa) {
  2755. return;
  2756. }
  2757. if (usa->sa.sa_family == AF_INET) {
  2758. getnameinfo(&usa->sa,
  2759. sizeof(usa->sin),
  2760. buf,
  2761. (unsigned)len,
  2762. NULL,
  2763. 0,
  2764. NI_NUMERICHOST);
  2765. }
  2766. #if defined(USE_IPV6)
  2767. else if (usa->sa.sa_family == AF_INET6) {
  2768. getnameinfo(&usa->sa,
  2769. sizeof(usa->sin6),
  2770. buf,
  2771. (unsigned)len,
  2772. NULL,
  2773. 0,
  2774. NI_NUMERICHOST);
  2775. }
  2776. #endif
  2777. #if defined(USE_X_DOM_SOCKET)
  2778. else if (usa->sa.sa_family == AF_UNIX) {
  2779. /* TODO: Define a remote address for unix domain sockets.
  2780. * This code will always return "localhost", identical to http+tcp:
  2781. getnameinfo(&usa->sa,
  2782. sizeof(usa->sun),
  2783. buf,
  2784. (unsigned)len,
  2785. NULL,
  2786. 0,
  2787. NI_NUMERICHOST);
  2788. */
  2789. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len)
  2790. }
  2791. #endif
  2792. }
  2793. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2794. * included in all responses other than 100, 101, 5xx. */
  2795. static void
  2796. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2797. {
  2798. #if !defined(REENTRANT_TIME)
  2799. struct tm *tm;
  2800. tm = ((t != NULL) ? gmtime(t) : NULL);
  2801. if (tm != NULL) {
  2802. #else
  2803. struct tm _tm;
  2804. struct tm *tm = &_tm;
  2805. if (t != NULL) {
  2806. gmtime_r(t, tm);
  2807. #endif
  2808. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2809. } else {
  2810. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2811. }
  2812. }
  2813. /* difftime for struct timespec. Return value is in seconds. */
  2814. static double
  2815. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2816. {
  2817. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2818. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2819. }
  2820. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2821. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2822. const char *func,
  2823. unsigned line,
  2824. const char *fmt,
  2825. va_list ap);
  2826. #include "external_mg_cry_internal_impl.inl"
  2827. #elif !defined(NO_FILESYSTEMS)
  2828. /* Print error message to the opened error log stream. */
  2829. static void
  2830. mg_cry_internal_impl(const struct mg_connection *conn,
  2831. const char *func,
  2832. unsigned line,
  2833. const char *fmt,
  2834. va_list ap)
  2835. {
  2836. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2837. struct mg_file fi;
  2838. time_t timestamp;
  2839. /* Unused, in the RELEASE build */
  2840. (void)func;
  2841. (void)line;
  2842. #if defined(GCC_DIAGNOSTIC)
  2843. #pragma GCC diagnostic push
  2844. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2845. #endif
  2846. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2847. #if defined(GCC_DIAGNOSTIC)
  2848. #pragma GCC diagnostic pop
  2849. #endif
  2850. buf[sizeof(buf) - 1] = 0;
  2851. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2852. if (!conn) {
  2853. puts(buf);
  2854. return;
  2855. }
  2856. /* Do not lock when getting the callback value, here and below.
  2857. * I suppose this is fine, since function cannot disappear in the
  2858. * same way string option can. */
  2859. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2860. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2861. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2862. if (mg_fopen(conn,
  2863. conn->dom_ctx->config[ERROR_LOG_FILE],
  2864. MG_FOPEN_MODE_APPEND,
  2865. &fi)
  2866. == 0) {
  2867. fi.access.fp = NULL;
  2868. }
  2869. } else {
  2870. fi.access.fp = NULL;
  2871. }
  2872. if (fi.access.fp != NULL) {
  2873. flockfile(fi.access.fp);
  2874. timestamp = time(NULL);
  2875. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2876. fprintf(fi.access.fp,
  2877. "[%010lu] [error] [client %s] ",
  2878. (unsigned long)timestamp,
  2879. src_addr);
  2880. if (conn->request_info.request_method != NULL) {
  2881. fprintf(fi.access.fp,
  2882. "%s %s: ",
  2883. conn->request_info.request_method,
  2884. conn->request_info.request_uri
  2885. ? conn->request_info.request_uri
  2886. : "");
  2887. }
  2888. fprintf(fi.access.fp, "%s", buf);
  2889. fputc('\n', fi.access.fp);
  2890. fflush(fi.access.fp);
  2891. funlockfile(fi.access.fp);
  2892. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2893. * mg_cry here anyway ;-) */
  2894. }
  2895. }
  2896. }
  2897. #else
  2898. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2899. #endif /* Externally provided function */
  2900. /* Construct fake connection structure. Used for logging, if connection
  2901. * is not applicable at the moment of logging. */
  2902. static struct mg_connection *
  2903. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2904. {
  2905. static const struct mg_connection conn_zero = {0};
  2906. *fc = conn_zero;
  2907. fc->phys_ctx = ctx;
  2908. fc->dom_ctx = &(ctx->dd);
  2909. return fc;
  2910. }
  2911. static void
  2912. mg_cry_internal_wrap(const struct mg_connection *conn,
  2913. struct mg_context *ctx,
  2914. const char *func,
  2915. unsigned line,
  2916. const char *fmt,
  2917. ...)
  2918. {
  2919. va_list ap;
  2920. va_start(ap, fmt);
  2921. if (!conn && ctx) {
  2922. struct mg_connection fc;
  2923. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2924. } else {
  2925. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2926. }
  2927. va_end(ap);
  2928. }
  2929. CIVETWEB_API void
  2930. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2931. {
  2932. va_list ap;
  2933. va_start(ap, fmt);
  2934. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2935. va_end(ap);
  2936. }
  2937. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2938. CIVETWEB_API const char *
  2939. mg_version(void)
  2940. {
  2941. return CIVETWEB_VERSION;
  2942. }
  2943. CIVETWEB_API const struct mg_request_info *
  2944. mg_get_request_info(const struct mg_connection *conn)
  2945. {
  2946. if (!conn) {
  2947. return NULL;
  2948. }
  2949. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2950. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2951. char txt[16];
  2952. struct mg_workerTLS *tls =
  2953. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2954. sprintf(txt, "%03i", conn->response_info.status_code);
  2955. if (strlen(txt) == 3) {
  2956. memcpy(tls->txtbuf, txt, 4);
  2957. } else {
  2958. strcpy(tls->txtbuf, "ERR");
  2959. }
  2960. ((struct mg_connection *)conn)->request_info.local_uri =
  2961. tls->txtbuf; /* use thread safe buffer */
  2962. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2963. tls->txtbuf; /* use the same thread safe buffer */
  2964. ((struct mg_connection *)conn)->request_info.request_uri =
  2965. tls->txtbuf; /* use the same thread safe buffer */
  2966. ((struct mg_connection *)conn)->request_info.num_headers =
  2967. conn->response_info.num_headers;
  2968. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2969. conn->response_info.http_headers,
  2970. sizeof(conn->response_info.http_headers));
  2971. } else
  2972. #endif
  2973. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2974. return NULL;
  2975. }
  2976. return &conn->request_info;
  2977. }
  2978. CIVETWEB_API const struct mg_response_info *
  2979. mg_get_response_info(const struct mg_connection *conn)
  2980. {
  2981. if (!conn) {
  2982. return NULL;
  2983. }
  2984. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2985. return NULL;
  2986. }
  2987. return &conn->response_info;
  2988. }
  2989. static const char *
  2990. get_proto_name(const struct mg_connection *conn)
  2991. {
  2992. #if defined(__clang__)
  2993. #pragma clang diagnostic push
  2994. #pragma clang diagnostic ignored "-Wunreachable-code"
  2995. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2996. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2997. * unreachable, but splitting into four different #ifdef clauses here is
  2998. * more complicated.
  2999. */
  3000. #endif
  3001. const struct mg_request_info *ri = &conn->request_info;
  3002. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3003. ? (ri->is_ssl ? "wss" : "ws")
  3004. : (ri->is_ssl ? "https" : "http"));
  3005. return proto;
  3006. #if defined(__clang__)
  3007. #pragma clang diagnostic pop
  3008. #endif
  3009. }
  3010. static int
  3011. mg_construct_local_link(const struct mg_connection *conn,
  3012. char *buf,
  3013. size_t buflen,
  3014. const char *define_proto,
  3015. int define_port,
  3016. const char *define_uri)
  3017. {
  3018. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3019. return -1;
  3020. } else {
  3021. int i, j;
  3022. int truncated = 0;
  3023. const struct mg_request_info *ri = &conn->request_info;
  3024. const char *proto =
  3025. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3026. const char *uri =
  3027. (define_uri != NULL)
  3028. ? define_uri
  3029. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3030. int port = (define_port > 0) ? define_port : ri->server_port;
  3031. int default_port = 80;
  3032. char *uri_encoded;
  3033. size_t uri_encoded_len;
  3034. if (uri == NULL) {
  3035. return -1;
  3036. }
  3037. uri_encoded_len = strlen(uri) * 3 + 1;
  3038. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3039. if (uri_encoded == NULL) {
  3040. return -1;
  3041. }
  3042. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3043. /* Directory separator should be preserved. */
  3044. for (i = j = 0; uri_encoded[i]; j++) {
  3045. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3046. uri_encoded[j] = '/';
  3047. i += 3;
  3048. } else {
  3049. uri_encoded[j] = uri_encoded[i++];
  3050. }
  3051. }
  3052. uri_encoded[j] = '\0';
  3053. #if defined(USE_X_DOM_SOCKET)
  3054. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3055. /* TODO: Define and document a link for UNIX domain sockets. */
  3056. /* There seems to be no official standard for this.
  3057. * Common uses seem to be "httpunix://", "http.unix://" or
  3058. * "http+unix://" as a protocol definition string, followed by
  3059. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3060. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3061. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3062. * "" (completely skipping the server name part). In any case, the
  3063. * last part is the server local path. */
  3064. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3065. mg_snprintf(conn,
  3066. &truncated,
  3067. buf,
  3068. buflen,
  3069. "%s.unix://%s%s",
  3070. proto,
  3071. server_name,
  3072. ri->local_uri);
  3073. default_port = 0;
  3074. mg_free(uri_encoded);
  3075. return 0;
  3076. }
  3077. #endif
  3078. if (define_proto) {
  3079. /* If we got a protocol name, use the default port accordingly. */
  3080. if ((0 == strcmp(define_proto, "https"))
  3081. || (0 == strcmp(define_proto, "wss"))) {
  3082. default_port = 443;
  3083. }
  3084. } else if (ri->is_ssl) {
  3085. /* If we did not get a protocol name, use TLS as default if it is
  3086. * already used. */
  3087. default_port = 443;
  3088. }
  3089. {
  3090. #if defined(USE_IPV6)
  3091. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3092. #endif
  3093. int auth_domain_check_enabled =
  3094. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3095. && (!mg_strcasecmp(
  3096. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3097. const char *server_domain =
  3098. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3099. char portstr[16];
  3100. char server_ip[48];
  3101. if (port != default_port) {
  3102. sprintf(portstr, ":%u", (unsigned)port);
  3103. } else {
  3104. portstr[0] = 0;
  3105. }
  3106. if (!auth_domain_check_enabled || !server_domain) {
  3107. sockaddr_to_string(server_ip,
  3108. sizeof(server_ip),
  3109. &conn->client.lsa);
  3110. server_domain = server_ip;
  3111. }
  3112. mg_snprintf(conn,
  3113. &truncated,
  3114. buf,
  3115. buflen,
  3116. #if defined(USE_IPV6)
  3117. "%s://%s%s%s%s%s",
  3118. proto,
  3119. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3120. server_domain,
  3121. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3122. #else
  3123. "%s://%s%s%s",
  3124. proto,
  3125. server_domain,
  3126. #endif
  3127. portstr,
  3128. uri_encoded);
  3129. mg_free(uri_encoded);
  3130. if (truncated) {
  3131. return -1;
  3132. }
  3133. return 0;
  3134. }
  3135. }
  3136. }
  3137. CIVETWEB_API int
  3138. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3139. {
  3140. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3141. }
  3142. /* Skip the characters until one of the delimiters characters found.
  3143. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3144. * Advance pointer to buffer to the next word. Return found 0-terminated
  3145. * word.
  3146. * Delimiters can be quoted with quotechar. */
  3147. static char *
  3148. skip_quoted(char **buf,
  3149. const char *delimiters,
  3150. const char *whitespace,
  3151. char quotechar)
  3152. {
  3153. char *p, *begin_word, *end_word, *end_whitespace;
  3154. begin_word = *buf;
  3155. end_word = begin_word + strcspn(begin_word, delimiters);
  3156. /* Check for quotechar */
  3157. if (end_word > begin_word) {
  3158. p = end_word - 1;
  3159. while (*p == quotechar) {
  3160. /* While the delimiter is quoted, look for the next delimiter. */
  3161. /* This happens, e.g., in calls from parse_auth_header,
  3162. * if the user name contains a " character. */
  3163. /* If there is anything beyond end_word, copy it. */
  3164. if (*end_word != '\0') {
  3165. size_t end_off = strcspn(end_word + 1, delimiters);
  3166. memmove(p, end_word, end_off + 1);
  3167. p += end_off; /* p must correspond to end_word - 1 */
  3168. end_word += end_off + 1;
  3169. } else {
  3170. *p = '\0';
  3171. break;
  3172. }
  3173. }
  3174. for (p++; p < end_word; p++) {
  3175. *p = '\0';
  3176. }
  3177. }
  3178. if (*end_word == '\0') {
  3179. *buf = end_word;
  3180. } else {
  3181. #if defined(GCC_DIAGNOSTIC)
  3182. /* Disable spurious conversion warning for GCC */
  3183. #pragma GCC diagnostic push
  3184. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3185. #endif /* defined(GCC_DIAGNOSTIC) */
  3186. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3187. #if defined(GCC_DIAGNOSTIC)
  3188. #pragma GCC diagnostic pop
  3189. #endif /* defined(GCC_DIAGNOSTIC) */
  3190. for (p = end_word; p < end_whitespace; p++) {
  3191. *p = '\0';
  3192. }
  3193. *buf = end_whitespace;
  3194. }
  3195. return begin_word;
  3196. }
  3197. /* Return HTTP header value, or NULL if not found. */
  3198. static const char *
  3199. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3200. {
  3201. int i;
  3202. for (i = 0; i < num_hdr; i++) {
  3203. if (!mg_strcasecmp(name, hdr[i].name)) {
  3204. return hdr[i].value;
  3205. }
  3206. }
  3207. return NULL;
  3208. }
  3209. /* Retrieve requested HTTP header multiple values, and return the number of
  3210. * found occurrences */
  3211. static int
  3212. get_req_headers(const struct mg_request_info *ri,
  3213. const char *name,
  3214. const char **output,
  3215. int output_max_size)
  3216. {
  3217. int i;
  3218. int cnt = 0;
  3219. if (ri) {
  3220. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3221. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3222. output[cnt++] = ri->http_headers[i].value;
  3223. }
  3224. }
  3225. }
  3226. return cnt;
  3227. }
  3228. CIVETWEB_API const char *
  3229. mg_get_header(const struct mg_connection *conn, const char *name)
  3230. {
  3231. if (!conn) {
  3232. return NULL;
  3233. }
  3234. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3235. return get_header(conn->request_info.http_headers,
  3236. conn->request_info.num_headers,
  3237. name);
  3238. }
  3239. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3240. return get_header(conn->response_info.http_headers,
  3241. conn->response_info.num_headers,
  3242. name);
  3243. }
  3244. return NULL;
  3245. }
  3246. static const char *
  3247. get_http_version(const struct mg_connection *conn)
  3248. {
  3249. if (!conn) {
  3250. return NULL;
  3251. }
  3252. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3253. return conn->request_info.http_version;
  3254. }
  3255. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3256. return conn->response_info.http_version;
  3257. }
  3258. return NULL;
  3259. }
  3260. /* A helper function for traversing a comma separated list of values.
  3261. * It returns a list pointer shifted to the next value, or NULL if the end
  3262. * of the list found.
  3263. * Value is stored in val vector. If value has form "x=y", then eq_val
  3264. * vector is initialized to point to the "y" part, and val vector length
  3265. * is adjusted to point only to "x". */
  3266. static const char *
  3267. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3268. {
  3269. int end;
  3270. reparse:
  3271. if (val == NULL || list == NULL || *list == '\0') {
  3272. /* End of the list */
  3273. return NULL;
  3274. }
  3275. /* Skip over leading LWS */
  3276. while (*list == ' ' || *list == '\t')
  3277. list++;
  3278. val->ptr = list;
  3279. if ((list = strchr(val->ptr, ',')) != NULL) {
  3280. /* Comma found. Store length and shift the list ptr */
  3281. val->len = ((size_t)(list - val->ptr));
  3282. list++;
  3283. } else {
  3284. /* This value is the last one */
  3285. list = val->ptr + strlen(val->ptr);
  3286. val->len = ((size_t)(list - val->ptr));
  3287. }
  3288. /* Adjust length for trailing LWS */
  3289. end = (int)val->len - 1;
  3290. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3291. end--;
  3292. val->len = (size_t)(end) + (size_t)(1);
  3293. if (val->len == 0) {
  3294. /* Ignore any empty entries. */
  3295. goto reparse;
  3296. }
  3297. if (eq_val != NULL) {
  3298. /* Value has form "x=y", adjust pointers and lengths
  3299. * so that val points to "x", and eq_val points to "y". */
  3300. eq_val->len = 0;
  3301. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3302. if (eq_val->ptr != NULL) {
  3303. eq_val->ptr++; /* Skip over '=' character */
  3304. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3305. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3306. }
  3307. }
  3308. return list;
  3309. }
  3310. /* A helper function for checking if a comma separated list of values
  3311. * contains
  3312. * the given option (case insensitvely).
  3313. * 'header' can be NULL, in which case false is returned. */
  3314. static int
  3315. header_has_option(const char *header, const char *option)
  3316. {
  3317. struct vec opt_vec;
  3318. struct vec eq_vec;
  3319. DEBUG_ASSERT(option != NULL);
  3320. DEBUG_ASSERT(option[0] != '\0');
  3321. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3322. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3323. return 1;
  3324. }
  3325. return 0;
  3326. }
  3327. /* Sorting function implemented in a separate file */
  3328. #include "sort.inl"
  3329. /* Pattern matching has been reimplemented in a new file */
  3330. #include "match.inl"
  3331. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3332. * This function must tolerate situations when connection info is not
  3333. * set up, for example if request parsing failed. */
  3334. static int
  3335. should_keep_alive(const struct mg_connection *conn)
  3336. {
  3337. const char *http_version;
  3338. const char *header;
  3339. /* First satisfy needs of the server */
  3340. if ((conn == NULL) || conn->must_close) {
  3341. /* Close, if civetweb framework needs to close */
  3342. return 0;
  3343. }
  3344. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3345. /* Close, if keep alive is not enabled */
  3346. return 0;
  3347. }
  3348. /* Check explicit wish of the client */
  3349. header = mg_get_header(conn, "Connection");
  3350. if (header) {
  3351. /* If there is a connection header from the client, obey */
  3352. if (header_has_option(header, "keep-alive")) {
  3353. return 1;
  3354. }
  3355. return 0;
  3356. }
  3357. /* Use default of the standard */
  3358. http_version = get_http_version(conn);
  3359. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3360. /* HTTP 1.1 default is keep alive */
  3361. return 1;
  3362. }
  3363. /* HTTP 1.0 (and earlier) default is to close the connection */
  3364. return 0;
  3365. }
  3366. static int
  3367. should_decode_url(const struct mg_connection *conn)
  3368. {
  3369. if (!conn || !conn->dom_ctx) {
  3370. return 0;
  3371. }
  3372. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3373. }
  3374. static int
  3375. should_decode_query_string(const struct mg_connection *conn)
  3376. {
  3377. if (!conn || !conn->dom_ctx) {
  3378. return 0;
  3379. }
  3380. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3381. == 0);
  3382. }
  3383. static const char *
  3384. suggest_connection_header(const struct mg_connection *conn)
  3385. {
  3386. return should_keep_alive(conn) ? "keep-alive" : "close";
  3387. }
  3388. #include "response.inl"
  3389. static void
  3390. send_no_cache_header(struct mg_connection *conn)
  3391. {
  3392. /* Send all current and obsolete cache opt-out directives. */
  3393. mg_response_header_add(conn,
  3394. "Cache-Control",
  3395. "no-cache, no-store, "
  3396. "must-revalidate, private, max-age=0",
  3397. -1);
  3398. mg_response_header_add(conn, "Expires", "0", -1);
  3399. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3400. /* Obsolete, but still send it for HTTP/1.0 */
  3401. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3402. }
  3403. }
  3404. static void
  3405. send_static_cache_header(struct mg_connection *conn)
  3406. {
  3407. #if !defined(NO_CACHING)
  3408. int max_age;
  3409. char val[64];
  3410. const char *cache_control =
  3411. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3412. /* If there is a full cache-control option configured,0 use it */
  3413. if (cache_control != NULL) {
  3414. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3415. return;
  3416. }
  3417. /* Read the server config to check how long a file may be cached.
  3418. * The configuration is in seconds. */
  3419. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3420. if (max_age <= 0) {
  3421. /* 0 means "do not cache". All values <0 are reserved
  3422. * and may be used differently in the future. */
  3423. /* If a file should not be cached, do not only send
  3424. * max-age=0, but also pragmas and Expires headers. */
  3425. send_no_cache_header(conn);
  3426. return;
  3427. }
  3428. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3429. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3430. /* See also https://www.mnot.net/cache_docs/ */
  3431. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3432. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3433. * leap
  3434. * year to 31622400 seconds. For the moment, we just send whatever has
  3435. * been configured, still the behavior for >1 year should be considered
  3436. * as undefined. */
  3437. mg_snprintf(
  3438. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3439. mg_response_header_add(conn, "Cache-Control", val, -1);
  3440. #else /* NO_CACHING */
  3441. send_no_cache_header(conn);
  3442. #endif /* !NO_CACHING */
  3443. }
  3444. static void
  3445. send_additional_header(struct mg_connection *conn)
  3446. {
  3447. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3448. #if !defined(NO_SSL)
  3449. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3450. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3451. if (max_age >= 0) {
  3452. char val[64];
  3453. mg_snprintf(conn,
  3454. NULL,
  3455. val,
  3456. sizeof(val),
  3457. "max-age=%lu",
  3458. (unsigned long)max_age);
  3459. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3460. }
  3461. }
  3462. #endif
  3463. if (header && header[0]) {
  3464. mg_response_header_add_lines(conn, header);
  3465. }
  3466. }
  3467. static void
  3468. send_cors_header(struct mg_connection *conn)
  3469. {
  3470. const char *origin_hdr = mg_get_header(conn, "Origin");
  3471. const char *cors_orig_cfg =
  3472. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3473. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3474. /* Cross-origin resource sharing (CORS), see
  3475. * http://www.html5rocks.com/en/tutorials/cors/,
  3476. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3477. * CORS preflight is not supported for files. */
  3478. mg_response_header_add(conn,
  3479. "Access-Control-Allow-Origin",
  3480. cors_orig_cfg,
  3481. -1);
  3482. }
  3483. }
  3484. #if !defined(NO_FILESYSTEMS)
  3485. static void handle_file_based_request(struct mg_connection *conn,
  3486. const char *path,
  3487. struct mg_file *filep);
  3488. #endif /* NO_FILESYSTEMS */
  3489. CIVETWEB_API const char *
  3490. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3491. {
  3492. /* See IANA HTTP status code assignment:
  3493. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3494. */
  3495. switch (response_code) {
  3496. /* RFC2616 Section 10.1 - Informational 1xx */
  3497. case 100:
  3498. return "Continue"; /* RFC2616 Section 10.1.1 */
  3499. case 101:
  3500. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3501. case 102:
  3502. return "Processing"; /* RFC2518 Section 10.1 */
  3503. /* RFC2616 Section 10.2 - Successful 2xx */
  3504. case 200:
  3505. return "OK"; /* RFC2616 Section 10.2.1 */
  3506. case 201:
  3507. return "Created"; /* RFC2616 Section 10.2.2 */
  3508. case 202:
  3509. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3510. case 203:
  3511. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3512. case 204:
  3513. return "No Content"; /* RFC2616 Section 10.2.5 */
  3514. case 205:
  3515. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3516. case 206:
  3517. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3518. case 207:
  3519. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3520. */
  3521. case 208:
  3522. return "Already Reported"; /* RFC5842 Section 7.1 */
  3523. case 226:
  3524. return "IM used"; /* RFC3229 Section 10.4.1 */
  3525. /* RFC2616 Section 10.3 - Redirection 3xx */
  3526. case 300:
  3527. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3528. case 301:
  3529. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3530. case 302:
  3531. return "Found"; /* RFC2616 Section 10.3.3 */
  3532. case 303:
  3533. return "See Other"; /* RFC2616 Section 10.3.4 */
  3534. case 304:
  3535. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3536. case 305:
  3537. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3538. case 307:
  3539. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3540. case 308:
  3541. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3542. /* RFC2616 Section 10.4 - Client Error 4xx */
  3543. case 400:
  3544. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3545. case 401:
  3546. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3547. case 402:
  3548. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3549. case 403:
  3550. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3551. case 404:
  3552. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3553. case 405:
  3554. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3555. case 406:
  3556. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3557. case 407:
  3558. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3559. case 408:
  3560. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3561. case 409:
  3562. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3563. case 410:
  3564. return "Gone"; /* RFC2616 Section 10.4.11 */
  3565. case 411:
  3566. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3567. case 412:
  3568. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3569. case 413:
  3570. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3571. case 414:
  3572. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3573. case 415:
  3574. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3575. case 416:
  3576. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3577. */
  3578. case 417:
  3579. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3580. case 421:
  3581. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3582. case 422:
  3583. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3584. * Section 11.2 */
  3585. case 423:
  3586. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3587. case 424:
  3588. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3589. * Section 11.4 */
  3590. case 426:
  3591. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3592. case 428:
  3593. return "Precondition Required"; /* RFC 6585, Section 3 */
  3594. case 429:
  3595. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3596. case 431:
  3597. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3598. case 451:
  3599. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3600. * Section 3 */
  3601. /* RFC2616 Section 10.5 - Server Error 5xx */
  3602. case 500:
  3603. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3604. case 501:
  3605. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3606. case 502:
  3607. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3608. case 503:
  3609. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3610. case 504:
  3611. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3612. case 505:
  3613. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3614. case 506:
  3615. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3616. case 507:
  3617. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3618. * Section 11.5 */
  3619. case 508:
  3620. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3621. case 510:
  3622. return "Not Extended"; /* RFC 2774, Section 7 */
  3623. case 511:
  3624. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3625. /* Other status codes, not shown in the IANA HTTP status code
  3626. * assignment.
  3627. * E.g., "de facto" standards due to common use, ... */
  3628. case 418:
  3629. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3630. case 419:
  3631. return "Authentication Timeout"; /* common use */
  3632. case 420:
  3633. return "Enhance Your Calm"; /* common use */
  3634. case 440:
  3635. return "Login Timeout"; /* common use */
  3636. case 509:
  3637. return "Bandwidth Limit Exceeded"; /* common use */
  3638. default:
  3639. /* This error code is unknown. This should not happen. */
  3640. if (conn) {
  3641. mg_cry_internal(conn,
  3642. "Unknown HTTP response code: %u",
  3643. response_code);
  3644. }
  3645. /* Return at least a category according to RFC 2616 Section 10. */
  3646. if (response_code >= 100 && response_code < 200) {
  3647. /* Unknown informational status code */
  3648. return "Information";
  3649. }
  3650. if (response_code >= 200 && response_code < 300) {
  3651. /* Unknown success code */
  3652. return "Success";
  3653. }
  3654. if (response_code >= 300 && response_code < 400) {
  3655. /* Unknown redirection code */
  3656. return "Redirection";
  3657. }
  3658. if (response_code >= 400 && response_code < 500) {
  3659. /* Unknown request error code */
  3660. return "Client Error";
  3661. }
  3662. if (response_code >= 500 && response_code < 600) {
  3663. /* Unknown server error code */
  3664. return "Server Error";
  3665. }
  3666. /* Response code not even within reasonable range */
  3667. return "";
  3668. }
  3669. }
  3670. static int
  3671. mg_send_http_error_impl(struct mg_connection *conn,
  3672. int status,
  3673. const char *fmt,
  3674. va_list args)
  3675. {
  3676. char errmsg_buf[MG_BUF_LEN];
  3677. va_list ap;
  3678. int has_body;
  3679. #if !defined(NO_FILESYSTEMS)
  3680. char path_buf[UTF8_PATH_MAX];
  3681. int len, i, page_handler_found, scope, truncated;
  3682. const char *error_handler = NULL;
  3683. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3684. const char *error_page_file_ext, *tstr;
  3685. #endif /* NO_FILESYSTEMS */
  3686. int handled_by_callback = 0;
  3687. if ((conn == NULL) || (fmt == NULL)) {
  3688. return -2;
  3689. }
  3690. /* Set status (for log) */
  3691. conn->status_code = status;
  3692. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3693. has_body = ((status > 199) && (status != 204) && (status != 304));
  3694. /* Prepare message in buf, if required */
  3695. if (has_body
  3696. || (!conn->in_error_handler
  3697. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3698. /* Store error message in errmsg_buf */
  3699. va_copy(ap, args);
  3700. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3701. va_end(ap);
  3702. /* In a debug build, print all html errors */
  3703. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3704. }
  3705. /* If there is a http_error callback, call it.
  3706. * But don't do it recursively, if callback calls mg_send_http_error again.
  3707. */
  3708. if (!conn->in_error_handler
  3709. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3710. /* Mark in_error_handler to avoid recursion and call user callback. */
  3711. conn->in_error_handler = 1;
  3712. handled_by_callback =
  3713. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3714. == 0);
  3715. conn->in_error_handler = 0;
  3716. }
  3717. if (!handled_by_callback) {
  3718. /* Check for recursion */
  3719. if (conn->in_error_handler) {
  3720. DEBUG_TRACE(
  3721. "Recursion when handling error %u - fall back to default",
  3722. status);
  3723. #if !defined(NO_FILESYSTEMS)
  3724. } else {
  3725. /* Send user defined error pages, if defined */
  3726. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3727. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3728. page_handler_found = 0;
  3729. if (error_handler != NULL) {
  3730. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3731. switch (scope) {
  3732. case 1: /* Handler for specific error, e.g. 404 error */
  3733. mg_snprintf(conn,
  3734. &truncated,
  3735. path_buf,
  3736. sizeof(path_buf) - 32,
  3737. "%serror%03u.",
  3738. error_handler,
  3739. status);
  3740. break;
  3741. case 2: /* Handler for error group, e.g., 5xx error
  3742. * handler
  3743. * for all server errors (500-599) */
  3744. mg_snprintf(conn,
  3745. &truncated,
  3746. path_buf,
  3747. sizeof(path_buf) - 32,
  3748. "%serror%01uxx.",
  3749. error_handler,
  3750. status / 100);
  3751. break;
  3752. default: /* Handler for all errors */
  3753. mg_snprintf(conn,
  3754. &truncated,
  3755. path_buf,
  3756. sizeof(path_buf) - 32,
  3757. "%serror.",
  3758. error_handler);
  3759. break;
  3760. }
  3761. /* String truncation in buf may only occur if
  3762. * error_handler is too long. This string is
  3763. * from the config, not from a client. */
  3764. (void)truncated;
  3765. /* The following code is redundant, but it should avoid
  3766. * false positives in static source code analyzers and
  3767. * vulnerability scanners.
  3768. */
  3769. path_buf[sizeof(path_buf) - 32] = 0;
  3770. len = (int)strlen(path_buf);
  3771. if (len > (int)sizeof(path_buf) - 32) {
  3772. len = (int)sizeof(path_buf) - 32;
  3773. }
  3774. /* Start with the file extension from the configuration. */
  3775. tstr = strchr(error_page_file_ext, '.');
  3776. while (tstr) {
  3777. for (i = 1;
  3778. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3779. i++) {
  3780. /* buffer overrun is not possible here, since
  3781. * (i < 32) && (len < sizeof(path_buf) - 32)
  3782. * ==> (i + len) < sizeof(path_buf) */
  3783. path_buf[len + i - 1] = tstr[i];
  3784. }
  3785. /* buffer overrun is not possible here, since
  3786. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3787. * ==> (i + len) <= sizeof(path_buf) */
  3788. path_buf[len + i - 1] = 0;
  3789. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3790. DEBUG_TRACE("Check error page %s - found",
  3791. path_buf);
  3792. page_handler_found = 1;
  3793. break;
  3794. }
  3795. DEBUG_TRACE("Check error page %s - not found",
  3796. path_buf);
  3797. /* Continue with the next file extension from the
  3798. * configuration (if there is a next one). */
  3799. tstr = strchr(tstr + i, '.');
  3800. }
  3801. }
  3802. }
  3803. if (page_handler_found) {
  3804. conn->in_error_handler = 1;
  3805. handle_file_based_request(conn, path_buf, &error_page_file);
  3806. conn->in_error_handler = 0;
  3807. return 0;
  3808. }
  3809. #endif /* NO_FILESYSTEMS */
  3810. }
  3811. /* No custom error page. Send default error page. */
  3812. conn->must_close = 1;
  3813. mg_response_header_start(conn, status);
  3814. send_no_cache_header(conn);
  3815. send_additional_header(conn);
  3816. send_cors_header(conn);
  3817. if (has_body) {
  3818. mg_response_header_add(conn,
  3819. "Content-Type",
  3820. "text/plain; charset=utf-8",
  3821. -1);
  3822. }
  3823. mg_response_header_send(conn);
  3824. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3825. if (has_body) {
  3826. /* For other errors, send a generic error message. */
  3827. const char *status_text = mg_get_response_code_text(conn, status);
  3828. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3829. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3830. } else {
  3831. /* No body allowed. Close the connection. */
  3832. DEBUG_TRACE("Error %i", status);
  3833. }
  3834. }
  3835. return 0;
  3836. }
  3837. CIVETWEB_API int
  3838. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3839. {
  3840. va_list ap;
  3841. int ret;
  3842. va_start(ap, fmt);
  3843. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3844. va_end(ap);
  3845. return ret;
  3846. }
  3847. CIVETWEB_API int
  3848. mg_send_http_ok(struct mg_connection *conn,
  3849. const char *mime_type,
  3850. long long content_length)
  3851. {
  3852. if ((mime_type == NULL) || (*mime_type == 0)) {
  3853. /* No content type defined: default to text/html */
  3854. mime_type = "text/html";
  3855. }
  3856. mg_response_header_start(conn, 200);
  3857. send_no_cache_header(conn);
  3858. send_additional_header(conn);
  3859. send_cors_header(conn);
  3860. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3861. if (content_length < 0) {
  3862. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3863. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3864. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3865. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3866. }
  3867. } else {
  3868. char len[32];
  3869. int trunc = 0;
  3870. mg_snprintf(conn,
  3871. &trunc,
  3872. len,
  3873. sizeof(len),
  3874. "%" UINT64_FMT,
  3875. (uint64_t)content_length);
  3876. if (!trunc) {
  3877. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3878. * !trunc is always true */
  3879. mg_response_header_add(conn, "Content-Length", len, -1);
  3880. }
  3881. }
  3882. mg_response_header_send(conn);
  3883. return 0;
  3884. }
  3885. CIVETWEB_API int
  3886. mg_send_http_redirect(struct mg_connection *conn,
  3887. const char *target_url,
  3888. int redirect_code)
  3889. {
  3890. /* Send a 30x redirect response.
  3891. *
  3892. * Redirect types (status codes):
  3893. *
  3894. * Status | Perm/Temp | Method | Version
  3895. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3896. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3897. * 303 | temporary | always use GET | HTTP/1.1
  3898. * 307 | temporary | always keep method | HTTP/1.1
  3899. * 308 | permanent | always keep method | HTTP/1.1
  3900. */
  3901. #if defined(MG_SEND_REDIRECT_BODY)
  3902. char redirect_body[MG_BUF_LEN];
  3903. size_t content_len = 0;
  3904. char content_len_text[32];
  3905. #endif
  3906. /* In case redirect_code=0, use 307. */
  3907. if (redirect_code == 0) {
  3908. redirect_code = 307;
  3909. }
  3910. /* In case redirect_code is none of the above, return error. */
  3911. if ((redirect_code != 301) && (redirect_code != 302)
  3912. && (redirect_code != 303) && (redirect_code != 307)
  3913. && (redirect_code != 308)) {
  3914. /* Parameter error */
  3915. return -2;
  3916. }
  3917. /* If target_url is not defined, redirect to "/". */
  3918. if ((target_url == NULL) || (*target_url == 0)) {
  3919. target_url = "/";
  3920. }
  3921. #if defined(MG_SEND_REDIRECT_BODY)
  3922. /* TODO: condition name? */
  3923. /* Prepare a response body with a hyperlink.
  3924. *
  3925. * According to RFC2616 (and RFC1945 before):
  3926. * Unless the request method was HEAD, the entity of the
  3927. * response SHOULD contain a short hypertext note with a hyperlink to
  3928. * the new URI(s).
  3929. *
  3930. * However, this response body is not useful in M2M communication.
  3931. * Probably the original reason in the RFC was, clients not supporting
  3932. * a 30x HTTP redirect could still show the HTML page and let the user
  3933. * press the link. Since current browsers support 30x HTTP, the additional
  3934. * HTML body does not seem to make sense anymore.
  3935. *
  3936. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3937. * but it only notes:
  3938. * The server's response payload usually contains a short
  3939. * hypertext note with a hyperlink to the new URI(s).
  3940. *
  3941. * Deactivated by default. If you need the 30x body, set the define.
  3942. */
  3943. mg_snprintf(
  3944. conn,
  3945. NULL /* ignore truncation */,
  3946. redirect_body,
  3947. sizeof(redirect_body),
  3948. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3949. redirect_text,
  3950. target_url,
  3951. target_url);
  3952. content_len = strlen(reply);
  3953. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  3954. #endif
  3955. /* Send all required headers */
  3956. mg_response_header_start(conn, redirect_code);
  3957. mg_response_header_add(conn, "Location", target_url, -1);
  3958. if ((redirect_code == 301) || (redirect_code == 308)) {
  3959. /* Permanent redirect */
  3960. send_static_cache_header(conn);
  3961. } else {
  3962. /* Temporary redirect */
  3963. send_no_cache_header(conn);
  3964. }
  3965. send_additional_header(conn);
  3966. send_cors_header(conn);
  3967. #if defined(MG_SEND_REDIRECT_BODY)
  3968. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  3969. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  3970. #else
  3971. mg_response_header_add(conn, "Content-Length", "0", 1);
  3972. #endif
  3973. mg_response_header_send(conn);
  3974. #if defined(MG_SEND_REDIRECT_BODY)
  3975. /* Send response body */
  3976. /* ... unless it is a HEAD request */
  3977. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  3978. ret = mg_write(conn, redirect_body, content_len);
  3979. }
  3980. #endif
  3981. return 1;
  3982. }
  3983. #if defined(_WIN32)
  3984. /* Create substitutes for POSIX functions in Win32. */
  3985. #if defined(GCC_DIAGNOSTIC)
  3986. /* Show no warning in case system functions are not used. */
  3987. #pragma GCC diagnostic push
  3988. #pragma GCC diagnostic ignored "-Wunused-function"
  3989. #endif
  3990. static int
  3991. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3992. {
  3993. (void)unused;
  3994. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  3995. InitializeCriticalSection(&mutex->sec);
  3996. return 0;
  3997. }
  3998. static int
  3999. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4000. {
  4001. DeleteCriticalSection(&mutex->sec);
  4002. return 0;
  4003. }
  4004. static int
  4005. pthread_mutex_lock(pthread_mutex_t *mutex)
  4006. {
  4007. EnterCriticalSection(&mutex->sec);
  4008. return 0;
  4009. }
  4010. static int
  4011. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4012. {
  4013. LeaveCriticalSection(&mutex->sec);
  4014. return 0;
  4015. }
  4016. FUNCTION_MAY_BE_UNUSED
  4017. static int
  4018. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4019. {
  4020. (void)unused;
  4021. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4022. cv->waiting_thread = NULL;
  4023. return 0;
  4024. }
  4025. FUNCTION_MAY_BE_UNUSED
  4026. static int
  4027. pthread_cond_timedwait(pthread_cond_t *cv,
  4028. pthread_mutex_t *mutex,
  4029. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4030. {
  4031. struct mg_workerTLS **ptls,
  4032. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4033. int ok;
  4034. uint64_t nsnow, nswaitabs;
  4035. int64_t nswaitrel;
  4036. DWORD mswaitrel;
  4037. pthread_mutex_lock(&cv->threadIdSec);
  4038. /* Add this thread to cv's waiting list */
  4039. ptls = &cv->waiting_thread;
  4040. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4041. ;
  4042. tls->next_waiting_thread = NULL;
  4043. *ptls = tls;
  4044. pthread_mutex_unlock(&cv->threadIdSec);
  4045. if (abstime) {
  4046. nsnow = mg_get_current_time_ns();
  4047. nswaitabs =
  4048. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4049. nswaitrel = nswaitabs - nsnow;
  4050. if (nswaitrel < 0) {
  4051. nswaitrel = 0;
  4052. }
  4053. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4054. } else {
  4055. mswaitrel = (DWORD)INFINITE;
  4056. }
  4057. pthread_mutex_unlock(mutex);
  4058. ok = (WAIT_OBJECT_0
  4059. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4060. if (!ok) {
  4061. ok = 1;
  4062. pthread_mutex_lock(&cv->threadIdSec);
  4063. ptls = &cv->waiting_thread;
  4064. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4065. if (*ptls == tls) {
  4066. *ptls = tls->next_waiting_thread;
  4067. ok = 0;
  4068. break;
  4069. }
  4070. }
  4071. pthread_mutex_unlock(&cv->threadIdSec);
  4072. if (ok) {
  4073. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4074. (DWORD)INFINITE);
  4075. }
  4076. }
  4077. /* This thread has been removed from cv's waiting list */
  4078. pthread_mutex_lock(mutex);
  4079. return ok ? 0 : -1;
  4080. }
  4081. FUNCTION_MAY_BE_UNUSED
  4082. static int
  4083. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4084. {
  4085. return pthread_cond_timedwait(cv, mutex, NULL);
  4086. }
  4087. FUNCTION_MAY_BE_UNUSED
  4088. static int
  4089. pthread_cond_signal(pthread_cond_t *cv)
  4090. {
  4091. HANDLE wkup = NULL;
  4092. BOOL ok = FALSE;
  4093. pthread_mutex_lock(&cv->threadIdSec);
  4094. if (cv->waiting_thread) {
  4095. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4096. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4097. ok = SetEvent(wkup);
  4098. DEBUG_ASSERT(ok);
  4099. }
  4100. pthread_mutex_unlock(&cv->threadIdSec);
  4101. return ok ? 0 : 1;
  4102. }
  4103. FUNCTION_MAY_BE_UNUSED
  4104. static int
  4105. pthread_cond_broadcast(pthread_cond_t *cv)
  4106. {
  4107. pthread_mutex_lock(&cv->threadIdSec);
  4108. while (cv->waiting_thread) {
  4109. pthread_cond_signal(cv);
  4110. }
  4111. pthread_mutex_unlock(&cv->threadIdSec);
  4112. return 0;
  4113. }
  4114. FUNCTION_MAY_BE_UNUSED
  4115. static int
  4116. pthread_cond_destroy(pthread_cond_t *cv)
  4117. {
  4118. pthread_mutex_lock(&cv->threadIdSec);
  4119. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4120. pthread_mutex_unlock(&cv->threadIdSec);
  4121. pthread_mutex_destroy(&cv->threadIdSec);
  4122. return 0;
  4123. }
  4124. #if defined(ALTERNATIVE_QUEUE)
  4125. FUNCTION_MAY_BE_UNUSED
  4126. static void *
  4127. event_create(void)
  4128. {
  4129. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4130. }
  4131. FUNCTION_MAY_BE_UNUSED
  4132. static int
  4133. event_wait(void *eventhdl)
  4134. {
  4135. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4136. return (res == WAIT_OBJECT_0);
  4137. }
  4138. FUNCTION_MAY_BE_UNUSED
  4139. static int
  4140. event_signal(void *eventhdl)
  4141. {
  4142. return (int)SetEvent((HANDLE)eventhdl);
  4143. }
  4144. FUNCTION_MAY_BE_UNUSED
  4145. static void
  4146. event_destroy(void *eventhdl)
  4147. {
  4148. CloseHandle((HANDLE)eventhdl);
  4149. }
  4150. #endif
  4151. #if defined(GCC_DIAGNOSTIC)
  4152. /* Enable unused function warning again */
  4153. #pragma GCC diagnostic pop
  4154. #endif
  4155. /* For Windows, change all slashes to backslashes in path names. */
  4156. static void
  4157. change_slashes_to_backslashes(char *path)
  4158. {
  4159. int i;
  4160. for (i = 0; path[i] != '\0'; i++) {
  4161. if (path[i] == '/') {
  4162. path[i] = '\\';
  4163. }
  4164. /* remove double backslash (check i > 0 to preserve UNC paths,
  4165. * like \\server\file.txt) */
  4166. if ((i > 0) && (path[i] == '\\')) {
  4167. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4168. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4169. }
  4170. }
  4171. }
  4172. }
  4173. static int
  4174. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4175. {
  4176. int diff;
  4177. do {
  4178. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4179. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4180. s1++;
  4181. s2++;
  4182. } while ((diff == 0) && (s1[-1] != L'\0'));
  4183. return diff;
  4184. }
  4185. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4186. * wbuf and wbuf_len is a target buffer and its length. */
  4187. static void
  4188. path_to_unicode(const struct mg_connection *conn,
  4189. const char *path,
  4190. wchar_t *wbuf,
  4191. size_t wbuf_len)
  4192. {
  4193. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4194. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4195. DWORD long_len, err;
  4196. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4197. mg_strlcpy(buf, path, sizeof(buf));
  4198. change_slashes_to_backslashes(buf);
  4199. /* Convert to Unicode and back. If doubly-converted string does not
  4200. * match the original, something is fishy, reject. */
  4201. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4202. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4203. WideCharToMultiByte(
  4204. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4205. if (strcmp(buf, buf2) != 0) {
  4206. wbuf[0] = L'\0';
  4207. }
  4208. /* Windows file systems are not case sensitive, but you can still use
  4209. * uppercase and lowercase letters (on all modern file systems).
  4210. * The server can check if the URI uses the same upper/lowercase
  4211. * letters an the file system, effectively making Windows servers
  4212. * case sensitive (like Linux servers are). It is still not possible
  4213. * to use two files with the same name in different cases on Windows
  4214. * (like /a and /A) - this would be possible in Linux.
  4215. * As a default, Windows is not case sensitive, but the case sensitive
  4216. * file name check can be activated by an additional configuration. */
  4217. if (conn) {
  4218. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4219. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4220. "yes")) {
  4221. /* Use case sensitive compare function */
  4222. fcompare = wcscmp;
  4223. }
  4224. }
  4225. (void)conn; /* conn is currently unused */
  4226. /* Only accept a full file path, not a Windows short (8.3) path. */
  4227. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4228. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4229. if (long_len == 0) {
  4230. err = GetLastError();
  4231. if (err == ERROR_FILE_NOT_FOUND) {
  4232. /* File does not exist. This is not always a problem here. */
  4233. return;
  4234. }
  4235. }
  4236. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4237. /* Short name is used. */
  4238. wbuf[0] = L'\0';
  4239. }
  4240. }
  4241. #if !defined(NO_FILESYSTEMS)
  4242. /* Get file information, return 1 if file exists, 0 if not */
  4243. static int
  4244. mg_stat(const struct mg_connection *conn,
  4245. const char *path,
  4246. struct mg_file_stat *filep)
  4247. {
  4248. wchar_t wbuf[UTF16_PATH_MAX];
  4249. WIN32_FILE_ATTRIBUTE_DATA info;
  4250. time_t creation_time;
  4251. size_t len;
  4252. if (!filep) {
  4253. return 0;
  4254. }
  4255. memset(filep, 0, sizeof(*filep));
  4256. if (mg_path_suspicious(conn, path)) {
  4257. return 0;
  4258. }
  4259. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4260. /* Windows happily opens files with some garbage at the end of file name.
  4261. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4262. * "a.cgi", despite one would expect an error back. */
  4263. len = strlen(path);
  4264. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4265. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4266. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4267. filep->last_modified =
  4268. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4269. info.ftLastWriteTime.dwHighDateTime);
  4270. /* On Windows, the file creation time can be higher than the
  4271. * modification time, e.g. when a file is copied.
  4272. * Since the Last-Modified timestamp is used for caching
  4273. * it should be based on the most recent timestamp. */
  4274. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4275. info.ftCreationTime.dwHighDateTime);
  4276. if (creation_time > filep->last_modified) {
  4277. filep->last_modified = creation_time;
  4278. }
  4279. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4280. return 1;
  4281. }
  4282. return 0;
  4283. }
  4284. #endif
  4285. static int
  4286. mg_remove(const struct mg_connection *conn, const char *path)
  4287. {
  4288. wchar_t wbuf[UTF16_PATH_MAX];
  4289. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4290. return DeleteFileW(wbuf) ? 0 : -1;
  4291. }
  4292. static int
  4293. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4294. {
  4295. wchar_t wbuf[UTF16_PATH_MAX];
  4296. (void)mode;
  4297. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4298. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4299. }
  4300. /* Create substitutes for POSIX functions in Win32. */
  4301. #if defined(GCC_DIAGNOSTIC)
  4302. /* Show no warning in case system functions are not used. */
  4303. #pragma GCC diagnostic push
  4304. #pragma GCC diagnostic ignored "-Wunused-function"
  4305. #endif
  4306. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4307. FUNCTION_MAY_BE_UNUSED
  4308. static DIR *
  4309. mg_opendir(const struct mg_connection *conn, const char *name)
  4310. {
  4311. DIR *dir = NULL;
  4312. wchar_t wpath[UTF16_PATH_MAX];
  4313. DWORD attrs;
  4314. if (name == NULL) {
  4315. SetLastError(ERROR_BAD_ARGUMENTS);
  4316. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4317. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4318. } else {
  4319. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4320. attrs = GetFileAttributesW(wpath);
  4321. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4322. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4323. (void)wcscat(wpath, L"\\*");
  4324. dir->handle = FindFirstFileW(wpath, &dir->info);
  4325. dir->result.d_name[0] = '\0';
  4326. } else {
  4327. mg_free(dir);
  4328. dir = NULL;
  4329. }
  4330. }
  4331. return dir;
  4332. }
  4333. FUNCTION_MAY_BE_UNUSED
  4334. static int
  4335. mg_closedir(DIR *dir)
  4336. {
  4337. int result = 0;
  4338. if (dir != NULL) {
  4339. if (dir->handle != INVALID_HANDLE_VALUE)
  4340. result = FindClose(dir->handle) ? 0 : -1;
  4341. mg_free(dir);
  4342. } else {
  4343. result = -1;
  4344. SetLastError(ERROR_BAD_ARGUMENTS);
  4345. }
  4346. return result;
  4347. }
  4348. FUNCTION_MAY_BE_UNUSED
  4349. static struct dirent *
  4350. mg_readdir(DIR *dir)
  4351. {
  4352. struct dirent *result = 0;
  4353. if (dir) {
  4354. if (dir->handle != INVALID_HANDLE_VALUE) {
  4355. result = &dir->result;
  4356. (void)WideCharToMultiByte(CP_UTF8,
  4357. 0,
  4358. dir->info.cFileName,
  4359. -1,
  4360. result->d_name,
  4361. sizeof(result->d_name),
  4362. NULL,
  4363. NULL);
  4364. if (!FindNextFileW(dir->handle, &dir->info)) {
  4365. (void)FindClose(dir->handle);
  4366. dir->handle = INVALID_HANDLE_VALUE;
  4367. }
  4368. } else {
  4369. SetLastError(ERROR_FILE_NOT_FOUND);
  4370. }
  4371. } else {
  4372. SetLastError(ERROR_BAD_ARGUMENTS);
  4373. }
  4374. return result;
  4375. }
  4376. #if !defined(HAVE_POLL)
  4377. #undef POLLIN
  4378. #undef POLLPRI
  4379. #undef POLLOUT
  4380. #undef POLLERR
  4381. #define POLLIN (1) /* Data ready - read will not block. */
  4382. #define POLLPRI (2) /* Priority data ready. */
  4383. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4384. #define POLLERR (8) /* Error event */
  4385. FUNCTION_MAY_BE_UNUSED
  4386. static int
  4387. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4388. {
  4389. struct timeval tv;
  4390. fd_set rset;
  4391. fd_set wset;
  4392. fd_set eset;
  4393. unsigned int i;
  4394. int result;
  4395. SOCKET maxfd = 0;
  4396. memset(&tv, 0, sizeof(tv));
  4397. tv.tv_sec = milliseconds / 1000;
  4398. tv.tv_usec = (milliseconds % 1000) * 1000;
  4399. FD_ZERO(&rset);
  4400. FD_ZERO(&wset);
  4401. FD_ZERO(&eset);
  4402. for (i = 0; i < n; i++) {
  4403. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4404. if (pfd[i].events & POLLIN) {
  4405. FD_SET(pfd[i].fd, &rset);
  4406. }
  4407. if (pfd[i].events & POLLOUT) {
  4408. FD_SET(pfd[i].fd, &wset);
  4409. }
  4410. /* Check for errors for any FD in the set */
  4411. FD_SET(pfd[i].fd, &eset);
  4412. }
  4413. pfd[i].revents = 0;
  4414. if (pfd[i].fd > maxfd) {
  4415. maxfd = pfd[i].fd;
  4416. }
  4417. }
  4418. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4419. for (i = 0; i < n; i++) {
  4420. if (FD_ISSET(pfd[i].fd, &rset)) {
  4421. pfd[i].revents |= POLLIN;
  4422. }
  4423. if (FD_ISSET(pfd[i].fd, &wset)) {
  4424. pfd[i].revents |= POLLOUT;
  4425. }
  4426. if (FD_ISSET(pfd[i].fd, &eset)) {
  4427. pfd[i].revents |= POLLERR;
  4428. }
  4429. }
  4430. }
  4431. /* We should subtract the time used in select from remaining
  4432. * "milliseconds", in particular if called from mg_poll with a
  4433. * timeout quantum.
  4434. * Unfortunately, the remaining time is not stored in "tv" in all
  4435. * implementations, so the result in "tv" must be considered undefined.
  4436. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4437. return result;
  4438. }
  4439. #endif /* HAVE_POLL */
  4440. #if defined(GCC_DIAGNOSTIC)
  4441. /* Enable unused function warning again */
  4442. #pragma GCC diagnostic pop
  4443. #endif
  4444. static void
  4445. set_close_on_exec(SOCKET sock,
  4446. const struct mg_connection *conn /* may be null */,
  4447. struct mg_context *ctx /* may be null */)
  4448. {
  4449. (void)conn; /* Unused. */
  4450. (void)ctx;
  4451. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4452. }
  4453. CIVETWEB_API int
  4454. mg_start_thread(mg_thread_func_t f, void *p)
  4455. {
  4456. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4457. /* Compile-time option to control stack size, e.g.
  4458. * -DUSE_STACK_SIZE=16384
  4459. */
  4460. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4461. == ((uintptr_t)(-1L)))
  4462. ? -1
  4463. : 0);
  4464. #else
  4465. return (
  4466. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4467. ? -1
  4468. : 0);
  4469. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4470. }
  4471. /* Start a thread storing the thread context. */
  4472. static int
  4473. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4474. void *p,
  4475. pthread_t *threadidptr)
  4476. {
  4477. uintptr_t uip;
  4478. HANDLE threadhandle;
  4479. int result = -1;
  4480. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4481. threadhandle = (HANDLE)uip;
  4482. if ((uip != 0) && (threadidptr != NULL)) {
  4483. *threadidptr = threadhandle;
  4484. result = 0;
  4485. }
  4486. return result;
  4487. }
  4488. /* Wait for a thread to finish. */
  4489. static int
  4490. mg_join_thread(pthread_t threadid)
  4491. {
  4492. int result;
  4493. DWORD dwevent;
  4494. result = -1;
  4495. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4496. if (dwevent == WAIT_FAILED) {
  4497. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4498. } else {
  4499. if (dwevent == WAIT_OBJECT_0) {
  4500. CloseHandle(threadid);
  4501. result = 0;
  4502. }
  4503. }
  4504. return result;
  4505. }
  4506. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4507. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4508. /* Create substitutes for POSIX functions in Win32. */
  4509. #if defined(GCC_DIAGNOSTIC)
  4510. /* Show no warning in case system functions are not used. */
  4511. #pragma GCC diagnostic push
  4512. #pragma GCC diagnostic ignored "-Wunused-function"
  4513. #endif
  4514. FUNCTION_MAY_BE_UNUSED
  4515. static HANDLE
  4516. dlopen(const char *dll_name, int flags)
  4517. {
  4518. wchar_t wbuf[UTF16_PATH_MAX];
  4519. (void)flags;
  4520. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4521. return LoadLibraryW(wbuf);
  4522. }
  4523. FUNCTION_MAY_BE_UNUSED
  4524. static int
  4525. dlclose(void *handle)
  4526. {
  4527. int result;
  4528. if (FreeLibrary((HMODULE)handle) != 0) {
  4529. result = 0;
  4530. } else {
  4531. result = -1;
  4532. }
  4533. return result;
  4534. }
  4535. #if defined(GCC_DIAGNOSTIC)
  4536. /* Enable unused function warning again */
  4537. #pragma GCC diagnostic pop
  4538. #endif
  4539. #endif
  4540. #if !defined(NO_CGI)
  4541. #define SIGKILL (0)
  4542. static int
  4543. kill(pid_t pid, int sig_num)
  4544. {
  4545. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4546. (void)CloseHandle((HANDLE)pid);
  4547. return 0;
  4548. }
  4549. #if !defined(WNOHANG)
  4550. #define WNOHANG (1)
  4551. #endif
  4552. static pid_t
  4553. waitpid(pid_t pid, int *status, int flags)
  4554. {
  4555. DWORD timeout = INFINITE;
  4556. DWORD waitres;
  4557. (void)status; /* Currently not used by any client here */
  4558. if ((flags | WNOHANG) == WNOHANG) {
  4559. timeout = 0;
  4560. }
  4561. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4562. if (waitres == WAIT_OBJECT_0) {
  4563. return pid;
  4564. }
  4565. if (waitres == WAIT_TIMEOUT) {
  4566. return 0;
  4567. }
  4568. return (pid_t)-1;
  4569. }
  4570. static void
  4571. trim_trailing_whitespaces(char *s)
  4572. {
  4573. char *e = s + strlen(s);
  4574. while ((e > s) && isspace((unsigned char)e[-1])) {
  4575. *(--e) = '\0';
  4576. }
  4577. }
  4578. static pid_t
  4579. spawn_process(struct mg_connection *conn,
  4580. const char *prog,
  4581. char *envblk,
  4582. char *envp[],
  4583. int fdin[2],
  4584. int fdout[2],
  4585. int fderr[2],
  4586. const char *dir,
  4587. unsigned char cgi_config_idx)
  4588. {
  4589. HANDLE me;
  4590. char *interp;
  4591. char *interp_arg = 0;
  4592. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4593. int truncated;
  4594. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4595. STARTUPINFOA si;
  4596. PROCESS_INFORMATION pi = {0};
  4597. (void)envp;
  4598. memset(&si, 0, sizeof(si));
  4599. si.cb = sizeof(si);
  4600. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4601. si.wShowWindow = SW_HIDE;
  4602. me = GetCurrentProcess();
  4603. DuplicateHandle(me,
  4604. (HANDLE)_get_osfhandle(fdin[0]),
  4605. me,
  4606. &si.hStdInput,
  4607. 0,
  4608. TRUE,
  4609. DUPLICATE_SAME_ACCESS);
  4610. DuplicateHandle(me,
  4611. (HANDLE)_get_osfhandle(fdout[1]),
  4612. me,
  4613. &si.hStdOutput,
  4614. 0,
  4615. TRUE,
  4616. DUPLICATE_SAME_ACCESS);
  4617. DuplicateHandle(me,
  4618. (HANDLE)_get_osfhandle(fderr[1]),
  4619. me,
  4620. &si.hStdError,
  4621. 0,
  4622. TRUE,
  4623. DUPLICATE_SAME_ACCESS);
  4624. /* Mark handles that should not be inherited. See
  4625. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4626. */
  4627. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4628. HANDLE_FLAG_INHERIT,
  4629. 0);
  4630. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4631. HANDLE_FLAG_INHERIT,
  4632. 0);
  4633. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4634. HANDLE_FLAG_INHERIT,
  4635. 0);
  4636. /* First check, if there is a CGI interpreter configured for all CGI
  4637. * scripts. */
  4638. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4639. if (interp != NULL) {
  4640. /* If there is a configured interpreter, check for additional arguments
  4641. */
  4642. interp_arg =
  4643. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4644. } else {
  4645. /* Otherwise, the interpreter must be stated in the first line of the
  4646. * CGI script file, after a #! (shebang) mark. */
  4647. buf[0] = buf[1] = '\0';
  4648. /* Get the full script path */
  4649. mg_snprintf(
  4650. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4651. if (truncated) {
  4652. pi.hProcess = (pid_t)-1;
  4653. goto spawn_cleanup;
  4654. }
  4655. /* Open the script file, to read the first line */
  4656. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4657. /* Read the first line of the script into the buffer */
  4658. mg_fgets(buf, sizeof(buf), &file);
  4659. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4660. buf[sizeof(buf) - 1] = '\0';
  4661. }
  4662. if ((buf[0] == '#') && (buf[1] == '!')) {
  4663. trim_trailing_whitespaces(buf + 2);
  4664. } else {
  4665. buf[2] = '\0';
  4666. }
  4667. interp = buf + 2;
  4668. }
  4669. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4670. if (interp[0] != '\0') {
  4671. /* This is an interpreted script file. We must call the interpreter. */
  4672. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4673. mg_snprintf(conn,
  4674. &truncated,
  4675. cmdline,
  4676. sizeof(cmdline),
  4677. "\"%s\" %s \"%s\\%s\"",
  4678. interp,
  4679. interp_arg,
  4680. full_dir,
  4681. prog);
  4682. } else {
  4683. mg_snprintf(conn,
  4684. &truncated,
  4685. cmdline,
  4686. sizeof(cmdline),
  4687. "\"%s\" \"%s\\%s\"",
  4688. interp,
  4689. full_dir,
  4690. prog);
  4691. }
  4692. } else {
  4693. /* This is (probably) a compiled program. We call it directly. */
  4694. mg_snprintf(conn,
  4695. &truncated,
  4696. cmdline,
  4697. sizeof(cmdline),
  4698. "\"%s\\%s\"",
  4699. full_dir,
  4700. prog);
  4701. }
  4702. if (truncated) {
  4703. pi.hProcess = (pid_t)-1;
  4704. goto spawn_cleanup;
  4705. }
  4706. DEBUG_TRACE("Running [%s]", cmdline);
  4707. if (CreateProcessA(NULL,
  4708. cmdline,
  4709. NULL,
  4710. NULL,
  4711. TRUE,
  4712. CREATE_NEW_PROCESS_GROUP,
  4713. envblk,
  4714. NULL,
  4715. &si,
  4716. &pi)
  4717. == 0) {
  4718. mg_cry_internal(
  4719. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4720. pi.hProcess = (pid_t)-1;
  4721. /* goto spawn_cleanup; */
  4722. }
  4723. spawn_cleanup:
  4724. (void)CloseHandle(si.hStdOutput);
  4725. (void)CloseHandle(si.hStdError);
  4726. (void)CloseHandle(si.hStdInput);
  4727. if (pi.hThread != NULL) {
  4728. (void)CloseHandle(pi.hThread);
  4729. }
  4730. return (pid_t)pi.hProcess;
  4731. }
  4732. #endif /* !NO_CGI */
  4733. static int
  4734. set_blocking_mode(SOCKET sock)
  4735. {
  4736. unsigned long non_blocking = 0;
  4737. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4738. }
  4739. static int
  4740. set_non_blocking_mode(SOCKET sock)
  4741. {
  4742. unsigned long non_blocking = 1;
  4743. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4744. }
  4745. #else
  4746. #if !defined(NO_FILESYSTEMS)
  4747. static int
  4748. mg_stat(const struct mg_connection *conn,
  4749. const char *path,
  4750. struct mg_file_stat *filep)
  4751. {
  4752. struct stat st;
  4753. if (!filep) {
  4754. return 0;
  4755. }
  4756. memset(filep, 0, sizeof(*filep));
  4757. if (mg_path_suspicious(conn, path)) {
  4758. return 0;
  4759. }
  4760. if (0 == stat(path, &st)) {
  4761. filep->size = (uint64_t)(st.st_size);
  4762. filep->last_modified = st.st_mtime;
  4763. filep->is_directory = S_ISDIR(st.st_mode);
  4764. return 1;
  4765. }
  4766. return 0;
  4767. }
  4768. #endif /* NO_FILESYSTEMS */
  4769. static void
  4770. set_close_on_exec(int fd,
  4771. const struct mg_connection *conn /* may be null */,
  4772. struct mg_context *ctx /* may be null */)
  4773. {
  4774. #if defined(__ZEPHYR__)
  4775. (void)fd;
  4776. (void)conn;
  4777. (void)ctx;
  4778. #else
  4779. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4780. if (conn || ctx) {
  4781. struct mg_connection fc;
  4782. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4783. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4784. __func__,
  4785. strerror(ERRNO));
  4786. }
  4787. }
  4788. #endif
  4789. }
  4790. CIVETWEB_API int
  4791. mg_start_thread(mg_thread_func_t func, void *param)
  4792. {
  4793. pthread_t thread_id;
  4794. pthread_attr_t attr;
  4795. int result;
  4796. (void)pthread_attr_init(&attr);
  4797. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4798. #if defined(__ZEPHYR__)
  4799. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4800. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4801. /* Compile-time option to control stack size,
  4802. * e.g. -DUSE_STACK_SIZE=16384 */
  4803. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4804. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4805. result = pthread_create(&thread_id, &attr, func, param);
  4806. pthread_attr_destroy(&attr);
  4807. return result;
  4808. }
  4809. /* Start a thread storing the thread context. */
  4810. static int
  4811. mg_start_thread_with_id(mg_thread_func_t func,
  4812. void *param,
  4813. pthread_t *threadidptr)
  4814. {
  4815. pthread_t thread_id;
  4816. pthread_attr_t attr;
  4817. int result;
  4818. (void)pthread_attr_init(&attr);
  4819. #if defined(__ZEPHYR__)
  4820. pthread_attr_setstack(&attr,
  4821. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4822. ZEPHYR_STACK_SIZE);
  4823. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4824. /* Compile-time option to control stack size,
  4825. * e.g. -DUSE_STACK_SIZE=16384 */
  4826. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4827. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4828. result = pthread_create(&thread_id, &attr, func, param);
  4829. pthread_attr_destroy(&attr);
  4830. if ((result == 0) && (threadidptr != NULL)) {
  4831. *threadidptr = thread_id;
  4832. }
  4833. return result;
  4834. }
  4835. /* Wait for a thread to finish. */
  4836. static int
  4837. mg_join_thread(pthread_t threadid)
  4838. {
  4839. int result;
  4840. result = pthread_join(threadid, NULL);
  4841. return result;
  4842. }
  4843. #if !defined(NO_CGI)
  4844. static pid_t
  4845. spawn_process(struct mg_connection *conn,
  4846. const char *prog,
  4847. char *envblk,
  4848. char *envp[],
  4849. int fdin[2],
  4850. int fdout[2],
  4851. int fderr[2],
  4852. const char *dir,
  4853. unsigned char cgi_config_idx)
  4854. {
  4855. pid_t pid;
  4856. const char *interp;
  4857. (void)envblk;
  4858. if ((pid = fork()) == -1) {
  4859. /* Parent */
  4860. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4861. } else if (pid != 0) {
  4862. /* Make sure children close parent-side descriptors.
  4863. * The caller will close the child-side immediately. */
  4864. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4865. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4866. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4867. } else {
  4868. /* Child */
  4869. if (chdir(dir) != 0) {
  4870. mg_cry_internal(
  4871. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4872. } else if (dup2(fdin[0], 0) == -1) {
  4873. mg_cry_internal(conn,
  4874. "%s: dup2(%d, 0): %s",
  4875. __func__,
  4876. fdin[0],
  4877. strerror(ERRNO));
  4878. } else if (dup2(fdout[1], 1) == -1) {
  4879. mg_cry_internal(conn,
  4880. "%s: dup2(%d, 1): %s",
  4881. __func__,
  4882. fdout[1],
  4883. strerror(ERRNO));
  4884. } else if (dup2(fderr[1], 2) == -1) {
  4885. mg_cry_internal(conn,
  4886. "%s: dup2(%d, 2): %s",
  4887. __func__,
  4888. fderr[1],
  4889. strerror(ERRNO));
  4890. } else {
  4891. struct sigaction sa;
  4892. /* Keep stderr and stdout in two different pipes.
  4893. * Stdout will be sent back to the client,
  4894. * stderr should go into a server error log. */
  4895. (void)close(fdin[0]);
  4896. (void)close(fdout[1]);
  4897. (void)close(fderr[1]);
  4898. /* Close write end fdin and read end fdout and fderr */
  4899. (void)close(fdin[1]);
  4900. (void)close(fdout[0]);
  4901. (void)close(fderr[0]);
  4902. /* After exec, all signal handlers are restored to their default
  4903. * values, with one exception of SIGCHLD. According to
  4904. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4905. * will leave unchanged after exec if it was set to be ignored.
  4906. * Restore it to default action. */
  4907. memset(&sa, 0, sizeof(sa));
  4908. sa.sa_handler = SIG_DFL;
  4909. sigaction(SIGCHLD, &sa, NULL);
  4910. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4911. if (interp == NULL) {
  4912. /* no interpreter configured, call the program directly */
  4913. (void)execle(prog, prog, NULL, envp);
  4914. mg_cry_internal(conn,
  4915. "%s: execle(%s): %s",
  4916. __func__,
  4917. prog,
  4918. strerror(ERRNO));
  4919. } else {
  4920. /* call the configured interpreter */
  4921. const char *interp_args =
  4922. conn->dom_ctx
  4923. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4924. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4925. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4926. } else {
  4927. (void)execle(interp, interp, prog, NULL, envp);
  4928. }
  4929. mg_cry_internal(conn,
  4930. "%s: execle(%s %s): %s",
  4931. __func__,
  4932. interp,
  4933. prog,
  4934. strerror(ERRNO));
  4935. }
  4936. }
  4937. exit(EXIT_FAILURE);
  4938. }
  4939. return pid;
  4940. }
  4941. #endif /* !NO_CGI */
  4942. static int
  4943. set_non_blocking_mode(SOCKET sock)
  4944. {
  4945. int flags = fcntl(sock, F_GETFL, 0);
  4946. if (flags < 0) {
  4947. return -1;
  4948. }
  4949. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4950. return -1;
  4951. }
  4952. return 0;
  4953. }
  4954. static int
  4955. set_blocking_mode(SOCKET sock)
  4956. {
  4957. int flags = fcntl(sock, F_GETFL, 0);
  4958. if (flags < 0) {
  4959. return -1;
  4960. }
  4961. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4962. return -1;
  4963. }
  4964. return 0;
  4965. }
  4966. #endif /* _WIN32 / else */
  4967. /* End of initial operating system specific define block. */
  4968. /* Get a random number (independent of C rand function) */
  4969. static uint64_t
  4970. get_random(void)
  4971. {
  4972. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4973. static uint64_t lcg = 0; /* Linear congruential generator */
  4974. uint64_t now = mg_get_current_time_ns();
  4975. if (lfsr == 0) {
  4976. /* lfsr will be only 0 if has not been initialized,
  4977. * so this code is called only once. */
  4978. lfsr = mg_get_current_time_ns();
  4979. lcg = mg_get_current_time_ns();
  4980. } else {
  4981. /* Get the next step of both random number generators. */
  4982. lfsr = (lfsr >> 1)
  4983. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4984. << 63);
  4985. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4986. }
  4987. /* Combining two pseudo-random number generators and a high resolution
  4988. * part
  4989. * of the current server time will make it hard (impossible?) to guess
  4990. * the
  4991. * next number. */
  4992. return (lfsr ^ lcg ^ now);
  4993. }
  4994. static int
  4995. mg_poll(struct mg_pollfd *pfd,
  4996. unsigned int n,
  4997. int milliseconds,
  4998. const stop_flag_t *stop_flag)
  4999. {
  5000. /* Call poll, but only for a maximum time of a few seconds.
  5001. * This will allow to stop the server after some seconds, instead
  5002. * of having to wait for a long socket timeout. */
  5003. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5004. int check_pollerr = 0;
  5005. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5006. /* If we wait for only one file descriptor, wait on error as well */
  5007. pfd[0].events |= POLLERR;
  5008. check_pollerr = 1;
  5009. }
  5010. do {
  5011. int result;
  5012. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5013. /* Shut down signal */
  5014. return -2;
  5015. }
  5016. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5017. ms_now = milliseconds;
  5018. }
  5019. result = poll(pfd, n, ms_now);
  5020. if (result != 0) {
  5021. /* Poll returned either success (1) or error (-1).
  5022. * Forward both to the caller. */
  5023. if ((check_pollerr)
  5024. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5025. == POLLERR)) {
  5026. /* One and only file descriptor returned error */
  5027. return -1;
  5028. }
  5029. return result;
  5030. }
  5031. /* Poll returned timeout (0). */
  5032. if (milliseconds > 0) {
  5033. milliseconds -= ms_now;
  5034. }
  5035. } while (milliseconds > 0);
  5036. /* timeout: return 0 */
  5037. return 0;
  5038. }
  5039. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5040. * descriptor.
  5041. * Return value:
  5042. * >=0 .. number of bytes successfully written
  5043. * -1 .. timeout
  5044. * -2 .. error
  5045. */
  5046. static int
  5047. push_inner(struct mg_context *ctx,
  5048. FILE *fp,
  5049. SOCKET sock,
  5050. SSL *ssl,
  5051. const char *buf,
  5052. int len,
  5053. double timeout)
  5054. {
  5055. uint64_t start = 0, now = 0, timeout_ns = 0;
  5056. int n, err;
  5057. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5058. #if defined(_WIN32)
  5059. typedef int len_t;
  5060. #else
  5061. typedef size_t len_t;
  5062. #endif
  5063. if (timeout > 0) {
  5064. now = mg_get_current_time_ns();
  5065. start = now;
  5066. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5067. }
  5068. if (ctx == NULL) {
  5069. return -2;
  5070. }
  5071. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5072. if (ssl) {
  5073. return -2;
  5074. }
  5075. #endif
  5076. /* Try to read until it succeeds, fails, times out, or the server
  5077. * shuts down. */
  5078. for (;;) {
  5079. #if defined(USE_MBEDTLS)
  5080. if (ssl != NULL) {
  5081. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5082. if (n <= 0) {
  5083. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5084. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5085. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5086. n = 0;
  5087. } else {
  5088. fprintf(stderr, "SSL write failed, error %d\n", n);
  5089. return -2;
  5090. }
  5091. } else {
  5092. err = 0;
  5093. }
  5094. } else
  5095. #elif !defined(NO_SSL)
  5096. if (ssl != NULL) {
  5097. ERR_clear_error();
  5098. n = SSL_write(ssl, buf, len);
  5099. if (n <= 0) {
  5100. err = SSL_get_error(ssl, n);
  5101. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5102. err = ERRNO;
  5103. } else if ((err == SSL_ERROR_WANT_READ)
  5104. || (err == SSL_ERROR_WANT_WRITE)) {
  5105. n = 0;
  5106. } else {
  5107. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5108. ERR_clear_error();
  5109. return -2;
  5110. }
  5111. ERR_clear_error();
  5112. } else {
  5113. err = 0;
  5114. }
  5115. } else
  5116. #endif
  5117. if (fp != NULL) {
  5118. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5119. if (ferror(fp)) {
  5120. n = -1;
  5121. err = ERRNO;
  5122. } else {
  5123. err = 0;
  5124. }
  5125. } else {
  5126. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5127. err = (n < 0) ? ERRNO : 0;
  5128. #if defined(_WIN32)
  5129. if (err == WSAEWOULDBLOCK) {
  5130. err = 0;
  5131. n = 0;
  5132. }
  5133. #else
  5134. if (ERROR_TRY_AGAIN(err)) {
  5135. err = 0;
  5136. n = 0;
  5137. }
  5138. #endif
  5139. if (n < 0) {
  5140. /* shutdown of the socket at client side */
  5141. return -2;
  5142. }
  5143. }
  5144. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5145. return -2;
  5146. }
  5147. if ((n > 0) || ((n == 0) && (len == 0))) {
  5148. /* some data has been read, or no data was requested */
  5149. return n;
  5150. }
  5151. if (n < 0) {
  5152. /* socket error - check errno */
  5153. DEBUG_TRACE("send() failed, error %d", err);
  5154. /* TODO (mid): error handling depending on the error code.
  5155. * These codes are different between Windows and Linux.
  5156. * Currently there is no problem with failing send calls,
  5157. * if there is a reproducible situation, it should be
  5158. * investigated in detail.
  5159. */
  5160. return -2;
  5161. }
  5162. /* Only in case n=0 (timeout), repeat calling the write function */
  5163. /* If send failed, wait before retry */
  5164. if (fp != NULL) {
  5165. /* For files, just wait a fixed time.
  5166. * Maybe it helps, maybe not. */
  5167. mg_sleep(5);
  5168. } else {
  5169. /* For sockets, wait for the socket using poll */
  5170. struct mg_pollfd pfd[1];
  5171. int pollres;
  5172. pfd[0].fd = sock;
  5173. pfd[0].events = POLLOUT;
  5174. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5175. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5176. return -2;
  5177. }
  5178. if (pollres > 0) {
  5179. continue;
  5180. }
  5181. }
  5182. if (timeout > 0) {
  5183. now = mg_get_current_time_ns();
  5184. if ((now - start) > timeout_ns) {
  5185. /* Timeout */
  5186. break;
  5187. }
  5188. }
  5189. }
  5190. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5191. used */
  5192. return -1;
  5193. }
  5194. static int
  5195. push_all(struct mg_context *ctx,
  5196. FILE *fp,
  5197. SOCKET sock,
  5198. SSL *ssl,
  5199. const char *buf,
  5200. int len)
  5201. {
  5202. double timeout = -1.0;
  5203. int n, nwritten = 0;
  5204. if (ctx == NULL) {
  5205. return -1;
  5206. }
  5207. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5208. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5209. }
  5210. if (timeout <= 0.0) {
  5211. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5212. / 1000.0;
  5213. }
  5214. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5215. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5216. if (n < 0) {
  5217. if (nwritten == 0) {
  5218. nwritten = -1; /* Propagate the error */
  5219. }
  5220. break;
  5221. } else if (n == 0) {
  5222. break; /* No more data to write */
  5223. } else {
  5224. nwritten += n;
  5225. len -= n;
  5226. }
  5227. }
  5228. return nwritten;
  5229. }
  5230. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5231. * Return value:
  5232. * >=0 .. number of bytes successfully read
  5233. * -1 .. timeout
  5234. * -2 .. error
  5235. */
  5236. static int
  5237. pull_inner(FILE *fp,
  5238. struct mg_connection *conn,
  5239. char *buf,
  5240. int len,
  5241. double timeout)
  5242. {
  5243. int nread, err = 0;
  5244. #if defined(_WIN32)
  5245. typedef int len_t;
  5246. #else
  5247. typedef size_t len_t;
  5248. #endif
  5249. /* We need an additional wait loop around this, because in some cases
  5250. * with TLSwe may get data from the socket but not from SSL_read.
  5251. * In this case we need to repeat at least once.
  5252. */
  5253. if (fp != NULL) {
  5254. /* Use read() instead of fread(), because if we're reading from the
  5255. * CGI pipe, fread() may block until IO buffer is filled up. We
  5256. * cannot afford to block and must pass all read bytes immediately
  5257. * to the client. */
  5258. nread = (int)read(fileno(fp), buf, (size_t)len);
  5259. err = (nread < 0) ? ERRNO : 0;
  5260. if ((nread == 0) && (len > 0)) {
  5261. /* Should get data, but got EOL */
  5262. return -2;
  5263. }
  5264. #if defined(USE_MBEDTLS)
  5265. } else if (conn->ssl != NULL) {
  5266. struct mg_pollfd pfd[1];
  5267. int to_read;
  5268. int pollres;
  5269. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5270. if (to_read > 0) {
  5271. /* We already know there is no more data buffered in conn->buf
  5272. * but there is more available in the SSL layer. So don't poll
  5273. * conn->client.sock yet. */
  5274. pollres = 1;
  5275. if (to_read > len)
  5276. to_read = len;
  5277. } else {
  5278. pfd[0].fd = conn->client.sock;
  5279. pfd[0].events = POLLIN;
  5280. to_read = len;
  5281. pollres = mg_poll(pfd,
  5282. 1,
  5283. (int)(timeout * 1000.0),
  5284. &(conn->phys_ctx->stop_flag));
  5285. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5286. return -2;
  5287. }
  5288. }
  5289. if (pollres > 0) {
  5290. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5291. if (nread <= 0) {
  5292. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5293. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5294. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5295. nread = 0;
  5296. } else {
  5297. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5298. return -2;
  5299. }
  5300. } else {
  5301. err = 0;
  5302. }
  5303. } else if (pollres < 0) {
  5304. /* Error */
  5305. return -2;
  5306. } else {
  5307. /* pollres = 0 means timeout */
  5308. nread = 0;
  5309. }
  5310. #elif !defined(NO_SSL)
  5311. } else if (conn->ssl != NULL) {
  5312. int ssl_pending;
  5313. struct mg_pollfd pfd[1];
  5314. int pollres;
  5315. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5316. /* We already know there is no more data buffered in conn->buf
  5317. * but there is more available in the SSL layer. So don't poll
  5318. * conn->client.sock yet. */
  5319. if (ssl_pending > len) {
  5320. ssl_pending = len;
  5321. }
  5322. pollres = 1;
  5323. } else {
  5324. pfd[0].fd = conn->client.sock;
  5325. pfd[0].events = POLLIN;
  5326. pollres = mg_poll(pfd,
  5327. 1,
  5328. (int)(timeout * 1000.0),
  5329. &(conn->phys_ctx->stop_flag));
  5330. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5331. return -2;
  5332. }
  5333. }
  5334. if (pollres > 0) {
  5335. ERR_clear_error();
  5336. nread =
  5337. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5338. if (nread <= 0) {
  5339. err = SSL_get_error(conn->ssl, nread);
  5340. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5341. err = ERRNO;
  5342. } else if ((err == SSL_ERROR_WANT_READ)
  5343. || (err == SSL_ERROR_WANT_WRITE)) {
  5344. nread = 0;
  5345. } else {
  5346. /* All errors should return -2 */
  5347. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5348. ERR_clear_error();
  5349. return -2;
  5350. }
  5351. ERR_clear_error();
  5352. } else {
  5353. err = 0;
  5354. }
  5355. } else if (pollres < 0) {
  5356. /* Error */
  5357. return -2;
  5358. } else {
  5359. /* pollres = 0 means timeout */
  5360. nread = 0;
  5361. }
  5362. #endif
  5363. } else {
  5364. struct mg_pollfd pfd[1];
  5365. int pollres;
  5366. pfd[0].fd = conn->client.sock;
  5367. pfd[0].events = POLLIN;
  5368. pollres = mg_poll(pfd,
  5369. 1,
  5370. (int)(timeout * 1000.0),
  5371. &(conn->phys_ctx->stop_flag));
  5372. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5373. return -2;
  5374. }
  5375. if (pollres > 0) {
  5376. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5377. err = (nread < 0) ? ERRNO : 0;
  5378. if (nread <= 0) {
  5379. /* shutdown of the socket at client side */
  5380. return -2;
  5381. }
  5382. } else if (pollres < 0) {
  5383. /* error calling poll */
  5384. return -2;
  5385. } else {
  5386. /* pollres = 0 means timeout */
  5387. nread = 0;
  5388. }
  5389. }
  5390. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5391. return -2;
  5392. }
  5393. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5394. /* some data has been read, or no data was requested */
  5395. return nread;
  5396. }
  5397. if (nread < 0) {
  5398. /* socket error - check errno */
  5399. #if defined(_WIN32)
  5400. if (err == WSAEWOULDBLOCK) {
  5401. /* TODO (low): check if this is still required */
  5402. /* standard case if called from close_socket_gracefully */
  5403. return -2;
  5404. } else if (err == WSAETIMEDOUT) {
  5405. /* TODO (low): check if this is still required */
  5406. /* timeout is handled by the while loop */
  5407. return 0;
  5408. } else if (err == WSAECONNABORTED) {
  5409. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5410. return -2;
  5411. } else {
  5412. DEBUG_TRACE("recv() failed, error %d", err);
  5413. return -2;
  5414. }
  5415. #else
  5416. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5417. * if the timeout is reached and if the socket was set to non-
  5418. * blocking in close_socket_gracefully, so we can not distinguish
  5419. * here. We have to wait for the timeout in both cases for now.
  5420. */
  5421. if (ERROR_TRY_AGAIN(err)) {
  5422. /* TODO (low): check if this is still required */
  5423. /* EAGAIN/EWOULDBLOCK:
  5424. * standard case if called from close_socket_gracefully
  5425. * => should return -1 */
  5426. /* or timeout occurred
  5427. * => the code must stay in the while loop */
  5428. /* EINTR can be generated on a socket with a timeout set even
  5429. * when SA_RESTART is effective for all relevant signals
  5430. * (see signal(7)).
  5431. * => stay in the while loop */
  5432. } else {
  5433. DEBUG_TRACE("recv() failed, error %d", err);
  5434. return -2;
  5435. }
  5436. #endif
  5437. }
  5438. /* Timeout occurred, but no data available. */
  5439. return -1;
  5440. }
  5441. static int
  5442. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5443. {
  5444. int n, nread = 0;
  5445. double timeout = -1.0;
  5446. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5447. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5448. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5449. }
  5450. if (timeout <= 0.0) {
  5451. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5452. / 1000.0;
  5453. }
  5454. start_time = mg_get_current_time_ns();
  5455. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5456. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5457. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5458. if (n == -2) {
  5459. if (nread == 0) {
  5460. nread = -1; /* Propagate the error */
  5461. }
  5462. break;
  5463. } else if (n == -1) {
  5464. /* timeout */
  5465. if (timeout >= 0.0) {
  5466. now = mg_get_current_time_ns();
  5467. if ((now - start_time) <= timeout_ns) {
  5468. continue;
  5469. }
  5470. }
  5471. break;
  5472. } else if (n == 0) {
  5473. break; /* No more data to read */
  5474. } else {
  5475. nread += n;
  5476. len -= n;
  5477. }
  5478. }
  5479. return nread;
  5480. }
  5481. static void
  5482. discard_unread_request_data(struct mg_connection *conn)
  5483. {
  5484. char buf[MG_BUF_LEN];
  5485. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5486. ;
  5487. }
  5488. static int
  5489. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5490. {
  5491. int64_t content_len, n, buffered_len, nread;
  5492. int64_t len64 =
  5493. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5494. * int, we may not read more
  5495. * bytes */
  5496. const char *body;
  5497. if (conn == NULL) {
  5498. return 0;
  5499. }
  5500. /* If Content-Length is not set for a response with body data,
  5501. * we do not know in advance how much data should be read. */
  5502. content_len = conn->content_len;
  5503. if (content_len < 0) {
  5504. /* The body data is completed when the connection is closed. */
  5505. content_len = INT64_MAX;
  5506. }
  5507. nread = 0;
  5508. if (conn->consumed_content < content_len) {
  5509. /* Adjust number of bytes to read. */
  5510. int64_t left_to_read = content_len - conn->consumed_content;
  5511. if (left_to_read < len64) {
  5512. /* Do not read more than the total content length of the
  5513. * request.
  5514. */
  5515. len64 = left_to_read;
  5516. }
  5517. /* Return buffered data */
  5518. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5519. - conn->consumed_content;
  5520. if (buffered_len > 0) {
  5521. if (len64 < buffered_len) {
  5522. buffered_len = len64;
  5523. }
  5524. body = conn->buf + conn->request_len + conn->consumed_content;
  5525. memcpy(buf, body, (size_t)buffered_len);
  5526. len64 -= buffered_len;
  5527. conn->consumed_content += buffered_len;
  5528. nread += buffered_len;
  5529. buf = (char *)buf + buffered_len;
  5530. }
  5531. /* We have returned all buffered data. Read new data from the remote
  5532. * socket.
  5533. */
  5534. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5535. conn->consumed_content += n;
  5536. nread += n;
  5537. } else {
  5538. nread = ((nread > 0) ? nread : n);
  5539. }
  5540. }
  5541. return (int)nread;
  5542. }
  5543. /* Forward declarations */
  5544. static void handle_request(struct mg_connection *);
  5545. static void log_access(const struct mg_connection *);
  5546. /* Handle request, update statistics and call access log */
  5547. static void
  5548. handle_request_stat_log(struct mg_connection *conn)
  5549. {
  5550. #if defined(USE_SERVER_STATS)
  5551. struct timespec tnow;
  5552. conn->conn_state = 4; /* processing */
  5553. #endif
  5554. handle_request(conn);
  5555. #if defined(USE_SERVER_STATS)
  5556. conn->conn_state = 5; /* processed */
  5557. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5558. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5559. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5560. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5561. conn->num_bytes_sent);
  5562. #endif
  5563. DEBUG_TRACE("%s", "handle_request done");
  5564. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5565. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5566. DEBUG_TRACE("%s", "end_request callback done");
  5567. }
  5568. log_access(conn);
  5569. }
  5570. #if defined(USE_HTTP2)
  5571. #if defined(NO_SSL)
  5572. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5573. #endif
  5574. #define USE_ALPN
  5575. #include "http2.inl"
  5576. /* Not supported with HTTP/2 */
  5577. #define HTTP1_only \
  5578. { \
  5579. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5580. http2_must_use_http1(conn); \
  5581. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5582. return; \
  5583. } \
  5584. }
  5585. #else
  5586. #define HTTP1_only
  5587. #endif
  5588. CIVETWEB_API int
  5589. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5590. {
  5591. if (len > INT_MAX) {
  5592. len = INT_MAX;
  5593. }
  5594. if (conn == NULL) {
  5595. return 0;
  5596. }
  5597. if (conn->is_chunked) {
  5598. size_t all_read = 0;
  5599. while (len > 0) {
  5600. if (conn->is_chunked >= 3) {
  5601. /* No more data left to read */
  5602. return 0;
  5603. }
  5604. if (conn->is_chunked != 1) {
  5605. /* Has error */
  5606. return -1;
  5607. }
  5608. if (conn->consumed_content != conn->content_len) {
  5609. /* copy from the current chunk */
  5610. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5611. if (read_ret < 1) {
  5612. /* read error */
  5613. conn->is_chunked = 2;
  5614. return -1;
  5615. }
  5616. all_read += (size_t)read_ret;
  5617. len -= (size_t)read_ret;
  5618. if (conn->consumed_content == conn->content_len) {
  5619. /* Add data bytes in the current chunk have been read,
  5620. * so we are expecting \r\n now. */
  5621. char x[2];
  5622. conn->content_len += 2;
  5623. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5624. || (x[1] != '\n')) {
  5625. /* Protocol violation */
  5626. conn->is_chunked = 2;
  5627. return -1;
  5628. }
  5629. }
  5630. } else {
  5631. /* fetch a new chunk */
  5632. size_t i;
  5633. char lenbuf[64];
  5634. char *end = NULL;
  5635. unsigned long chunkSize = 0;
  5636. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5637. conn->content_len++;
  5638. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5639. lenbuf[i] = 0;
  5640. }
  5641. if ((i > 0) && (lenbuf[i] == '\r')
  5642. && (lenbuf[i - 1] != '\r')) {
  5643. continue;
  5644. }
  5645. if ((i > 1) && (lenbuf[i] == '\n')
  5646. && (lenbuf[i - 1] == '\r')) {
  5647. lenbuf[i + 1] = 0;
  5648. chunkSize = strtoul(lenbuf, &end, 16);
  5649. if (chunkSize == 0) {
  5650. /* regular end of content */
  5651. conn->is_chunked = 3;
  5652. }
  5653. break;
  5654. }
  5655. if (!isxdigit((unsigned char)lenbuf[i])) {
  5656. /* illegal character for chunk length */
  5657. conn->is_chunked = 2;
  5658. return -1;
  5659. }
  5660. }
  5661. if ((end == NULL) || (*end != '\r')) {
  5662. /* chunksize not set correctly */
  5663. conn->is_chunked = 2;
  5664. return -1;
  5665. }
  5666. if (chunkSize == 0) {
  5667. /* try discarding trailer for keep-alive */
  5668. conn->content_len += 2;
  5669. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5670. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5671. conn->is_chunked = 4;
  5672. }
  5673. break;
  5674. }
  5675. /* append a new chunk */
  5676. conn->content_len += (int64_t)chunkSize;
  5677. }
  5678. }
  5679. return (int)all_read;
  5680. }
  5681. return mg_read_inner(conn, buf, len);
  5682. }
  5683. CIVETWEB_API int
  5684. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5685. {
  5686. time_t now;
  5687. int n, total, allowed;
  5688. if (conn == NULL) {
  5689. return 0;
  5690. }
  5691. if (len > INT_MAX) {
  5692. return -1;
  5693. }
  5694. /* Mark connection as "data sent" */
  5695. conn->request_state = 10;
  5696. #if defined(USE_HTTP2)
  5697. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5698. http2_data_frame_head(conn, len, 0);
  5699. }
  5700. #endif
  5701. if (conn->throttle > 0) {
  5702. if ((now = time(NULL)) != conn->last_throttle_time) {
  5703. conn->last_throttle_time = now;
  5704. conn->last_throttle_bytes = 0;
  5705. }
  5706. allowed = conn->throttle - conn->last_throttle_bytes;
  5707. if (allowed > (int)len) {
  5708. allowed = (int)len;
  5709. }
  5710. total = push_all(conn->phys_ctx,
  5711. NULL,
  5712. conn->client.sock,
  5713. conn->ssl,
  5714. (const char *)buf,
  5715. allowed);
  5716. if (total == allowed) {
  5717. buf = (const char *)buf + total;
  5718. conn->last_throttle_bytes += total;
  5719. while ((total < (int)len)
  5720. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5721. allowed = (conn->throttle > ((int)len - total))
  5722. ? (int)len - total
  5723. : conn->throttle;
  5724. n = push_all(conn->phys_ctx,
  5725. NULL,
  5726. conn->client.sock,
  5727. conn->ssl,
  5728. (const char *)buf,
  5729. allowed);
  5730. if (n != allowed) {
  5731. break;
  5732. }
  5733. sleep(1);
  5734. conn->last_throttle_bytes = allowed;
  5735. conn->last_throttle_time = time(NULL);
  5736. buf = (const char *)buf + n;
  5737. total += n;
  5738. }
  5739. }
  5740. } else {
  5741. total = push_all(conn->phys_ctx,
  5742. NULL,
  5743. conn->client.sock,
  5744. conn->ssl,
  5745. (const char *)buf,
  5746. (int)len);
  5747. }
  5748. if (total > 0) {
  5749. conn->num_bytes_sent += total;
  5750. }
  5751. return total;
  5752. }
  5753. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5754. CIVETWEB_API int
  5755. mg_send_chunk(struct mg_connection *conn,
  5756. const char *chunk,
  5757. unsigned int chunk_len)
  5758. {
  5759. char lenbuf[16];
  5760. size_t lenbuf_len;
  5761. int ret;
  5762. int t;
  5763. /* First store the length information in a text buffer. */
  5764. sprintf(lenbuf, "%x\r\n", chunk_len);
  5765. lenbuf_len = strlen(lenbuf);
  5766. /* Then send length information, chunk and terminating \r\n. */
  5767. ret = mg_write(conn, lenbuf, lenbuf_len);
  5768. if (ret != (int)lenbuf_len) {
  5769. return -1;
  5770. }
  5771. t = ret;
  5772. ret = mg_write(conn, chunk, chunk_len);
  5773. if (ret != (int)chunk_len) {
  5774. return -1;
  5775. }
  5776. t += ret;
  5777. ret = mg_write(conn, "\r\n", 2);
  5778. if (ret != 2) {
  5779. return -1;
  5780. }
  5781. t += ret;
  5782. return t;
  5783. }
  5784. #if defined(GCC_DIAGNOSTIC)
  5785. /* This block forwards format strings to printf implementations,
  5786. * so we need to disable the format-nonliteral warning. */
  5787. #pragma GCC diagnostic push
  5788. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5789. #endif
  5790. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5791. static int
  5792. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5793. {
  5794. va_list ap_copy;
  5795. size_t size = MG_BUF_LEN / 4;
  5796. int len = -1;
  5797. *buf = NULL;
  5798. while (len < 0) {
  5799. if (*buf) {
  5800. mg_free(*buf);
  5801. }
  5802. size *= 4;
  5803. *buf = (char *)mg_malloc(size);
  5804. if (!*buf) {
  5805. break;
  5806. }
  5807. va_copy(ap_copy, ap);
  5808. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5809. va_end(ap_copy);
  5810. (*buf)[size - 1] = 0;
  5811. }
  5812. return len;
  5813. }
  5814. /* Print message to buffer. If buffer is large enough to hold the message,
  5815. * return buffer. If buffer is to small, allocate large enough buffer on
  5816. * heap,
  5817. * and return allocated buffer. */
  5818. static int
  5819. alloc_vprintf(char **out_buf,
  5820. char *prealloc_buf,
  5821. size_t prealloc_size,
  5822. const char *fmt,
  5823. va_list ap)
  5824. {
  5825. va_list ap_copy;
  5826. int len;
  5827. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5828. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5829. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5830. * Therefore, we make two passes: on first pass, get required message
  5831. * length.
  5832. * On second pass, actually print the message. */
  5833. va_copy(ap_copy, ap);
  5834. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5835. va_end(ap_copy);
  5836. if (len < 0) {
  5837. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5838. * Switch to alternative code path that uses incremental
  5839. * allocations.
  5840. */
  5841. va_copy(ap_copy, ap);
  5842. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5843. va_end(ap_copy);
  5844. } else if ((size_t)(len) >= prealloc_size) {
  5845. /* The pre-allocated buffer not large enough. */
  5846. /* Allocate a new buffer. */
  5847. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5848. if (!*out_buf) {
  5849. /* Allocation failed. Return -1 as "out of memory" error. */
  5850. return -1;
  5851. }
  5852. /* Buffer allocation successful. Store the string there. */
  5853. va_copy(ap_copy, ap);
  5854. IGNORE_UNUSED_RESULT(
  5855. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5856. va_end(ap_copy);
  5857. } else {
  5858. /* The pre-allocated buffer is large enough.
  5859. * Use it to store the string and return the address. */
  5860. va_copy(ap_copy, ap);
  5861. IGNORE_UNUSED_RESULT(
  5862. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5863. va_end(ap_copy);
  5864. *out_buf = prealloc_buf;
  5865. }
  5866. return len;
  5867. }
  5868. static int
  5869. alloc_printf(char **out_buf, const char *fmt, ...)
  5870. {
  5871. va_list ap;
  5872. int result;
  5873. va_start(ap, fmt);
  5874. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  5875. va_end(ap);
  5876. return result;
  5877. }
  5878. #if defined(GCC_DIAGNOSTIC)
  5879. /* Enable format-nonliteral warning again. */
  5880. #pragma GCC diagnostic pop
  5881. #endif
  5882. static int
  5883. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5884. {
  5885. char mem[MG_BUF_LEN];
  5886. char *buf = NULL;
  5887. int len;
  5888. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5889. len = mg_write(conn, buf, (size_t)len);
  5890. }
  5891. if (buf != mem) {
  5892. mg_free(buf);
  5893. }
  5894. return len;
  5895. }
  5896. CIVETWEB_API int
  5897. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5898. {
  5899. va_list ap;
  5900. int result;
  5901. va_start(ap, fmt);
  5902. result = mg_vprintf(conn, fmt, ap);
  5903. va_end(ap);
  5904. return result;
  5905. }
  5906. CIVETWEB_API int
  5907. mg_url_decode(const char *src,
  5908. int src_len,
  5909. char *dst,
  5910. int dst_len,
  5911. int is_form_url_encoded)
  5912. {
  5913. int i, j, a, b;
  5914. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5915. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5916. if ((i < src_len - 2) && (src[i] == '%')
  5917. && isxdigit((unsigned char)src[i + 1])
  5918. && isxdigit((unsigned char)src[i + 2])) {
  5919. a = tolower((unsigned char)src[i + 1]);
  5920. b = tolower((unsigned char)src[i + 2]);
  5921. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5922. i += 2;
  5923. } else if (is_form_url_encoded && (src[i] == '+')) {
  5924. dst[j] = ' ';
  5925. } else {
  5926. dst[j] = src[i];
  5927. }
  5928. }
  5929. dst[j] = '\0'; /* Null-terminate the destination */
  5930. return (i >= src_len) ? j : -1;
  5931. }
  5932. /* form url decoding of an entire string */
  5933. static void
  5934. url_decode_in_place(char *buf)
  5935. {
  5936. int len = (int)strlen(buf);
  5937. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5938. }
  5939. CIVETWEB_API int
  5940. mg_get_var(const char *data,
  5941. size_t data_len,
  5942. const char *name,
  5943. char *dst,
  5944. size_t dst_len)
  5945. {
  5946. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5947. }
  5948. CIVETWEB_API int
  5949. mg_get_var2(const char *data,
  5950. size_t data_len,
  5951. const char *name,
  5952. char *dst,
  5953. size_t dst_len,
  5954. size_t occurrence)
  5955. {
  5956. const char *p, *e, *s;
  5957. size_t name_len;
  5958. int len;
  5959. if ((dst == NULL) || (dst_len == 0)) {
  5960. len = -2;
  5961. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5962. len = -1;
  5963. dst[0] = '\0';
  5964. } else {
  5965. name_len = strlen(name);
  5966. e = data + data_len;
  5967. len = -1;
  5968. dst[0] = '\0';
  5969. /* data is "var1=val1&var2=val2...". Find variable first */
  5970. for (p = data; p + name_len < e; p++) {
  5971. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5972. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5973. /* Point p to variable value */
  5974. p += name_len + 1;
  5975. /* Point s to the end of the value */
  5976. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5977. if (s == NULL) {
  5978. s = e;
  5979. }
  5980. DEBUG_ASSERT(s >= p);
  5981. if (s < p) {
  5982. return -3;
  5983. }
  5984. /* Decode variable into destination buffer */
  5985. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5986. /* Redirect error code from -1 to -2 (destination buffer too
  5987. * small). */
  5988. if (len == -1) {
  5989. len = -2;
  5990. }
  5991. break;
  5992. }
  5993. }
  5994. }
  5995. return len;
  5996. }
  5997. /* split a string "key1=val1&key2=val2" into key/value pairs */
  5998. CIVETWEB_API int
  5999. mg_split_form_urlencoded(char *data,
  6000. struct mg_header *form_fields,
  6001. unsigned num_form_fields)
  6002. {
  6003. char *b;
  6004. int i;
  6005. int num = 0;
  6006. if (data == NULL) {
  6007. /* parameter error */
  6008. return -1;
  6009. }
  6010. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6011. /* determine the number of expected fields */
  6012. if (data[0] == 0) {
  6013. return 0;
  6014. }
  6015. /* count number of & to return the number of key-value-pairs */
  6016. num = 1;
  6017. while (*data) {
  6018. if (*data == '&') {
  6019. num++;
  6020. }
  6021. data++;
  6022. }
  6023. return num;
  6024. }
  6025. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6026. /* parameter error */
  6027. return -1;
  6028. }
  6029. for (i = 0; i < (int)num_form_fields; i++) {
  6030. /* extract key-value pairs from input data */
  6031. while ((*data == ' ') || (*data == '\t')) {
  6032. /* skip initial spaces */
  6033. data++;
  6034. }
  6035. if (*data == 0) {
  6036. /* end of string reached */
  6037. break;
  6038. }
  6039. form_fields[num].name = data;
  6040. /* find & or = */
  6041. b = data;
  6042. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6043. b++;
  6044. }
  6045. if (*b == 0) {
  6046. /* last key without value */
  6047. form_fields[num].value = NULL;
  6048. } else if (*b == '&') {
  6049. /* mid key without value */
  6050. form_fields[num].value = NULL;
  6051. } else {
  6052. /* terminate string */
  6053. *b = 0;
  6054. /* value starts after '=' */
  6055. data = b + 1;
  6056. form_fields[num].value = data;
  6057. }
  6058. /* new field is stored */
  6059. num++;
  6060. /* find a next key */
  6061. b = strchr(data, '&');
  6062. if (b == 0) {
  6063. /* no more data */
  6064. break;
  6065. } else {
  6066. /* terminate value of last field at '&' */
  6067. *b = 0;
  6068. /* next key-value-pairs starts after '&' */
  6069. data = b + 1;
  6070. }
  6071. }
  6072. /* Decode all values */
  6073. for (i = 0; i < num; i++) {
  6074. if (form_fields[i].name) {
  6075. url_decode_in_place((char *)form_fields[i].name);
  6076. }
  6077. if (form_fields[i].value) {
  6078. url_decode_in_place((char *)form_fields[i].value);
  6079. }
  6080. }
  6081. /* return number of fields found */
  6082. return num;
  6083. }
  6084. /* HCP24: some changes to compare whole var_name */
  6085. CIVETWEB_API int
  6086. mg_get_cookie(const char *cookie_header,
  6087. const char *var_name,
  6088. char *dst,
  6089. size_t dst_size)
  6090. {
  6091. const char *s, *p, *end;
  6092. int name_len, len = -1;
  6093. if ((dst == NULL) || (dst_size == 0)) {
  6094. return -2;
  6095. }
  6096. dst[0] = '\0';
  6097. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6098. return -1;
  6099. }
  6100. name_len = (int)strlen(var_name);
  6101. end = s + strlen(s);
  6102. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6103. if (s[name_len] == '=') {
  6104. /* HCP24: now check is it a substring or a full cookie name */
  6105. if ((s == cookie_header) || (s[-1] == ' ')) {
  6106. s += name_len + 1;
  6107. if ((p = strchr(s, ' ')) == NULL) {
  6108. p = end;
  6109. }
  6110. if (p[-1] == ';') {
  6111. p--;
  6112. }
  6113. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6114. s++;
  6115. p--;
  6116. }
  6117. if ((size_t)(p - s) < dst_size) {
  6118. len = (int)(p - s);
  6119. mg_strlcpy(dst, s, (size_t)len + 1);
  6120. } else {
  6121. len = -3;
  6122. }
  6123. break;
  6124. }
  6125. }
  6126. }
  6127. return len;
  6128. }
  6129. CIVETWEB_API int
  6130. mg_base64_encode(const unsigned char *src,
  6131. size_t src_len,
  6132. char *dst,
  6133. size_t *dst_len)
  6134. {
  6135. static const char *b64 =
  6136. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6137. size_t i, j;
  6138. int a, b, c;
  6139. if (dst_len != NULL) {
  6140. /* Expected length including 0 termination: */
  6141. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6142. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6143. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6144. if (*dst_len < expected_len) {
  6145. if (*dst_len > 0) {
  6146. dst[0] = '\0';
  6147. }
  6148. *dst_len = expected_len;
  6149. return 0;
  6150. }
  6151. }
  6152. for (i = j = 0; i < src_len; i += 3) {
  6153. a = src[i];
  6154. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6155. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6156. dst[j++] = b64[a >> 2];
  6157. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6158. if (i + 1 < src_len) {
  6159. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6160. }
  6161. if (i + 2 < src_len) {
  6162. dst[j++] = b64[c & 63];
  6163. }
  6164. }
  6165. while (j % 4 != 0) {
  6166. dst[j++] = '=';
  6167. }
  6168. dst[j++] = '\0';
  6169. if (dst_len != NULL) {
  6170. *dst_len = (size_t)j;
  6171. }
  6172. /* Return -1 for "OK" */
  6173. return -1;
  6174. }
  6175. static unsigned char
  6176. b64reverse(char letter)
  6177. {
  6178. if ((letter >= 'A') && (letter <= 'Z')) {
  6179. return letter - 'A';
  6180. }
  6181. if ((letter >= 'a') && (letter <= 'z')) {
  6182. return letter - 'a' + 26;
  6183. }
  6184. if ((letter >= '0') && (letter <= '9')) {
  6185. return letter - '0' + 52;
  6186. }
  6187. if (letter == '+') {
  6188. return 62;
  6189. }
  6190. if (letter == '/') {
  6191. return 63;
  6192. }
  6193. if (letter == '=') {
  6194. return 255; /* normal end */
  6195. }
  6196. return 254; /* error */
  6197. }
  6198. CIVETWEB_API int
  6199. mg_base64_decode(const char *src,
  6200. size_t src_len,
  6201. unsigned char *dst,
  6202. size_t *dst_len)
  6203. {
  6204. size_t i;
  6205. unsigned char a, b, c, d;
  6206. size_t dst_len_limit = (size_t)-1;
  6207. size_t dst_len_used = 0;
  6208. if (dst_len != NULL) {
  6209. dst_len_limit = *dst_len;
  6210. *dst_len = 0;
  6211. }
  6212. for (i = 0; i < src_len; i += 4) {
  6213. /* Read 4 characters from BASE64 string */
  6214. a = b64reverse(src[i]);
  6215. if (a >= 254) {
  6216. return (int)i;
  6217. }
  6218. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6219. if (b >= 254) {
  6220. return (int)i + 1;
  6221. }
  6222. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6223. if (c == 254) {
  6224. return (int)i + 2;
  6225. }
  6226. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6227. if (d == 254) {
  6228. return (int)i + 3;
  6229. }
  6230. /* Add first (of 3) decoded character */
  6231. if (dst_len_used < dst_len_limit) {
  6232. dst[dst_len_used] = (a << 2) + (b >> 4);
  6233. }
  6234. dst_len_used++;
  6235. if (c != 255) {
  6236. if (dst_len_used < dst_len_limit) {
  6237. dst[dst_len_used] = (b << 4) + (c >> 2);
  6238. }
  6239. dst_len_used++;
  6240. if (d != 255) {
  6241. if (dst_len_used < dst_len_limit) {
  6242. dst[dst_len_used] = (c << 6) + d;
  6243. }
  6244. dst_len_used++;
  6245. }
  6246. }
  6247. }
  6248. /* Add terminating zero */
  6249. if (dst_len_used < dst_len_limit) {
  6250. dst[dst_len_used] = '\0';
  6251. }
  6252. dst_len_used++;
  6253. if (dst_len != NULL) {
  6254. *dst_len = dst_len_used;
  6255. }
  6256. if (dst_len_used > dst_len_limit) {
  6257. /* Out of memory */
  6258. return 0;
  6259. }
  6260. /* Return -1 for "OK" */
  6261. return -1;
  6262. }
  6263. static int
  6264. is_put_or_delete_method(const struct mg_connection *conn)
  6265. {
  6266. if (conn) {
  6267. const char *s = conn->request_info.request_method;
  6268. if (s != NULL) {
  6269. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6270. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6271. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6272. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6273. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6274. || !strcmp(s, "COPY"));
  6275. }
  6276. }
  6277. return 0;
  6278. }
  6279. static int
  6280. is_civetweb_webdav_method(const struct mg_connection *conn)
  6281. {
  6282. /* Note: Here we only have to identify the WebDav methods that need special
  6283. * handling in the CivetWeb code - not all methods used in WebDav. In
  6284. * particular, methods used on directories (when using Windows Explorer as
  6285. * WebDav client).
  6286. */
  6287. if (conn) {
  6288. const char *s = conn->request_info.request_method;
  6289. if (s != NULL) {
  6290. /* These are the civetweb builtin DAV methods */
  6291. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6292. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6293. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6294. }
  6295. }
  6296. return 0;
  6297. }
  6298. #if !defined(NO_FILES)
  6299. static int
  6300. extention_matches_script(
  6301. struct mg_connection *conn, /* in: request (must be valid) */
  6302. const char *filename /* in: filename (must be valid) */
  6303. )
  6304. {
  6305. #if !defined(NO_CGI)
  6306. unsigned char cgi_config_idx, inc, max;
  6307. #endif
  6308. #if defined(USE_LUA)
  6309. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6310. filename)
  6311. > 0) {
  6312. return 1;
  6313. }
  6314. #endif
  6315. #if defined(USE_DUKTAPE)
  6316. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6317. filename)
  6318. > 0) {
  6319. return 1;
  6320. }
  6321. #endif
  6322. #if !defined(NO_CGI)
  6323. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6324. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6325. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6326. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6327. && (match_prefix_strlen(
  6328. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6329. filename)
  6330. > 0)) {
  6331. return 1;
  6332. }
  6333. }
  6334. #endif
  6335. /* filename and conn could be unused, if all preocessor conditions
  6336. * are false (no script language supported). */
  6337. (void)filename;
  6338. (void)conn;
  6339. return 0;
  6340. }
  6341. static int
  6342. extention_matches_template_text(
  6343. struct mg_connection *conn, /* in: request (must be valid) */
  6344. const char *filename /* in: filename (must be valid) */
  6345. )
  6346. {
  6347. #if defined(USE_LUA)
  6348. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6349. filename)
  6350. > 0) {
  6351. return 1;
  6352. }
  6353. #endif
  6354. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6355. > 0) {
  6356. return 1;
  6357. }
  6358. return 0;
  6359. }
  6360. /* For given directory path, substitute it to valid index file.
  6361. * Return 1 if index file has been found, 0 if not found.
  6362. * If the file is found, it's stats is returned in stp. */
  6363. static int
  6364. substitute_index_file(struct mg_connection *conn,
  6365. char *path,
  6366. size_t path_len,
  6367. struct mg_file_stat *filestat)
  6368. {
  6369. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6370. struct vec filename_vec;
  6371. size_t n = strlen(path);
  6372. int found = 0;
  6373. /* The 'path' given to us points to the directory. Remove all trailing
  6374. * directory separator characters from the end of the path, and
  6375. * then append single directory separator character. */
  6376. while ((n > 0) && (path[n - 1] == '/')) {
  6377. n--;
  6378. }
  6379. path[n] = '/';
  6380. /* Traverse index files list. For each entry, append it to the given
  6381. * path and see if the file exists. If it exists, break the loop */
  6382. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6383. /* Ignore too long entries that may overflow path buffer */
  6384. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6385. continue;
  6386. }
  6387. /* Prepare full path to the index file */
  6388. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6389. /* Does it exist? */
  6390. if (mg_stat(conn, path, filestat)) {
  6391. /* Yes it does, break the loop */
  6392. found = 1;
  6393. break;
  6394. }
  6395. }
  6396. /* If no index file exists, restore directory path */
  6397. if (!found) {
  6398. path[n] = '\0';
  6399. }
  6400. return found;
  6401. }
  6402. #endif
  6403. static void
  6404. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6405. char *filename, /* out: filename */
  6406. size_t filename_buf_len, /* in: size of filename buffer */
  6407. struct mg_file_stat *filestat, /* out: file status structure */
  6408. int *is_found, /* out: file found (directly) */
  6409. int *is_script_resource, /* out: handled by a script? */
  6410. int *is_websocket_request, /* out: websocket connection? */
  6411. int *is_put_or_delete_request, /* out: put/delete a file? */
  6412. int *is_webdav_request, /* out: webdav request? */
  6413. int *is_template_text /* out: SSI file or LSP file? */
  6414. )
  6415. {
  6416. char const *accept_encoding;
  6417. #if !defined(NO_FILES)
  6418. const char *uri = conn->request_info.local_uri;
  6419. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6420. const char *rewrite;
  6421. struct vec a, b;
  6422. ptrdiff_t match_len;
  6423. char gz_path[UTF8_PATH_MAX];
  6424. int truncated;
  6425. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6426. char *tmp_str;
  6427. size_t tmp_str_len, sep_pos;
  6428. int allow_substitute_script_subresources;
  6429. #endif
  6430. #else
  6431. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6432. #endif
  6433. /* Step 1: Set all initially unknown outputs to zero */
  6434. memset(filestat, 0, sizeof(*filestat));
  6435. *filename = 0;
  6436. *is_found = 0;
  6437. *is_script_resource = 0;
  6438. *is_template_text = 0;
  6439. /* Step 2: Classify the request method */
  6440. /* Step 2a: Check if the request attempts to modify the file system */
  6441. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6442. /* Step 2b: Check if the request uses WebDav method that requires special
  6443. * handling */
  6444. *is_webdav_request = is_civetweb_webdav_method(conn);
  6445. /* Step 3: Check if it is a websocket request, and modify the document
  6446. * root if required */
  6447. #if defined(USE_WEBSOCKET)
  6448. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6449. #if !defined(NO_FILES)
  6450. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6451. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6452. }
  6453. #endif /* !NO_FILES */
  6454. #else /* USE_WEBSOCKET */
  6455. *is_websocket_request = 0;
  6456. #endif /* USE_WEBSOCKET */
  6457. /* Step 4: Check if gzip encoded response is allowed */
  6458. conn->accept_gzip = 0;
  6459. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6460. if (strstr(accept_encoding, "gzip") != NULL) {
  6461. conn->accept_gzip = 1;
  6462. }
  6463. }
  6464. #if !defined(NO_FILES)
  6465. /* Step 5: If there is no root directory, don't look for files. */
  6466. /* Note that root == NULL is a regular use case here. This occurs,
  6467. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6468. * config is not required. */
  6469. if (root == NULL) {
  6470. /* all file related outputs have already been set to 0, just return
  6471. */
  6472. return;
  6473. }
  6474. /* Step 6: Determine the local file path from the root path and the
  6475. * request uri. */
  6476. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6477. * part of the path one byte on the right. */
  6478. truncated = 0;
  6479. mg_snprintf(
  6480. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6481. if (truncated) {
  6482. goto interpret_cleanup;
  6483. }
  6484. /* Step 7: URI rewriting */
  6485. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6486. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6487. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6488. mg_snprintf(conn,
  6489. &truncated,
  6490. filename,
  6491. filename_buf_len - 1,
  6492. "%.*s%s",
  6493. (int)b.len,
  6494. b.ptr,
  6495. uri + match_len);
  6496. break;
  6497. }
  6498. }
  6499. if (truncated) {
  6500. goto interpret_cleanup;
  6501. }
  6502. /* Step 8: Check if the file exists at the server */
  6503. /* Local file path and name, corresponding to requested URI
  6504. * is now stored in "filename" variable. */
  6505. if (mg_stat(conn, filename, filestat)) {
  6506. int uri_len = (int)strlen(uri);
  6507. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6508. /* 8.1: File exists. */
  6509. *is_found = 1;
  6510. /* 8.2: Check if it is a script type. */
  6511. if (extention_matches_script(conn, filename)) {
  6512. /* The request addresses a CGI resource, Lua script or
  6513. * server-side javascript.
  6514. * The URI corresponds to the script itself (like
  6515. * /path/script.cgi), and there is no additional resource
  6516. * path (like /path/script.cgi/something).
  6517. * Requests that modify (replace or delete) a resource, like
  6518. * PUT and DELETE requests, should replace/delete the script
  6519. * file.
  6520. * Requests that read or write from/to a resource, like GET and
  6521. * POST requests, should call the script and return the
  6522. * generated response. */
  6523. *is_script_resource = (!*is_put_or_delete_request);
  6524. }
  6525. /* 8.3: Check for SSI and LSP files */
  6526. if (extention_matches_template_text(conn, filename)) {
  6527. /* Same as above, but for *.lsp and *.shtml files. */
  6528. /* A "template text" is a file delivered directly to the client,
  6529. * but with some text tags replaced by dynamic content.
  6530. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6531. * (LP, LSP) file. */
  6532. *is_template_text = (!*is_put_or_delete_request);
  6533. }
  6534. /* 8.4: If the request target is a directory, there could be
  6535. * a substitute file (index.html, index.cgi, ...). */
  6536. /* But do not substitute a directory for a WebDav request */
  6537. if (filestat->is_directory && is_uri_end_slash
  6538. && (!*is_webdav_request)) {
  6539. /* Use a local copy here, since substitute_index_file will
  6540. * change the content of the file status */
  6541. struct mg_file_stat tmp_filestat;
  6542. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6543. if (substitute_index_file(
  6544. conn, filename, filename_buf_len, &tmp_filestat)) {
  6545. /* Substitute file found. Copy stat to the output, then
  6546. * check if the file is a script file */
  6547. *filestat = tmp_filestat;
  6548. if (extention_matches_script(conn, filename)) {
  6549. /* Substitute file is a script file */
  6550. *is_script_resource = 1;
  6551. } else if (extention_matches_template_text(conn, filename)) {
  6552. /* Substitute file is a LSP or SSI file */
  6553. *is_template_text = 1;
  6554. } else {
  6555. /* Substitute file is a regular file */
  6556. *is_script_resource = 0;
  6557. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6558. }
  6559. }
  6560. /* If there is no substitute file, the server could return
  6561. * a directory listing in a later step */
  6562. }
  6563. return;
  6564. }
  6565. /* Step 9: Check for zipped files: */
  6566. /* If we can't find the actual file, look for the file
  6567. * with the same name but a .gz extension. If we find it,
  6568. * use that and set the gzipped flag in the file struct
  6569. * to indicate that the response need to have the content-
  6570. * encoding: gzip header.
  6571. * We can only do this if the browser declares support. */
  6572. if (conn->accept_gzip) {
  6573. mg_snprintf(
  6574. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6575. if (truncated) {
  6576. goto interpret_cleanup;
  6577. }
  6578. if (mg_stat(conn, gz_path, filestat)) {
  6579. if (filestat) {
  6580. filestat->is_gzipped = 1;
  6581. *is_found = 1;
  6582. }
  6583. /* Currently gz files can not be scripts. */
  6584. return;
  6585. }
  6586. }
  6587. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6588. /* Step 10: Script resources may handle sub-resources */
  6589. /* Support PATH_INFO for CGI scripts. */
  6590. tmp_str_len = strlen(filename);
  6591. tmp_str =
  6592. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6593. if (!tmp_str) {
  6594. /* Out of memory */
  6595. goto interpret_cleanup;
  6596. }
  6597. memcpy(tmp_str, filename, tmp_str_len + 1);
  6598. /* Check config, if index scripts may have sub-resources */
  6599. allow_substitute_script_subresources =
  6600. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6601. "yes");
  6602. if (*is_webdav_request) {
  6603. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6604. * PROPFIND for their subresources? */
  6605. /* allow_substitute_script_subresources = 0; */
  6606. }
  6607. sep_pos = tmp_str_len;
  6608. while (sep_pos > 0) {
  6609. sep_pos--;
  6610. if (tmp_str[sep_pos] == '/') {
  6611. int is_script = 0, does_exist = 0;
  6612. tmp_str[sep_pos] = 0;
  6613. if (tmp_str[0]) {
  6614. is_script = extention_matches_script(conn, tmp_str);
  6615. does_exist = mg_stat(conn, tmp_str, filestat);
  6616. }
  6617. if (does_exist && is_script) {
  6618. filename[sep_pos] = 0;
  6619. memmove(filename + sep_pos + 2,
  6620. filename + sep_pos + 1,
  6621. strlen(filename + sep_pos + 1) + 1);
  6622. conn->path_info = filename + sep_pos + 1;
  6623. filename[sep_pos + 1] = '/';
  6624. *is_script_resource = 1;
  6625. *is_found = 1;
  6626. break;
  6627. }
  6628. if (allow_substitute_script_subresources) {
  6629. if (substitute_index_file(
  6630. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6631. /* some intermediate directory has an index file */
  6632. if (extention_matches_script(conn, tmp_str)) {
  6633. size_t script_name_len = strlen(tmp_str);
  6634. /* subres_name read before this memory locatio will be
  6635. overwritten */
  6636. char *subres_name = filename + sep_pos;
  6637. size_t subres_name_len = strlen(subres_name);
  6638. DEBUG_TRACE("Substitute script %s serving path %s",
  6639. tmp_str,
  6640. filename);
  6641. /* this index file is a script */
  6642. if ((script_name_len + subres_name_len + 2)
  6643. >= filename_buf_len) {
  6644. mg_free(tmp_str);
  6645. goto interpret_cleanup;
  6646. }
  6647. conn->path_info =
  6648. filename + script_name_len + 1; /* new target */
  6649. memmove(conn->path_info, subres_name, subres_name_len);
  6650. conn->path_info[subres_name_len] = 0;
  6651. memcpy(filename, tmp_str, script_name_len + 1);
  6652. *is_script_resource = 1;
  6653. *is_found = 1;
  6654. break;
  6655. } else {
  6656. DEBUG_TRACE("Substitute file %s serving path %s",
  6657. tmp_str,
  6658. filename);
  6659. /* non-script files will not have sub-resources */
  6660. filename[sep_pos] = 0;
  6661. conn->path_info = 0;
  6662. *is_script_resource = 0;
  6663. *is_found = 0;
  6664. break;
  6665. }
  6666. }
  6667. }
  6668. tmp_str[sep_pos] = '/';
  6669. }
  6670. }
  6671. mg_free(tmp_str);
  6672. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6673. #endif /* !defined(NO_FILES) */
  6674. return;
  6675. #if !defined(NO_FILES)
  6676. /* Reset all outputs */
  6677. interpret_cleanup:
  6678. memset(filestat, 0, sizeof(*filestat));
  6679. *filename = 0;
  6680. *is_found = 0;
  6681. *is_script_resource = 0;
  6682. *is_websocket_request = 0;
  6683. *is_put_or_delete_request = 0;
  6684. #endif /* !defined(NO_FILES) */
  6685. }
  6686. /* Check whether full request is buffered. Return:
  6687. * -1 if request or response is malformed
  6688. * 0 if request or response is not yet fully buffered
  6689. * >0 actual request length, including last \r\n\r\n */
  6690. static int
  6691. get_http_header_len(const char *buf, int buflen)
  6692. {
  6693. int i;
  6694. for (i = 0; i < buflen; i++) {
  6695. /* Do an unsigned comparison in some conditions below */
  6696. const unsigned char c = (unsigned char)buf[i];
  6697. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6698. && !isprint(c)) {
  6699. /* abort scan as soon as one malformed character is found */
  6700. return -1;
  6701. }
  6702. if (i < buflen - 1) {
  6703. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6704. /* Two newline, no carriage return - not standard compliant,
  6705. * but it should be accepted */
  6706. return i + 2;
  6707. }
  6708. }
  6709. if (i < buflen - 3) {
  6710. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6711. && (buf[i + 3] == '\n')) {
  6712. /* Two \r\n - standard compliant */
  6713. return i + 4;
  6714. }
  6715. }
  6716. }
  6717. return 0;
  6718. }
  6719. #if !defined(NO_CACHING)
  6720. /* Convert month to the month number. Return -1 on error, or month number */
  6721. static int
  6722. get_month_index(const char *s)
  6723. {
  6724. size_t i;
  6725. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6726. if (!strcmp(s, month_names[i])) {
  6727. return (int)i;
  6728. }
  6729. }
  6730. return -1;
  6731. }
  6732. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6733. static time_t
  6734. parse_date_string(const char *datetime)
  6735. {
  6736. char month_str[32] = {0};
  6737. int second, minute, hour, day, month, year;
  6738. time_t result = (time_t)0;
  6739. struct tm tm;
  6740. if ((sscanf(datetime,
  6741. "%d/%3s/%d %d:%d:%d",
  6742. &day,
  6743. month_str,
  6744. &year,
  6745. &hour,
  6746. &minute,
  6747. &second)
  6748. == 6)
  6749. || (sscanf(datetime,
  6750. "%d %3s %d %d:%d:%d",
  6751. &day,
  6752. month_str,
  6753. &year,
  6754. &hour,
  6755. &minute,
  6756. &second)
  6757. == 6)
  6758. || (sscanf(datetime,
  6759. "%*3s, %d %3s %d %d:%d:%d",
  6760. &day,
  6761. month_str,
  6762. &year,
  6763. &hour,
  6764. &minute,
  6765. &second)
  6766. == 6)
  6767. || (sscanf(datetime,
  6768. "%d-%3s-%d %d:%d:%d",
  6769. &day,
  6770. month_str,
  6771. &year,
  6772. &hour,
  6773. &minute,
  6774. &second)
  6775. == 6)) {
  6776. month = get_month_index(month_str);
  6777. if ((month >= 0) && (year >= 1970)) {
  6778. memset(&tm, 0, sizeof(tm));
  6779. tm.tm_year = year - 1900;
  6780. tm.tm_mon = month;
  6781. tm.tm_mday = day;
  6782. tm.tm_hour = hour;
  6783. tm.tm_min = minute;
  6784. tm.tm_sec = second;
  6785. result = timegm(&tm);
  6786. }
  6787. }
  6788. return result;
  6789. }
  6790. #endif /* !NO_CACHING */
  6791. /* Pre-process URIs according to RFC + protect against directory disclosure
  6792. * attacks by removing '..', excessive '/' and '\' characters */
  6793. static void
  6794. remove_dot_segments(char *inout)
  6795. {
  6796. /* Windows backend protection
  6797. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6798. * in URI by slash */
  6799. char *out_end = inout;
  6800. char *in = inout;
  6801. if (!in) {
  6802. /* Param error. */
  6803. return;
  6804. }
  6805. while (*in) {
  6806. if (*in == '\\') {
  6807. *in = '/';
  6808. }
  6809. in++;
  6810. }
  6811. /* Algorithm "remove_dot_segments" from
  6812. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6813. /* Step 1:
  6814. * The input buffer is initialized.
  6815. * The output buffer is initialized to the empty string.
  6816. */
  6817. in = inout;
  6818. /* Step 2:
  6819. * While the input buffer is not empty, loop as follows:
  6820. */
  6821. /* Less than out_end of the inout buffer is used as output, so keep
  6822. * condition: out_end <= in */
  6823. while (*in) {
  6824. /* Step 2a:
  6825. * If the input buffer begins with a prefix of "../" or "./",
  6826. * then remove that prefix from the input buffer;
  6827. */
  6828. if (!strncmp(in, "../", 3)) {
  6829. in += 3;
  6830. } else if (!strncmp(in, "./", 2)) {
  6831. in += 2;
  6832. }
  6833. /* otherwise */
  6834. /* Step 2b:
  6835. * if the input buffer begins with a prefix of "/./" or "/.",
  6836. * where "." is a complete path segment, then replace that
  6837. * prefix with "/" in the input buffer;
  6838. */
  6839. else if (!strncmp(in, "/./", 3)) {
  6840. in += 2;
  6841. } else if (!strcmp(in, "/.")) {
  6842. in[1] = 0;
  6843. }
  6844. /* otherwise */
  6845. /* Step 2c:
  6846. * if the input buffer begins with a prefix of "/../" or "/..",
  6847. * where ".." is a complete path segment, then replace that
  6848. * prefix with "/" in the input buffer and remove the last
  6849. * segment and its preceding "/" (if any) from the output
  6850. * buffer;
  6851. */
  6852. else if (!strncmp(in, "/../", 4)) {
  6853. in += 3;
  6854. if (inout != out_end) {
  6855. /* remove last segment */
  6856. do {
  6857. out_end--;
  6858. } while ((inout != out_end) && (*out_end != '/'));
  6859. }
  6860. } else if (!strcmp(in, "/..")) {
  6861. in[1] = 0;
  6862. if (inout != out_end) {
  6863. /* remove last segment */
  6864. do {
  6865. out_end--;
  6866. } while ((inout != out_end) && (*out_end != '/'));
  6867. }
  6868. }
  6869. /* otherwise */
  6870. /* Step 2d:
  6871. * if the input buffer consists only of "." or "..", then remove
  6872. * that from the input buffer;
  6873. */
  6874. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6875. *in = 0;
  6876. }
  6877. /* otherwise */
  6878. /* Step 2e:
  6879. * move the first path segment in the input buffer to the end of
  6880. * the output buffer, including the initial "/" character (if
  6881. * any) and any subsequent characters up to, but not including,
  6882. * the next "/" character or the end of the input buffer.
  6883. */
  6884. else {
  6885. do {
  6886. *out_end = *in;
  6887. out_end++;
  6888. in++;
  6889. } while ((*in != 0) && (*in != '/'));
  6890. }
  6891. }
  6892. /* Step 3:
  6893. * Finally, the output buffer is returned as the result of
  6894. * remove_dot_segments.
  6895. */
  6896. /* Terminate output */
  6897. *out_end = 0;
  6898. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6899. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6900. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6901. * or "//" anymore.
  6902. */
  6903. out_end = in = inout;
  6904. while (*in) {
  6905. if (*in == '.') {
  6906. /* remove . at the end or preceding of / */
  6907. char *in_ahead = in;
  6908. do {
  6909. in_ahead++;
  6910. } while (*in_ahead == '.');
  6911. if (*in_ahead == '/') {
  6912. in = in_ahead;
  6913. if ((out_end != inout) && (out_end[-1] == '/')) {
  6914. /* remove generated // */
  6915. out_end--;
  6916. }
  6917. } else if (*in_ahead == 0) {
  6918. in = in_ahead;
  6919. } else {
  6920. do {
  6921. *out_end++ = '.';
  6922. in++;
  6923. } while (in != in_ahead);
  6924. }
  6925. } else if (*in == '/') {
  6926. /* replace // by / */
  6927. *out_end++ = '/';
  6928. do {
  6929. in++;
  6930. } while (*in == '/');
  6931. } else {
  6932. *out_end++ = *in;
  6933. in++;
  6934. }
  6935. }
  6936. *out_end = 0;
  6937. }
  6938. static const struct {
  6939. const char *extension;
  6940. size_t ext_len;
  6941. const char *mime_type;
  6942. } builtin_mime_types[] = {
  6943. /* IANA registered MIME types
  6944. * (http://www.iana.org/assignments/media-types)
  6945. * application types */
  6946. {".bin", 4, "application/octet-stream"},
  6947. {".deb", 4, "application/octet-stream"},
  6948. {".dmg", 4, "application/octet-stream"},
  6949. {".dll", 4, "application/octet-stream"},
  6950. {".doc", 4, "application/msword"},
  6951. {".eps", 4, "application/postscript"},
  6952. {".exe", 4, "application/octet-stream"},
  6953. {".iso", 4, "application/octet-stream"},
  6954. {".js", 3, "application/javascript"},
  6955. {".json", 5, "application/json"},
  6956. {".msi", 4, "application/octet-stream"},
  6957. {".pdf", 4, "application/pdf"},
  6958. {".ps", 3, "application/postscript"},
  6959. {".rtf", 4, "application/rtf"},
  6960. {".xhtml", 6, "application/xhtml+xml"},
  6961. {".xsl", 4, "application/xml"},
  6962. {".xslt", 5, "application/xml"},
  6963. /* fonts */
  6964. {".ttf", 4, "application/font-sfnt"},
  6965. {".cff", 4, "application/font-sfnt"},
  6966. {".otf", 4, "application/font-sfnt"},
  6967. {".aat", 4, "application/font-sfnt"},
  6968. {".sil", 4, "application/font-sfnt"},
  6969. {".pfr", 4, "application/font-tdpfr"},
  6970. {".woff", 5, "application/font-woff"},
  6971. {".woff2", 6, "application/font-woff2"},
  6972. /* audio */
  6973. {".mp3", 4, "audio/mpeg"},
  6974. {".oga", 4, "audio/ogg"},
  6975. {".ogg", 4, "audio/ogg"},
  6976. /* image */
  6977. {".gif", 4, "image/gif"},
  6978. {".ief", 4, "image/ief"},
  6979. {".jpeg", 5, "image/jpeg"},
  6980. {".jpg", 4, "image/jpeg"},
  6981. {".jpm", 4, "image/jpm"},
  6982. {".jpx", 4, "image/jpx"},
  6983. {".png", 4, "image/png"},
  6984. {".svg", 4, "image/svg+xml"},
  6985. {".tif", 4, "image/tiff"},
  6986. {".tiff", 5, "image/tiff"},
  6987. /* model */
  6988. {".wrl", 4, "model/vrml"},
  6989. /* text */
  6990. {".css", 4, "text/css"},
  6991. {".csv", 4, "text/csv"},
  6992. {".htm", 4, "text/html"},
  6993. {".html", 5, "text/html"},
  6994. {".sgm", 4, "text/sgml"},
  6995. {".shtm", 5, "text/html"},
  6996. {".shtml", 6, "text/html"},
  6997. {".txt", 4, "text/plain"},
  6998. {".xml", 4, "text/xml"},
  6999. /* video */
  7000. {".mov", 4, "video/quicktime"},
  7001. {".mp4", 4, "video/mp4"},
  7002. {".mpeg", 5, "video/mpeg"},
  7003. {".mpg", 4, "video/mpeg"},
  7004. {".ogv", 4, "video/ogg"},
  7005. {".qt", 3, "video/quicktime"},
  7006. /* not registered types
  7007. * (http://reference.sitepoint.com/html/mime-types-full,
  7008. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7009. {".arj", 4, "application/x-arj-compressed"},
  7010. {".gz", 3, "application/x-gunzip"},
  7011. {".rar", 4, "application/x-arj-compressed"},
  7012. {".swf", 4, "application/x-shockwave-flash"},
  7013. {".tar", 4, "application/x-tar"},
  7014. {".tgz", 4, "application/x-tar-gz"},
  7015. {".torrent", 8, "application/x-bittorrent"},
  7016. {".ppt", 4, "application/x-mspowerpoint"},
  7017. {".xls", 4, "application/x-msexcel"},
  7018. {".zip", 4, "application/x-zip-compressed"},
  7019. {".aac",
  7020. 4,
  7021. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7022. {".flac", 5, "audio/flac"},
  7023. {".aif", 4, "audio/x-aif"},
  7024. {".m3u", 4, "audio/x-mpegurl"},
  7025. {".mid", 4, "audio/x-midi"},
  7026. {".ra", 3, "audio/x-pn-realaudio"},
  7027. {".ram", 4, "audio/x-pn-realaudio"},
  7028. {".wav", 4, "audio/x-wav"},
  7029. {".bmp", 4, "image/bmp"},
  7030. {".ico", 4, "image/x-icon"},
  7031. {".pct", 4, "image/x-pct"},
  7032. {".pict", 5, "image/pict"},
  7033. {".rgb", 4, "image/x-rgb"},
  7034. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7035. {".asf", 4, "video/x-ms-asf"},
  7036. {".avi", 4, "video/x-msvideo"},
  7037. {".m4v", 4, "video/x-m4v"},
  7038. {NULL, 0, NULL}};
  7039. CIVETWEB_API const char *
  7040. mg_get_builtin_mime_type(const char *path)
  7041. {
  7042. const char *ext;
  7043. size_t i, path_len;
  7044. path_len = strlen(path);
  7045. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7046. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7047. if ((path_len > builtin_mime_types[i].ext_len)
  7048. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7049. return builtin_mime_types[i].mime_type;
  7050. }
  7051. }
  7052. return "text/plain";
  7053. }
  7054. /* Look at the "path" extension and figure what mime type it has.
  7055. * Store mime type in the vector. */
  7056. static void
  7057. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7058. {
  7059. struct vec ext_vec, mime_vec;
  7060. const char *list, *ext;
  7061. size_t path_len;
  7062. path_len = strlen(path);
  7063. if ((conn == NULL) || (vec == NULL)) {
  7064. if (vec != NULL) {
  7065. memset(vec, '\0', sizeof(struct vec));
  7066. }
  7067. return;
  7068. }
  7069. /* Scan user-defined mime types first, in case user wants to
  7070. * override default mime types. */
  7071. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7072. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7073. /* ext now points to the path suffix */
  7074. ext = path + path_len - ext_vec.len;
  7075. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7076. *vec = mime_vec;
  7077. return;
  7078. }
  7079. }
  7080. vec->ptr = mg_get_builtin_mime_type(path);
  7081. vec->len = strlen(vec->ptr);
  7082. }
  7083. /* Stringify binary data. Output buffer must be twice as big as input,
  7084. * because each byte takes 2 bytes in string representation */
  7085. static void
  7086. bin2str(char *to, const unsigned char *p, size_t len)
  7087. {
  7088. static const char *hex = "0123456789abcdef";
  7089. for (; len--; p++) {
  7090. *to++ = hex[p[0] >> 4];
  7091. *to++ = hex[p[0] & 0x0f];
  7092. }
  7093. *to = '\0';
  7094. }
  7095. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7096. */
  7097. CIVETWEB_API char *
  7098. mg_md5(char buf[33], ...)
  7099. {
  7100. md5_byte_t hash[16];
  7101. const char *p;
  7102. va_list ap;
  7103. md5_state_t ctx;
  7104. md5_init(&ctx);
  7105. va_start(ap, buf);
  7106. while ((p = va_arg(ap, const char *)) != NULL) {
  7107. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7108. }
  7109. va_end(ap);
  7110. md5_finish(&ctx, hash);
  7111. bin2str(buf, hash, sizeof(hash));
  7112. return buf;
  7113. }
  7114. /* Check the user's password, return 1 if OK */
  7115. static int
  7116. check_password_digest(const char *method,
  7117. const char *ha1,
  7118. const char *uri,
  7119. const char *nonce,
  7120. const char *nc,
  7121. const char *cnonce,
  7122. const char *qop,
  7123. const char *response)
  7124. {
  7125. char ha2[32 + 1], expected_response[32 + 1];
  7126. /* Some of the parameters may be NULL */
  7127. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7128. || (qop == NULL) || (response == NULL)) {
  7129. return 0;
  7130. }
  7131. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7132. if (strlen(response) != 32) {
  7133. return 0;
  7134. }
  7135. mg_md5(ha2, method, ":", uri, NULL);
  7136. mg_md5(expected_response,
  7137. ha1,
  7138. ":",
  7139. nonce,
  7140. ":",
  7141. nc,
  7142. ":",
  7143. cnonce,
  7144. ":",
  7145. qop,
  7146. ":",
  7147. ha2,
  7148. NULL);
  7149. return mg_strcasecmp(response, expected_response) == 0;
  7150. }
  7151. #if !defined(NO_FILESYSTEMS)
  7152. /* Use the global passwords file, if specified by auth_gpass option,
  7153. * or search for .htpasswd in the requested directory. */
  7154. static void
  7155. open_auth_file(struct mg_connection *conn,
  7156. const char *path,
  7157. struct mg_file *filep)
  7158. {
  7159. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7160. char name[UTF8_PATH_MAX];
  7161. const char *p, *e,
  7162. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7163. int truncated;
  7164. if (gpass != NULL) {
  7165. /* Use global passwords file */
  7166. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7167. #if defined(DEBUG)
  7168. /* Use mg_cry_internal here, since gpass has been
  7169. * configured. */
  7170. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7171. #endif
  7172. }
  7173. /* Important: using local struct mg_file to test path for
  7174. * is_directory flag. If filep is used, mg_stat() makes it
  7175. * appear as if auth file was opened.
  7176. * TODO(mid): Check if this is still required after rewriting
  7177. * mg_stat */
  7178. } else if (mg_stat(conn, path, &filep->stat)
  7179. && filep->stat.is_directory) {
  7180. mg_snprintf(conn,
  7181. &truncated,
  7182. name,
  7183. sizeof(name),
  7184. "%s/%s",
  7185. path,
  7186. PASSWORDS_FILE_NAME);
  7187. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7188. #if defined(DEBUG)
  7189. /* Don't use mg_cry_internal here, but only a trace, since
  7190. * this is a typical case. It will occur for every directory
  7191. * without a password file. */
  7192. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7193. #endif
  7194. }
  7195. } else {
  7196. /* Try to find .htpasswd in requested directory. */
  7197. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7198. if (e[0] == '/') {
  7199. break;
  7200. }
  7201. }
  7202. mg_snprintf(conn,
  7203. &truncated,
  7204. name,
  7205. sizeof(name),
  7206. "%.*s/%s",
  7207. (int)(e - p),
  7208. p,
  7209. PASSWORDS_FILE_NAME);
  7210. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7211. #if defined(DEBUG)
  7212. /* Don't use mg_cry_internal here, but only a trace, since
  7213. * this is a typical case. It will occur for every directory
  7214. * without a password file. */
  7215. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7216. #endif
  7217. }
  7218. }
  7219. }
  7220. }
  7221. #endif /* NO_FILESYSTEMS */
  7222. /* Parsed Authorization header */
  7223. struct ah {
  7224. char *user;
  7225. int type; /* 1 = basic, 2 = digest */
  7226. char *plain_password; /* Basic only */
  7227. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7228. };
  7229. /* Return 1 on success. Always initializes the ah structure. */
  7230. static int
  7231. parse_auth_header(struct mg_connection *conn,
  7232. char *buf,
  7233. size_t buf_size,
  7234. struct ah *ah)
  7235. {
  7236. char *name, *value, *s;
  7237. const char *auth_header;
  7238. uint64_t nonce;
  7239. if (!ah || !conn) {
  7240. return 0;
  7241. }
  7242. (void)memset(ah, 0, sizeof(*ah));
  7243. auth_header = mg_get_header(conn, "Authorization");
  7244. if (auth_header == NULL) {
  7245. /* No Authorization header at all */
  7246. return 0;
  7247. }
  7248. if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
  7249. /* Basic Auth (we never asked for this, but some client may send it) */
  7250. char *split;
  7251. const char *userpw_b64 = auth_header + 6;
  7252. size_t userpw_b64_len = strlen(userpw_b64);
  7253. size_t buf_len_r = buf_size;
  7254. if (mg_base64_decode(
  7255. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7256. != -1) {
  7257. return 0; /* decode error */
  7258. }
  7259. split = strchr(buf, ':');
  7260. if (!split) {
  7261. return 0; /* Format error */
  7262. }
  7263. /* Separate string at ':' */
  7264. *split = 0;
  7265. /* User name is before ':', Password is after ':' */
  7266. ah->user = buf;
  7267. ah->type = 1;
  7268. ah->plain_password = split + 1;
  7269. return 1;
  7270. } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
  7271. /* Digest Auth ... implemented below */
  7272. ah->type = 2;
  7273. } else {
  7274. /* Unknown or invalid Auth method */
  7275. return 0;
  7276. }
  7277. /* Make modifiable copy of the auth header */
  7278. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7279. s = buf;
  7280. /* Parse authorization header */
  7281. for (;;) {
  7282. /* Gobble initial spaces */
  7283. while (isspace((unsigned char)*s)) {
  7284. s++;
  7285. }
  7286. name = skip_quoted(&s, "=", " ", 0);
  7287. /* Value is either quote-delimited, or ends at first comma or space.
  7288. */
  7289. if (s[0] == '\"') {
  7290. s++;
  7291. value = skip_quoted(&s, "\"", " ", '\\');
  7292. if (s[0] == ',') {
  7293. s++;
  7294. }
  7295. } else {
  7296. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7297. * uses spaces */
  7298. }
  7299. if (*name == '\0') {
  7300. break;
  7301. }
  7302. if (!strcmp(name, "username")) {
  7303. ah->user = value;
  7304. } else if (!strcmp(name, "cnonce")) {
  7305. ah->cnonce = value;
  7306. } else if (!strcmp(name, "response")) {
  7307. ah->response = value;
  7308. } else if (!strcmp(name, "uri")) {
  7309. ah->uri = value;
  7310. } else if (!strcmp(name, "qop")) {
  7311. ah->qop = value;
  7312. } else if (!strcmp(name, "nc")) {
  7313. ah->nc = value;
  7314. } else if (!strcmp(name, "nonce")) {
  7315. ah->nonce = value;
  7316. }
  7317. }
  7318. #if !defined(NO_NONCE_CHECK)
  7319. /* Read the nonce from the response. */
  7320. if (ah->nonce == NULL) {
  7321. return 0;
  7322. }
  7323. s = NULL;
  7324. nonce = strtoull(ah->nonce, &s, 10);
  7325. if ((s == NULL) || (*s != 0)) {
  7326. return 0;
  7327. }
  7328. /* Convert the nonce from the client to a number. */
  7329. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7330. /* The converted number corresponds to the time the nounce has been
  7331. * created. This should not be earlier than the server start. */
  7332. /* Server side nonce check is valuable in all situations but one:
  7333. * if the server restarts frequently, but the client should not see
  7334. * that, so the server should accept nonces from previous starts. */
  7335. /* However, the reasonable default is to not accept a nonce from a
  7336. * previous start, so if anyone changed the access rights between
  7337. * two restarts, a new login is required. */
  7338. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7339. /* nonce is from a previous start of the server and no longer valid
  7340. * (replay attack?) */
  7341. return 0;
  7342. }
  7343. /* Check if the nonce is too high, so it has not (yet) been used by the
  7344. * server. */
  7345. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7346. + conn->dom_ctx->nonce_count)) {
  7347. return 0;
  7348. }
  7349. #else
  7350. (void)nonce;
  7351. #endif
  7352. return (ah->user != NULL);
  7353. }
  7354. static const char *
  7355. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7356. {
  7357. if (!filep) {
  7358. return NULL;
  7359. }
  7360. if (filep->access.fp != NULL) {
  7361. return fgets(buf, (int)size, filep->access.fp);
  7362. } else {
  7363. return NULL;
  7364. }
  7365. }
  7366. /* Define the initial recursion depth for procesesing htpasswd files that
  7367. * include other htpasswd
  7368. * (or even the same) files. It is not difficult to provide a file or files
  7369. * s.t. they force civetweb
  7370. * to infinitely recurse and then crash.
  7371. */
  7372. #define INITIAL_DEPTH 9
  7373. #if INITIAL_DEPTH <= 0
  7374. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7375. #endif
  7376. #if !defined(NO_FILESYSTEMS)
  7377. struct read_auth_file_struct {
  7378. struct mg_connection *conn;
  7379. struct ah ah;
  7380. const char *domain;
  7381. char buf[256 + 256 + 40];
  7382. const char *f_user;
  7383. const char *f_domain;
  7384. const char *f_ha1;
  7385. };
  7386. static int
  7387. read_auth_file(struct mg_file *filep,
  7388. struct read_auth_file_struct *workdata,
  7389. int depth)
  7390. {
  7391. int is_authorized = 0;
  7392. struct mg_file fp;
  7393. size_t l;
  7394. if (!filep || !workdata || (0 == depth)) {
  7395. return 0;
  7396. }
  7397. /* Loop over passwords file */
  7398. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7399. l = strlen(workdata->buf);
  7400. while (l > 0) {
  7401. if (isspace((unsigned char)workdata->buf[l - 1])
  7402. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7403. l--;
  7404. workdata->buf[l] = 0;
  7405. } else
  7406. break;
  7407. }
  7408. if (l < 1) {
  7409. continue;
  7410. }
  7411. workdata->f_user = workdata->buf;
  7412. if (workdata->f_user[0] == ':') {
  7413. /* user names may not contain a ':' and may not be empty,
  7414. * so lines starting with ':' may be used for a special purpose
  7415. */
  7416. if (workdata->f_user[1] == '#') {
  7417. /* :# is a comment */
  7418. continue;
  7419. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7420. if (mg_fopen(workdata->conn,
  7421. workdata->f_user + 9,
  7422. MG_FOPEN_MODE_READ,
  7423. &fp)) {
  7424. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7425. (void)mg_fclose(
  7426. &fp.access); /* ignore error on read only file */
  7427. /* No need to continue processing files once we have a
  7428. * match, since nothing will reset it back
  7429. * to 0.
  7430. */
  7431. if (is_authorized) {
  7432. return is_authorized;
  7433. }
  7434. } else {
  7435. mg_cry_internal(workdata->conn,
  7436. "%s: cannot open authorization file: %s",
  7437. __func__,
  7438. workdata->buf);
  7439. }
  7440. continue;
  7441. }
  7442. /* everything is invalid for the moment (might change in the
  7443. * future) */
  7444. mg_cry_internal(workdata->conn,
  7445. "%s: syntax error in authorization file: %s",
  7446. __func__,
  7447. workdata->buf);
  7448. continue;
  7449. }
  7450. workdata->f_domain = strchr(workdata->f_user, ':');
  7451. if (workdata->f_domain == NULL) {
  7452. mg_cry_internal(workdata->conn,
  7453. "%s: syntax error in authorization file: %s",
  7454. __func__,
  7455. workdata->buf);
  7456. continue;
  7457. }
  7458. *(char *)(workdata->f_domain) = 0;
  7459. (workdata->f_domain)++;
  7460. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7461. if (workdata->f_ha1 == NULL) {
  7462. mg_cry_internal(workdata->conn,
  7463. "%s: syntax error in authorization file: %s",
  7464. __func__,
  7465. workdata->buf);
  7466. continue;
  7467. }
  7468. *(char *)(workdata->f_ha1) = 0;
  7469. (workdata->f_ha1)++;
  7470. if (!strcmp(workdata->ah.user, workdata->f_user)
  7471. && !strcmp(workdata->domain, workdata->f_domain)) {
  7472. switch (workdata->ah.type) {
  7473. case 1: /* Basic */
  7474. {
  7475. size_t mlen = strlen(workdata->f_user)
  7476. + strlen(workdata->domain)
  7477. + strlen(workdata->ah.plain_password) + 3;
  7478. char md5[33];
  7479. mg_md5(md5,
  7480. workdata->f_user,
  7481. ":",
  7482. workdata->domain,
  7483. ":",
  7484. workdata->ah.plain_password,
  7485. NULL);
  7486. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7487. }
  7488. case 2: /* Digest */
  7489. return check_password_digest(
  7490. workdata->conn->request_info.request_method,
  7491. workdata->f_ha1,
  7492. workdata->ah.uri,
  7493. workdata->ah.nonce,
  7494. workdata->ah.nc,
  7495. workdata->ah.cnonce,
  7496. workdata->ah.qop,
  7497. workdata->ah.response);
  7498. default: /* None/Other/Unknown */
  7499. return 0;
  7500. }
  7501. }
  7502. }
  7503. return is_authorized;
  7504. }
  7505. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7506. static int
  7507. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7508. {
  7509. struct read_auth_file_struct workdata;
  7510. char buf[MG_BUF_LEN];
  7511. if (!conn || !conn->dom_ctx) {
  7512. return 0;
  7513. }
  7514. memset(&workdata, 0, sizeof(workdata));
  7515. workdata.conn = conn;
  7516. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7517. return 0;
  7518. }
  7519. /* CGI needs it as REMOTE_USER */
  7520. conn->request_info.remote_user =
  7521. mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
  7522. if (realm) {
  7523. workdata.domain = realm;
  7524. } else {
  7525. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7526. }
  7527. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7528. }
  7529. /* Public function to check http digest authentication header */
  7530. CIVETWEB_API int
  7531. mg_check_digest_access_authentication(struct mg_connection *conn,
  7532. const char *realm,
  7533. const char *filename)
  7534. {
  7535. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7536. int auth;
  7537. if (!conn || !filename) {
  7538. return -1;
  7539. }
  7540. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7541. return -2;
  7542. }
  7543. auth = authorize(conn, &file, realm);
  7544. mg_fclose(&file.access);
  7545. return auth;
  7546. }
  7547. #endif /* NO_FILESYSTEMS */
  7548. /* Return 1 if request is authorised, 0 otherwise. */
  7549. static int
  7550. check_authorization(struct mg_connection *conn, const char *path)
  7551. {
  7552. #if !defined(NO_FILESYSTEMS)
  7553. char fname[UTF8_PATH_MAX];
  7554. struct vec uri_vec, filename_vec;
  7555. const char *list;
  7556. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7557. int authorized = 1, truncated;
  7558. if (!conn || !conn->dom_ctx) {
  7559. return 0;
  7560. }
  7561. list = conn->dom_ctx->config[PROTECT_URI];
  7562. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7563. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7564. mg_snprintf(conn,
  7565. &truncated,
  7566. fname,
  7567. sizeof(fname),
  7568. "%.*s",
  7569. (int)filename_vec.len,
  7570. filename_vec.ptr);
  7571. if (truncated
  7572. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7573. mg_cry_internal(conn,
  7574. "%s: cannot open %s: %s",
  7575. __func__,
  7576. fname,
  7577. strerror(errno));
  7578. }
  7579. break;
  7580. }
  7581. }
  7582. if (!is_file_opened(&file.access)) {
  7583. open_auth_file(conn, path, &file);
  7584. }
  7585. if (is_file_opened(&file.access)) {
  7586. authorized = authorize(conn, &file, NULL);
  7587. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7588. }
  7589. return authorized;
  7590. #else
  7591. (void)conn;
  7592. (void)path;
  7593. return 1;
  7594. #endif /* NO_FILESYSTEMS */
  7595. }
  7596. /* Internal function. Assumes conn is valid */
  7597. static void
  7598. send_authorization_request(struct mg_connection *conn, const char *realm)
  7599. {
  7600. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7601. int trunc = 0;
  7602. char buf[128];
  7603. if (!realm) {
  7604. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7605. }
  7606. mg_lock_context(conn->phys_ctx);
  7607. nonce += conn->dom_ctx->nonce_count;
  7608. ++conn->dom_ctx->nonce_count;
  7609. mg_unlock_context(conn->phys_ctx);
  7610. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7611. conn->must_close = 1;
  7612. /* Create 401 response */
  7613. mg_response_header_start(conn, 401);
  7614. send_no_cache_header(conn);
  7615. send_additional_header(conn);
  7616. mg_response_header_add(conn, "Content-Length", "0", -1);
  7617. /* Content for "WWW-Authenticate" header */
  7618. mg_snprintf(conn,
  7619. &trunc,
  7620. buf,
  7621. sizeof(buf),
  7622. "Digest qop=\"auth\", realm=\"%s\", "
  7623. "nonce=\"%" UINT64_FMT "\"",
  7624. realm,
  7625. nonce);
  7626. if (!trunc) {
  7627. /* !trunc should always be true */
  7628. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7629. }
  7630. /* Send all headers */
  7631. mg_response_header_send(conn);
  7632. }
  7633. /* Interface function. Parameters are provided by the user, so do
  7634. * at least some basic checks.
  7635. */
  7636. CIVETWEB_API int
  7637. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7638. const char *realm)
  7639. {
  7640. if (conn && conn->dom_ctx) {
  7641. send_authorization_request(conn, realm);
  7642. return 0;
  7643. }
  7644. return -1;
  7645. }
  7646. #if !defined(NO_FILES)
  7647. static int
  7648. is_authorized_for_put(struct mg_connection *conn)
  7649. {
  7650. int ret = 0;
  7651. if (conn) {
  7652. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7653. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7654. if (passfile != NULL
  7655. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7656. ret = authorize(conn, &file, NULL);
  7657. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7658. }
  7659. }
  7660. DEBUG_TRACE("file write authorization: %i", ret);
  7661. return ret;
  7662. }
  7663. #endif
  7664. CIVETWEB_API int
  7665. mg_modify_passwords_file_ha1(const char *fname,
  7666. const char *domain,
  7667. const char *user,
  7668. const char *ha1)
  7669. {
  7670. int found = 0, i, result = 1;
  7671. char line[512], u[256], d[256], h[256];
  7672. struct stat st = {0};
  7673. FILE *fp = NULL;
  7674. char *temp_file = NULL;
  7675. int temp_file_offs = 0;
  7676. /* Regard empty password as no password - remove user record. */
  7677. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7678. ha1 = NULL;
  7679. }
  7680. /* Other arguments must not be empty */
  7681. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7682. return 0;
  7683. }
  7684. /* Using the given file format, user name and domain must not contain
  7685. * the ':' character */
  7686. if (strchr(user, ':') != NULL) {
  7687. return 0;
  7688. }
  7689. if (strchr(domain, ':') != NULL) {
  7690. return 0;
  7691. }
  7692. /* Do not allow control characters like newline in user name and domain.
  7693. * Do not allow excessively long names either. */
  7694. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7695. if (iscntrl((unsigned char)user[i])) {
  7696. return 0;
  7697. }
  7698. }
  7699. if (user[i]) {
  7700. return 0; /* user name too long */
  7701. }
  7702. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7703. if (iscntrl((unsigned char)domain[i])) {
  7704. return 0;
  7705. }
  7706. }
  7707. if (domain[i]) {
  7708. return 0; /* domain name too long */
  7709. }
  7710. /* The maximum length of the path to the password file is limited */
  7711. if (strlen(fname) >= UTF8_PATH_MAX) {
  7712. return 0;
  7713. }
  7714. /* Check if the file exists, and get file size */
  7715. if (0 == stat(fname, &st)) {
  7716. int temp_buf_len = (int)st.st_size + 1024;
  7717. /* Allocate memory (instead of using a temporary file) */
  7718. temp_file = (char *)mg_calloc(temp_buf_len, 1);
  7719. if (!temp_file) {
  7720. /* Out of memory */
  7721. return 0;
  7722. }
  7723. /* File exists. Read it into a memory buffer. */
  7724. fp = fopen(fname, "r");
  7725. if (fp == NULL) {
  7726. /* Cannot read file. No permission? */
  7727. mg_free(temp_file);
  7728. return 0;
  7729. }
  7730. /* Read content and store in memory */
  7731. while ((fgets(line, sizeof(line), fp) != NULL)
  7732. && ((temp_file_offs + 600) < temp_buf_len)) {
  7733. /* file format is "user:domain:hash\n" */
  7734. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7735. continue;
  7736. }
  7737. u[255] = 0;
  7738. d[255] = 0;
  7739. h[255] = 0;
  7740. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7741. /* Found the user: change the password hash or drop the user
  7742. */
  7743. if ((ha1 != NULL) && (!found)) {
  7744. i = sprintf(temp_file + temp_file_offs,
  7745. "%s:%s:%s\n",
  7746. user,
  7747. domain,
  7748. ha1);
  7749. if (i < 1) {
  7750. fclose(fp);
  7751. mg_free(temp_file);
  7752. return 0;
  7753. }
  7754. temp_file_offs += i;
  7755. }
  7756. found = 1;
  7757. } else {
  7758. /* Copy existing user, including password hash */
  7759. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7760. if (i < 1) {
  7761. fclose(fp);
  7762. mg_free(temp_file);
  7763. return 0;
  7764. }
  7765. temp_file_offs += i;
  7766. }
  7767. }
  7768. fclose(fp);
  7769. }
  7770. /* Create new file */
  7771. fp = fopen(fname, "w");
  7772. if (!fp) {
  7773. mg_free(temp_file);
  7774. return 0;
  7775. }
  7776. #if !defined(_WIN32)
  7777. /* On Linux & co., restrict file read/write permissions to the owner */
  7778. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7779. result = 0;
  7780. }
  7781. #endif
  7782. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7783. /* Store buffered content of old file */
  7784. if (fwrite(temp_file, 1, temp_file_offs, fp)
  7785. != (size_t)temp_file_offs) {
  7786. result = 0;
  7787. }
  7788. }
  7789. /* If new user, just add it */
  7790. if ((ha1 != NULL) && (!found)) {
  7791. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7792. result = 0;
  7793. }
  7794. }
  7795. /* All data written */
  7796. if (fclose(fp) != 0) {
  7797. result = 0;
  7798. }
  7799. mg_free(temp_file);
  7800. return result;
  7801. }
  7802. CIVETWEB_API int
  7803. mg_modify_passwords_file(const char *fname,
  7804. const char *domain,
  7805. const char *user,
  7806. const char *pass)
  7807. {
  7808. char ha1buf[33];
  7809. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7810. return 0;
  7811. }
  7812. if ((pass == NULL) || (pass[0] == 0)) {
  7813. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7814. }
  7815. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7816. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7817. }
  7818. static int
  7819. is_valid_port(unsigned long port)
  7820. {
  7821. return (port <= 0xffff);
  7822. }
  7823. static int
  7824. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7825. {
  7826. struct addrinfo hints, *res, *ressave;
  7827. int func_ret = 0;
  7828. int gai_ret;
  7829. memset(&hints, 0, sizeof(struct addrinfo));
  7830. hints.ai_family = af;
  7831. if (!resolve_src) {
  7832. hints.ai_flags = AI_NUMERICHOST;
  7833. }
  7834. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7835. if (gai_ret != 0) {
  7836. /* gai_strerror could be used to convert gai_ret to a string */
  7837. /* POSIX return values: see
  7838. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7839. */
  7840. /* Windows return values: see
  7841. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7842. */
  7843. return 0;
  7844. }
  7845. ressave = res;
  7846. while (res) {
  7847. if ((dstlen >= (size_t)res->ai_addrlen)
  7848. && (res->ai_addr->sa_family == af)) {
  7849. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7850. func_ret = 1;
  7851. }
  7852. res = res->ai_next;
  7853. }
  7854. freeaddrinfo(ressave);
  7855. return func_ret;
  7856. }
  7857. static int
  7858. connect_socket(
  7859. struct mg_context *ctx /* may be NULL */,
  7860. const char *host,
  7861. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7862. int use_ssl, /* 0 or 1 */
  7863. struct mg_error_data *error,
  7864. SOCKET *sock /* output: socket, must not be NULL */,
  7865. union usa *sa /* output: socket address, must not be NULL */
  7866. )
  7867. {
  7868. int ip_ver = 0;
  7869. int conn_ret = -1;
  7870. int sockerr = 0;
  7871. *sock = INVALID_SOCKET;
  7872. memset(sa, 0, sizeof(*sa));
  7873. if (host == NULL) {
  7874. if (error != NULL) {
  7875. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7876. mg_snprintf(NULL,
  7877. NULL, /* No truncation check for ebuf */
  7878. error->text,
  7879. error->text_buffer_size,
  7880. "%s",
  7881. "NULL host");
  7882. }
  7883. return 0;
  7884. }
  7885. #if defined(USE_X_DOM_SOCKET)
  7886. if (port == -99) {
  7887. /* Unix domain socket */
  7888. size_t hostlen = strlen(host);
  7889. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7890. if (error != NULL) {
  7891. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7892. mg_snprintf(NULL,
  7893. NULL, /* No truncation check for ebuf */
  7894. error->text,
  7895. error->text_buffer_size,
  7896. "%s",
  7897. "host length exceeds limit");
  7898. }
  7899. return 0;
  7900. }
  7901. } else
  7902. #endif
  7903. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7904. if (error != NULL) {
  7905. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7906. mg_snprintf(NULL,
  7907. NULL, /* No truncation check for ebuf */
  7908. error->text,
  7909. error->text_buffer_size,
  7910. "%s",
  7911. "invalid port");
  7912. }
  7913. return 0;
  7914. }
  7915. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7916. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7917. if (use_ssl && (TLS_client_method == NULL)) {
  7918. if (error != NULL) {
  7919. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  7920. mg_snprintf(NULL,
  7921. NULL, /* No truncation check for ebuf */
  7922. error->text,
  7923. error->text_buffer_size,
  7924. "%s",
  7925. "SSL is not initialized");
  7926. }
  7927. return 0;
  7928. }
  7929. #else
  7930. if (use_ssl && (SSLv23_client_method == NULL)) {
  7931. if (error != 0) {
  7932. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  7933. mg_snprintf(NULL,
  7934. NULL, /* No truncation check for ebuf */
  7935. error->text,
  7936. error->text_buffer_size,
  7937. "%s",
  7938. "SSL is not initialized");
  7939. }
  7940. return 0;
  7941. }
  7942. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7943. #else
  7944. (void)use_ssl;
  7945. #endif /* NO SSL */
  7946. #if defined(USE_X_DOM_SOCKET)
  7947. if (port == -99) {
  7948. size_t hostlen = strlen(host);
  7949. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  7950. ip_ver = -99;
  7951. sa->sun.sun_family = AF_UNIX;
  7952. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  7953. memcpy(sa->sun.sun_path, host, hostlen);
  7954. } else
  7955. #endif
  7956. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7957. sa->sin.sin_port = htons((uint16_t)port);
  7958. ip_ver = 4;
  7959. #if defined(USE_IPV6)
  7960. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7961. sa->sin6.sin6_port = htons((uint16_t)port);
  7962. ip_ver = 6;
  7963. } else if (host[0] == '[') {
  7964. /* While getaddrinfo on Windows will work with [::1],
  7965. * getaddrinfo on Linux only works with ::1 (without []). */
  7966. size_t l = strlen(host + 1);
  7967. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7968. if (h) {
  7969. h[l - 1] = 0;
  7970. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7971. sa->sin6.sin6_port = htons((uint16_t)port);
  7972. ip_ver = 6;
  7973. }
  7974. mg_free(h);
  7975. }
  7976. #endif
  7977. }
  7978. if (ip_ver == 0) {
  7979. if (error != NULL) {
  7980. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  7981. mg_snprintf(NULL,
  7982. NULL, /* No truncation check for ebuf */
  7983. error->text,
  7984. error->text_buffer_size,
  7985. "%s",
  7986. "host not found");
  7987. }
  7988. return 0;
  7989. }
  7990. if (ip_ver == 4) {
  7991. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7992. }
  7993. #if defined(USE_IPV6)
  7994. else if (ip_ver == 6) {
  7995. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7996. }
  7997. #endif
  7998. #if defined(USE_X_DOM_SOCKET)
  7999. else if (ip_ver == -99) {
  8000. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8001. }
  8002. #endif
  8003. if (*sock == INVALID_SOCKET) {
  8004. if (error != NULL) {
  8005. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8006. error->code_sub = ERRNO;
  8007. mg_snprintf(NULL,
  8008. NULL, /* No truncation check for ebuf */
  8009. error->text,
  8010. error->text_buffer_size,
  8011. "socket(): %s",
  8012. strerror(ERRNO));
  8013. }
  8014. return 0;
  8015. }
  8016. if (0 != set_non_blocking_mode(*sock)) {
  8017. if (error != NULL) {
  8018. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8019. error->code_sub = ERRNO;
  8020. mg_snprintf(NULL,
  8021. NULL, /* No truncation check for ebuf */
  8022. error->text,
  8023. error->text_buffer_size,
  8024. "Cannot set socket to non-blocking: %s",
  8025. strerror(ERRNO));
  8026. }
  8027. closesocket(*sock);
  8028. *sock = INVALID_SOCKET;
  8029. return 0;
  8030. }
  8031. set_close_on_exec(*sock, NULL, ctx);
  8032. if (ip_ver == 4) {
  8033. /* connected with IPv4 */
  8034. conn_ret = connect(*sock,
  8035. (struct sockaddr *)((void *)&sa->sin),
  8036. sizeof(sa->sin));
  8037. }
  8038. #if defined(USE_IPV6)
  8039. else if (ip_ver == 6) {
  8040. /* connected with IPv6 */
  8041. conn_ret = connect(*sock,
  8042. (struct sockaddr *)((void *)&sa->sin6),
  8043. sizeof(sa->sin6));
  8044. }
  8045. #endif
  8046. #if defined(USE_X_DOM_SOCKET)
  8047. else if (ip_ver == -99) {
  8048. /* connected to domain socket */
  8049. conn_ret = connect(*sock,
  8050. (struct sockaddr *)((void *)&sa->sun),
  8051. sizeof(sa->sun));
  8052. }
  8053. #endif
  8054. if (conn_ret != 0) {
  8055. sockerr = ERRNO;
  8056. }
  8057. #if defined(_WIN32)
  8058. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8059. #else
  8060. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8061. #endif
  8062. /* Data for getsockopt */
  8063. void *psockerr = &sockerr;
  8064. int ret;
  8065. #if defined(_WIN32)
  8066. int len = (int)sizeof(sockerr);
  8067. #else
  8068. socklen_t len = (socklen_t)sizeof(sockerr);
  8069. #endif
  8070. /* Data for poll */
  8071. struct mg_pollfd pfd[1];
  8072. int pollres;
  8073. int ms_wait = 10000; /* 10 second timeout */
  8074. stop_flag_t nonstop;
  8075. STOP_FLAG_ASSIGN(&nonstop, 0);
  8076. /* For a non-blocking socket, the connect sequence is:
  8077. * 1) call connect (will not block)
  8078. * 2) wait until the socket is ready for writing (select or poll)
  8079. * 3) check connection state with getsockopt
  8080. */
  8081. pfd[0].fd = *sock;
  8082. pfd[0].events = POLLOUT;
  8083. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8084. if (pollres != 1) {
  8085. /* Not connected */
  8086. if (error != NULL) {
  8087. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8088. mg_snprintf(NULL,
  8089. NULL, /* No truncation check for ebuf */
  8090. error->text,
  8091. error->text_buffer_size,
  8092. "connect(%s:%d): timeout",
  8093. host,
  8094. port);
  8095. }
  8096. closesocket(*sock);
  8097. *sock = INVALID_SOCKET;
  8098. return 0;
  8099. }
  8100. #if defined(_WIN32)
  8101. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8102. #else
  8103. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8104. #endif
  8105. if ((ret == 0) && (sockerr == 0)) {
  8106. conn_ret = 0;
  8107. }
  8108. }
  8109. if (conn_ret != 0) {
  8110. /* Not connected */
  8111. if (error != NULL) {
  8112. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8113. error->code_sub = ERRNO;
  8114. mg_snprintf(NULL,
  8115. NULL, /* No truncation check for ebuf */
  8116. error->text,
  8117. error->text_buffer_size,
  8118. "connect(%s:%d): error %s",
  8119. host,
  8120. port,
  8121. strerror(sockerr));
  8122. }
  8123. closesocket(*sock);
  8124. *sock = INVALID_SOCKET;
  8125. return 0;
  8126. }
  8127. return 1;
  8128. }
  8129. CIVETWEB_API int
  8130. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8131. {
  8132. static const char *dont_escape = "._-$,;~()";
  8133. static const char *hex = "0123456789abcdef";
  8134. char *pos = dst;
  8135. const char *end = dst + dst_len - 1;
  8136. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8137. if (isalnum((unsigned char)*src)
  8138. || (strchr(dont_escape, *src) != NULL)) {
  8139. *pos = *src;
  8140. } else if (pos + 2 < end) {
  8141. pos[0] = '%';
  8142. pos[1] = hex[(unsigned char)*src >> 4];
  8143. pos[2] = hex[(unsigned char)*src & 0xf];
  8144. pos += 2;
  8145. } else {
  8146. break;
  8147. }
  8148. }
  8149. *pos = '\0';
  8150. return (*src == '\0') ? (int)(pos - dst) : -1;
  8151. }
  8152. /* Return 0 on success, non-zero if an error occurs. */
  8153. static int
  8154. print_dir_entry(struct mg_connection *conn, struct de *de)
  8155. {
  8156. size_t namesize, escsize, i;
  8157. char *href, *esc, *p;
  8158. char size[64], mod[64];
  8159. #if defined(REENTRANT_TIME)
  8160. struct tm _tm;
  8161. struct tm *tm = &_tm;
  8162. #else
  8163. struct tm *tm;
  8164. #endif
  8165. /* Estimate worst case size for encoding and escaping */
  8166. namesize = strlen(de->file_name) + 1;
  8167. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8168. href = (char *)mg_malloc(namesize * 3 + escsize);
  8169. if (href == NULL) {
  8170. return -1;
  8171. }
  8172. mg_url_encode(de->file_name, href, namesize * 3);
  8173. esc = NULL;
  8174. if (escsize > 0) {
  8175. /* HTML escaping needed */
  8176. esc = href + namesize * 3;
  8177. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8178. mg_strlcpy(p, de->file_name + i, 2);
  8179. if (*p == '&') {
  8180. strcpy(p, "&amp;");
  8181. } else if (*p == '<') {
  8182. strcpy(p, "&lt;");
  8183. } else if (*p == '>') {
  8184. strcpy(p, "&gt;");
  8185. }
  8186. }
  8187. }
  8188. if (de->file.is_directory) {
  8189. mg_snprintf(conn,
  8190. NULL, /* Buffer is big enough */
  8191. size,
  8192. sizeof(size),
  8193. "%s",
  8194. "[DIRECTORY]");
  8195. } else {
  8196. /* We use (signed) cast below because MSVC 6 compiler cannot
  8197. * convert unsigned __int64 to double. Sigh. */
  8198. if (de->file.size < 1024) {
  8199. mg_snprintf(conn,
  8200. NULL, /* Buffer is big enough */
  8201. size,
  8202. sizeof(size),
  8203. "%d",
  8204. (int)de->file.size);
  8205. } else if (de->file.size < 0x100000) {
  8206. mg_snprintf(conn,
  8207. NULL, /* Buffer is big enough */
  8208. size,
  8209. sizeof(size),
  8210. "%.1fk",
  8211. (double)de->file.size / 1024.0);
  8212. } else if (de->file.size < 0x40000000) {
  8213. mg_snprintf(conn,
  8214. NULL, /* Buffer is big enough */
  8215. size,
  8216. sizeof(size),
  8217. "%.1fM",
  8218. (double)de->file.size / 1048576);
  8219. } else {
  8220. mg_snprintf(conn,
  8221. NULL, /* Buffer is big enough */
  8222. size,
  8223. sizeof(size),
  8224. "%.1fG",
  8225. (double)de->file.size / 1073741824);
  8226. }
  8227. }
  8228. /* Note: mg_snprintf will not cause a buffer overflow above.
  8229. * So, string truncation checks are not required here. */
  8230. #if defined(REENTRANT_TIME)
  8231. localtime_r(&de->file.last_modified, tm);
  8232. #else
  8233. tm = localtime(&de->file.last_modified);
  8234. #endif
  8235. if (tm != NULL) {
  8236. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8237. } else {
  8238. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8239. }
  8240. mg_printf(conn,
  8241. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8242. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8243. href,
  8244. de->file.is_directory ? "/" : "",
  8245. esc ? esc : de->file_name,
  8246. de->file.is_directory ? "/" : "",
  8247. mod,
  8248. size);
  8249. mg_free(href);
  8250. return 0;
  8251. }
  8252. /* This function is called from send_directory() and used for
  8253. * sorting directory entries by size, name, or modification time. */
  8254. static int
  8255. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8256. {
  8257. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8258. if (p1 && p2) {
  8259. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8260. int cmp_result = 0;
  8261. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8262. query_string = "n";
  8263. }
  8264. /* Sort Directories vs Files */
  8265. if (a->file.is_directory && !b->file.is_directory) {
  8266. return -1; /* Always put directories on top */
  8267. } else if (!a->file.is_directory && b->file.is_directory) {
  8268. return 1; /* Always put directories on top */
  8269. }
  8270. /* Sort by size or date */
  8271. if (*query_string == 's') {
  8272. cmp_result = (a->file.size == b->file.size)
  8273. ? 0
  8274. : ((a->file.size > b->file.size) ? 1 : -1);
  8275. } else if (*query_string == 'd') {
  8276. cmp_result =
  8277. (a->file.last_modified == b->file.last_modified)
  8278. ? 0
  8279. : ((a->file.last_modified > b->file.last_modified) ? 1
  8280. : -1);
  8281. }
  8282. /* Sort by name:
  8283. * if (*query_string == 'n') ...
  8284. * but also sort files of same size/date by name as secondary criterion.
  8285. */
  8286. if (cmp_result == 0) {
  8287. cmp_result = strcmp(a->file_name, b->file_name);
  8288. }
  8289. /* For descending order, invert result */
  8290. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8291. }
  8292. return 0;
  8293. }
  8294. static int
  8295. must_hide_file(struct mg_connection *conn, const char *path)
  8296. {
  8297. if (conn && conn->dom_ctx) {
  8298. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8299. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8300. return (match_prefix_strlen(pw_pattern, path) > 0)
  8301. || (match_prefix_strlen(pattern, path) > 0);
  8302. }
  8303. return 0;
  8304. }
  8305. #if !defined(NO_FILESYSTEMS)
  8306. static int
  8307. scan_directory(struct mg_connection *conn,
  8308. const char *dir,
  8309. void *data,
  8310. int (*cb)(struct de *, void *))
  8311. {
  8312. char path[UTF8_PATH_MAX];
  8313. struct dirent *dp;
  8314. DIR *dirp;
  8315. struct de de;
  8316. int truncated;
  8317. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8318. return 0;
  8319. } else {
  8320. while ((dp = mg_readdir(dirp)) != NULL) {
  8321. /* Do not show current dir and hidden files */
  8322. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8323. || must_hide_file(conn, dp->d_name)) {
  8324. continue;
  8325. }
  8326. mg_snprintf(
  8327. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8328. /* If we don't memset stat structure to zero, mtime will have
  8329. * garbage and strftime() will segfault later on in
  8330. * print_dir_entry(). memset is required only if mg_stat()
  8331. * fails. For more details, see
  8332. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8333. memset(&de.file, 0, sizeof(de.file));
  8334. if (truncated) {
  8335. /* If the path is not complete, skip processing. */
  8336. continue;
  8337. }
  8338. if (!mg_stat(conn, path, &de.file)) {
  8339. mg_cry_internal(conn,
  8340. "%s: mg_stat(%s) failed: %s",
  8341. __func__,
  8342. path,
  8343. strerror(ERRNO));
  8344. }
  8345. de.file_name = dp->d_name;
  8346. if (cb(&de, data)) {
  8347. /* stopped */
  8348. break;
  8349. }
  8350. }
  8351. (void)mg_closedir(dirp);
  8352. }
  8353. return 1;
  8354. }
  8355. #endif /* NO_FILESYSTEMS */
  8356. #if !defined(NO_FILES)
  8357. static int
  8358. remove_directory(struct mg_connection *conn, const char *dir)
  8359. {
  8360. char path[UTF8_PATH_MAX];
  8361. struct dirent *dp;
  8362. DIR *dirp;
  8363. struct de de;
  8364. int truncated;
  8365. int ok = 1;
  8366. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8367. return 0;
  8368. } else {
  8369. while ((dp = mg_readdir(dirp)) != NULL) {
  8370. /* Do not show current dir (but show hidden files as they will
  8371. * also be removed) */
  8372. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8373. continue;
  8374. }
  8375. mg_snprintf(
  8376. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8377. /* If we don't memset stat structure to zero, mtime will have
  8378. * garbage and strftime() will segfault later on in
  8379. * print_dir_entry(). memset is required only if mg_stat()
  8380. * fails. For more details, see
  8381. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8382. memset(&de.file, 0, sizeof(de.file));
  8383. if (truncated) {
  8384. /* Do not delete anything shorter */
  8385. ok = 0;
  8386. continue;
  8387. }
  8388. if (!mg_stat(conn, path, &de.file)) {
  8389. mg_cry_internal(conn,
  8390. "%s: mg_stat(%s) failed: %s",
  8391. __func__,
  8392. path,
  8393. strerror(ERRNO));
  8394. ok = 0;
  8395. }
  8396. if (de.file.is_directory) {
  8397. if (remove_directory(conn, path) == 0) {
  8398. ok = 0;
  8399. }
  8400. } else {
  8401. /* This will fail file is the file is in memory */
  8402. if (mg_remove(conn, path) == 0) {
  8403. ok = 0;
  8404. }
  8405. }
  8406. }
  8407. (void)mg_closedir(dirp);
  8408. IGNORE_UNUSED_RESULT(rmdir(dir));
  8409. }
  8410. return ok;
  8411. }
  8412. #endif
  8413. struct dir_scan_data {
  8414. struct de *entries;
  8415. size_t num_entries;
  8416. size_t arr_size;
  8417. };
  8418. #if !defined(NO_FILESYSTEMS)
  8419. static int
  8420. dir_scan_callback(struct de *de, void *data)
  8421. {
  8422. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8423. struct de *entries = dsd->entries;
  8424. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8425. /* Here "entries" is a temporary pointer and can be replaced,
  8426. * "dsd->entries" is the original pointer */
  8427. entries =
  8428. (struct de *)mg_realloc(entries,
  8429. dsd->arr_size * 2 * sizeof(entries[0]));
  8430. if (entries == NULL) {
  8431. /* stop scan */
  8432. return 1;
  8433. }
  8434. dsd->entries = entries;
  8435. dsd->arr_size *= 2;
  8436. }
  8437. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8438. if (entries[dsd->num_entries].file_name == NULL) {
  8439. /* stop scan */
  8440. return 1;
  8441. }
  8442. entries[dsd->num_entries].file = de->file;
  8443. dsd->num_entries++;
  8444. return 0;
  8445. }
  8446. static void
  8447. handle_directory_request(struct mg_connection *conn, const char *dir)
  8448. {
  8449. size_t i;
  8450. int sort_direction;
  8451. struct dir_scan_data data = {NULL, 0, 128};
  8452. char date[64], *esc, *p;
  8453. const char *title;
  8454. time_t curtime = time(NULL);
  8455. if (!conn) {
  8456. return;
  8457. }
  8458. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8459. mg_send_http_error(conn,
  8460. 500,
  8461. "Error: Cannot open directory\nopendir(%s): %s",
  8462. dir,
  8463. strerror(ERRNO));
  8464. return;
  8465. }
  8466. gmt_time_string(date, sizeof(date), &curtime);
  8467. esc = NULL;
  8468. title = conn->request_info.local_uri;
  8469. if (title[strcspn(title, "&<>")]) {
  8470. /* HTML escaping needed */
  8471. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8472. if (esc) {
  8473. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8474. mg_strlcpy(p, title + i, 2);
  8475. if (*p == '&') {
  8476. strcpy(p, "&amp;");
  8477. } else if (*p == '<') {
  8478. strcpy(p, "&lt;");
  8479. } else if (*p == '>') {
  8480. strcpy(p, "&gt;");
  8481. }
  8482. }
  8483. } else {
  8484. title = "";
  8485. }
  8486. }
  8487. sort_direction = ((conn->request_info.query_string != NULL)
  8488. && (conn->request_info.query_string[0] != '\0')
  8489. && (conn->request_info.query_string[1] == 'd'))
  8490. ? 'a'
  8491. : 'd';
  8492. conn->must_close = 1;
  8493. /* Create 200 OK response */
  8494. mg_response_header_start(conn, 200);
  8495. send_static_cache_header(conn);
  8496. send_additional_header(conn);
  8497. mg_response_header_add(conn,
  8498. "Content-Type",
  8499. "text/html; charset=utf-8",
  8500. -1);
  8501. /* Send all headers */
  8502. mg_response_header_send(conn);
  8503. /* Body */
  8504. mg_printf(conn,
  8505. "<html><head><title>Index of %s</title>"
  8506. "<style>th {text-align: left;}</style></head>"
  8507. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8508. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8509. "<th><a href=\"?d%c\">Modified</a></th>"
  8510. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8511. "<tr><td colspan=\"3\"><hr></td></tr>",
  8512. esc ? esc : title,
  8513. esc ? esc : title,
  8514. sort_direction,
  8515. sort_direction,
  8516. sort_direction);
  8517. mg_free(esc);
  8518. /* Print first entry - link to a parent directory */
  8519. mg_printf(conn,
  8520. "<tr><td><a href=\"%s\">%s</a></td>"
  8521. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8522. "..",
  8523. "Parent directory",
  8524. "-",
  8525. "-");
  8526. /* Sort and print directory entries */
  8527. if (data.entries != NULL) {
  8528. mg_sort(data.entries,
  8529. data.num_entries,
  8530. sizeof(data.entries[0]),
  8531. compare_dir_entries,
  8532. (void *)conn->request_info.query_string);
  8533. for (i = 0; i < data.num_entries; i++) {
  8534. print_dir_entry(conn, &data.entries[i]);
  8535. mg_free(data.entries[i].file_name);
  8536. }
  8537. mg_free(data.entries);
  8538. }
  8539. mg_printf(conn, "%s", "</table></pre></body></html>");
  8540. conn->status_code = 200;
  8541. }
  8542. #endif /* NO_FILESYSTEMS */
  8543. /* Send len bytes from the opened file to the client. */
  8544. static void
  8545. send_file_data(struct mg_connection *conn,
  8546. struct mg_file *filep,
  8547. int64_t offset,
  8548. int64_t len,
  8549. int no_buffering)
  8550. {
  8551. char buf[MG_BUF_LEN];
  8552. int to_read, num_read, num_written;
  8553. int64_t size;
  8554. if (!filep || !conn) {
  8555. return;
  8556. }
  8557. /* Sanity check the offset */
  8558. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8559. : (int64_t)(filep->stat.size);
  8560. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8561. if (len > 0 && filep->access.fp != NULL) {
  8562. /* file stored on disk */
  8563. #if defined(__linux__)
  8564. /* sendfile is only available for Linux */
  8565. if ((conn->ssl == 0) && (conn->throttle == 0)
  8566. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8567. "yes"))) {
  8568. off_t sf_offs = (off_t)offset;
  8569. ssize_t sf_sent;
  8570. int sf_file = fileno(filep->access.fp);
  8571. int loop_cnt = 0;
  8572. do {
  8573. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8574. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8575. size_t sf_tosend =
  8576. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8577. sf_sent =
  8578. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8579. if (sf_sent > 0) {
  8580. len -= sf_sent;
  8581. offset += sf_sent;
  8582. } else if (loop_cnt == 0) {
  8583. /* This file can not be sent using sendfile.
  8584. * This might be the case for pseudo-files in the
  8585. * /sys/ and /proc/ file system.
  8586. * Use the regular user mode copy code instead. */
  8587. break;
  8588. } else if (sf_sent == 0) {
  8589. /* No error, but 0 bytes sent. May be EOF? */
  8590. return;
  8591. }
  8592. loop_cnt++;
  8593. } while ((len > 0) && (sf_sent >= 0));
  8594. if (sf_sent > 0) {
  8595. return; /* OK */
  8596. }
  8597. /* sf_sent<0 means error, thus fall back to the classic way */
  8598. /* This is always the case, if sf_file is not a "normal" file,
  8599. * e.g., for sending data from the output of a CGI process. */
  8600. offset = (int64_t)sf_offs;
  8601. }
  8602. #endif
  8603. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8604. mg_cry_internal(conn,
  8605. "%s: fseeko() failed: %s",
  8606. __func__,
  8607. strerror(ERRNO));
  8608. mg_send_http_error(
  8609. conn,
  8610. 500,
  8611. "%s",
  8612. "Error: Unable to access file at requested position.");
  8613. } else {
  8614. while (len > 0) {
  8615. /* Calculate how much to read from the file into the buffer. */
  8616. /* If no_buffering is set, we should not wait until the
  8617. * CGI->Server buffer is filled, but send everything
  8618. * immediately. In theory buffering could be turned off using
  8619. * setbuf(filep->access.fp, NULL);
  8620. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8621. * but in practice this does not work. A "Linux only" solution
  8622. * may be to use select(). The only portable way is to read byte
  8623. * by byte, but this is quite inefficient from a performance
  8624. * point of view. */
  8625. to_read = no_buffering ? 1 : sizeof(buf);
  8626. if ((int64_t)to_read > len) {
  8627. to_read = (int)len;
  8628. }
  8629. /* Read from file, exit the loop on error */
  8630. if ((num_read =
  8631. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8632. <= 0) {
  8633. break;
  8634. }
  8635. /* Send read bytes to the client, exit the loop on error */
  8636. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8637. != num_read) {
  8638. break;
  8639. }
  8640. /* Both read and were successful, adjust counters */
  8641. len -= num_written;
  8642. }
  8643. }
  8644. }
  8645. }
  8646. static int
  8647. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8648. {
  8649. return sscanf(header,
  8650. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8651. a,
  8652. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8653. // to an integer value, but function will not report
  8654. // conversion errors; consider using 'strtol' instead
  8655. }
  8656. static void
  8657. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8658. {
  8659. if ((filestat != NULL) && (buf != NULL)) {
  8660. mg_snprintf(NULL,
  8661. NULL, /* All calls to construct_etag use 64 byte buffer */
  8662. buf,
  8663. buf_len,
  8664. "\"%lx.%" INT64_FMT "\"",
  8665. (unsigned long)filestat->last_modified,
  8666. filestat->size);
  8667. }
  8668. }
  8669. static void
  8670. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8671. {
  8672. if (filep != NULL && filep->fp != NULL) {
  8673. #if defined(_WIN32)
  8674. (void)conn; /* Unused. */
  8675. #else
  8676. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8677. mg_cry_internal(conn,
  8678. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8679. __func__,
  8680. strerror(ERRNO));
  8681. }
  8682. #endif
  8683. }
  8684. }
  8685. #if defined(USE_ZLIB)
  8686. #include "mod_zlib.inl"
  8687. #endif
  8688. #if !defined(NO_FILESYSTEMS)
  8689. static void
  8690. handle_static_file_request(struct mg_connection *conn,
  8691. const char *path,
  8692. struct mg_file *filep,
  8693. const char *mime_type,
  8694. const char *additional_headers)
  8695. {
  8696. char lm[64], etag[64];
  8697. char range[128]; /* large enough, so there will be no overflow */
  8698. const char *range_hdr;
  8699. int64_t cl, r1, r2;
  8700. struct vec mime_vec;
  8701. int n, truncated;
  8702. char gz_path[UTF8_PATH_MAX];
  8703. const char *encoding = 0;
  8704. int is_head_request;
  8705. #if defined(USE_ZLIB)
  8706. /* Compression is allowed, unless there is a reason not to use
  8707. * compression. If the file is already compressed, too small or a
  8708. * "range" request was made, on the fly compression is not possible. */
  8709. int allow_on_the_fly_compression = 1;
  8710. #endif
  8711. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8712. return;
  8713. }
  8714. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8715. if (mime_type == NULL) {
  8716. get_mime_type(conn, path, &mime_vec);
  8717. } else {
  8718. mime_vec.ptr = mime_type;
  8719. mime_vec.len = strlen(mime_type);
  8720. }
  8721. if (filep->stat.size > INT64_MAX) {
  8722. mg_send_http_error(conn,
  8723. 500,
  8724. "Error: File size is too large to send\n%" INT64_FMT,
  8725. filep->stat.size);
  8726. return;
  8727. }
  8728. cl = (int64_t)filep->stat.size;
  8729. conn->status_code = 200;
  8730. range[0] = '\0';
  8731. #if defined(USE_ZLIB)
  8732. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8733. * it's important to rewrite the filename after resolving
  8734. * the mime type from it, to preserve the actual file's type */
  8735. if (!conn->accept_gzip) {
  8736. allow_on_the_fly_compression = 0;
  8737. }
  8738. #endif
  8739. /* Check if there is a range header */
  8740. range_hdr = mg_get_header(conn, "Range");
  8741. /* For gzipped files, add *.gz */
  8742. if (filep->stat.is_gzipped) {
  8743. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8744. if (truncated) {
  8745. mg_send_http_error(conn,
  8746. 500,
  8747. "Error: Path of zipped file too long (%s)",
  8748. path);
  8749. return;
  8750. }
  8751. path = gz_path;
  8752. encoding = "gzip";
  8753. #if defined(USE_ZLIB)
  8754. /* File is already compressed. No "on the fly" compression. */
  8755. allow_on_the_fly_compression = 0;
  8756. #endif
  8757. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8758. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8759. struct mg_file_stat file_stat;
  8760. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8761. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8762. && !file_stat.is_directory) {
  8763. file_stat.is_gzipped = 1;
  8764. filep->stat = file_stat;
  8765. cl = (int64_t)filep->stat.size;
  8766. path = gz_path;
  8767. encoding = "gzip";
  8768. #if defined(USE_ZLIB)
  8769. /* File is already compressed. No "on the fly" compression. */
  8770. allow_on_the_fly_compression = 0;
  8771. #endif
  8772. }
  8773. }
  8774. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8775. mg_send_http_error(conn,
  8776. 500,
  8777. "Error: Cannot open file\nfopen(%s): %s",
  8778. path,
  8779. strerror(ERRNO));
  8780. return;
  8781. }
  8782. fclose_on_exec(&filep->access, conn);
  8783. /* If "Range" request was made: parse header, send only selected part
  8784. * of the file. */
  8785. r1 = r2 = 0;
  8786. if ((range_hdr != NULL)
  8787. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8788. && (r2 >= 0)) {
  8789. /* actually, range requests don't play well with a pre-gzipped
  8790. * file (since the range is specified in the uncompressed space) */
  8791. if (filep->stat.is_gzipped) {
  8792. mg_send_http_error(
  8793. conn,
  8794. 416, /* 416 = Range Not Satisfiable */
  8795. "%s",
  8796. "Error: Range requests in gzipped files are not supported");
  8797. (void)mg_fclose(
  8798. &filep->access); /* ignore error on read only file */
  8799. return;
  8800. }
  8801. conn->status_code = 206;
  8802. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8803. mg_snprintf(conn,
  8804. NULL, /* range buffer is big enough */
  8805. range,
  8806. sizeof(range),
  8807. "bytes "
  8808. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8809. r1,
  8810. r1 + cl - 1,
  8811. filep->stat.size);
  8812. #if defined(USE_ZLIB)
  8813. /* Do not compress ranges. */
  8814. allow_on_the_fly_compression = 0;
  8815. #endif
  8816. }
  8817. /* Do not compress small files. Small files do not benefit from file
  8818. * compression, but there is still some overhead. */
  8819. #if defined(USE_ZLIB)
  8820. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8821. /* File is below the size limit. */
  8822. allow_on_the_fly_compression = 0;
  8823. }
  8824. #endif
  8825. /* Prepare Etag, and Last-Modified headers. */
  8826. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8827. construct_etag(etag, sizeof(etag), &filep->stat);
  8828. /* Create 2xx (200, 206) response */
  8829. mg_response_header_start(conn, conn->status_code);
  8830. send_static_cache_header(conn);
  8831. send_additional_header(conn);
  8832. send_cors_header(conn);
  8833. mg_response_header_add(conn,
  8834. "Content-Type",
  8835. mime_vec.ptr,
  8836. (int)mime_vec.len);
  8837. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8838. mg_response_header_add(conn, "Etag", etag, -1);
  8839. #if defined(USE_ZLIB)
  8840. /* On the fly compression allowed */
  8841. if (allow_on_the_fly_compression) {
  8842. /* For on the fly compression, we don't know the content size in
  8843. * advance, so we have to use chunked encoding */
  8844. encoding = "gzip";
  8845. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8846. /* HTTP/2 is always using "chunks" (frames) */
  8847. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8848. }
  8849. } else
  8850. #endif
  8851. {
  8852. /* Without on-the-fly compression, we know the content-length
  8853. * and we can use ranges (with on-the-fly compression we cannot).
  8854. * So we send these response headers only in this case. */
  8855. char len[32];
  8856. int trunc = 0;
  8857. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8858. if (!trunc) {
  8859. mg_response_header_add(conn, "Content-Length", len, -1);
  8860. }
  8861. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8862. }
  8863. if (encoding) {
  8864. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8865. }
  8866. if (range[0] != 0) {
  8867. mg_response_header_add(conn, "Content-Range", range, -1);
  8868. }
  8869. /* The code above does not add any header starting with X- to make
  8870. * sure no one of the additional_headers is included twice */
  8871. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8872. mg_response_header_add_lines(conn, additional_headers);
  8873. }
  8874. /* Send all headers */
  8875. mg_response_header_send(conn);
  8876. if (!is_head_request) {
  8877. #if defined(USE_ZLIB)
  8878. if (allow_on_the_fly_compression) {
  8879. /* Compress and send */
  8880. send_compressed_data(conn, filep);
  8881. } else
  8882. #endif
  8883. {
  8884. /* Send file directly */
  8885. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  8886. }
  8887. }
  8888. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8889. }
  8890. CIVETWEB_API int
  8891. mg_send_file_body(struct mg_connection *conn, const char *path)
  8892. {
  8893. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8894. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8895. return -1;
  8896. }
  8897. fclose_on_exec(&file.access, conn);
  8898. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  8899. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8900. return 0; /* >= 0 for OK */
  8901. }
  8902. #endif /* NO_FILESYSTEMS */
  8903. #if !defined(NO_CACHING)
  8904. /* Return True if we should reply 304 Not Modified. */
  8905. static int
  8906. is_not_modified(const struct mg_connection *conn,
  8907. const struct mg_file_stat *filestat)
  8908. {
  8909. char etag[64];
  8910. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8911. const char *inm = mg_get_header(conn, "If-None-Match");
  8912. construct_etag(etag, sizeof(etag), filestat);
  8913. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8914. || ((ims != NULL)
  8915. && (filestat->last_modified <= parse_date_string(ims)));
  8916. }
  8917. static void
  8918. handle_not_modified_static_file_request(struct mg_connection *conn,
  8919. struct mg_file *filep)
  8920. {
  8921. char lm[64], etag[64];
  8922. if ((conn == NULL) || (filep == NULL)) {
  8923. return;
  8924. }
  8925. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8926. construct_etag(etag, sizeof(etag), &filep->stat);
  8927. /* Create 304 "not modified" response */
  8928. mg_response_header_start(conn, 304);
  8929. send_static_cache_header(conn);
  8930. send_additional_header(conn);
  8931. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8932. mg_response_header_add(conn, "Etag", etag, -1);
  8933. /* Send all headers */
  8934. mg_response_header_send(conn);
  8935. }
  8936. #endif
  8937. #if !defined(NO_FILESYSTEMS)
  8938. CIVETWEB_API void
  8939. mg_send_file(struct mg_connection *conn, const char *path)
  8940. {
  8941. mg_send_mime_file2(conn, path, NULL, NULL);
  8942. }
  8943. CIVETWEB_API void
  8944. mg_send_mime_file(struct mg_connection *conn,
  8945. const char *path,
  8946. const char *mime_type)
  8947. {
  8948. mg_send_mime_file2(conn, path, mime_type, NULL);
  8949. }
  8950. CIVETWEB_API void
  8951. mg_send_mime_file2(struct mg_connection *conn,
  8952. const char *path,
  8953. const char *mime_type,
  8954. const char *additional_headers)
  8955. {
  8956. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8957. if (!conn) {
  8958. /* No conn */
  8959. return;
  8960. }
  8961. if (mg_stat(conn, path, &file.stat)) {
  8962. #if !defined(NO_CACHING)
  8963. if (is_not_modified(conn, &file.stat)) {
  8964. /* Send 304 "Not Modified" - this must not send any body data */
  8965. handle_not_modified_static_file_request(conn, &file);
  8966. } else
  8967. #endif /* NO_CACHING */
  8968. if (file.stat.is_directory) {
  8969. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8970. "yes")) {
  8971. handle_directory_request(conn, path);
  8972. } else {
  8973. mg_send_http_error(conn,
  8974. 403,
  8975. "%s",
  8976. "Error: Directory listing denied");
  8977. }
  8978. } else {
  8979. handle_static_file_request(
  8980. conn, path, &file, mime_type, additional_headers);
  8981. }
  8982. } else {
  8983. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8984. }
  8985. }
  8986. /* For a given PUT path, create all intermediate subdirectories.
  8987. * Return 0 if the path itself is a directory.
  8988. * Return 1 if the path leads to a file.
  8989. * Return -1 for if the path is too long.
  8990. * Return -2 if path can not be created.
  8991. */
  8992. static int
  8993. put_dir(struct mg_connection *conn, const char *path)
  8994. {
  8995. char buf[UTF8_PATH_MAX];
  8996. const char *s, *p;
  8997. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8998. size_t len;
  8999. int res = 1;
  9000. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9001. len = (size_t)(p - path);
  9002. if (len >= sizeof(buf)) {
  9003. /* path too long */
  9004. res = -1;
  9005. break;
  9006. }
  9007. memcpy(buf, path, len);
  9008. buf[len] = '\0';
  9009. /* Try to create intermediate directory */
  9010. DEBUG_TRACE("mkdir(%s)", buf);
  9011. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9012. /* path does not exist and can not be created */
  9013. res = -2;
  9014. break;
  9015. }
  9016. /* Is path itself a directory? */
  9017. if (p[1] == '\0') {
  9018. res = 0;
  9019. }
  9020. }
  9021. return res;
  9022. }
  9023. static void
  9024. remove_bad_file(const struct mg_connection *conn, const char *path)
  9025. {
  9026. int r = mg_remove(conn, path);
  9027. if (r != 0) {
  9028. mg_cry_internal(conn,
  9029. "%s: Cannot remove invalid file %s",
  9030. __func__,
  9031. path);
  9032. }
  9033. }
  9034. CIVETWEB_API long long
  9035. mg_store_body(struct mg_connection *conn, const char *path)
  9036. {
  9037. char buf[MG_BUF_LEN];
  9038. long long len = 0;
  9039. int ret, n;
  9040. struct mg_file fi;
  9041. if (conn->consumed_content != 0) {
  9042. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9043. return -11;
  9044. }
  9045. ret = put_dir(conn, path);
  9046. if (ret < 0) {
  9047. /* -1 for path too long,
  9048. * -2 for path can not be created. */
  9049. return ret;
  9050. }
  9051. if (ret != 1) {
  9052. /* Return 0 means, path itself is a directory. */
  9053. return 0;
  9054. }
  9055. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9056. return -12;
  9057. }
  9058. ret = mg_read(conn, buf, sizeof(buf));
  9059. while (ret > 0) {
  9060. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9061. if (n != ret) {
  9062. (void)mg_fclose(
  9063. &fi.access); /* File is bad and will be removed anyway. */
  9064. remove_bad_file(conn, path);
  9065. return -13;
  9066. }
  9067. len += ret;
  9068. ret = mg_read(conn, buf, sizeof(buf));
  9069. }
  9070. /* File is open for writing. If fclose fails, there was probably an
  9071. * error flushing the buffer to disk, so the file on disk might be
  9072. * broken. Delete it and return an error to the caller. */
  9073. if (mg_fclose(&fi.access) != 0) {
  9074. remove_bad_file(conn, path);
  9075. return -14;
  9076. }
  9077. return len;
  9078. }
  9079. #endif /* NO_FILESYSTEMS */
  9080. /* Parse a buffer:
  9081. * Forward the string pointer till the end of a word, then
  9082. * terminate it and forward till the begin of the next word.
  9083. */
  9084. static int
  9085. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9086. {
  9087. /* Forward until a space is found - use isgraph here */
  9088. /* See http://www.cplusplus.com/reference/cctype/ */
  9089. while (isgraph((unsigned char)**ppw)) {
  9090. (*ppw)++;
  9091. }
  9092. /* Check end of word */
  9093. if (eol) {
  9094. /* must be a end of line */
  9095. if ((**ppw != '\r') && (**ppw != '\n')) {
  9096. return -1;
  9097. }
  9098. } else {
  9099. /* must be a end of a word, but not a line */
  9100. if (**ppw != ' ') {
  9101. return -1;
  9102. }
  9103. }
  9104. /* Terminate and forward to the next word */
  9105. do {
  9106. **ppw = 0;
  9107. (*ppw)++;
  9108. } while (isspace((unsigned char)**ppw));
  9109. /* Check after term */
  9110. if (!eol) {
  9111. /* if it's not the end of line, there must be a next word */
  9112. if (!isgraph((unsigned char)**ppw)) {
  9113. return -1;
  9114. }
  9115. }
  9116. /* ok */
  9117. return 1;
  9118. }
  9119. /* Parse HTTP headers from the given buffer, advance buf pointer
  9120. * to the point where parsing stopped.
  9121. * All parameters must be valid pointers (not NULL).
  9122. * Return <0 on error. */
  9123. static int
  9124. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9125. {
  9126. int i;
  9127. int num_headers = 0;
  9128. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9129. char *dp = *buf;
  9130. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9131. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9132. dp++;
  9133. }
  9134. if (dp == *buf) {
  9135. /* End of headers reached. */
  9136. break;
  9137. }
  9138. /* Drop all spaces after header name before : */
  9139. while (*dp == ' ') {
  9140. *dp = 0;
  9141. dp++;
  9142. }
  9143. if (*dp != ':') {
  9144. /* This is not a valid field. */
  9145. return -1;
  9146. }
  9147. /* End of header key (*dp == ':') */
  9148. /* Truncate here and set the key name */
  9149. *dp = 0;
  9150. hdr[i].name = *buf;
  9151. /* Skip all spaces */
  9152. do {
  9153. dp++;
  9154. } while ((*dp == ' ') || (*dp == '\t'));
  9155. /* The rest of the line is the value */
  9156. hdr[i].value = dp;
  9157. /* Find end of line */
  9158. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9159. dp++;
  9160. };
  9161. /* eliminate \r */
  9162. if (*dp == '\r') {
  9163. *dp = 0;
  9164. dp++;
  9165. if (*dp != '\n') {
  9166. /* This is not a valid line. */
  9167. return -1;
  9168. }
  9169. }
  9170. /* here *dp is either 0 or '\n' */
  9171. /* in any case, we have a new header */
  9172. num_headers = i + 1;
  9173. if (*dp) {
  9174. *dp = 0;
  9175. dp++;
  9176. *buf = dp;
  9177. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9178. /* This is the end of the header */
  9179. break;
  9180. }
  9181. } else {
  9182. *buf = dp;
  9183. break;
  9184. }
  9185. }
  9186. return num_headers;
  9187. }
  9188. struct mg_http_method_info {
  9189. const char *name;
  9190. int request_has_body;
  9191. int response_has_body;
  9192. int is_safe;
  9193. int is_idempotent;
  9194. int is_cacheable;
  9195. };
  9196. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9197. static const struct mg_http_method_info http_methods[] = {
  9198. /* HTTP (RFC 2616) */
  9199. {"GET", 0, 1, 1, 1, 1},
  9200. {"POST", 1, 1, 0, 0, 0},
  9201. {"PUT", 1, 0, 0, 1, 0},
  9202. {"DELETE", 0, 0, 0, 1, 0},
  9203. {"HEAD", 0, 0, 1, 1, 1},
  9204. {"OPTIONS", 0, 0, 1, 1, 0},
  9205. {"CONNECT", 1, 1, 0, 0, 0},
  9206. /* TRACE method (RFC 2616) is not supported for security reasons */
  9207. /* PATCH method (RFC 5789) */
  9208. {"PATCH", 1, 0, 0, 0, 0},
  9209. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9210. /* WEBDAV (RFC 2518) */
  9211. {"PROPFIND", 0, 1, 1, 1, 0},
  9212. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9213. * Some PROPFIND results MAY be cached, with care,
  9214. * as there is no cache validation mechanism for
  9215. * most properties. This method is both safe and
  9216. * idempotent (see Section 9.1 of [RFC2616]). */
  9217. {"MKCOL", 0, 0, 0, 1, 0},
  9218. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9219. * When MKCOL is invoked without a request body,
  9220. * the newly created collection SHOULD have no
  9221. * members. A MKCOL request message may contain
  9222. * a message body. The precise behavior of a MKCOL
  9223. * request when the body is present is undefined,
  9224. * ... ==> We do not support MKCOL with body data.
  9225. * This method is idempotent, but not safe (see
  9226. * Section 9.1 of [RFC2616]). Responses to this
  9227. * method MUST NOT be cached. */
  9228. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9229. {"LOCK", 1, 1, 0, 0, 0},
  9230. {"UNLOCK", 1, 0, 0, 0, 0},
  9231. {"PROPPATCH", 1, 1, 0, 0, 0},
  9232. {"COPY", 1, 0, 0, 0, 0},
  9233. {"MOVE", 1, 1, 0, 0, 0},
  9234. /* Unsupported WEBDAV Methods: */
  9235. /* + 11 methods from RFC 3253 */
  9236. /* ORDERPATCH (RFC 3648) */
  9237. /* ACL (RFC 3744) */
  9238. /* SEARCH (RFC 5323) */
  9239. /* + MicroSoft extensions
  9240. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9241. /* REPORT method (RFC 3253) */
  9242. {"REPORT", 1, 1, 1, 1, 1},
  9243. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9244. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9245. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9246. * to be useful for REST in case a "GET request with body" is
  9247. * required. */
  9248. {NULL, 0, 0, 0, 0, 0}
  9249. /* end of list */
  9250. };
  9251. /* All method names */
  9252. static char *all_methods = NULL; /* Built by mg_init_library */
  9253. static const struct mg_http_method_info *
  9254. get_http_method_info(const char *method)
  9255. {
  9256. /* Check if the method is known to the server. The list of all known
  9257. * HTTP methods can be found here at
  9258. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9259. */
  9260. const struct mg_http_method_info *m = http_methods;
  9261. while (m->name) {
  9262. if (!strcmp(m->name, method)) {
  9263. return m;
  9264. }
  9265. m++;
  9266. }
  9267. return NULL;
  9268. }
  9269. static int
  9270. is_valid_http_method(const char *method)
  9271. {
  9272. return (get_http_method_info(method) != NULL);
  9273. }
  9274. /* Parse HTTP request, fill in mg_request_info structure.
  9275. * This function modifies the buffer by NUL-terminating
  9276. * HTTP request components, header names and header values.
  9277. * Parameters:
  9278. * buf (in/out): pointer to the HTTP header to parse and split
  9279. * len (in): length of HTTP header buffer
  9280. * re (out): parsed header as mg_request_info
  9281. * buf and ri must be valid pointers (not NULL), len>0.
  9282. * Returns <0 on error. */
  9283. static int
  9284. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9285. {
  9286. int request_length;
  9287. int init_skip = 0;
  9288. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9289. * remote_port */
  9290. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9291. NULL;
  9292. ri->num_headers = 0;
  9293. /* RFC says that all initial whitespaces should be ignored */
  9294. /* This included all leading \r and \n (isspace) */
  9295. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9296. while ((len > 0) && isspace((unsigned char)*buf)) {
  9297. buf++;
  9298. len--;
  9299. init_skip++;
  9300. }
  9301. if (len == 0) {
  9302. /* Incomplete request */
  9303. return 0;
  9304. }
  9305. /* Control characters are not allowed, including zero */
  9306. if (iscntrl((unsigned char)*buf)) {
  9307. return -1;
  9308. }
  9309. /* Find end of HTTP header */
  9310. request_length = get_http_header_len(buf, len);
  9311. if (request_length <= 0) {
  9312. return request_length;
  9313. }
  9314. buf[request_length - 1] = '\0';
  9315. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9316. return -1;
  9317. }
  9318. /* The first word has to be the HTTP method */
  9319. ri->request_method = buf;
  9320. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9321. return -1;
  9322. }
  9323. /* The second word is the URI */
  9324. ri->request_uri = buf;
  9325. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9326. return -1;
  9327. }
  9328. /* Next would be the HTTP version */
  9329. ri->http_version = buf;
  9330. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9331. return -1;
  9332. }
  9333. /* Check for a valid HTTP version key */
  9334. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9335. /* Invalid request */
  9336. return -1;
  9337. }
  9338. ri->http_version += 5;
  9339. /* Check for a valid http method */
  9340. if (!is_valid_http_method(ri->request_method)) {
  9341. return -1;
  9342. }
  9343. /* Parse all HTTP headers */
  9344. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9345. if (ri->num_headers < 0) {
  9346. /* Error while parsing headers */
  9347. return -1;
  9348. }
  9349. return request_length + init_skip;
  9350. }
  9351. static int
  9352. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9353. {
  9354. int response_length;
  9355. int init_skip = 0;
  9356. char *tmp, *tmp2;
  9357. long l;
  9358. /* Initialize elements. */
  9359. ri->http_version = ri->status_text = NULL;
  9360. ri->num_headers = ri->status_code = 0;
  9361. /* RFC says that all initial whitespaces should be ignored */
  9362. /* This included all leading \r and \n (isspace) */
  9363. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9364. while ((len > 0) && isspace((unsigned char)*buf)) {
  9365. buf++;
  9366. len--;
  9367. init_skip++;
  9368. }
  9369. if (len == 0) {
  9370. /* Incomplete request */
  9371. return 0;
  9372. }
  9373. /* Control characters are not allowed, including zero */
  9374. if (iscntrl((unsigned char)*buf)) {
  9375. return -1;
  9376. }
  9377. /* Find end of HTTP header */
  9378. response_length = get_http_header_len(buf, len);
  9379. if (response_length <= 0) {
  9380. return response_length;
  9381. }
  9382. buf[response_length - 1] = '\0';
  9383. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9384. return -1;
  9385. }
  9386. /* The first word is the HTTP version */
  9387. /* Check for a valid HTTP version key */
  9388. if (strncmp(buf, "HTTP/", 5) != 0) {
  9389. /* Invalid request */
  9390. return -1;
  9391. }
  9392. buf += 5;
  9393. if (!isgraph((unsigned char)buf[0])) {
  9394. /* Invalid request */
  9395. return -1;
  9396. }
  9397. ri->http_version = buf;
  9398. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9399. return -1;
  9400. }
  9401. /* The second word is the status as a number */
  9402. tmp = buf;
  9403. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9404. return -1;
  9405. }
  9406. l = strtol(tmp, &tmp2, 10);
  9407. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9408. /* Everything else but a 3 digit code is invalid */
  9409. return -1;
  9410. }
  9411. ri->status_code = (int)l;
  9412. /* The rest of the line is the status text */
  9413. ri->status_text = buf;
  9414. /* Find end of status text */
  9415. /* isgraph or isspace = isprint */
  9416. while (isprint((unsigned char)*buf)) {
  9417. buf++;
  9418. }
  9419. if ((*buf != '\r') && (*buf != '\n')) {
  9420. return -1;
  9421. }
  9422. /* Terminate string and forward buf to next line */
  9423. do {
  9424. *buf = 0;
  9425. buf++;
  9426. } while (isspace((unsigned char)*buf));
  9427. /* Parse all HTTP headers */
  9428. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9429. if (ri->num_headers < 0) {
  9430. /* Error while parsing headers */
  9431. return -1;
  9432. }
  9433. return response_length + init_skip;
  9434. }
  9435. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9436. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9437. * buffer (which marks the end of HTTP request). Buffer buf may already
  9438. * have some data. The length of the data is stored in nread.
  9439. * Upon every read operation, increase nread by the number of bytes read. */
  9440. static int
  9441. read_message(FILE *fp,
  9442. struct mg_connection *conn,
  9443. char *buf,
  9444. int bufsiz,
  9445. int *nread)
  9446. {
  9447. int request_len, n = 0;
  9448. struct timespec last_action_time;
  9449. double request_timeout;
  9450. if (!conn) {
  9451. return 0;
  9452. }
  9453. memset(&last_action_time, 0, sizeof(last_action_time));
  9454. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9455. /* value of request_timeout is in seconds, config in milliseconds */
  9456. request_timeout =
  9457. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9458. } else {
  9459. request_timeout =
  9460. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9461. / 1000.0;
  9462. }
  9463. if (conn->handled_requests > 0) {
  9464. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9465. request_timeout =
  9466. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9467. / 1000.0;
  9468. }
  9469. }
  9470. request_len = get_http_header_len(buf, *nread);
  9471. while (request_len == 0) {
  9472. /* Full request not yet received */
  9473. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9474. /* Server is to be stopped. */
  9475. return -1;
  9476. }
  9477. if (*nread >= bufsiz) {
  9478. /* Request too long */
  9479. return -2;
  9480. }
  9481. n = pull_inner(
  9482. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9483. if (n == -2) {
  9484. /* Receive error */
  9485. return -1;
  9486. }
  9487. /* update clock after every read request */
  9488. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9489. if (n > 0) {
  9490. *nread += n;
  9491. request_len = get_http_header_len(buf, *nread);
  9492. }
  9493. if ((request_len == 0) && (request_timeout >= 0)) {
  9494. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9495. > request_timeout) {
  9496. /* Timeout */
  9497. return -1;
  9498. }
  9499. }
  9500. }
  9501. return request_len;
  9502. }
  9503. #if !defined(NO_CGI) || !defined(NO_FILES)
  9504. static int
  9505. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9506. {
  9507. const char *expect;
  9508. char buf[MG_BUF_LEN];
  9509. int success = 0;
  9510. if (!conn) {
  9511. return 0;
  9512. }
  9513. expect = mg_get_header(conn, "Expect");
  9514. DEBUG_ASSERT(fp != NULL);
  9515. if (!fp) {
  9516. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9517. return 0;
  9518. }
  9519. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9520. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9521. */
  9522. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9523. } else {
  9524. if (expect != NULL) {
  9525. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9526. conn->status_code = 100;
  9527. } else {
  9528. conn->status_code = 200;
  9529. }
  9530. DEBUG_ASSERT(conn->consumed_content == 0);
  9531. if (conn->consumed_content != 0) {
  9532. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9533. return 0;
  9534. }
  9535. for (;;) {
  9536. int nread = mg_read(conn, buf, sizeof(buf));
  9537. if (nread <= 0) {
  9538. success = (nread == 0);
  9539. break;
  9540. }
  9541. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9542. break;
  9543. }
  9544. }
  9545. /* Each error code path in this function must send an error */
  9546. if (!success) {
  9547. /* NOTE: Maybe some data has already been sent. */
  9548. /* TODO (low): If some data has been sent, a correct error
  9549. * reply can no longer be sent, so just close the connection */
  9550. mg_send_http_error(conn, 500, "%s", "");
  9551. }
  9552. }
  9553. return success;
  9554. }
  9555. #endif
  9556. #if defined(USE_TIMERS)
  9557. #define TIMER_API static
  9558. #include "timer.inl"
  9559. #endif /* USE_TIMERS */
  9560. #if !defined(NO_CGI)
  9561. /* This structure helps to create an environment for the spawned CGI
  9562. * program.
  9563. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9564. * last element must be NULL.
  9565. * However, on Windows there is a requirement that all these
  9566. * VARIABLE=VALUE\0
  9567. * strings must reside in a contiguous buffer. The end of the buffer is
  9568. * marked by two '\0' characters.
  9569. * We satisfy both worlds: we create an envp array (which is vars), all
  9570. * entries are actually pointers inside buf. */
  9571. struct cgi_environment {
  9572. struct mg_connection *conn;
  9573. /* Data block */
  9574. char *buf; /* Environment buffer */
  9575. size_t buflen; /* Space available in buf */
  9576. size_t bufused; /* Space taken in buf */
  9577. /* Index block */
  9578. char **var; /* char **envp */
  9579. size_t varlen; /* Number of variables available in var */
  9580. size_t varused; /* Number of variables stored in var */
  9581. };
  9582. static void addenv(struct cgi_environment *env,
  9583. PRINTF_FORMAT_STRING(const char *fmt),
  9584. ...) PRINTF_ARGS(2, 3);
  9585. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9586. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9587. static void
  9588. addenv(struct cgi_environment *env, const char *fmt, ...)
  9589. {
  9590. size_t i, n, space;
  9591. int truncated = 0;
  9592. char *added;
  9593. va_list ap;
  9594. if ((env->varlen - env->varused) < 2) {
  9595. mg_cry_internal(env->conn,
  9596. "%s: Cannot register CGI variable [%s]",
  9597. __func__,
  9598. fmt);
  9599. return;
  9600. }
  9601. /* Calculate how much space is left in the buffer */
  9602. space = (env->buflen - env->bufused);
  9603. do {
  9604. /* Space for "\0\0" is always needed. */
  9605. if (space <= 2) {
  9606. /* Allocate new buffer */
  9607. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9608. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9609. if (!added) {
  9610. /* Out of memory */
  9611. mg_cry_internal(
  9612. env->conn,
  9613. "%s: Cannot allocate memory for CGI variable [%s]",
  9614. __func__,
  9615. fmt);
  9616. return;
  9617. }
  9618. /* Retarget pointers */
  9619. env->buf = added;
  9620. env->buflen = n;
  9621. for (i = 0, n = 0; i < env->varused; i++) {
  9622. env->var[i] = added + n;
  9623. n += strlen(added + n) + 1;
  9624. }
  9625. space = (env->buflen - env->bufused);
  9626. }
  9627. /* Make a pointer to the free space int the buffer */
  9628. added = env->buf + env->bufused;
  9629. /* Copy VARIABLE=VALUE\0 string into the free space */
  9630. va_start(ap, fmt);
  9631. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9632. va_end(ap);
  9633. /* Do not add truncated strings to the environment */
  9634. if (truncated) {
  9635. /* Reallocate the buffer */
  9636. space = 0;
  9637. }
  9638. } while (truncated);
  9639. /* Calculate number of bytes added to the environment */
  9640. n = strlen(added) + 1;
  9641. env->bufused += n;
  9642. /* Append a pointer to the added string into the envp array */
  9643. env->var[env->varused] = added;
  9644. env->varused++;
  9645. }
  9646. /* Return 0 on success, non-zero if an error occurs. */
  9647. static int
  9648. prepare_cgi_environment(struct mg_connection *conn,
  9649. const char *prog,
  9650. struct cgi_environment *env,
  9651. unsigned char cgi_config_idx)
  9652. {
  9653. const char *s;
  9654. struct vec var_vec;
  9655. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9656. int i, truncated, uri_len;
  9657. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9658. return -1;
  9659. }
  9660. env->conn = conn;
  9661. env->buflen = CGI_ENVIRONMENT_SIZE;
  9662. env->bufused = 0;
  9663. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9664. if (env->buf == NULL) {
  9665. mg_cry_internal(conn,
  9666. "%s: Not enough memory for environmental buffer",
  9667. __func__);
  9668. return -1;
  9669. }
  9670. env->varlen = MAX_CGI_ENVIR_VARS;
  9671. env->varused = 0;
  9672. env->var =
  9673. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9674. if (env->var == NULL) {
  9675. mg_cry_internal(conn,
  9676. "%s: Not enough memory for environmental variables",
  9677. __func__);
  9678. mg_free(env->buf);
  9679. return -1;
  9680. }
  9681. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9682. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9683. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9684. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9685. /* Prepare the environment block */
  9686. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9687. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9688. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9689. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9690. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9691. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9692. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9693. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9694. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9695. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9696. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9697. /* SCRIPT_NAME */
  9698. uri_len = (int)strlen(conn->request_info.local_uri);
  9699. if (conn->path_info == NULL) {
  9700. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9701. /* URI: /path_to_script/script.cgi */
  9702. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9703. } else {
  9704. /* URI: /path_to_script/ ... using index.cgi */
  9705. const char *index_file = strrchr(prog, '/');
  9706. if (index_file) {
  9707. addenv(env,
  9708. "SCRIPT_NAME=%s%s",
  9709. conn->request_info.local_uri,
  9710. index_file + 1);
  9711. }
  9712. }
  9713. } else {
  9714. /* URI: /path_to_script/script.cgi/path_info */
  9715. addenv(env,
  9716. "SCRIPT_NAME=%.*s",
  9717. uri_len - (int)strlen(conn->path_info),
  9718. conn->request_info.local_uri);
  9719. }
  9720. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9721. if (conn->path_info == NULL) {
  9722. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9723. } else {
  9724. addenv(env,
  9725. "PATH_TRANSLATED=%s%s",
  9726. conn->dom_ctx->config[DOCUMENT_ROOT],
  9727. conn->path_info);
  9728. }
  9729. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9730. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9731. addenv(env, "CONTENT_TYPE=%s", s);
  9732. }
  9733. if (conn->request_info.query_string != NULL) {
  9734. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9735. }
  9736. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9737. addenv(env, "CONTENT_LENGTH=%s", s);
  9738. }
  9739. if ((s = getenv("PATH")) != NULL) {
  9740. addenv(env, "PATH=%s", s);
  9741. }
  9742. if (conn->path_info != NULL) {
  9743. addenv(env, "PATH_INFO=%s", conn->path_info);
  9744. }
  9745. if (conn->status_code > 0) {
  9746. /* CGI error handler should show the status code */
  9747. addenv(env, "STATUS=%d", conn->status_code);
  9748. }
  9749. #if defined(_WIN32)
  9750. if ((s = getenv("COMSPEC")) != NULL) {
  9751. addenv(env, "COMSPEC=%s", s);
  9752. }
  9753. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9754. addenv(env, "SYSTEMROOT=%s", s);
  9755. }
  9756. if ((s = getenv("SystemDrive")) != NULL) {
  9757. addenv(env, "SystemDrive=%s", s);
  9758. }
  9759. if ((s = getenv("ProgramFiles")) != NULL) {
  9760. addenv(env, "ProgramFiles=%s", s);
  9761. }
  9762. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9763. addenv(env, "ProgramFiles(x86)=%s", s);
  9764. }
  9765. #else
  9766. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9767. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9768. }
  9769. #endif /* _WIN32 */
  9770. if ((s = getenv("PERLLIB")) != NULL) {
  9771. addenv(env, "PERLLIB=%s", s);
  9772. }
  9773. if (conn->request_info.remote_user != NULL) {
  9774. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9775. addenv(env, "%s", "AUTH_TYPE=Digest");
  9776. }
  9777. /* Add all headers as HTTP_* variables */
  9778. for (i = 0; i < conn->request_info.num_headers; i++) {
  9779. (void)mg_snprintf(conn,
  9780. &truncated,
  9781. http_var_name,
  9782. sizeof(http_var_name),
  9783. "HTTP_%s",
  9784. conn->request_info.http_headers[i].name);
  9785. if (truncated) {
  9786. mg_cry_internal(conn,
  9787. "%s: HTTP header variable too long [%s]",
  9788. __func__,
  9789. conn->request_info.http_headers[i].name);
  9790. continue;
  9791. }
  9792. /* Convert variable name into uppercase, and change - to _ */
  9793. for (p = http_var_name; *p != '\0'; p++) {
  9794. if (*p == '-') {
  9795. *p = '_';
  9796. }
  9797. *p = (char)toupper((unsigned char)*p);
  9798. }
  9799. addenv(env,
  9800. "%s=%s",
  9801. http_var_name,
  9802. conn->request_info.http_headers[i].value);
  9803. }
  9804. /* Add user-specified variables */
  9805. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9806. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9807. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9808. }
  9809. env->var[env->varused] = NULL;
  9810. env->buf[env->bufused] = '\0';
  9811. return 0;
  9812. }
  9813. /* Data for CGI process control: PID and number of references */
  9814. struct process_control_data {
  9815. pid_t pid;
  9816. ptrdiff_t references;
  9817. };
  9818. static int
  9819. abort_cgi_process(void *data)
  9820. {
  9821. /* Waitpid checks for child status and won't work for a pid that does
  9822. * not identify a child of the current process. Thus, if the pid is
  9823. * reused, we will not affect a different process. */
  9824. struct process_control_data *proc = (struct process_control_data *)data;
  9825. int status = 0;
  9826. ptrdiff_t refs;
  9827. pid_t ret_pid;
  9828. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9829. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9830. /* Stop child process */
  9831. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9832. kill(proc->pid, SIGABRT);
  9833. /* Wait until process is terminated (don't leave zombies) */
  9834. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9835. ;
  9836. } else {
  9837. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9838. }
  9839. /* Dec reference counter */
  9840. refs = mg_atomic_dec(&proc->references);
  9841. if (refs == 0) {
  9842. /* no more references - free data */
  9843. mg_free(data);
  9844. }
  9845. return 0;
  9846. }
  9847. /* Local (static) function assumes all arguments are valid. */
  9848. static void
  9849. handle_cgi_request(struct mg_connection *conn,
  9850. const char *prog,
  9851. unsigned char cgi_config_idx)
  9852. {
  9853. char *buf;
  9854. size_t buflen;
  9855. int headers_len, data_len, i, truncated;
  9856. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9857. const char *status, *status_text;
  9858. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9859. struct mg_request_info ri;
  9860. struct cgi_environment blk;
  9861. FILE *in = NULL, *out = NULL, *err = NULL;
  9862. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9863. pid_t pid = (pid_t)-1;
  9864. struct process_control_data *proc = NULL;
  9865. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  9866. int no_buffering = 0;
  9867. #if defined(USE_TIMERS)
  9868. double cgi_timeout;
  9869. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9870. /* Get timeout in seconds */
  9871. cgi_timeout =
  9872. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9873. } else {
  9874. cgi_timeout =
  9875. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9876. }
  9877. #endif
  9878. if (cfg_buffering != NULL) {
  9879. if (!mg_strcasecmp(cfg_buffering, "no")) {
  9880. no_buffering = 1;
  9881. }
  9882. }
  9883. buf = NULL;
  9884. buflen = conn->phys_ctx->max_request_size;
  9885. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9886. if (i != 0) {
  9887. blk.buf = NULL;
  9888. blk.var = NULL;
  9889. goto done;
  9890. }
  9891. /* CGI must be executed in its own directory. 'dir' must point to the
  9892. * directory containing executable program, 'p' must point to the
  9893. * executable program name relative to 'dir'. */
  9894. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9895. if (truncated) {
  9896. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9897. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9898. goto done;
  9899. }
  9900. if ((p = strrchr(dir, '/')) != NULL) {
  9901. *p++ = '\0';
  9902. } else {
  9903. dir[0] = '.';
  9904. dir[1] = '\0';
  9905. p = (char *)prog;
  9906. }
  9907. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9908. status = strerror(ERRNO);
  9909. mg_cry_internal(
  9910. conn,
  9911. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9912. prog,
  9913. status);
  9914. mg_send_http_error(conn,
  9915. 500,
  9916. "Error: Cannot create CGI pipe: %s",
  9917. status);
  9918. goto done;
  9919. }
  9920. proc = (struct process_control_data *)
  9921. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9922. if (proc == NULL) {
  9923. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9924. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9925. goto done;
  9926. }
  9927. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9928. pid = spawn_process(
  9929. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9930. if (pid == (pid_t)-1) {
  9931. status = strerror(ERRNO);
  9932. mg_cry_internal(
  9933. conn,
  9934. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9935. prog,
  9936. status);
  9937. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9938. mg_free(proc);
  9939. proc = NULL;
  9940. goto done;
  9941. }
  9942. /* Store data in shared process_control_data */
  9943. proc->pid = pid;
  9944. proc->references = 1;
  9945. #if defined(USE_TIMERS)
  9946. if (cgi_timeout > 0.0) {
  9947. proc->references = 2;
  9948. // Start a timer for CGI
  9949. timer_add(conn->phys_ctx,
  9950. cgi_timeout /* in seconds */,
  9951. 0.0,
  9952. 1,
  9953. abort_cgi_process,
  9954. (void *)proc,
  9955. NULL);
  9956. }
  9957. #endif
  9958. /* Parent closes only one side of the pipes.
  9959. * If we don't mark them as closed, close() attempt before
  9960. * return from this function throws an exception on Windows.
  9961. * Windows does not like when closed descriptor is closed again. */
  9962. (void)close(fdin[0]);
  9963. (void)close(fdout[1]);
  9964. (void)close(fderr[1]);
  9965. fdin[0] = fdout[1] = fderr[1] = -1;
  9966. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9967. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9968. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9969. status = strerror(ERRNO);
  9970. mg_cry_internal(conn,
  9971. "Error: CGI program \"%s\": Can not open fd: %s",
  9972. prog,
  9973. status);
  9974. mg_send_http_error(conn,
  9975. 500,
  9976. "Error: CGI can not open fd\nfdopen: %s",
  9977. status);
  9978. goto done;
  9979. }
  9980. setbuf(in, NULL);
  9981. setbuf(out, NULL);
  9982. setbuf(err, NULL);
  9983. fout.access.fp = out;
  9984. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9985. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9986. conn->content_len);
  9987. /* This is a POST/PUT request, or another request with body data. */
  9988. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9989. /* Error sending the body data */
  9990. mg_cry_internal(
  9991. conn,
  9992. "Error: CGI program \"%s\": Forward body data failed",
  9993. prog);
  9994. goto done;
  9995. }
  9996. }
  9997. /* Close so child gets an EOF. */
  9998. fclose(in);
  9999. in = NULL;
  10000. fdin[1] = -1;
  10001. /* Now read CGI reply into a buffer. We need to set correct
  10002. * status code, thus we need to see all HTTP headers first.
  10003. * Do not send anything back to client, until we buffer in all
  10004. * HTTP headers. */
  10005. data_len = 0;
  10006. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10007. if (buf == NULL) {
  10008. mg_send_http_error(conn,
  10009. 500,
  10010. "Error: Not enough memory for CGI buffer (%u bytes)",
  10011. (unsigned int)buflen);
  10012. mg_cry_internal(
  10013. conn,
  10014. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10015. "bytes)",
  10016. prog,
  10017. (unsigned int)buflen);
  10018. goto done;
  10019. }
  10020. DEBUG_TRACE("CGI: %s", "wait for response");
  10021. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10022. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10023. if (headers_len <= 0) {
  10024. /* Could not parse the CGI response. Check if some error message on
  10025. * stderr. */
  10026. i = pull_all(err, conn, buf, (int)buflen);
  10027. if (i > 0) {
  10028. /* CGI program explicitly sent an error */
  10029. /* Write the error message to the internal log */
  10030. mg_cry_internal(conn,
  10031. "Error: CGI program \"%s\" sent error "
  10032. "message: [%.*s]",
  10033. prog,
  10034. i,
  10035. buf);
  10036. /* Don't send the error message back to the client */
  10037. mg_send_http_error(conn,
  10038. 500,
  10039. "Error: CGI program \"%s\" failed.",
  10040. prog);
  10041. } else {
  10042. /* CGI program did not explicitly send an error, but a broken
  10043. * respon header */
  10044. mg_cry_internal(conn,
  10045. "Error: CGI program sent malformed or too big "
  10046. "(>%u bytes) HTTP headers: [%.*s]",
  10047. (unsigned)buflen,
  10048. data_len,
  10049. buf);
  10050. mg_send_http_error(conn,
  10051. 500,
  10052. "Error: CGI program sent malformed or too big "
  10053. "(>%u bytes) HTTP headers: [%.*s]",
  10054. (unsigned)buflen,
  10055. data_len,
  10056. buf);
  10057. }
  10058. /* in both cases, abort processing CGI */
  10059. goto done;
  10060. }
  10061. pbuf = buf;
  10062. buf[headers_len - 1] = '\0';
  10063. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10064. /* Make up and send the status line */
  10065. status_text = "OK";
  10066. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10067. != NULL) {
  10068. conn->status_code = atoi(status);
  10069. status_text = status;
  10070. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10071. status_text++;
  10072. }
  10073. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10074. != NULL) {
  10075. conn->status_code = 307;
  10076. } else {
  10077. conn->status_code = 200;
  10078. }
  10079. if (!should_keep_alive(conn)) {
  10080. conn->must_close = 1;
  10081. }
  10082. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10083. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10084. /* Send headers */
  10085. for (i = 0; i < ri.num_headers; i++) {
  10086. DEBUG_TRACE("CGI header: %s: %s",
  10087. ri.http_headers[i].name,
  10088. ri.http_headers[i].value);
  10089. mg_printf(conn,
  10090. "%s: %s\r\n",
  10091. ri.http_headers[i].name,
  10092. ri.http_headers[i].value);
  10093. }
  10094. mg_write(conn, "\r\n", 2);
  10095. /* Send chunk of data that may have been read after the headers */
  10096. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10097. /* Read the rest of CGI output and send to the client */
  10098. DEBUG_TRACE("CGI: %s", "forward all data");
  10099. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10100. DEBUG_TRACE("CGI: %s", "all data sent");
  10101. done:
  10102. mg_free(blk.var);
  10103. mg_free(blk.buf);
  10104. if (pid != (pid_t)-1) {
  10105. abort_cgi_process((void *)proc);
  10106. }
  10107. if (fdin[0] != -1) {
  10108. close(fdin[0]);
  10109. }
  10110. if (fdout[1] != -1) {
  10111. close(fdout[1]);
  10112. }
  10113. if (fderr[1] != -1) {
  10114. close(fderr[1]);
  10115. }
  10116. if (in != NULL) {
  10117. fclose(in);
  10118. } else if (fdin[1] != -1) {
  10119. close(fdin[1]);
  10120. }
  10121. if (out != NULL) {
  10122. fclose(out);
  10123. } else if (fdout[0] != -1) {
  10124. close(fdout[0]);
  10125. }
  10126. if (err != NULL) {
  10127. fclose(err);
  10128. } else if (fderr[0] != -1) {
  10129. close(fderr[0]);
  10130. }
  10131. mg_free(buf);
  10132. }
  10133. #endif /* !NO_CGI */
  10134. #if !defined(NO_FILES)
  10135. static void
  10136. dav_mkcol(struct mg_connection *conn, const char *path)
  10137. {
  10138. int rc, body_len;
  10139. struct de de;
  10140. if (conn == NULL) {
  10141. return;
  10142. }
  10143. /* TODO (mid): Check the mg_send_http_error situations in this function
  10144. */
  10145. memset(&de.file, 0, sizeof(de.file));
  10146. if (!mg_stat(conn, path, &de.file)) {
  10147. mg_cry_internal(conn,
  10148. "%s: mg_stat(%s) failed: %s",
  10149. __func__,
  10150. path,
  10151. strerror(ERRNO));
  10152. }
  10153. if (de.file.last_modified) {
  10154. /* TODO (mid): This check does not seem to make any sense ! */
  10155. /* TODO (mid): Add a webdav unit test first, before changing
  10156. * anything here. */
  10157. mg_send_http_error(
  10158. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10159. return;
  10160. }
  10161. body_len = conn->data_len - conn->request_len;
  10162. if (body_len > 0) {
  10163. mg_send_http_error(
  10164. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10165. return;
  10166. }
  10167. rc = mg_mkdir(conn, path, 0755);
  10168. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10169. if (rc == 0) {
  10170. /* Create 201 "Created" response */
  10171. mg_response_header_start(conn, 201);
  10172. send_static_cache_header(conn);
  10173. send_additional_header(conn);
  10174. mg_response_header_add(conn, "Content-Length", "0", -1);
  10175. /* Send all headers - there is no body */
  10176. mg_response_header_send(conn);
  10177. } else {
  10178. int http_status = 500;
  10179. switch (errno) {
  10180. case EEXIST:
  10181. http_status = 405;
  10182. break;
  10183. case EACCES:
  10184. http_status = 403;
  10185. break;
  10186. case ENOENT:
  10187. http_status = 409;
  10188. break;
  10189. }
  10190. mg_send_http_error(conn,
  10191. http_status,
  10192. "Error processing %s: %s",
  10193. path,
  10194. strerror(ERRNO));
  10195. }
  10196. }
  10197. /* Forward decrlaration */
  10198. static int get_uri_type(const char *uri);
  10199. static const char *
  10200. get_rel_url_at_current_server(const char *uri,
  10201. const struct mg_connection *conn);
  10202. static void
  10203. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10204. {
  10205. const char *overwrite_hdr;
  10206. const char *destination_hdr;
  10207. const char *root;
  10208. int rc, dest_uri_type;
  10209. int http_status = 400;
  10210. int do_overwrite = 0;
  10211. int destination_ok = 0;
  10212. char dest_path[UTF8_PATH_MAX];
  10213. struct mg_file_stat ignored;
  10214. if (conn == NULL) {
  10215. return;
  10216. }
  10217. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10218. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10219. destination_hdr = mg_get_header(conn, "Destination");
  10220. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10221. do_overwrite = 1;
  10222. }
  10223. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10224. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10225. return;
  10226. }
  10227. if (root != NULL) {
  10228. char *local_dest = NULL;
  10229. dest_uri_type = get_uri_type(destination_hdr);
  10230. if (dest_uri_type == 2) {
  10231. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10232. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10233. const char *h =
  10234. get_rel_url_at_current_server(destination_hdr, conn);
  10235. if (h) {
  10236. int len = (int)strlen(h);
  10237. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10238. mg_url_decode(h, len, local_dest, len + 1, 0);
  10239. }
  10240. }
  10241. if (local_dest != NULL) {
  10242. remove_dot_segments(local_dest);
  10243. if (local_dest[0] == '/') {
  10244. int trunc_check = 0;
  10245. mg_snprintf(conn,
  10246. &trunc_check,
  10247. dest_path,
  10248. sizeof(dest_path),
  10249. "%s/%s",
  10250. root,
  10251. local_dest);
  10252. if (trunc_check == 0) {
  10253. destination_ok = 1;
  10254. }
  10255. }
  10256. mg_free(local_dest);
  10257. }
  10258. }
  10259. if (!destination_ok) {
  10260. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10261. return;
  10262. }
  10263. /* Check now if this file exists */
  10264. if (mg_stat(conn, dest_path, &ignored)) {
  10265. /* File exists */
  10266. if (do_overwrite) {
  10267. /* Overwrite allowed: delete the file first */
  10268. if (0 != remove(dest_path)) {
  10269. /* No overwrite: return error */
  10270. mg_send_http_error(conn,
  10271. 403,
  10272. "Cannot overwrite file: %s",
  10273. dest_path);
  10274. return;
  10275. }
  10276. } else {
  10277. /* No overwrite: return error */
  10278. mg_send_http_error(conn,
  10279. 412,
  10280. "Destination already exists: %s",
  10281. dest_path);
  10282. return;
  10283. }
  10284. }
  10285. /* Copy / Move / Rename operation. */
  10286. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10287. #if defined(_WIN32)
  10288. {
  10289. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10290. wchar_t wSource[UTF16_PATH_MAX];
  10291. wchar_t wDest[UTF16_PATH_MAX];
  10292. BOOL ok;
  10293. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10294. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10295. if (do_copy) {
  10296. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10297. } else {
  10298. ok = MoveFileExW(wSource,
  10299. wDest,
  10300. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10301. }
  10302. if (ok) {
  10303. rc = 0;
  10304. } else {
  10305. DWORD lastErr = GetLastError();
  10306. if (lastErr == ERROR_ALREADY_EXISTS) {
  10307. mg_send_http_error(conn,
  10308. 412,
  10309. "Destination already exists: %s",
  10310. dest_path);
  10311. return;
  10312. }
  10313. rc = -1;
  10314. http_status = 400;
  10315. }
  10316. }
  10317. #else
  10318. {
  10319. /* Linux uses already UTF-8, we don't need to convert file names. */
  10320. if (do_copy) {
  10321. /* TODO: COPY for Linux. */
  10322. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10323. return;
  10324. }
  10325. rc = rename(path, dest_path);
  10326. if (rc) {
  10327. switch (errno) {
  10328. case EEXIST:
  10329. http_status = 412;
  10330. break;
  10331. case EACCES:
  10332. http_status = 403;
  10333. break;
  10334. case ENOENT:
  10335. http_status = 409;
  10336. break;
  10337. }
  10338. }
  10339. }
  10340. #endif
  10341. if (rc == 0) {
  10342. /* Create 204 "No Content" response */
  10343. mg_response_header_start(conn, 204);
  10344. mg_response_header_add(conn, "Content-Length", "0", -1);
  10345. /* Send all headers - there is no body */
  10346. mg_response_header_send(conn);
  10347. } else {
  10348. mg_send_http_error(conn, http_status, "Operation failed");
  10349. }
  10350. }
  10351. static void
  10352. put_file(struct mg_connection *conn, const char *path)
  10353. {
  10354. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10355. const char *range;
  10356. int64_t r1, r2;
  10357. int rc;
  10358. if (conn == NULL) {
  10359. return;
  10360. }
  10361. DEBUG_TRACE("store %s", path);
  10362. if (mg_stat(conn, path, &file.stat)) {
  10363. /* File already exists */
  10364. conn->status_code = 200;
  10365. if (file.stat.is_directory) {
  10366. /* This is an already existing directory,
  10367. * so there is nothing to do for the server. */
  10368. rc = 0;
  10369. } else {
  10370. /* File exists and is not a directory. */
  10371. /* Can it be replaced? */
  10372. /* Check if the server may write this file */
  10373. if (access(path, W_OK) == 0) {
  10374. /* Access granted */
  10375. rc = 1;
  10376. } else {
  10377. mg_send_http_error(
  10378. conn,
  10379. 403,
  10380. "Error: Put not possible\nReplacing %s is not allowed",
  10381. path);
  10382. return;
  10383. }
  10384. }
  10385. } else {
  10386. /* File should be created */
  10387. conn->status_code = 201;
  10388. rc = put_dir(conn, path);
  10389. }
  10390. if (rc == 0) {
  10391. /* put_dir returns 0 if path is a directory */
  10392. /* Create response */
  10393. mg_response_header_start(conn, conn->status_code);
  10394. send_no_cache_header(conn);
  10395. send_additional_header(conn);
  10396. mg_response_header_add(conn, "Content-Length", "0", -1);
  10397. /* Send all headers - there is no body */
  10398. mg_response_header_send(conn);
  10399. /* Request to create a directory has been fulfilled successfully.
  10400. * No need to put a file. */
  10401. return;
  10402. }
  10403. if (rc == -1) {
  10404. /* put_dir returns -1 if the path is too long */
  10405. mg_send_http_error(conn,
  10406. 414,
  10407. "Error: Path too long\nput_dir(%s): %s",
  10408. path,
  10409. strerror(ERRNO));
  10410. return;
  10411. }
  10412. if (rc == -2) {
  10413. /* put_dir returns -2 if the directory can not be created */
  10414. mg_send_http_error(conn,
  10415. 500,
  10416. "Error: Can not create directory\nput_dir(%s): %s",
  10417. path,
  10418. strerror(ERRNO));
  10419. return;
  10420. }
  10421. /* A file should be created or overwritten. */
  10422. /* Currently CivetWeb does not need read+write access. */
  10423. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10424. || file.access.fp == NULL) {
  10425. (void)mg_fclose(&file.access);
  10426. mg_send_http_error(conn,
  10427. 500,
  10428. "Error: Can not create file\nfopen(%s): %s",
  10429. path,
  10430. strerror(ERRNO));
  10431. return;
  10432. }
  10433. fclose_on_exec(&file.access, conn);
  10434. range = mg_get_header(conn, "Content-Range");
  10435. r1 = r2 = 0;
  10436. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10437. conn->status_code = 206; /* Partial content */
  10438. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10439. mg_send_http_error(conn,
  10440. 500,
  10441. "Error: Internal error processing file %s",
  10442. path);
  10443. return;
  10444. }
  10445. }
  10446. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10447. /* forward_body_data failed.
  10448. * The error code has already been sent to the client,
  10449. * and conn->status_code is already set. */
  10450. (void)mg_fclose(&file.access);
  10451. return;
  10452. }
  10453. if (mg_fclose(&file.access) != 0) {
  10454. /* fclose failed. This might have different reasons, but a likely
  10455. * one is "no space on disk", http 507. */
  10456. conn->status_code = 507;
  10457. }
  10458. /* Create response (status_code has been set before) */
  10459. mg_response_header_start(conn, conn->status_code);
  10460. send_no_cache_header(conn);
  10461. send_additional_header(conn);
  10462. mg_response_header_add(conn, "Content-Length", "0", -1);
  10463. /* Send all headers - there is no body */
  10464. mg_response_header_send(conn);
  10465. }
  10466. static void
  10467. delete_file(struct mg_connection *conn, const char *path)
  10468. {
  10469. struct de de;
  10470. memset(&de.file, 0, sizeof(de.file));
  10471. if (!mg_stat(conn, path, &de.file)) {
  10472. /* mg_stat returns 0 if the file does not exist */
  10473. mg_send_http_error(conn,
  10474. 404,
  10475. "Error: Cannot delete file\nFile %s not found",
  10476. path);
  10477. return;
  10478. }
  10479. DEBUG_TRACE("delete %s", path);
  10480. if (de.file.is_directory) {
  10481. if (remove_directory(conn, path)) {
  10482. /* Delete is successful: Return 204 without content. */
  10483. mg_send_http_error(conn, 204, "%s", "");
  10484. } else {
  10485. /* Delete is not successful: Return 500 (Server error). */
  10486. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10487. }
  10488. return;
  10489. }
  10490. /* This is an existing file (not a directory).
  10491. * Check if write permission is granted. */
  10492. if (access(path, W_OK) != 0) {
  10493. /* File is read only */
  10494. mg_send_http_error(
  10495. conn,
  10496. 403,
  10497. "Error: Delete not possible\nDeleting %s is not allowed",
  10498. path);
  10499. return;
  10500. }
  10501. /* Try to delete it. */
  10502. if (mg_remove(conn, path) == 0) {
  10503. /* Delete was successful: Return 204 without content. */
  10504. mg_response_header_start(conn, 204);
  10505. send_no_cache_header(conn);
  10506. send_additional_header(conn);
  10507. mg_response_header_add(conn, "Content-Length", "0", -1);
  10508. mg_response_header_send(conn);
  10509. } else {
  10510. /* Delete not successful (file locked). */
  10511. mg_send_http_error(conn,
  10512. 423,
  10513. "Error: Cannot delete file\nremove(%s): %s",
  10514. path,
  10515. strerror(ERRNO));
  10516. }
  10517. }
  10518. #endif /* !NO_FILES */
  10519. #if !defined(NO_FILESYSTEMS)
  10520. static void
  10521. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10522. static void
  10523. do_ssi_include(struct mg_connection *conn,
  10524. const char *ssi,
  10525. char *tag,
  10526. int include_level)
  10527. {
  10528. char file_name[MG_BUF_LEN], path[512], *p;
  10529. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10530. size_t len;
  10531. int truncated = 0;
  10532. if (conn == NULL) {
  10533. return;
  10534. }
  10535. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10536. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10537. * always < MG_BUF_LEN. */
  10538. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10539. /* File name is relative to the webserver root */
  10540. file_name[511] = 0;
  10541. (void)mg_snprintf(conn,
  10542. &truncated,
  10543. path,
  10544. sizeof(path),
  10545. "%s/%s",
  10546. conn->dom_ctx->config[DOCUMENT_ROOT],
  10547. file_name);
  10548. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10549. /* File name is relative to the webserver working directory
  10550. * or it is absolute system path */
  10551. file_name[511] = 0;
  10552. (void)
  10553. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10554. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10555. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10556. /* File name is relative to the current document */
  10557. file_name[511] = 0;
  10558. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10559. if (!truncated) {
  10560. if ((p = strrchr(path, '/')) != NULL) {
  10561. p[1] = '\0';
  10562. }
  10563. len = strlen(path);
  10564. (void)mg_snprintf(conn,
  10565. &truncated,
  10566. path + len,
  10567. sizeof(path) - len,
  10568. "%s",
  10569. file_name);
  10570. }
  10571. } else {
  10572. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10573. return;
  10574. }
  10575. if (truncated) {
  10576. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10577. return;
  10578. }
  10579. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10580. mg_cry_internal(conn,
  10581. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10582. tag,
  10583. path,
  10584. strerror(ERRNO));
  10585. } else {
  10586. fclose_on_exec(&file.access, conn);
  10587. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10588. > 0) {
  10589. send_ssi_file(conn, path, &file, include_level + 1);
  10590. } else {
  10591. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10592. }
  10593. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10594. }
  10595. }
  10596. #if !defined(NO_POPEN)
  10597. static void
  10598. do_ssi_exec(struct mg_connection *conn, char *tag)
  10599. {
  10600. char cmd[1024] = "";
  10601. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10602. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10603. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10604. } else {
  10605. cmd[1023] = 0;
  10606. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10607. mg_cry_internal(conn,
  10608. "Cannot SSI #exec: [%s]: %s",
  10609. cmd,
  10610. strerror(ERRNO));
  10611. } else {
  10612. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10613. pclose(file.access.fp);
  10614. }
  10615. }
  10616. }
  10617. #endif /* !NO_POPEN */
  10618. static int
  10619. mg_fgetc(struct mg_file *filep)
  10620. {
  10621. if (filep == NULL) {
  10622. return EOF;
  10623. }
  10624. if (filep->access.fp != NULL) {
  10625. return fgetc(filep->access.fp);
  10626. } else {
  10627. return EOF;
  10628. }
  10629. }
  10630. static void
  10631. send_ssi_file(struct mg_connection *conn,
  10632. const char *path,
  10633. struct mg_file *filep,
  10634. int include_level)
  10635. {
  10636. char buf[MG_BUF_LEN];
  10637. int ch, len, in_tag, in_ssi_tag;
  10638. if (include_level > 10) {
  10639. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10640. return;
  10641. }
  10642. in_tag = in_ssi_tag = len = 0;
  10643. /* Read file, byte by byte, and look for SSI include tags */
  10644. while ((ch = mg_fgetc(filep)) != EOF) {
  10645. if (in_tag) {
  10646. /* We are in a tag, either SSI tag or html tag */
  10647. if (ch == '>') {
  10648. /* Tag is closing */
  10649. buf[len++] = '>';
  10650. if (in_ssi_tag) {
  10651. /* Handle SSI tag */
  10652. buf[len] = 0;
  10653. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10654. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10655. #if !defined(NO_POPEN)
  10656. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10657. do_ssi_exec(conn, buf + 9);
  10658. #endif /* !NO_POPEN */
  10659. } else {
  10660. mg_cry_internal(conn,
  10661. "%s: unknown SSI "
  10662. "command: \"%s\"",
  10663. path,
  10664. buf);
  10665. }
  10666. len = 0;
  10667. in_ssi_tag = in_tag = 0;
  10668. } else {
  10669. /* Not an SSI tag */
  10670. /* Flush buffer */
  10671. (void)mg_write(conn, buf, (size_t)len);
  10672. len = 0;
  10673. in_tag = 0;
  10674. }
  10675. } else {
  10676. /* Tag is still open */
  10677. buf[len++] = (char)(ch & 0xff);
  10678. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10679. /* All SSI tags start with <!--# */
  10680. in_ssi_tag = 1;
  10681. }
  10682. if ((len + 2) > (int)sizeof(buf)) {
  10683. /* Tag to long for buffer */
  10684. mg_cry_internal(conn, "%s: tag is too large", path);
  10685. return;
  10686. }
  10687. }
  10688. } else {
  10689. /* We are not in a tag yet. */
  10690. if (ch == '<') {
  10691. /* Tag is opening */
  10692. in_tag = 1;
  10693. if (len > 0) {
  10694. /* Flush current buffer.
  10695. * Buffer is filled with "len" bytes. */
  10696. (void)mg_write(conn, buf, (size_t)len);
  10697. }
  10698. /* Store the < */
  10699. len = 1;
  10700. buf[0] = '<';
  10701. } else {
  10702. /* No Tag */
  10703. /* Add data to buffer */
  10704. buf[len++] = (char)(ch & 0xff);
  10705. /* Flush if buffer is full */
  10706. if (len == (int)sizeof(buf)) {
  10707. mg_write(conn, buf, (size_t)len);
  10708. len = 0;
  10709. }
  10710. }
  10711. }
  10712. }
  10713. /* Send the rest of buffered data */
  10714. if (len > 0) {
  10715. mg_write(conn, buf, (size_t)len);
  10716. }
  10717. }
  10718. static void
  10719. handle_ssi_file_request(struct mg_connection *conn,
  10720. const char *path,
  10721. struct mg_file *filep)
  10722. {
  10723. char date[64];
  10724. time_t curtime = time(NULL);
  10725. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10726. return;
  10727. }
  10728. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10729. /* File exists (precondition for calling this function),
  10730. * but can not be opened by the server. */
  10731. mg_send_http_error(conn,
  10732. 500,
  10733. "Error: Cannot read file\nfopen(%s): %s",
  10734. path,
  10735. strerror(ERRNO));
  10736. } else {
  10737. /* Set "must_close" for HTTP/1.x, since we do not know the
  10738. * content length */
  10739. conn->must_close = 1;
  10740. gmt_time_string(date, sizeof(date), &curtime);
  10741. fclose_on_exec(&filep->access, conn);
  10742. /* 200 OK response */
  10743. mg_response_header_start(conn, 200);
  10744. send_no_cache_header(conn);
  10745. send_additional_header(conn);
  10746. send_cors_header(conn);
  10747. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10748. mg_response_header_send(conn);
  10749. /* Header sent, now send body */
  10750. send_ssi_file(conn, path, filep, 0);
  10751. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10752. }
  10753. }
  10754. #endif /* NO_FILESYSTEMS */
  10755. #if !defined(NO_FILES)
  10756. static void
  10757. send_options(struct mg_connection *conn)
  10758. {
  10759. if (!conn || !all_methods) {
  10760. return;
  10761. }
  10762. /* We do not set a "Cache-Control" header here, but leave the default.
  10763. * Since browsers do not send an OPTIONS request, we can not test the
  10764. * effect anyway. */
  10765. mg_response_header_start(conn, 200);
  10766. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10767. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10768. /* Use the same as before */
  10769. mg_response_header_add(conn, "Allow", all_methods, -1);
  10770. mg_response_header_add(conn, "DAV", "1", -1);
  10771. } else {
  10772. /* TODO: Check this later for HTTP/2 */
  10773. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10774. }
  10775. send_additional_header(conn);
  10776. mg_response_header_send(conn);
  10777. }
  10778. /* Writes PROPFIND properties for a collection element */
  10779. static int
  10780. print_props(struct mg_connection *conn,
  10781. const char *uri,
  10782. const char *name,
  10783. struct mg_file_stat *filep)
  10784. {
  10785. size_t i;
  10786. char mtime[64];
  10787. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10788. char *link_concat;
  10789. size_t link_concat_len;
  10790. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10791. return 0;
  10792. }
  10793. link_concat_len = strlen(uri) + strlen(name) + 1;
  10794. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  10795. if (!link_concat) {
  10796. return 0;
  10797. }
  10798. strcpy(link_concat, uri);
  10799. strcat(link_concat, name);
  10800. /* Get full link used in request */
  10801. mg_construct_local_link(
  10802. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  10803. /*
  10804. OutputDebugStringA("print_props:\n uri: ");
  10805. OutputDebugStringA(uri);
  10806. OutputDebugStringA("\n name: ");
  10807. OutputDebugStringA(name);
  10808. OutputDebugStringA("\n link: ");
  10809. OutputDebugStringA(link_buf);
  10810. OutputDebugStringA("\n");
  10811. */
  10812. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10813. mg_printf(conn,
  10814. "<d:response>"
  10815. "<d:href>%s</d:href>"
  10816. "<d:propstat>"
  10817. "<d:prop>"
  10818. "<d:resourcetype>%s</d:resourcetype>"
  10819. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10820. "<d:getlastmodified>%s</d:getlastmodified>"
  10821. "<d:lockdiscovery>",
  10822. link_buf,
  10823. filep->is_directory ? "<d:collection/>" : "",
  10824. filep->size,
  10825. mtime);
  10826. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10827. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10828. if (!strcmp(dav_lock[i].path, link_buf)) {
  10829. mg_printf(conn,
  10830. "<d:activelock>"
  10831. "<d:locktype><d:write/></d:locktype>"
  10832. "<d:lockscope><d:exclusive/></d:lockscope>"
  10833. "<d:depth>0</d:depth>"
  10834. "<d:owner>%s</d:owner>"
  10835. "<d:timeout>Second-%u</d:timeout>"
  10836. "<d:locktoken>"
  10837. "<d:href>%s</d:href>"
  10838. "</d:locktoken>"
  10839. "</d:activelock>\n",
  10840. dav_lock[i].user,
  10841. (unsigned)LOCK_DURATION_S,
  10842. dav_lock[i].token);
  10843. }
  10844. }
  10845. mg_printf(conn,
  10846. "</d:lockdiscovery>"
  10847. "</d:prop>"
  10848. "<d:status>HTTP/1.1 200 OK</d:status>"
  10849. "</d:propstat>"
  10850. "</d:response>\n");
  10851. mg_free(link_concat);
  10852. return 1;
  10853. }
  10854. static int
  10855. print_dav_dir_entry(struct de *de, void *data)
  10856. {
  10857. struct mg_connection *conn = (struct mg_connection *)data;
  10858. if (!de || !conn
  10859. || !print_props(
  10860. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10861. /* stop scan */
  10862. return 1;
  10863. }
  10864. return 0;
  10865. }
  10866. static void
  10867. handle_propfind(struct mg_connection *conn,
  10868. const char *path,
  10869. struct mg_file_stat *filep)
  10870. {
  10871. const char *depth = mg_get_header(conn, "Depth");
  10872. if (!conn || !path || !filep || !conn->dom_ctx) {
  10873. return;
  10874. }
  10875. /* return 207 "Multi-Status" */
  10876. conn->must_close = 1;
  10877. mg_response_header_start(conn, 207);
  10878. send_static_cache_header(conn);
  10879. send_additional_header(conn);
  10880. mg_response_header_add(conn,
  10881. "Content-Type",
  10882. "application/xml; charset=utf-8",
  10883. -1);
  10884. mg_response_header_send(conn);
  10885. /* Content */
  10886. mg_printf(conn,
  10887. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10888. "<d:multistatus xmlns:d='DAV:'>\n");
  10889. /* Print properties for the requested resource itself */
  10890. print_props(conn, conn->request_info.local_uri, "", filep);
  10891. /* If it is a directory, print directory entries too if Depth is not 0
  10892. */
  10893. if (filep->is_directory
  10894. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10895. "yes")
  10896. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10897. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10898. }
  10899. mg_printf(conn, "%s\n", "</d:multistatus>");
  10900. }
  10901. static void
  10902. dav_lock_file(struct mg_connection *conn, const char *path)
  10903. {
  10904. /* internal function - therefore conn is assumed to be valid */
  10905. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10906. uint64_t new_locktime;
  10907. int lock_index = -1;
  10908. int i;
  10909. uint64_t LOCK_DURATION_NS =
  10910. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  10911. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10912. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  10913. return;
  10914. }
  10915. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10916. /* const char *refresh = mg_get_header(conn, "If"); */
  10917. /* Link refresh should have an "If" header:
  10918. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  10919. * But it seems Windows Explorer does not send them.
  10920. */
  10921. mg_lock_context(conn->phys_ctx);
  10922. new_locktime = mg_get_current_time_ns();
  10923. /* Find a slot for a lock */
  10924. while (lock_index < 0) {
  10925. /* find existing lock */
  10926. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10927. if (!strcmp(dav_lock[i].path, link_buf)) {
  10928. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  10929. /* locked by the same user */
  10930. dav_lock[i].locktime = new_locktime;
  10931. lock_index = i;
  10932. break;
  10933. } else {
  10934. /* already locked by someone else */
  10935. if (new_locktime
  10936. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  10937. /* Lock expired */
  10938. dav_lock[i].path[0] = 0;
  10939. } else {
  10940. /* Lock still valid */
  10941. mg_unlock_context(conn->phys_ctx);
  10942. mg_send_http_error(conn, 423, "%s", "Already locked");
  10943. return;
  10944. }
  10945. }
  10946. }
  10947. }
  10948. /* create new lock token */
  10949. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10950. if (dav_lock[i].path[0] == 0) {
  10951. char s[32];
  10952. dav_lock[i].locktime = mg_get_current_time_ns();
  10953. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  10954. mg_md5(dav_lock[i].token,
  10955. link_buf,
  10956. "\x01",
  10957. s,
  10958. "\x01",
  10959. conn->request_info.remote_user,
  10960. NULL);
  10961. mg_strlcpy(dav_lock[i].path,
  10962. link_buf,
  10963. sizeof(dav_lock[i].path));
  10964. mg_strlcpy(dav_lock[i].user,
  10965. conn->request_info.remote_user,
  10966. sizeof(dav_lock[i].user));
  10967. lock_index = i;
  10968. break;
  10969. }
  10970. }
  10971. if (lock_index < 0) {
  10972. /* too many locks. Find oldest lock */
  10973. uint64_t oldest_locktime = dav_lock[0].locktime;
  10974. lock_index = 0;
  10975. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  10976. if (dav_lock[i].locktime < oldest_locktime) {
  10977. oldest_locktime = dav_lock[i].locktime;
  10978. lock_index = i;
  10979. }
  10980. }
  10981. /* invalidate oldest lock */
  10982. dav_lock[lock_index].path[0] = 0;
  10983. }
  10984. }
  10985. mg_unlock_context(conn->phys_ctx);
  10986. /* return 200 "OK" */
  10987. conn->must_close = 1;
  10988. mg_response_header_start(conn, 200);
  10989. send_static_cache_header(conn);
  10990. send_additional_header(conn);
  10991. mg_response_header_add(conn,
  10992. "Content-Type",
  10993. "application/xml; charset=utf-8",
  10994. -1);
  10995. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  10996. mg_response_header_send(conn);
  10997. /* Content */
  10998. mg_printf(conn,
  10999. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11000. "<d:prop xmlns:d=\"DAV:\">\n"
  11001. " <d:lockdiscovery>\n"
  11002. " <d:activelock>\n"
  11003. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11004. " <d:locktype><d:write/></d:locktype>\n"
  11005. " <d:owner>\n"
  11006. " <d:href>%s</d:href>\n"
  11007. " </d:owner>\n"
  11008. " <d:timeout>Second-%u</d:timeout>\n"
  11009. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11010. " <d:lockroot>\n"
  11011. " <d:href>%s</d:href>\n"
  11012. " </d:lockroot>\n"
  11013. " </d:activelock>\n"
  11014. " </d:lockdiscovery>\n"
  11015. " </d:prop>\n",
  11016. dav_lock[lock_index].user,
  11017. (LOCK_DURATION_S),
  11018. dav_lock[lock_index].token,
  11019. dav_lock[lock_index].path);
  11020. }
  11021. static void
  11022. dav_unlock_file(struct mg_connection *conn, const char *path)
  11023. {
  11024. /* internal function - therefore conn is assumed to be valid */
  11025. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11026. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11027. int lock_index;
  11028. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11029. return;
  11030. }
  11031. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11032. mg_lock_context(conn->phys_ctx);
  11033. /* find existing lock */
  11034. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11035. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11036. /* Success: return 204 "No Content" */
  11037. mg_unlock_context(conn->phys_ctx);
  11038. conn->must_close = 1;
  11039. mg_response_header_start(conn, 204);
  11040. mg_response_header_send(conn);
  11041. return;
  11042. }
  11043. }
  11044. mg_unlock_context(conn->phys_ctx);
  11045. /* Error: Cannot unlock a resource that is not locked */
  11046. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11047. }
  11048. static void
  11049. dav_proppatch(struct mg_connection *conn, const char *path)
  11050. {
  11051. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11052. if (!conn || !path || !conn->dom_ctx) {
  11053. return;
  11054. }
  11055. /* return 207 "Multi-Status" */
  11056. conn->must_close = 1;
  11057. mg_response_header_start(conn, 207);
  11058. send_static_cache_header(conn);
  11059. send_additional_header(conn);
  11060. mg_response_header_add(conn,
  11061. "Content-Type",
  11062. "application/xml; charset=utf-8",
  11063. -1);
  11064. mg_response_header_send(conn);
  11065. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11066. /* Content */
  11067. mg_printf(conn,
  11068. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11069. "<d:multistatus xmlns:d='DAV:'>\n"
  11070. "<d:response>\n<d:href>%s</d:href>\n",
  11071. link_buf);
  11072. mg_printf(conn,
  11073. "<d:propstat><d:status>HTTP/1.1 403 "
  11074. "Forbidden</d:status></d:propstat>\n");
  11075. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11076. }
  11077. #endif
  11078. CIVETWEB_API void
  11079. mg_lock_connection(struct mg_connection *conn)
  11080. {
  11081. if (conn) {
  11082. (void)pthread_mutex_lock(&conn->mutex);
  11083. }
  11084. }
  11085. CIVETWEB_API void
  11086. mg_unlock_connection(struct mg_connection *conn)
  11087. {
  11088. if (conn) {
  11089. (void)pthread_mutex_unlock(&conn->mutex);
  11090. }
  11091. }
  11092. CIVETWEB_API void
  11093. mg_lock_context(struct mg_context *ctx)
  11094. {
  11095. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11096. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11097. }
  11098. }
  11099. CIVETWEB_API void
  11100. mg_unlock_context(struct mg_context *ctx)
  11101. {
  11102. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11103. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11104. }
  11105. }
  11106. #if defined(USE_LUA)
  11107. #include "mod_lua.inl"
  11108. #endif /* USE_LUA */
  11109. #if defined(USE_DUKTAPE)
  11110. #include "mod_duktape.inl"
  11111. #endif /* USE_DUKTAPE */
  11112. #if defined(USE_WEBSOCKET)
  11113. #if !defined(NO_SSL_DL)
  11114. #if !defined(OPENSSL_API_3_0)
  11115. #define SHA_API static
  11116. #include "sha1.inl"
  11117. #endif
  11118. #endif
  11119. static int
  11120. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11121. {
  11122. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11123. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11124. size_t dst_len = sizeof(b64_sha);
  11125. #if !defined(OPENSSL_API_3_0)
  11126. SHA_CTX sha_ctx;
  11127. #endif
  11128. int truncated;
  11129. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11130. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11131. if (truncated) {
  11132. conn->must_close = 1;
  11133. return 0;
  11134. }
  11135. DEBUG_TRACE("%s", "Send websocket handshake");
  11136. #if defined(OPENSSL_API_3_0)
  11137. EVP_Digest((unsigned char *)buf,
  11138. (uint32_t)strlen(buf),
  11139. (unsigned char *)sha,
  11140. NULL,
  11141. EVP_get_digestbyname("sha1"),
  11142. NULL);
  11143. #else
  11144. SHA1_Init(&sha_ctx);
  11145. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11146. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11147. #endif
  11148. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11149. mg_printf(conn,
  11150. "HTTP/1.1 101 Switching Protocols\r\n"
  11151. "Upgrade: websocket\r\n"
  11152. "Connection: Upgrade\r\n"
  11153. "Sec-WebSocket-Accept: %s\r\n",
  11154. b64_sha);
  11155. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11156. // Send negotiated compression extension parameters
  11157. websocket_deflate_response(conn);
  11158. #endif
  11159. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11160. mg_printf(conn,
  11161. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11162. conn->request_info.acceptedWebSocketSubprotocol);
  11163. } else {
  11164. mg_printf(conn, "%s", "\r\n");
  11165. }
  11166. return 1;
  11167. }
  11168. #if !defined(MG_MAX_UNANSWERED_PING)
  11169. /* Configuration of the maximum number of websocket PINGs that might
  11170. * stay unanswered before the connection is considered broken.
  11171. * Note: The name of this define may still change (until it is
  11172. * defined as a compile parameter in a documentation).
  11173. */
  11174. #define MG_MAX_UNANSWERED_PING (5)
  11175. #endif
  11176. static void
  11177. read_websocket(struct mg_connection *conn,
  11178. mg_websocket_data_handler ws_data_handler,
  11179. void *callback_data)
  11180. {
  11181. /* Pointer to the beginning of the portion of the incoming websocket
  11182. * message queue.
  11183. * The original websocket upgrade request is never removed, so the queue
  11184. * begins after it. */
  11185. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11186. int n, error, exit_by_callback;
  11187. int ret;
  11188. /* body_len is the length of the entire queue in bytes
  11189. * len is the length of the current message
  11190. * data_len is the length of the current message's data payload
  11191. * header_len is the length of the current message's header */
  11192. size_t i, len, mask_len = 0, header_len, body_len;
  11193. uint64_t data_len = 0;
  11194. /* "The masking key is a 32-bit value chosen at random by the client."
  11195. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11196. */
  11197. unsigned char mask[4];
  11198. /* data points to the place where the message is stored when passed to
  11199. * the websocket_data callback. This is either mem on the stack, or a
  11200. * dynamically allocated buffer if it is too large. */
  11201. unsigned char mem[4096];
  11202. unsigned char mop; /* mask flag and opcode */
  11203. /* Variables used for connection monitoring */
  11204. double timeout = -1.0;
  11205. int enable_ping_pong = 0;
  11206. int ping_count = 0;
  11207. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11208. enable_ping_pong =
  11209. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11210. "yes");
  11211. }
  11212. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11213. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11214. }
  11215. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11216. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11217. }
  11218. if (timeout <= 0.0) {
  11219. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11220. }
  11221. /* Enter data processing loop */
  11222. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11223. conn->request_info.remote_addr,
  11224. conn->request_info.remote_port);
  11225. conn->in_websocket_handling = 1;
  11226. mg_set_thread_name("wsock");
  11227. /* Loop continuously, reading messages from the socket, invoking the
  11228. * callback, and waiting repeatedly until an error occurs. */
  11229. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11230. && (!conn->must_close)) {
  11231. header_len = 0;
  11232. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11233. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11234. len = buf[1] & 127;
  11235. mask_len = (buf[1] & 128) ? 4 : 0;
  11236. if ((len < 126) && (body_len >= mask_len)) {
  11237. /* inline 7-bit length field */
  11238. data_len = len;
  11239. header_len = 2 + mask_len;
  11240. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11241. /* 16-bit length field */
  11242. header_len = 4 + mask_len;
  11243. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11244. } else if (body_len >= (10 + mask_len)) {
  11245. /* 64-bit length field */
  11246. uint32_t l1, l2;
  11247. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11248. memcpy(&l2, &buf[6], 4);
  11249. header_len = 10 + mask_len;
  11250. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11251. if (data_len > (uint64_t)0x7FFF0000ul) {
  11252. /* no can do */
  11253. mg_cry_internal(
  11254. conn,
  11255. "%s",
  11256. "websocket out of memory; closing connection");
  11257. break;
  11258. }
  11259. }
  11260. }
  11261. if ((header_len > 0) && (body_len >= header_len)) {
  11262. /* Allocate space to hold websocket payload */
  11263. unsigned char *data = mem;
  11264. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11265. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11266. conn->phys_ctx);
  11267. if (data == NULL) {
  11268. /* Allocation failed, exit the loop and then close the
  11269. * connection */
  11270. mg_cry_internal(
  11271. conn,
  11272. "%s",
  11273. "websocket out of memory; closing connection");
  11274. break;
  11275. }
  11276. }
  11277. /* Copy the mask before we shift the queue and destroy it */
  11278. if (mask_len > 0) {
  11279. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11280. } else {
  11281. memset(mask, 0, sizeof(mask));
  11282. }
  11283. /* Read frame payload from the first message in the queue into
  11284. * data and advance the queue by moving the memory in place. */
  11285. DEBUG_ASSERT(body_len >= header_len);
  11286. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11287. mop = buf[0]; /* current mask and opcode */
  11288. /* Overflow case */
  11289. len = body_len - header_len;
  11290. memcpy(data, buf + header_len, len);
  11291. error = 0;
  11292. while ((uint64_t)len < data_len) {
  11293. n = pull_inner(NULL,
  11294. conn,
  11295. (char *)(data + len),
  11296. (int)(data_len - len),
  11297. timeout);
  11298. if (n <= -2) {
  11299. error = 1;
  11300. break;
  11301. } else if (n > 0) {
  11302. len += (size_t)n;
  11303. } else {
  11304. /* Timeout: should retry */
  11305. /* TODO: retry condition */
  11306. }
  11307. }
  11308. if (error) {
  11309. mg_cry_internal(
  11310. conn,
  11311. "%s",
  11312. "Websocket pull failed; closing connection");
  11313. if (data != mem) {
  11314. mg_free(data);
  11315. }
  11316. break;
  11317. }
  11318. conn->data_len = conn->request_len;
  11319. } else {
  11320. mop = buf[0]; /* current mask and opcode, overwritten by
  11321. * memmove() */
  11322. /* Length of the message being read at the front of the
  11323. * queue. Cast to 31 bit is OK, since we limited
  11324. * data_len before. */
  11325. len = (size_t)data_len + header_len;
  11326. /* Copy the data payload into the data pointer for the
  11327. * callback. Cast to 31 bit is OK, since we
  11328. * limited data_len */
  11329. memcpy(data, buf + header_len, (size_t)data_len);
  11330. /* Move the queue forward len bytes */
  11331. memmove(buf, buf + len, body_len - len);
  11332. /* Mark the queue as advanced */
  11333. conn->data_len -= (int)len;
  11334. }
  11335. /* Apply mask if necessary */
  11336. if (mask_len > 0) {
  11337. for (i = 0; i < (size_t)data_len; i++) {
  11338. data[i] ^= mask[i & 3];
  11339. }
  11340. }
  11341. exit_by_callback = 0;
  11342. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11343. /* filter PONG messages */
  11344. DEBUG_TRACE("PONG from %s:%u",
  11345. conn->request_info.remote_addr,
  11346. conn->request_info.remote_port);
  11347. /* No unanwered PINGs left */
  11348. ping_count = 0;
  11349. } else if (enable_ping_pong
  11350. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11351. /* reply PING messages */
  11352. DEBUG_TRACE("Reply PING from %s:%u",
  11353. conn->request_info.remote_addr,
  11354. conn->request_info.remote_port);
  11355. ret = mg_websocket_write(conn,
  11356. MG_WEBSOCKET_OPCODE_PONG,
  11357. (char *)data,
  11358. (size_t)data_len);
  11359. if (ret <= 0) {
  11360. /* Error: send failed */
  11361. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11362. break;
  11363. }
  11364. } else {
  11365. /* Exit the loop if callback signals to exit (server side),
  11366. * or "connection close" opcode received (client side). */
  11367. if (ws_data_handler != NULL) {
  11368. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11369. if (mop & 0x40) {
  11370. /* Inflate the data received if bit RSV1 is set. */
  11371. if (!conn->websocket_deflate_initialized) {
  11372. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11373. exit_by_callback = 1;
  11374. }
  11375. if (!exit_by_callback) {
  11376. size_t inflate_buf_size_old = 0;
  11377. size_t inflate_buf_size =
  11378. data_len
  11379. * 4; // Initial guess of the inflated message
  11380. // size. We double the memory when needed.
  11381. Bytef *inflated = NULL;
  11382. Bytef *new_mem = NULL;
  11383. conn->websocket_inflate_state.avail_in =
  11384. (uInt)(data_len + 4);
  11385. conn->websocket_inflate_state.next_in = data;
  11386. // Add trailing 0x00 0x00 0xff 0xff bytes
  11387. data[data_len] = '\x00';
  11388. data[data_len + 1] = '\x00';
  11389. data[data_len + 2] = '\xff';
  11390. data[data_len + 3] = '\xff';
  11391. do {
  11392. if (inflate_buf_size_old == 0) {
  11393. new_mem =
  11394. (Bytef *)mg_calloc(inflate_buf_size,
  11395. sizeof(Bytef));
  11396. } else {
  11397. inflate_buf_size *= 2;
  11398. new_mem =
  11399. (Bytef *)mg_realloc(inflated,
  11400. inflate_buf_size);
  11401. }
  11402. if (new_mem == NULL) {
  11403. mg_cry_internal(
  11404. conn,
  11405. "Out of memory: Cannot allocate "
  11406. "inflate buffer of %lu bytes",
  11407. (unsigned long)inflate_buf_size);
  11408. exit_by_callback = 1;
  11409. break;
  11410. }
  11411. inflated = new_mem;
  11412. conn->websocket_inflate_state.avail_out =
  11413. (uInt)(inflate_buf_size
  11414. - inflate_buf_size_old);
  11415. conn->websocket_inflate_state.next_out =
  11416. inflated + inflate_buf_size_old;
  11417. ret = inflate(&conn->websocket_inflate_state,
  11418. Z_SYNC_FLUSH);
  11419. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11420. || ret == Z_MEM_ERROR) {
  11421. mg_cry_internal(
  11422. conn,
  11423. "ZLIB inflate error: %i %s",
  11424. ret,
  11425. (conn->websocket_inflate_state.msg
  11426. ? conn->websocket_inflate_state.msg
  11427. : "<no error message>"));
  11428. exit_by_callback = 1;
  11429. break;
  11430. }
  11431. inflate_buf_size_old = inflate_buf_size;
  11432. } while (conn->websocket_inflate_state.avail_out
  11433. == 0);
  11434. inflate_buf_size -=
  11435. conn->websocket_inflate_state.avail_out;
  11436. if (!ws_data_handler(conn,
  11437. mop,
  11438. (char *)inflated,
  11439. inflate_buf_size,
  11440. callback_data)) {
  11441. exit_by_callback = 1;
  11442. }
  11443. mg_free(inflated);
  11444. }
  11445. } else
  11446. #endif
  11447. if (!ws_data_handler(conn,
  11448. mop,
  11449. (char *)data,
  11450. (size_t)data_len,
  11451. callback_data)) {
  11452. exit_by_callback = 1;
  11453. }
  11454. }
  11455. }
  11456. /* It a buffer has been allocated, free it again */
  11457. if (data != mem) {
  11458. mg_free(data);
  11459. }
  11460. if (exit_by_callback) {
  11461. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11462. conn->request_info.remote_addr,
  11463. conn->request_info.remote_port);
  11464. break;
  11465. }
  11466. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11467. /* Opcode == 8, connection close */
  11468. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11469. conn->request_info.remote_addr,
  11470. conn->request_info.remote_port);
  11471. break;
  11472. }
  11473. /* Not breaking the loop, process next websocket frame. */
  11474. } else {
  11475. /* Read from the socket into the next available location in the
  11476. * message queue. */
  11477. n = pull_inner(NULL,
  11478. conn,
  11479. conn->buf + conn->data_len,
  11480. conn->buf_size - conn->data_len,
  11481. timeout);
  11482. if (n <= -2) {
  11483. /* Error, no bytes read */
  11484. DEBUG_TRACE("PULL from %s:%u failed",
  11485. conn->request_info.remote_addr,
  11486. conn->request_info.remote_port);
  11487. break;
  11488. }
  11489. if (n > 0) {
  11490. conn->data_len += n;
  11491. /* Reset open PING count */
  11492. ping_count = 0;
  11493. } else {
  11494. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11495. && (!conn->must_close)) {
  11496. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11497. /* Stop sending PING */
  11498. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11499. "- closing connection",
  11500. ping_count,
  11501. conn->request_info.remote_addr,
  11502. conn->request_info.remote_port);
  11503. break;
  11504. }
  11505. if (enable_ping_pong) {
  11506. /* Send Websocket PING message */
  11507. DEBUG_TRACE("PING to %s:%u",
  11508. conn->request_info.remote_addr,
  11509. conn->request_info.remote_port);
  11510. ret = mg_websocket_write(conn,
  11511. MG_WEBSOCKET_OPCODE_PING,
  11512. NULL,
  11513. 0);
  11514. if (ret <= 0) {
  11515. /* Error: send failed */
  11516. DEBUG_TRACE("Send PING failed (%i)", ret);
  11517. break;
  11518. }
  11519. ping_count++;
  11520. }
  11521. }
  11522. /* Timeout: should retry */
  11523. /* TODO: get timeout def */
  11524. }
  11525. }
  11526. }
  11527. /* Leave data processing loop */
  11528. mg_set_thread_name("worker");
  11529. conn->in_websocket_handling = 0;
  11530. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11531. conn->request_info.remote_addr,
  11532. conn->request_info.remote_port);
  11533. }
  11534. static int
  11535. mg_websocket_write_exec(struct mg_connection *conn,
  11536. int opcode,
  11537. const char *data,
  11538. size_t dataLen,
  11539. uint32_t masking_key)
  11540. {
  11541. unsigned char header[14];
  11542. size_t headerLen;
  11543. int retval;
  11544. #if defined(GCC_DIAGNOSTIC)
  11545. /* Disable spurious conversion warning for GCC */
  11546. #pragma GCC diagnostic push
  11547. #pragma GCC diagnostic ignored "-Wconversion"
  11548. #endif
  11549. /* Note that POSIX/Winsock's send() is threadsafe
  11550. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11551. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11552. * push(), although that is only a problem if the packet is large or
  11553. * outgoing buffer is full). */
  11554. /* TODO: Check if this lock should be moved to user land.
  11555. * Currently the server sets this lock for websockets, but
  11556. * not for any other connection. It must be set for every
  11557. * conn read/written by more than one thread, no matter if
  11558. * it is a websocket or regular connection. */
  11559. (void)mg_lock_connection(conn);
  11560. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11561. size_t deflated_size = 0;
  11562. Bytef *deflated = 0;
  11563. // Deflate websocket messages over 100kb
  11564. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11565. if (use_deflate) {
  11566. if (!conn->websocket_deflate_initialized) {
  11567. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11568. return 0;
  11569. }
  11570. // Deflating the message
  11571. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11572. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11573. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11574. deflated_size = (size_t)compressBound((uLong)dataLen);
  11575. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11576. if (deflated == NULL) {
  11577. mg_cry_internal(
  11578. conn,
  11579. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11580. (unsigned long)deflated_size);
  11581. mg_unlock_connection(conn);
  11582. return -1;
  11583. }
  11584. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11585. conn->websocket_deflate_state.next_out = deflated;
  11586. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11587. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11588. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11589. } else
  11590. #endif
  11591. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11592. #if defined(GCC_DIAGNOSTIC)
  11593. #pragma GCC diagnostic pop
  11594. #endif
  11595. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11596. if (dataLen < 126) {
  11597. /* inline 7-bit length field */
  11598. header[1] = (unsigned char)dataLen;
  11599. headerLen = 2;
  11600. } else if (dataLen <= 0xFFFF) {
  11601. /* 16-bit length field */
  11602. uint16_t len = htons((uint16_t)dataLen);
  11603. header[1] = 126;
  11604. memcpy(header + 2, &len, 2);
  11605. headerLen = 4;
  11606. } else {
  11607. /* 64-bit length field */
  11608. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11609. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11610. header[1] = 127;
  11611. memcpy(header + 2, &len1, 4);
  11612. memcpy(header + 6, &len2, 4);
  11613. headerLen = 10;
  11614. }
  11615. if (masking_key) {
  11616. /* add mask */
  11617. header[1] |= 0x80;
  11618. memcpy(header + headerLen, &masking_key, 4);
  11619. headerLen += 4;
  11620. }
  11621. retval = mg_write(conn, header, headerLen);
  11622. if (retval != (int)headerLen) {
  11623. /* Did not send complete header */
  11624. retval = -1;
  11625. } else {
  11626. if (dataLen > 0) {
  11627. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11628. if (use_deflate) {
  11629. retval = mg_write(conn, deflated, dataLen);
  11630. mg_free(deflated);
  11631. } else
  11632. #endif
  11633. retval = mg_write(conn, data, dataLen);
  11634. }
  11635. /* if dataLen == 0, the header length (2) is returned */
  11636. }
  11637. /* TODO: Remove this unlock as well, when lock is removed. */
  11638. mg_unlock_connection(conn);
  11639. return retval;
  11640. }
  11641. CIVETWEB_API int
  11642. mg_websocket_write(struct mg_connection *conn,
  11643. int opcode,
  11644. const char *data,
  11645. size_t dataLen)
  11646. {
  11647. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11648. }
  11649. static void
  11650. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11651. {
  11652. size_t i = 0;
  11653. i = 0;
  11654. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11655. /* Convert in 32 bit words, if data is 4 byte aligned */
  11656. while (i < (in_len - 3)) {
  11657. *(uint32_t *)(void *)(out + i) =
  11658. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11659. i += 4;
  11660. }
  11661. }
  11662. if (i != in_len) {
  11663. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11664. while (i < in_len) {
  11665. *(uint8_t *)(void *)(out + i) =
  11666. *(uint8_t *)(void *)(in + i)
  11667. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11668. i++;
  11669. }
  11670. }
  11671. }
  11672. CIVETWEB_API int
  11673. mg_websocket_client_write(struct mg_connection *conn,
  11674. int opcode,
  11675. const char *data,
  11676. size_t dataLen)
  11677. {
  11678. int retval = -1;
  11679. char *masked_data =
  11680. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11681. uint32_t masking_key = 0;
  11682. if (masked_data == NULL) {
  11683. /* Return -1 in an error case */
  11684. mg_cry_internal(conn,
  11685. "%s",
  11686. "Cannot allocate buffer for masked websocket response: "
  11687. "Out of memory");
  11688. return -1;
  11689. }
  11690. do {
  11691. /* Get a masking key - but not 0 */
  11692. masking_key = (uint32_t)get_random();
  11693. } while (masking_key == 0);
  11694. mask_data(data, dataLen, masking_key, masked_data);
  11695. retval = mg_websocket_write_exec(
  11696. conn, opcode, masked_data, dataLen, masking_key);
  11697. mg_free(masked_data);
  11698. return retval;
  11699. }
  11700. static void
  11701. handle_websocket_request(struct mg_connection *conn,
  11702. const char *path,
  11703. int is_callback_resource,
  11704. struct mg_websocket_subprotocols *subprotocols,
  11705. mg_websocket_connect_handler ws_connect_handler,
  11706. mg_websocket_ready_handler ws_ready_handler,
  11707. mg_websocket_data_handler ws_data_handler,
  11708. mg_websocket_close_handler ws_close_handler,
  11709. void *cbData)
  11710. {
  11711. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11712. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11713. ptrdiff_t lua_websock = 0;
  11714. #if !defined(USE_LUA)
  11715. (void)path;
  11716. #endif
  11717. /* Step 1: Check websocket protocol version. */
  11718. /* Step 1.1: Check Sec-WebSocket-Key. */
  11719. if (!websock_key) {
  11720. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11721. * requires a Sec-WebSocket-Key header.
  11722. */
  11723. /* It could be the hixie draft version
  11724. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11725. */
  11726. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11727. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11728. char key3[8];
  11729. if ((key1 != NULL) && (key2 != NULL)) {
  11730. /* This version uses 8 byte body data in a GET request */
  11731. conn->content_len = 8;
  11732. if (8 == mg_read(conn, key3, 8)) {
  11733. /* This is the hixie version */
  11734. mg_send_http_error(conn,
  11735. 426,
  11736. "%s",
  11737. "Protocol upgrade to RFC 6455 required");
  11738. return;
  11739. }
  11740. }
  11741. /* This is an unknown version */
  11742. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11743. return;
  11744. }
  11745. /* Step 1.2: Check websocket protocol version. */
  11746. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11747. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11748. /* Reject wrong versions */
  11749. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11750. return;
  11751. }
  11752. /* Step 1.3: Could check for "Host", but we do not really need this
  11753. * value for anything, so just ignore it. */
  11754. /* Step 2: If a callback is responsible, call it. */
  11755. if (is_callback_resource) {
  11756. /* Step 2.1 check and select subprotocol */
  11757. const char *protocols[64]; // max 64 headers
  11758. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11759. "Sec-WebSocket-Protocol",
  11760. protocols,
  11761. 64);
  11762. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11763. int headerNo, idx;
  11764. size_t len;
  11765. const char *sep, *curSubProtocol,
  11766. *acceptedWebSocketSubprotocol = NULL;
  11767. /* look for matching subprotocol */
  11768. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11769. /* There might be multiple headers ... */
  11770. const char *protocol = protocols[headerNo];
  11771. curSubProtocol = protocol;
  11772. /* ... and in every header there might be a , separated list */
  11773. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11774. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11775. curSubProtocol++;
  11776. sep = strchr(curSubProtocol, ',');
  11777. if (sep) {
  11778. len = (size_t)(sep - curSubProtocol);
  11779. } else {
  11780. len = strlen(curSubProtocol);
  11781. }
  11782. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11783. // COMPARE: curSubProtocol ==
  11784. // subprotocols->subprotocols[idx]
  11785. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11786. && (strncmp(curSubProtocol,
  11787. subprotocols->subprotocols[idx],
  11788. len)
  11789. == 0)) {
  11790. acceptedWebSocketSubprotocol =
  11791. subprotocols->subprotocols[idx];
  11792. break;
  11793. }
  11794. }
  11795. curSubProtocol += len;
  11796. }
  11797. }
  11798. conn->request_info.acceptedWebSocketSubprotocol =
  11799. acceptedWebSocketSubprotocol;
  11800. }
  11801. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11802. websocket_deflate_negotiate(conn);
  11803. #endif
  11804. if ((ws_connect_handler != NULL)
  11805. && (ws_connect_handler(conn, cbData) != 0)) {
  11806. /* C callback has returned non-zero, do not proceed with
  11807. * handshake.
  11808. */
  11809. /* Note that C callbacks are no longer called when Lua is
  11810. * responsible, so C can no longer filter callbacks for Lua. */
  11811. return;
  11812. }
  11813. }
  11814. #if defined(USE_LUA)
  11815. /* Step 3: No callback. Check if Lua is responsible. */
  11816. else {
  11817. /* Step 3.1: Check if Lua is responsible. */
  11818. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11819. lua_websock = match_prefix_strlen(
  11820. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11821. }
  11822. if (lua_websock > 0) {
  11823. /* Step 3.2: Lua is responsible: call it. */
  11824. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11825. if (!conn->lua_websocket_state) {
  11826. /* Lua rejected the new client */
  11827. return;
  11828. }
  11829. }
  11830. }
  11831. #endif
  11832. /* Step 4: Check if there is a responsible websocket handler. */
  11833. if (!is_callback_resource && !lua_websock) {
  11834. /* There is no callback, and Lua is not responsible either. */
  11835. /* Reply with a 404 Not Found. We are still at a standard
  11836. * HTTP request here, before the websocket handshake, so
  11837. * we can still send standard HTTP error replies. */
  11838. mg_send_http_error(conn, 404, "%s", "Not found");
  11839. return;
  11840. }
  11841. /* Step 5: The websocket connection has been accepted */
  11842. if (!send_websocket_handshake(conn, websock_key)) {
  11843. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11844. return;
  11845. }
  11846. /* Step 6: Call the ready handler */
  11847. if (is_callback_resource) {
  11848. if (ws_ready_handler != NULL) {
  11849. ws_ready_handler(conn, cbData);
  11850. }
  11851. #if defined(USE_LUA)
  11852. } else if (lua_websock) {
  11853. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11854. /* the ready handler returned false */
  11855. return;
  11856. }
  11857. #endif
  11858. }
  11859. /* Step 7: Enter the read loop */
  11860. if (is_callback_resource) {
  11861. read_websocket(conn, ws_data_handler, cbData);
  11862. #if defined(USE_LUA)
  11863. } else if (lua_websock) {
  11864. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11865. #endif
  11866. }
  11867. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11868. /* Step 8: Close the deflate & inflate buffers */
  11869. if (conn->websocket_deflate_initialized) {
  11870. deflateEnd(&conn->websocket_deflate_state);
  11871. inflateEnd(&conn->websocket_inflate_state);
  11872. }
  11873. #endif
  11874. /* Step 9: Call the close handler */
  11875. if (ws_close_handler) {
  11876. ws_close_handler(conn, cbData);
  11877. }
  11878. }
  11879. #endif /* !USE_WEBSOCKET */
  11880. /* Is upgrade request:
  11881. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11882. * 1 = upgrade to websocket
  11883. * 2 = upgrade to HTTP/2
  11884. * -1 = upgrade to unknown protocol
  11885. */
  11886. static int
  11887. should_switch_to_protocol(const struct mg_connection *conn)
  11888. {
  11889. const char *connection_headers[8];
  11890. const char *upgrade_to;
  11891. int connection_header_count, i, should_upgrade;
  11892. /* A websocket protocol has the following HTTP headers:
  11893. *
  11894. * Connection: Upgrade
  11895. * Upgrade: Websocket
  11896. *
  11897. * It seems some clients use multiple headers:
  11898. * see https://github.com/civetweb/civetweb/issues/1083
  11899. */
  11900. connection_header_count = get_req_headers(&conn->request_info,
  11901. "Connection",
  11902. connection_headers,
  11903. 8);
  11904. should_upgrade = 0;
  11905. for (i = 0; i < connection_header_count; i++) {
  11906. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  11907. should_upgrade = 1;
  11908. }
  11909. }
  11910. if (!should_upgrade) {
  11911. return PROTOCOL_TYPE_HTTP1;
  11912. }
  11913. upgrade_to = mg_get_header(conn, "Upgrade");
  11914. if (upgrade_to == NULL) {
  11915. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11916. return -1;
  11917. }
  11918. /* Upgrade to ... */
  11919. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  11920. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11921. * "Sec-WebSocket-Version" are also required.
  11922. * Don't check them here, since even an unsupported websocket protocol
  11923. * request still IS a websocket request (in contrast to a standard HTTP
  11924. * request). It will fail later in handle_websocket_request.
  11925. */
  11926. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11927. }
  11928. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  11929. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11930. }
  11931. /* Upgrade to another protocol */
  11932. return -1;
  11933. }
  11934. static int
  11935. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11936. {
  11937. int n;
  11938. unsigned int a, b, c, d, slash;
  11939. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  11940. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  11941. // integer value, but function will not report conversion
  11942. // errors; consider using 'strtol' instead
  11943. slash = 32;
  11944. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  11945. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  11946. // an integer value, but function will not report conversion
  11947. // errors; consider using 'strtol' instead
  11948. n = 0;
  11949. }
  11950. }
  11951. if ((n > 0) && ((size_t)n == vec->len)) {
  11952. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11953. /* IPv4 format */
  11954. if (sa->sa.sa_family == AF_INET) {
  11955. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  11956. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11957. | ((uint32_t)c << 8) | (uint32_t)d;
  11958. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11959. return (ip & mask) == net;
  11960. }
  11961. return 0;
  11962. }
  11963. }
  11964. #if defined(USE_IPV6)
  11965. else {
  11966. char ad[50];
  11967. const char *p;
  11968. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11969. slash = 128;
  11970. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11971. n = 0;
  11972. }
  11973. }
  11974. if ((n <= 0) && no_strict) {
  11975. /* no square brackets? */
  11976. p = strchr(vec->ptr, '/');
  11977. if (p && (p < (vec->ptr + vec->len))) {
  11978. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11979. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11980. n += (int)(p - vec->ptr);
  11981. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11982. } else {
  11983. n = 0;
  11984. }
  11985. } else if (vec->len < sizeof(ad)) {
  11986. n = (int)vec->len;
  11987. slash = 128;
  11988. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11989. }
  11990. }
  11991. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11992. p = ad;
  11993. c = 0;
  11994. /* zone indexes are unsupported, at least two colons are needed */
  11995. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11996. if (*(p++) == ':') {
  11997. c++;
  11998. }
  11999. }
  12000. if ((*p == '\0') && (c >= 2)) {
  12001. struct sockaddr_in6 sin6;
  12002. unsigned int i;
  12003. /* for strict validation, an actual IPv6 argument is needed */
  12004. if (sa->sa.sa_family != AF_INET6) {
  12005. return 0;
  12006. }
  12007. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12008. /* IPv6 format */
  12009. for (i = 0; i < 16; i++) {
  12010. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12011. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12012. uint8_t mask = 0;
  12013. if (8 * i + 8 < slash) {
  12014. mask = 0xFFu;
  12015. } else if (8 * i < slash) {
  12016. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12017. }
  12018. if ((ip & mask) != net) {
  12019. return 0;
  12020. }
  12021. }
  12022. return 1;
  12023. }
  12024. }
  12025. }
  12026. }
  12027. #else
  12028. (void)no_strict;
  12029. #endif
  12030. /* malformed */
  12031. return -1;
  12032. }
  12033. static int
  12034. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12035. {
  12036. int throttle = 0;
  12037. struct vec vec, val;
  12038. char mult;
  12039. double v;
  12040. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12041. mult = ',';
  12042. if ((val.ptr == NULL)
  12043. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12044. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12045. // to an integer value, but function will not report
  12046. // conversion errors; consider using 'strtol' instead
  12047. || (v < 0)
  12048. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12049. && (mult != ','))) {
  12050. continue;
  12051. }
  12052. v *= (lowercase(&mult) == 'k')
  12053. ? 1024
  12054. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12055. if (vec.len == 1 && vec.ptr[0] == '*') {
  12056. throttle = (int)v;
  12057. } else {
  12058. int matched = parse_match_net(&vec, rsa, 0);
  12059. if (matched >= 0) {
  12060. /* a valid IP subnet */
  12061. if (matched) {
  12062. throttle = (int)v;
  12063. }
  12064. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12065. throttle = (int)v;
  12066. }
  12067. }
  12068. }
  12069. return throttle;
  12070. }
  12071. /* The mg_upload function is superseded by mg_handle_form_request. */
  12072. #include "handle_form.inl"
  12073. static int
  12074. get_first_ssl_listener_index(const struct mg_context *ctx)
  12075. {
  12076. unsigned int i;
  12077. int idx = -1;
  12078. if (ctx) {
  12079. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12080. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12081. }
  12082. }
  12083. return idx;
  12084. }
  12085. /* Return host (without port) */
  12086. static void
  12087. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12088. {
  12089. const char *host_header =
  12090. get_header(ri->http_headers, ri->num_headers, "Host");
  12091. host->ptr = NULL;
  12092. host->len = 0;
  12093. if (host_header != NULL) {
  12094. const char *pos;
  12095. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12096. * is found. */
  12097. if (*host_header == '[') {
  12098. pos = strchr(host_header, ']');
  12099. if (!pos) {
  12100. /* Malformed hostname starts with '[', but no ']' found */
  12101. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12102. return;
  12103. }
  12104. /* terminate after ']' */
  12105. host->ptr = host_header;
  12106. host->len = (size_t)(pos + 1 - host_header);
  12107. } else {
  12108. /* Otherwise, a ':' separates hostname and port number */
  12109. pos = strchr(host_header, ':');
  12110. if (pos != NULL) {
  12111. host->len = (size_t)(pos - host_header);
  12112. } else {
  12113. host->len = strlen(host_header);
  12114. }
  12115. host->ptr = host_header;
  12116. }
  12117. }
  12118. }
  12119. static int
  12120. switch_domain_context(struct mg_connection *conn)
  12121. {
  12122. struct vec host;
  12123. get_host_from_request_info(&host, &conn->request_info);
  12124. if (host.ptr) {
  12125. if (conn->ssl) {
  12126. /* This is a HTTPS connection, maybe we have a hostname
  12127. * from SNI (set in ssl_servername_callback). */
  12128. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12129. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12130. /* We are not using the default domain */
  12131. if ((strlen(sslhost) != host.len)
  12132. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12133. /* Mismatch between SNI domain and HTTP domain */
  12134. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12135. sslhost,
  12136. (int)host.len,
  12137. host.ptr);
  12138. return 0;
  12139. }
  12140. }
  12141. } else {
  12142. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12143. while (dom) {
  12144. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12145. size_t domNameLen = strlen(domName);
  12146. if ((domNameLen == host.len)
  12147. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12148. /* Found matching domain */
  12149. DEBUG_TRACE("HTTP domain %s found",
  12150. dom->config[AUTHENTICATION_DOMAIN]);
  12151. /* TODO: Check if this is a HTTP or HTTPS domain */
  12152. conn->dom_ctx = dom;
  12153. break;
  12154. }
  12155. mg_lock_context(conn->phys_ctx);
  12156. dom = dom->next;
  12157. mg_unlock_context(conn->phys_ctx);
  12158. }
  12159. }
  12160. DEBUG_TRACE("HTTP%s Host: %.*s",
  12161. conn->ssl ? "S" : "",
  12162. (int)host.len,
  12163. host.ptr);
  12164. } else {
  12165. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12166. return 1;
  12167. }
  12168. return 1;
  12169. }
  12170. static void
  12171. redirect_to_https_port(struct mg_connection *conn, int port)
  12172. {
  12173. char target_url[MG_BUF_LEN];
  12174. int truncated = 0;
  12175. const char *expect_proto =
  12176. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12177. /* Use "308 Permanent Redirect" */
  12178. int redirect_code = 308;
  12179. /* In any case, close the current connection */
  12180. conn->must_close = 1;
  12181. /* Send host, port, uri and (if it exists) ?query_string */
  12182. if (mg_construct_local_link(
  12183. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12184. < 0) {
  12185. truncated = 1;
  12186. } else if (conn->request_info.query_string != NULL) {
  12187. size_t slen1 = strlen(target_url);
  12188. size_t slen2 = strlen(conn->request_info.query_string);
  12189. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12190. target_url[slen1] = '?';
  12191. memcpy(target_url + slen1 + 1,
  12192. conn->request_info.query_string,
  12193. slen2);
  12194. target_url[slen1 + slen2 + 1] = 0;
  12195. } else {
  12196. truncated = 1;
  12197. }
  12198. }
  12199. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12200. * is used as buffer size) */
  12201. if (truncated) {
  12202. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12203. return;
  12204. }
  12205. /* Use redirect helper function */
  12206. mg_send_http_redirect(conn, target_url, redirect_code);
  12207. }
  12208. static void
  12209. mg_set_handler_type(struct mg_context *phys_ctx,
  12210. struct mg_domain_context *dom_ctx,
  12211. const char *uri,
  12212. int handler_type,
  12213. int is_delete_request,
  12214. mg_request_handler handler,
  12215. struct mg_websocket_subprotocols *subprotocols,
  12216. mg_websocket_connect_handler connect_handler,
  12217. mg_websocket_ready_handler ready_handler,
  12218. mg_websocket_data_handler data_handler,
  12219. mg_websocket_close_handler close_handler,
  12220. mg_authorization_handler auth_handler,
  12221. void *cbdata)
  12222. {
  12223. struct mg_handler_info *tmp_rh, **lastref;
  12224. size_t urilen = strlen(uri);
  12225. if (handler_type == WEBSOCKET_HANDLER) {
  12226. DEBUG_ASSERT(handler == NULL);
  12227. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12228. || ready_handler != NULL || data_handler != NULL
  12229. || close_handler != NULL);
  12230. DEBUG_ASSERT(auth_handler == NULL);
  12231. if (handler != NULL) {
  12232. return;
  12233. }
  12234. if (!is_delete_request && (connect_handler == NULL)
  12235. && (ready_handler == NULL) && (data_handler == NULL)
  12236. && (close_handler == NULL)) {
  12237. return;
  12238. }
  12239. if (auth_handler != NULL) {
  12240. return;
  12241. }
  12242. } else if (handler_type == REQUEST_HANDLER) {
  12243. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12244. && data_handler == NULL && close_handler == NULL);
  12245. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12246. DEBUG_ASSERT(auth_handler == NULL);
  12247. if ((connect_handler != NULL) || (ready_handler != NULL)
  12248. || (data_handler != NULL) || (close_handler != NULL)) {
  12249. return;
  12250. }
  12251. if (!is_delete_request && (handler == NULL)) {
  12252. return;
  12253. }
  12254. if (auth_handler != NULL) {
  12255. return;
  12256. }
  12257. } else if (handler_type == AUTH_HANDLER) {
  12258. DEBUG_ASSERT(handler == NULL);
  12259. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12260. && data_handler == NULL && close_handler == NULL);
  12261. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12262. if (handler != NULL) {
  12263. return;
  12264. }
  12265. if ((connect_handler != NULL) || (ready_handler != NULL)
  12266. || (data_handler != NULL) || (close_handler != NULL)) {
  12267. return;
  12268. }
  12269. if (!is_delete_request && (auth_handler == NULL)) {
  12270. return;
  12271. }
  12272. } else {
  12273. /* Unknown handler type. */
  12274. return;
  12275. }
  12276. if (!phys_ctx || !dom_ctx) {
  12277. /* no context available */
  12278. return;
  12279. }
  12280. mg_lock_context(phys_ctx);
  12281. /* first try to find an existing handler */
  12282. do {
  12283. lastref = &(dom_ctx->handlers);
  12284. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12285. tmp_rh = tmp_rh->next) {
  12286. if (tmp_rh->handler_type == handler_type
  12287. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12288. if (!is_delete_request) {
  12289. /* update existing handler */
  12290. if (handler_type == REQUEST_HANDLER) {
  12291. /* Wait for end of use before updating */
  12292. if (tmp_rh->refcount) {
  12293. mg_unlock_context(phys_ctx);
  12294. mg_sleep(1);
  12295. mg_lock_context(phys_ctx);
  12296. /* tmp_rh might have been freed, search again. */
  12297. break;
  12298. }
  12299. /* Ok, the handler is no more use -> Update it */
  12300. tmp_rh->handler = handler;
  12301. } else if (handler_type == WEBSOCKET_HANDLER) {
  12302. tmp_rh->subprotocols = subprotocols;
  12303. tmp_rh->connect_handler = connect_handler;
  12304. tmp_rh->ready_handler = ready_handler;
  12305. tmp_rh->data_handler = data_handler;
  12306. tmp_rh->close_handler = close_handler;
  12307. } else { /* AUTH_HANDLER */
  12308. tmp_rh->auth_handler = auth_handler;
  12309. }
  12310. tmp_rh->cbdata = cbdata;
  12311. } else {
  12312. /* remove existing handler */
  12313. if (handler_type == REQUEST_HANDLER) {
  12314. /* Wait for end of use before removing */
  12315. if (tmp_rh->refcount) {
  12316. tmp_rh->removing = 1;
  12317. mg_unlock_context(phys_ctx);
  12318. mg_sleep(1);
  12319. mg_lock_context(phys_ctx);
  12320. /* tmp_rh might have been freed, search again. */
  12321. break;
  12322. }
  12323. /* Ok, the handler is no more used */
  12324. }
  12325. *lastref = tmp_rh->next;
  12326. mg_free(tmp_rh->uri);
  12327. mg_free(tmp_rh);
  12328. }
  12329. mg_unlock_context(phys_ctx);
  12330. return;
  12331. }
  12332. lastref = &(tmp_rh->next);
  12333. }
  12334. } while (tmp_rh != NULL);
  12335. if (is_delete_request) {
  12336. /* no handler to set, this was a remove request to a non-existing
  12337. * handler */
  12338. mg_unlock_context(phys_ctx);
  12339. return;
  12340. }
  12341. tmp_rh =
  12342. (struct mg_handler_info *)mg_calloc_ctx(1,
  12343. sizeof(struct mg_handler_info),
  12344. phys_ctx);
  12345. if (tmp_rh == NULL) {
  12346. mg_unlock_context(phys_ctx);
  12347. mg_cry_ctx_internal(phys_ctx,
  12348. "%s",
  12349. "Cannot create new request handler struct, OOM");
  12350. return;
  12351. }
  12352. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12353. if (!tmp_rh->uri) {
  12354. mg_unlock_context(phys_ctx);
  12355. mg_free(tmp_rh);
  12356. mg_cry_ctx_internal(phys_ctx,
  12357. "%s",
  12358. "Cannot create new request handler struct, OOM");
  12359. return;
  12360. }
  12361. tmp_rh->uri_len = urilen;
  12362. if (handler_type == REQUEST_HANDLER) {
  12363. tmp_rh->refcount = 0;
  12364. tmp_rh->removing = 0;
  12365. tmp_rh->handler = handler;
  12366. } else if (handler_type == WEBSOCKET_HANDLER) {
  12367. tmp_rh->subprotocols = subprotocols;
  12368. tmp_rh->connect_handler = connect_handler;
  12369. tmp_rh->ready_handler = ready_handler;
  12370. tmp_rh->data_handler = data_handler;
  12371. tmp_rh->close_handler = close_handler;
  12372. } else { /* AUTH_HANDLER */
  12373. tmp_rh->auth_handler = auth_handler;
  12374. }
  12375. tmp_rh->cbdata = cbdata;
  12376. tmp_rh->handler_type = handler_type;
  12377. tmp_rh->next = NULL;
  12378. *lastref = tmp_rh;
  12379. mg_unlock_context(phys_ctx);
  12380. }
  12381. CIVETWEB_API void
  12382. mg_set_request_handler(struct mg_context *ctx,
  12383. const char *uri,
  12384. mg_request_handler handler,
  12385. void *cbdata)
  12386. {
  12387. mg_set_handler_type(ctx,
  12388. &(ctx->dd),
  12389. uri,
  12390. REQUEST_HANDLER,
  12391. handler == NULL,
  12392. handler,
  12393. NULL,
  12394. NULL,
  12395. NULL,
  12396. NULL,
  12397. NULL,
  12398. NULL,
  12399. cbdata);
  12400. }
  12401. CIVETWEB_API void
  12402. mg_set_websocket_handler(struct mg_context *ctx,
  12403. const char *uri,
  12404. mg_websocket_connect_handler connect_handler,
  12405. mg_websocket_ready_handler ready_handler,
  12406. mg_websocket_data_handler data_handler,
  12407. mg_websocket_close_handler close_handler,
  12408. void *cbdata)
  12409. {
  12410. mg_set_websocket_handler_with_subprotocols(ctx,
  12411. uri,
  12412. NULL,
  12413. connect_handler,
  12414. ready_handler,
  12415. data_handler,
  12416. close_handler,
  12417. cbdata);
  12418. }
  12419. CIVETWEB_API void
  12420. mg_set_websocket_handler_with_subprotocols(
  12421. struct mg_context *ctx,
  12422. const char *uri,
  12423. struct mg_websocket_subprotocols *subprotocols,
  12424. mg_websocket_connect_handler connect_handler,
  12425. mg_websocket_ready_handler ready_handler,
  12426. mg_websocket_data_handler data_handler,
  12427. mg_websocket_close_handler close_handler,
  12428. void *cbdata)
  12429. {
  12430. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12431. && (data_handler == NULL)
  12432. && (close_handler == NULL);
  12433. mg_set_handler_type(ctx,
  12434. &(ctx->dd),
  12435. uri,
  12436. WEBSOCKET_HANDLER,
  12437. is_delete_request,
  12438. NULL,
  12439. subprotocols,
  12440. connect_handler,
  12441. ready_handler,
  12442. data_handler,
  12443. close_handler,
  12444. NULL,
  12445. cbdata);
  12446. }
  12447. CIVETWEB_API void
  12448. mg_set_auth_handler(struct mg_context *ctx,
  12449. const char *uri,
  12450. mg_authorization_handler handler,
  12451. void *cbdata)
  12452. {
  12453. mg_set_handler_type(ctx,
  12454. &(ctx->dd),
  12455. uri,
  12456. AUTH_HANDLER,
  12457. handler == NULL,
  12458. NULL,
  12459. NULL,
  12460. NULL,
  12461. NULL,
  12462. NULL,
  12463. NULL,
  12464. handler,
  12465. cbdata);
  12466. }
  12467. static int
  12468. get_request_handler(struct mg_connection *conn,
  12469. int handler_type,
  12470. mg_request_handler *handler,
  12471. struct mg_websocket_subprotocols **subprotocols,
  12472. mg_websocket_connect_handler *connect_handler,
  12473. mg_websocket_ready_handler *ready_handler,
  12474. mg_websocket_data_handler *data_handler,
  12475. mg_websocket_close_handler *close_handler,
  12476. mg_authorization_handler *auth_handler,
  12477. void **cbdata,
  12478. struct mg_handler_info **handler_info)
  12479. {
  12480. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12481. if (request_info) {
  12482. const char *uri = request_info->local_uri;
  12483. size_t urilen = strlen(uri);
  12484. struct mg_handler_info *tmp_rh;
  12485. int step, matched;
  12486. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12487. return 0;
  12488. }
  12489. mg_lock_context(conn->phys_ctx);
  12490. for (step = 0; step < 3; step++) {
  12491. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12492. tmp_rh = tmp_rh->next) {
  12493. if (tmp_rh->handler_type != handler_type) {
  12494. continue;
  12495. }
  12496. if (step == 0) {
  12497. /* first try for an exact match */
  12498. matched = (tmp_rh->uri_len == urilen)
  12499. && (strcmp(tmp_rh->uri, uri) == 0);
  12500. } else if (step == 1) {
  12501. /* next try for a partial match, we will accept
  12502. uri/something */
  12503. matched =
  12504. (tmp_rh->uri_len < urilen)
  12505. && (uri[tmp_rh->uri_len] == '/')
  12506. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12507. } else {
  12508. /* finally try for pattern match */
  12509. matched =
  12510. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12511. }
  12512. if (matched) {
  12513. if (handler_type == WEBSOCKET_HANDLER) {
  12514. *subprotocols = tmp_rh->subprotocols;
  12515. *connect_handler = tmp_rh->connect_handler;
  12516. *ready_handler = tmp_rh->ready_handler;
  12517. *data_handler = tmp_rh->data_handler;
  12518. *close_handler = tmp_rh->close_handler;
  12519. } else if (handler_type == REQUEST_HANDLER) {
  12520. if (tmp_rh->removing) {
  12521. /* Treat as none found */
  12522. step = 2;
  12523. break;
  12524. }
  12525. *handler = tmp_rh->handler;
  12526. /* Acquire handler and give it back */
  12527. tmp_rh->refcount++;
  12528. *handler_info = tmp_rh;
  12529. } else { /* AUTH_HANDLER */
  12530. *auth_handler = tmp_rh->auth_handler;
  12531. }
  12532. *cbdata = tmp_rh->cbdata;
  12533. mg_unlock_context(conn->phys_ctx);
  12534. return 1;
  12535. }
  12536. }
  12537. }
  12538. mg_unlock_context(conn->phys_ctx);
  12539. }
  12540. return 0; /* none found */
  12541. }
  12542. /* Check if the script file is in a path, allowed for script files.
  12543. * This can be used if uploading files is possible not only for the server
  12544. * admin, and the upload mechanism does not check the file extension.
  12545. */
  12546. static int
  12547. is_in_script_path(const struct mg_connection *conn, const char *path)
  12548. {
  12549. /* TODO (Feature): Add config value for allowed script path.
  12550. * Default: All allowed. */
  12551. (void)conn;
  12552. (void)path;
  12553. return 1;
  12554. }
  12555. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12556. static int
  12557. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12558. int bits,
  12559. char *data,
  12560. size_t len,
  12561. void *cbdata)
  12562. {
  12563. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12564. if (pcallbacks->websocket_data) {
  12565. return pcallbacks->websocket_data(conn, bits, data, len);
  12566. }
  12567. /* No handler set - assume "OK" */
  12568. return 1;
  12569. }
  12570. static void
  12571. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12572. void *cbdata)
  12573. {
  12574. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12575. if (pcallbacks->connection_close) {
  12576. pcallbacks->connection_close(conn);
  12577. }
  12578. }
  12579. #endif
  12580. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12581. */
  12582. static void
  12583. release_handler_ref(struct mg_connection *conn,
  12584. struct mg_handler_info *handler_info)
  12585. {
  12586. if (handler_info != NULL) {
  12587. /* Use context lock for ref counter */
  12588. mg_lock_context(conn->phys_ctx);
  12589. handler_info->refcount--;
  12590. mg_unlock_context(conn->phys_ctx);
  12591. }
  12592. }
  12593. /* This is the heart of the Civetweb's logic.
  12594. * This function is called when the request is read, parsed and validated,
  12595. * and Civetweb must decide what action to take: serve a file, or
  12596. * a directory, or call embedded function, etcetera. */
  12597. static void
  12598. handle_request(struct mg_connection *conn)
  12599. {
  12600. struct mg_request_info *ri = &conn->request_info;
  12601. char path[UTF8_PATH_MAX];
  12602. int uri_len, ssl_index;
  12603. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12604. is_put_or_delete_request = 0, is_callback_resource = 0,
  12605. is_template_text_file = 0, is_webdav_request = 0;
  12606. int i;
  12607. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12608. mg_request_handler callback_handler = NULL;
  12609. struct mg_handler_info *handler_info = NULL;
  12610. struct mg_websocket_subprotocols *subprotocols;
  12611. mg_websocket_connect_handler ws_connect_handler = NULL;
  12612. mg_websocket_ready_handler ws_ready_handler = NULL;
  12613. mg_websocket_data_handler ws_data_handler = NULL;
  12614. mg_websocket_close_handler ws_close_handler = NULL;
  12615. void *callback_data = NULL;
  12616. mg_authorization_handler auth_handler = NULL;
  12617. void *auth_callback_data = NULL;
  12618. int handler_type;
  12619. time_t curtime = time(NULL);
  12620. char date[64];
  12621. char *tmp;
  12622. path[0] = 0;
  12623. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12624. conn->request_state = 0;
  12625. /* 1. get the request url */
  12626. /* 1.1. split into url and query string */
  12627. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12628. != NULL) {
  12629. *((char *)conn->request_info.query_string++) = '\0';
  12630. }
  12631. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12632. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12633. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12634. if (ssl_index >= 0) {
  12635. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12636. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12637. redirect_to_https_port(conn, port);
  12638. } else {
  12639. /* A http to https forward port has been specified,
  12640. * but no https port to forward to. */
  12641. mg_send_http_error(conn,
  12642. 503,
  12643. "%s",
  12644. "Error: SSL forward not configured properly");
  12645. mg_cry_internal(conn,
  12646. "%s",
  12647. "Can not redirect to SSL, no SSL port available");
  12648. }
  12649. return;
  12650. }
  12651. uri_len = (int)strlen(ri->local_uri);
  12652. /* 1.3. decode url (if config says so) */
  12653. if (should_decode_url(conn)) {
  12654. url_decode_in_place((char *)ri->local_uri);
  12655. }
  12656. /* URL decode the query-string only if explicitly set in the configuration */
  12657. if (conn->request_info.query_string) {
  12658. if (should_decode_query_string(conn)) {
  12659. url_decode_in_place((char *)conn->request_info.query_string);
  12660. }
  12661. }
  12662. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12663. * possible. The fact that we cleaned the URI is stored in that the
  12664. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12665. * ri->local_uri_raw still points to memory allocated in
  12666. * worker_thread_run(). ri->local_uri is private to the request so we
  12667. * don't have to use preallocated memory here. */
  12668. tmp = mg_strdup(ri->local_uri_raw);
  12669. if (!tmp) {
  12670. /* Out of memory. We cannot do anything reasonable here. */
  12671. return;
  12672. }
  12673. remove_dot_segments(tmp);
  12674. ri->local_uri = tmp;
  12675. /* step 1. completed, the url is known now */
  12676. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12677. /* 2. if this ip has limited speed, set it for this connection */
  12678. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12679. &conn->client.rsa,
  12680. ri->local_uri);
  12681. /* 3. call a "handle everything" callback, if registered */
  12682. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12683. /* Note that since V1.7 the "begin_request" function is called
  12684. * before an authorization check. If an authorization check is
  12685. * required, use a request_handler instead. */
  12686. i = conn->phys_ctx->callbacks.begin_request(conn);
  12687. if (i > 0) {
  12688. /* callback already processed the request. Store the
  12689. return value as a status code for the access log. */
  12690. conn->status_code = i;
  12691. if (!conn->must_close) {
  12692. discard_unread_request_data(conn);
  12693. }
  12694. DEBUG_TRACE("%s", "begin_request handled request");
  12695. return;
  12696. } else if (i == 0) {
  12697. /* civetweb should process the request */
  12698. } else {
  12699. /* unspecified - may change with the next version */
  12700. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12701. return;
  12702. }
  12703. }
  12704. /* request not yet handled by a handler or redirect, so the request
  12705. * is processed here */
  12706. /* 4. Check for CORS preflight requests and handle them (if configured).
  12707. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12708. */
  12709. if (!strcmp(ri->request_method, "OPTIONS")) {
  12710. /* Send a response to CORS preflights only if
  12711. * access_control_allow_methods is not NULL and not an empty string.
  12712. * In this case, scripts can still handle CORS. */
  12713. const char *cors_meth_cfg =
  12714. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12715. const char *cors_orig_cfg =
  12716. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12717. const char *cors_origin =
  12718. get_header(ri->http_headers, ri->num_headers, "Origin");
  12719. const char *cors_acrm = get_header(ri->http_headers,
  12720. ri->num_headers,
  12721. "Access-Control-Request-Method");
  12722. /* Todo: check if cors_origin is in cors_orig_cfg.
  12723. * Or, let the client check this. */
  12724. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12725. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12726. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12727. /* This is a valid CORS preflight, and the server is configured
  12728. * to handle it automatically. */
  12729. const char *cors_acrh =
  12730. get_header(ri->http_headers,
  12731. ri->num_headers,
  12732. "Access-Control-Request-Headers");
  12733. gmt_time_string(date, sizeof(date), &curtime);
  12734. mg_printf(conn,
  12735. "HTTP/1.1 200 OK\r\n"
  12736. "Date: %s\r\n"
  12737. "Access-Control-Allow-Origin: %s\r\n"
  12738. "Access-Control-Allow-Methods: %s\r\n"
  12739. "Content-Length: 0\r\n"
  12740. "Connection: %s\r\n",
  12741. date,
  12742. cors_orig_cfg,
  12743. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12744. suggest_connection_header(conn));
  12745. if (cors_acrh != NULL) {
  12746. /* CORS request is asking for additional headers */
  12747. const char *cors_hdr_cfg =
  12748. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12749. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12750. /* Allow only if access_control_allow_headers is
  12751. * not NULL and not an empty string. If this
  12752. * configuration is set to *, allow everything.
  12753. * Otherwise this configuration must be a list
  12754. * of allowed HTTP header names. */
  12755. mg_printf(conn,
  12756. "Access-Control-Allow-Headers: %s\r\n",
  12757. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12758. : cors_hdr_cfg));
  12759. }
  12760. }
  12761. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12762. mg_printf(conn, "\r\n");
  12763. DEBUG_TRACE("%s", "OPTIONS done");
  12764. return;
  12765. }
  12766. }
  12767. /* 5. interpret the url to find out how the request must be handled
  12768. */
  12769. /* 5.1. first test, if the request targets the regular http(s)://
  12770. * protocol namespace or the websocket ws(s):// protocol namespace.
  12771. */
  12772. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12773. #if defined(USE_WEBSOCKET)
  12774. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12775. #else
  12776. handler_type = REQUEST_HANDLER;
  12777. #endif /* defined(USE_WEBSOCKET) */
  12778. if (is_websocket_request) {
  12779. HTTP1_only;
  12780. }
  12781. /* 5.2. check if the request will be handled by a callback */
  12782. if (get_request_handler(conn,
  12783. handler_type,
  12784. &callback_handler,
  12785. &subprotocols,
  12786. &ws_connect_handler,
  12787. &ws_ready_handler,
  12788. &ws_data_handler,
  12789. &ws_close_handler,
  12790. NULL,
  12791. &callback_data,
  12792. &handler_info)) {
  12793. /* 5.2.1. A callback will handle this request. All requests
  12794. * handled by a callback have to be considered as requests
  12795. * to a script resource. */
  12796. is_callback_resource = 1;
  12797. is_script_resource = 1;
  12798. is_put_or_delete_request = is_put_or_delete_method(conn);
  12799. /* Never handle a C callback according to File WebDav rules,
  12800. * even if it is a webdav method */
  12801. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12802. } else {
  12803. no_callback_resource:
  12804. /* 5.2.2. No callback is responsible for this request. The URI
  12805. * addresses a file based resource (static content or Lua/cgi
  12806. * scripts in the file system). */
  12807. is_callback_resource = 0;
  12808. interpret_uri(conn,
  12809. path,
  12810. sizeof(path),
  12811. &file.stat,
  12812. &is_found,
  12813. &is_script_resource,
  12814. &is_websocket_request,
  12815. &is_put_or_delete_request,
  12816. &is_webdav_request,
  12817. &is_template_text_file);
  12818. }
  12819. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12820. if (is_webdav_request) {
  12821. /* TODO: Do we need a config option? */
  12822. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  12823. if (webdav_enable[0] != 'y') {
  12824. mg_send_http_error(conn,
  12825. 405,
  12826. "%s method not allowed",
  12827. conn->request_info.request_method);
  12828. DEBUG_TRACE("%s", "webdav rejected");
  12829. return;
  12830. }
  12831. }
  12832. /* 6. authorization check */
  12833. /* 6.1. a custom authorization handler is installed */
  12834. if (get_request_handler(conn,
  12835. AUTH_HANDLER,
  12836. NULL,
  12837. NULL,
  12838. NULL,
  12839. NULL,
  12840. NULL,
  12841. NULL,
  12842. &auth_handler,
  12843. &auth_callback_data,
  12844. NULL)) {
  12845. if (!auth_handler(conn, auth_callback_data)) {
  12846. /* Callback handler will not be used anymore. Release it */
  12847. release_handler_ref(conn, handler_info);
  12848. DEBUG_TRACE("%s", "auth handler rejected request");
  12849. return;
  12850. }
  12851. } else if (is_put_or_delete_request && !is_script_resource
  12852. && !is_callback_resource) {
  12853. HTTP1_only;
  12854. /* 6.2. this request is a PUT/DELETE to a real file */
  12855. /* 6.2.1. thus, the server must have real files */
  12856. #if defined(NO_FILES)
  12857. if (1) {
  12858. #else
  12859. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  12860. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  12861. #endif
  12862. /* This code path will not be called for request handlers */
  12863. DEBUG_ASSERT(handler_info == NULL);
  12864. /* This server does not have any real files, thus the
  12865. * PUT/DELETE methods are not valid. */
  12866. mg_send_http_error(conn,
  12867. 405,
  12868. "%s method not allowed",
  12869. conn->request_info.request_method);
  12870. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  12871. return;
  12872. }
  12873. #if !defined(NO_FILES)
  12874. /* 6.2.2. Check if put authorization for static files is
  12875. * available.
  12876. */
  12877. if (!is_authorized_for_put(conn)) {
  12878. send_authorization_request(conn, NULL);
  12879. DEBUG_TRACE("%s", "file write needs authorization");
  12880. return;
  12881. }
  12882. #endif
  12883. } else {
  12884. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12885. * or it is a PUT or DELETE request to a resource that does not
  12886. * correspond to a file. Check authorization. */
  12887. if (!check_authorization(conn, path)) {
  12888. send_authorization_request(conn, NULL);
  12889. /* Callback handler will not be used anymore. Release it */
  12890. release_handler_ref(conn, handler_info);
  12891. DEBUG_TRACE("%s", "access authorization required");
  12892. return;
  12893. }
  12894. }
  12895. /* request is authorized or does not need authorization */
  12896. /* 7. check if there are request handlers for this uri */
  12897. if (is_callback_resource) {
  12898. HTTP1_only;
  12899. if (!is_websocket_request) {
  12900. i = callback_handler(conn, callback_data);
  12901. /* Callback handler will not be used anymore. Release it */
  12902. release_handler_ref(conn, handler_info);
  12903. if (i > 0) {
  12904. /* Do nothing, callback has served the request. Store
  12905. * then return value as status code for the log and discard
  12906. * all data from the client not used by the callback. */
  12907. conn->status_code = i;
  12908. if (!conn->must_close) {
  12909. discard_unread_request_data(conn);
  12910. }
  12911. } else {
  12912. /* The handler did NOT handle the request. */
  12913. /* Some proper reactions would be:
  12914. * a) close the connections without sending anything
  12915. * b) send a 404 not found
  12916. * c) try if there is a file matching the URI
  12917. * It would be possible to do a, b or c in the callback
  12918. * implementation, and return 1 - we cannot do anything
  12919. * here, that is not possible in the callback.
  12920. *
  12921. * TODO: What would be the best reaction here?
  12922. * (Note: The reaction may change, if there is a better
  12923. * idea.)
  12924. */
  12925. /* For the moment, use option c: We look for a proper file,
  12926. * but since a file request is not always a script resource,
  12927. * the authorization check might be different. */
  12928. callback_handler = NULL;
  12929. /* Here we are at a dead end:
  12930. * According to URI matching, a callback should be
  12931. * responsible for handling the request,
  12932. * we called it, but the callback declared itself
  12933. * not responsible.
  12934. * We use a goto here, to get out of this dead end,
  12935. * and continue with the default handling.
  12936. * A goto here is simpler and better to understand
  12937. * than some curious loop. */
  12938. goto no_callback_resource;
  12939. }
  12940. } else {
  12941. #if defined(USE_WEBSOCKET)
  12942. handle_websocket_request(conn,
  12943. path,
  12944. is_callback_resource,
  12945. subprotocols,
  12946. ws_connect_handler,
  12947. ws_ready_handler,
  12948. ws_data_handler,
  12949. ws_close_handler,
  12950. callback_data);
  12951. #endif
  12952. }
  12953. DEBUG_TRACE("%s", "websocket handling done");
  12954. return;
  12955. }
  12956. /* 8. handle websocket requests */
  12957. #if defined(USE_WEBSOCKET)
  12958. if (is_websocket_request) {
  12959. HTTP1_only;
  12960. if (is_script_resource) {
  12961. if (is_in_script_path(conn, path)) {
  12962. /* Websocket Lua script */
  12963. handle_websocket_request(conn,
  12964. path,
  12965. 0 /* Lua Script */,
  12966. NULL,
  12967. NULL,
  12968. NULL,
  12969. NULL,
  12970. NULL,
  12971. conn->phys_ctx->user_data);
  12972. } else {
  12973. /* Script was in an illegal path */
  12974. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12975. }
  12976. } else {
  12977. mg_send_http_error(conn, 404, "%s", "Not found");
  12978. }
  12979. DEBUG_TRACE("%s", "websocket script done");
  12980. return;
  12981. } else
  12982. #endif
  12983. #if defined(NO_FILES)
  12984. /* 9a. In case the server uses only callbacks, this uri is
  12985. * unknown.
  12986. * Then, all request handling ends here. */
  12987. mg_send_http_error(conn, 404, "%s", "Not Found");
  12988. #else
  12989. /* 9b. This request is either for a static file or resource handled
  12990. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12991. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12992. mg_send_http_error(conn, 404, "%s", "Not Found");
  12993. DEBUG_TRACE("%s", "no document root available");
  12994. return;
  12995. }
  12996. /* 10. Request is handled by a script */
  12997. if (is_script_resource) {
  12998. HTTP1_only;
  12999. handle_file_based_request(conn, path, &file);
  13000. DEBUG_TRACE("%s", "script handling done");
  13001. return;
  13002. }
  13003. /* Request was not handled by a callback or script. It will be
  13004. * handled by a server internal method. */
  13005. /* 11. Handle put/delete/mkcol requests */
  13006. if (is_put_or_delete_request) {
  13007. HTTP1_only;
  13008. /* 11.1. PUT method */
  13009. if (!strcmp(ri->request_method, "PUT")) {
  13010. put_file(conn, path);
  13011. DEBUG_TRACE("handling %s request to %s done",
  13012. ri->request_method,
  13013. path);
  13014. return;
  13015. }
  13016. /* 11.2. DELETE method */
  13017. if (!strcmp(ri->request_method, "DELETE")) {
  13018. delete_file(conn, path);
  13019. DEBUG_TRACE("handling %s request to %s done",
  13020. ri->request_method,
  13021. path);
  13022. return;
  13023. }
  13024. /* 11.3. MKCOL method */
  13025. if (!strcmp(ri->request_method, "MKCOL")) {
  13026. dav_mkcol(conn, path);
  13027. DEBUG_TRACE("handling %s request to %s done",
  13028. ri->request_method,
  13029. path);
  13030. return;
  13031. }
  13032. /* 11.4. MOVE method */
  13033. if (!strcmp(ri->request_method, "MOVE")) {
  13034. dav_move_file(conn, path, 0);
  13035. DEBUG_TRACE("handling %s request to %s done",
  13036. ri->request_method,
  13037. path);
  13038. return;
  13039. }
  13040. if (!strcmp(ri->request_method, "COPY")) {
  13041. dav_move_file(conn, path, 1);
  13042. DEBUG_TRACE("handling %s request to %s done",
  13043. ri->request_method,
  13044. path);
  13045. return;
  13046. }
  13047. /* 11.5. LOCK method */
  13048. if (!strcmp(ri->request_method, "LOCK")) {
  13049. dav_lock_file(conn, path);
  13050. DEBUG_TRACE("handling %s request to %s done",
  13051. ri->request_method,
  13052. path);
  13053. return;
  13054. }
  13055. /* 11.6. UNLOCK method */
  13056. if (!strcmp(ri->request_method, "UNLOCK")) {
  13057. dav_unlock_file(conn, path);
  13058. DEBUG_TRACE("handling %s request to %s done",
  13059. ri->request_method,
  13060. path);
  13061. return;
  13062. }
  13063. /* 11.7. PROPPATCH method */
  13064. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13065. dav_proppatch(conn, path);
  13066. DEBUG_TRACE("handling %s request to %s done",
  13067. ri->request_method,
  13068. path);
  13069. return;
  13070. }
  13071. /* 11.8. Other methods, e.g.: PATCH
  13072. * This method is not supported for static resources,
  13073. * only for scripts (Lua, CGI) and callbacks. */
  13074. mg_send_http_error(conn,
  13075. 405,
  13076. "%s method not allowed",
  13077. conn->request_info.request_method);
  13078. DEBUG_TRACE("method %s on %s is not supported",
  13079. ri->request_method,
  13080. path);
  13081. return;
  13082. }
  13083. /* 11. File does not exist, or it was configured that it should be
  13084. * hidden */
  13085. if (!is_found || (must_hide_file(conn, path))) {
  13086. mg_send_http_error(conn, 404, "%s", "Not found");
  13087. DEBUG_TRACE("handling %s request to %s: file not found",
  13088. ri->request_method,
  13089. path);
  13090. return;
  13091. }
  13092. /* 12. Directory uris should end with a slash */
  13093. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13094. && (ri->local_uri[uri_len - 1] != '/')) {
  13095. /* Path + server root */
  13096. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13097. char *new_path;
  13098. if (ri->query_string) {
  13099. buflen += strlen(ri->query_string);
  13100. }
  13101. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13102. if (!new_path) {
  13103. mg_send_http_error(conn, 500, "out or memory");
  13104. } else {
  13105. mg_get_request_link(conn, new_path, buflen - 1);
  13106. strcat(new_path, "/");
  13107. if (ri->query_string) {
  13108. /* Append ? and query string */
  13109. strcat(new_path, "?");
  13110. strcat(new_path, ri->query_string);
  13111. }
  13112. mg_send_http_redirect(conn, new_path, 301);
  13113. mg_free(new_path);
  13114. }
  13115. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13116. ri->request_method,
  13117. path);
  13118. return;
  13119. }
  13120. /* 13. Handle other methods than GET/HEAD */
  13121. /* 13.1. Handle PROPFIND */
  13122. if (!strcmp(ri->request_method, "PROPFIND")) {
  13123. handle_propfind(conn, path, &file.stat);
  13124. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13125. return;
  13126. }
  13127. /* 13.2. Handle OPTIONS for files */
  13128. if (!strcmp(ri->request_method, "OPTIONS")) {
  13129. /* This standard handler is only used for real files.
  13130. * Scripts should support the OPTIONS method themselves, to allow a
  13131. * maximum flexibility.
  13132. * Lua and CGI scripts may fully support CORS this way (including
  13133. * preflights). */
  13134. send_options(conn);
  13135. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13136. return;
  13137. }
  13138. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13139. if ((0 != strcmp(ri->request_method, "GET"))
  13140. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13141. mg_send_http_error(conn,
  13142. 405,
  13143. "%s method not allowed",
  13144. conn->request_info.request_method);
  13145. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13146. return;
  13147. }
  13148. /* 14. directories */
  13149. if (file.stat.is_directory) {
  13150. /* Substitute files have already been handled above. */
  13151. /* Here we can either generate and send a directory listing,
  13152. * or send an "access denied" error. */
  13153. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13154. "yes")) {
  13155. handle_directory_request(conn, path);
  13156. } else {
  13157. mg_send_http_error(conn,
  13158. 403,
  13159. "%s",
  13160. "Error: Directory listing denied");
  13161. }
  13162. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13163. return;
  13164. }
  13165. /* 15. Files with search/replace patterns: LSP and SSI */
  13166. if (is_template_text_file) {
  13167. HTTP1_only;
  13168. handle_file_based_request(conn, path, &file);
  13169. DEBUG_TRACE("handling %s request to %s done (template)",
  13170. ri->request_method,
  13171. path);
  13172. return;
  13173. }
  13174. /* 16. Static file - maybe cached */
  13175. #if !defined(NO_CACHING)
  13176. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13177. /* Send 304 "Not Modified" - this must not send any body data */
  13178. handle_not_modified_static_file_request(conn, &file);
  13179. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13180. ri->request_method,
  13181. path);
  13182. return;
  13183. }
  13184. #endif /* !NO_CACHING */
  13185. /* 17. Static file - not cached */
  13186. handle_static_file_request(conn, path, &file, NULL, NULL);
  13187. DEBUG_TRACE("handling %s request to %s done (static)",
  13188. ri->request_method,
  13189. path);
  13190. #endif /* !defined(NO_FILES) */
  13191. }
  13192. #if !defined(NO_FILESYSTEMS)
  13193. static void
  13194. handle_file_based_request(struct mg_connection *conn,
  13195. const char *path,
  13196. struct mg_file *file)
  13197. {
  13198. #if !defined(NO_CGI)
  13199. unsigned char cgi_config_idx, inc, max;
  13200. #endif
  13201. if (!conn || !conn->dom_ctx) {
  13202. return;
  13203. }
  13204. #if defined(USE_LUA)
  13205. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13206. path)
  13207. > 0) {
  13208. if (is_in_script_path(conn, path)) {
  13209. /* Lua server page: an SSI like page containing mostly plain
  13210. * html code plus some tags with server generated contents. */
  13211. handle_lsp_request(conn, path, file, NULL);
  13212. } else {
  13213. /* Script was in an illegal path */
  13214. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13215. }
  13216. return;
  13217. }
  13218. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13219. > 0) {
  13220. if (is_in_script_path(conn, path)) {
  13221. /* Lua in-server module script: a CGI like script used to
  13222. * generate the entire reply. */
  13223. mg_exec_lua_script(conn, path, NULL);
  13224. } else {
  13225. /* Script was in an illegal path */
  13226. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13227. }
  13228. return;
  13229. }
  13230. #endif
  13231. #if defined(USE_DUKTAPE)
  13232. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13233. path)
  13234. > 0) {
  13235. if (is_in_script_path(conn, path)) {
  13236. /* Call duktape to generate the page */
  13237. mg_exec_duktape_script(conn, path);
  13238. } else {
  13239. /* Script was in an illegal path */
  13240. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13241. }
  13242. return;
  13243. }
  13244. #endif
  13245. #if !defined(NO_CGI)
  13246. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13247. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13248. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13249. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13250. if (match_prefix_strlen(
  13251. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13252. path)
  13253. > 0) {
  13254. if (is_in_script_path(conn, path)) {
  13255. /* CGI scripts may support all HTTP methods */
  13256. handle_cgi_request(conn, path, cgi_config_idx);
  13257. } else {
  13258. /* Script was in an illegal path */
  13259. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13260. }
  13261. return;
  13262. }
  13263. }
  13264. }
  13265. #endif /* !NO_CGI */
  13266. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13267. if (is_in_script_path(conn, path)) {
  13268. handle_ssi_file_request(conn, path, file);
  13269. } else {
  13270. /* Script was in an illegal path */
  13271. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13272. }
  13273. return;
  13274. }
  13275. #if !defined(NO_CACHING)
  13276. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13277. /* Send 304 "Not Modified" - this must not send any body data */
  13278. handle_not_modified_static_file_request(conn, file);
  13279. return;
  13280. }
  13281. #endif /* !NO_CACHING */
  13282. handle_static_file_request(conn, path, file, NULL, NULL);
  13283. }
  13284. #endif /* NO_FILESYSTEMS */
  13285. static void
  13286. close_all_listening_sockets(struct mg_context *ctx)
  13287. {
  13288. unsigned int i;
  13289. if (!ctx) {
  13290. return;
  13291. }
  13292. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13293. closesocket(ctx->listening_sockets[i].sock);
  13294. #if defined(USE_X_DOM_SOCKET)
  13295. /* For unix domain sockets, the socket name represents a file that has
  13296. * to be deleted. */
  13297. /* See
  13298. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13299. */
  13300. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13301. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13302. IGNORE_UNUSED_RESULT(
  13303. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13304. }
  13305. #endif
  13306. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13307. }
  13308. mg_free(ctx->listening_sockets);
  13309. ctx->listening_sockets = NULL;
  13310. mg_free(ctx->listening_socket_fds);
  13311. ctx->listening_socket_fds = NULL;
  13312. }
  13313. /* Valid listening port specification is: [ip_address:]port[s]
  13314. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13315. * Examples for IPv6: [::]:80, [::1]:80,
  13316. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13317. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13318. * In order to bind to both, IPv4 and IPv6, you can either add
  13319. * both ports using 8080,[::]:8080, or the short form +8080.
  13320. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13321. * one only accepting IPv4 the other only IPv6. +8080 creates
  13322. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13323. * environment, they might work differently, or might not work
  13324. * at all - it must be tested what options work best in the
  13325. * relevant network environment.
  13326. */
  13327. static int
  13328. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13329. {
  13330. unsigned int a, b, c, d;
  13331. unsigned port;
  13332. unsigned long portUL;
  13333. int ch, len;
  13334. const char *cb;
  13335. char *endptr;
  13336. #if defined(USE_IPV6)
  13337. char buf[100] = {0};
  13338. #endif
  13339. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13340. * Also, all-zeroes in the socket address means binding to all addresses
  13341. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13342. memset(so, 0, sizeof(*so));
  13343. so->lsa.sin.sin_family = AF_INET;
  13344. *ip_version = 0;
  13345. /* Initialize len as invalid. */
  13346. port = 0;
  13347. len = 0;
  13348. /* Test for different ways to format this string */
  13349. if (sscanf(vec->ptr,
  13350. "%u.%u.%u.%u:%u%n",
  13351. &a,
  13352. &b,
  13353. &c,
  13354. &d,
  13355. &port,
  13356. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13357. // to an integer value, but function will not report
  13358. // conversion errors; consider using 'strtol' instead
  13359. == 5) {
  13360. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13361. so->lsa.sin.sin_addr.s_addr =
  13362. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13363. so->lsa.sin.sin_port = htons((uint16_t)port);
  13364. *ip_version = 4;
  13365. #if defined(USE_IPV6)
  13366. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13367. && ((size_t)len <= vec->len)
  13368. && mg_inet_pton(
  13369. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13370. /* IPv6 address, examples: see above */
  13371. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13372. */
  13373. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13374. *ip_version = 6;
  13375. #endif
  13376. } else if ((vec->ptr[0] == '+')
  13377. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13378. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13379. // string to an integer value, but function will not
  13380. // report conversion errors; consider using 'strtol'
  13381. // instead
  13382. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13383. /* Add 1 to len for the + character we skipped before */
  13384. len++;
  13385. #if defined(USE_IPV6)
  13386. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13387. so->lsa.sin6.sin6_family = AF_INET6;
  13388. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13389. *ip_version = 4 + 6;
  13390. #else
  13391. /* Bind to IPv4 only, since IPv6 is not built in. */
  13392. so->lsa.sin.sin_port = htons((uint16_t)port);
  13393. *ip_version = 4;
  13394. #endif
  13395. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13396. && (vec->ptr != endptr)) {
  13397. len = (int)(endptr - vec->ptr);
  13398. port = (uint16_t)portUL;
  13399. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13400. so->lsa.sin.sin_port = htons((uint16_t)port);
  13401. *ip_version = 4;
  13402. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13403. /* String could be a hostname. This check algorithm
  13404. * will only work for RFC 952 compliant hostnames,
  13405. * starting with a letter, containing only letters,
  13406. * digits and hyphen ('-'). Newer specs may allow
  13407. * more, but this is not guaranteed here, since it
  13408. * may interfere with rules for port option lists. */
  13409. /* According to RFC 1035, hostnames are restricted to 255 characters
  13410. * in total (63 between two dots). */
  13411. char hostname[256];
  13412. size_t hostnlen = (size_t)(cb - vec->ptr);
  13413. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13414. /* This would be invalid in any case */
  13415. *ip_version = 0;
  13416. return 0;
  13417. }
  13418. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13419. if (mg_inet_pton(
  13420. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13421. if (sscanf(cb + 1, "%u%n", &port, &len)
  13422. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13423. // string to an integer value, but function will not
  13424. // report conversion errors; consider using 'strtol'
  13425. // instead
  13426. *ip_version = 4;
  13427. so->lsa.sin.sin_port = htons((uint16_t)port);
  13428. len += (int)(hostnlen + 1);
  13429. } else {
  13430. len = 0;
  13431. }
  13432. #if defined(USE_IPV6)
  13433. } else if (mg_inet_pton(AF_INET6,
  13434. hostname,
  13435. &so->lsa.sin6,
  13436. sizeof(so->lsa.sin6),
  13437. 1)) {
  13438. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13439. *ip_version = 6;
  13440. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13441. len += (int)(hostnlen + 1);
  13442. } else {
  13443. len = 0;
  13444. }
  13445. #endif
  13446. } else {
  13447. len = 0;
  13448. }
  13449. #if defined(USE_X_DOM_SOCKET)
  13450. } else if (vec->ptr[0] == 'x') {
  13451. /* unix (linux) domain socket */
  13452. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13453. len = vec->len;
  13454. so->lsa.sun.sun_family = AF_UNIX;
  13455. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13456. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13457. port = 0;
  13458. *ip_version = 99;
  13459. } else {
  13460. /* String too long */
  13461. len = 0;
  13462. }
  13463. #endif
  13464. } else {
  13465. /* Parsing failure. */
  13466. len = 0;
  13467. }
  13468. /* sscanf and the option splitting code ensure the following condition
  13469. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13470. if ((len > 0) && is_valid_port(port)
  13471. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13472. /* Next character after the port number */
  13473. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13474. so->is_ssl = (ch == 's');
  13475. so->ssl_redir = (ch == 'r');
  13476. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13477. return 1;
  13478. }
  13479. }
  13480. /* Reset ip_version to 0 if there is an error */
  13481. *ip_version = 0;
  13482. return 0;
  13483. }
  13484. /* Is there any SSL port in use? */
  13485. static int
  13486. is_ssl_port_used(const char *ports)
  13487. {
  13488. if (ports) {
  13489. /* There are several different allowed syntax variants:
  13490. * - "80" for a single port using every network interface
  13491. * - "localhost:80" for a single port using only localhost
  13492. * - "80,localhost:8080" for two ports, one bound to localhost
  13493. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13494. * to IPv4 localhost, one to IPv6 localhost
  13495. * - "+80" use port 80 for IPv4 and IPv6
  13496. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13497. * for both: IPv4 and IPv4
  13498. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13499. * additionally port 8080 bound to localhost connections
  13500. *
  13501. * If we just look for 's' anywhere in the string, "localhost:80"
  13502. * will be detected as SSL (false positive).
  13503. * Looking for 's' after a digit may cause false positives in
  13504. * "my24service:8080".
  13505. * Looking from 's' backward if there are only ':' and numbers
  13506. * before will not work for "24service:8080" (non SSL, port 8080)
  13507. * or "24s" (SSL, port 24).
  13508. *
  13509. * Remark: Initially hostnames were not allowed to start with a
  13510. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13511. * Section 2.1).
  13512. *
  13513. * To get this correct, the entire string must be parsed as a whole,
  13514. * reading it as a list element for element and parsing with an
  13515. * algorithm equivalent to parse_port_string.
  13516. *
  13517. * In fact, we use local interface names here, not arbitrary
  13518. * hostnames, so in most cases the only name will be "localhost".
  13519. *
  13520. * So, for now, we use this simple algorithm, that may still return
  13521. * a false positive in bizarre cases.
  13522. */
  13523. int i;
  13524. int portslen = (int)strlen(ports);
  13525. char prevIsNumber = 0;
  13526. for (i = 0; i < portslen; i++) {
  13527. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13528. return 1;
  13529. }
  13530. if (ports[i] >= '0' && ports[i] <= '9') {
  13531. prevIsNumber = 1;
  13532. } else {
  13533. prevIsNumber = 0;
  13534. }
  13535. }
  13536. }
  13537. return 0;
  13538. }
  13539. static int
  13540. set_ports_option(struct mg_context *phys_ctx)
  13541. {
  13542. const char *list;
  13543. int on = 1;
  13544. #if defined(USE_IPV6)
  13545. int off = 0;
  13546. #endif
  13547. struct vec vec;
  13548. struct socket so, *ptr;
  13549. struct mg_pollfd *pfd;
  13550. union usa usa;
  13551. socklen_t len;
  13552. int ip_version;
  13553. int portsTotal = 0;
  13554. int portsOk = 0;
  13555. const char *opt_txt;
  13556. long opt_listen_backlog;
  13557. if (!phys_ctx) {
  13558. return 0;
  13559. }
  13560. memset(&so, 0, sizeof(so));
  13561. memset(&usa, 0, sizeof(usa));
  13562. len = sizeof(usa);
  13563. list = phys_ctx->dd.config[LISTENING_PORTS];
  13564. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13565. portsTotal++;
  13566. if (!parse_port_string(&vec, &so, &ip_version)) {
  13567. mg_cry_ctx_internal(
  13568. phys_ctx,
  13569. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13570. (int)vec.len,
  13571. vec.ptr,
  13572. portsTotal,
  13573. "[IP_ADDRESS:]PORT[s|r]");
  13574. continue;
  13575. }
  13576. #if !defined(NO_SSL)
  13577. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13578. mg_cry_ctx_internal(phys_ctx,
  13579. "Cannot add SSL socket (entry %i)",
  13580. portsTotal);
  13581. continue;
  13582. }
  13583. #endif
  13584. /* Create socket. */
  13585. /* For a list of protocol numbers (e.g., TCP==6) see:
  13586. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13587. */
  13588. if ((so.sock =
  13589. socket(so.lsa.sa.sa_family,
  13590. SOCK_STREAM,
  13591. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13592. == INVALID_SOCKET) {
  13593. mg_cry_ctx_internal(phys_ctx,
  13594. "cannot create socket (entry %i)",
  13595. portsTotal);
  13596. continue;
  13597. }
  13598. #if defined(_WIN32)
  13599. /* Windows SO_REUSEADDR lets many procs binds to a
  13600. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13601. * if someone already has the socket -- DTL */
  13602. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13603. * Windows might need a few seconds before
  13604. * the same port can be used again in the
  13605. * same process, so a short Sleep may be
  13606. * required between mg_stop and mg_start.
  13607. */
  13608. if (setsockopt(so.sock,
  13609. SOL_SOCKET,
  13610. SO_EXCLUSIVEADDRUSE,
  13611. (SOCK_OPT_TYPE)&on,
  13612. sizeof(on))
  13613. != 0) {
  13614. /* Set reuse option, but don't abort on errors. */
  13615. mg_cry_ctx_internal(
  13616. phys_ctx,
  13617. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13618. portsTotal);
  13619. }
  13620. #else
  13621. if (setsockopt(so.sock,
  13622. SOL_SOCKET,
  13623. SO_REUSEADDR,
  13624. (SOCK_OPT_TYPE)&on,
  13625. sizeof(on))
  13626. != 0) {
  13627. /* Set reuse option, but don't abort on errors. */
  13628. mg_cry_ctx_internal(
  13629. phys_ctx,
  13630. "cannot set socket option SO_REUSEADDR (entry %i)",
  13631. portsTotal);
  13632. }
  13633. #endif
  13634. #if defined(USE_X_DOM_SOCKET)
  13635. if (ip_version == 99) {
  13636. /* Unix domain socket */
  13637. } else
  13638. #endif
  13639. if (ip_version > 4) {
  13640. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13641. #if defined(USE_IPV6)
  13642. if (ip_version > 6) {
  13643. if (so.lsa.sa.sa_family == AF_INET6
  13644. && setsockopt(so.sock,
  13645. IPPROTO_IPV6,
  13646. IPV6_V6ONLY,
  13647. (void *)&off,
  13648. sizeof(off))
  13649. != 0) {
  13650. /* Set IPv6 only option, but don't abort on errors. */
  13651. mg_cry_ctx_internal(phys_ctx,
  13652. "cannot set socket option "
  13653. "IPV6_V6ONLY=off (entry %i)",
  13654. portsTotal);
  13655. }
  13656. } else {
  13657. if (so.lsa.sa.sa_family == AF_INET6
  13658. && setsockopt(so.sock,
  13659. IPPROTO_IPV6,
  13660. IPV6_V6ONLY,
  13661. (void *)&on,
  13662. sizeof(on))
  13663. != 0) {
  13664. /* Set IPv6 only option, but don't abort on errors. */
  13665. mg_cry_ctx_internal(phys_ctx,
  13666. "cannot set socket option "
  13667. "IPV6_V6ONLY=on (entry %i)",
  13668. portsTotal);
  13669. }
  13670. }
  13671. #else
  13672. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13673. closesocket(so.sock);
  13674. so.sock = INVALID_SOCKET;
  13675. continue;
  13676. #endif
  13677. }
  13678. if (so.lsa.sa.sa_family == AF_INET) {
  13679. len = sizeof(so.lsa.sin);
  13680. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13681. mg_cry_ctx_internal(phys_ctx,
  13682. "cannot bind to %.*s: %d (%s)",
  13683. (int)vec.len,
  13684. vec.ptr,
  13685. (int)ERRNO,
  13686. strerror(errno));
  13687. closesocket(so.sock);
  13688. so.sock = INVALID_SOCKET;
  13689. continue;
  13690. }
  13691. }
  13692. #if defined(USE_IPV6)
  13693. else if (so.lsa.sa.sa_family == AF_INET6) {
  13694. len = sizeof(so.lsa.sin6);
  13695. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13696. mg_cry_ctx_internal(phys_ctx,
  13697. "cannot bind to IPv6 %.*s: %d (%s)",
  13698. (int)vec.len,
  13699. vec.ptr,
  13700. (int)ERRNO,
  13701. strerror(errno));
  13702. closesocket(so.sock);
  13703. so.sock = INVALID_SOCKET;
  13704. continue;
  13705. }
  13706. }
  13707. #endif
  13708. #if defined(USE_X_DOM_SOCKET)
  13709. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13710. len = sizeof(so.lsa.sun);
  13711. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13712. mg_cry_ctx_internal(phys_ctx,
  13713. "cannot bind to unix socket %s: %d (%s)",
  13714. so.lsa.sun.sun_path,
  13715. (int)ERRNO,
  13716. strerror(errno));
  13717. closesocket(so.sock);
  13718. so.sock = INVALID_SOCKET;
  13719. continue;
  13720. }
  13721. }
  13722. #endif
  13723. else {
  13724. mg_cry_ctx_internal(
  13725. phys_ctx,
  13726. "cannot bind: address family not supported (entry %i)",
  13727. portsTotal);
  13728. closesocket(so.sock);
  13729. so.sock = INVALID_SOCKET;
  13730. continue;
  13731. }
  13732. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13733. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13734. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13735. mg_cry_ctx_internal(phys_ctx,
  13736. "%s value \"%s\" is invalid",
  13737. config_options[LISTEN_BACKLOG_SIZE].name,
  13738. opt_txt);
  13739. closesocket(so.sock);
  13740. so.sock = INVALID_SOCKET;
  13741. continue;
  13742. }
  13743. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13744. mg_cry_ctx_internal(phys_ctx,
  13745. "cannot listen to %.*s: %d (%s)",
  13746. (int)vec.len,
  13747. vec.ptr,
  13748. (int)ERRNO,
  13749. strerror(errno));
  13750. closesocket(so.sock);
  13751. so.sock = INVALID_SOCKET;
  13752. continue;
  13753. }
  13754. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13755. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13756. int err = (int)ERRNO;
  13757. mg_cry_ctx_internal(phys_ctx,
  13758. "call to getsockname failed %.*s: %d (%s)",
  13759. (int)vec.len,
  13760. vec.ptr,
  13761. err,
  13762. strerror(errno));
  13763. closesocket(so.sock);
  13764. so.sock = INVALID_SOCKET;
  13765. continue;
  13766. }
  13767. /* Update lsa port in case of random free ports */
  13768. #if defined(USE_IPV6)
  13769. if (so.lsa.sa.sa_family == AF_INET6) {
  13770. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13771. } else
  13772. #endif
  13773. {
  13774. so.lsa.sin.sin_port = usa.sin.sin_port;
  13775. }
  13776. if ((ptr = (struct socket *)
  13777. mg_realloc_ctx(phys_ctx->listening_sockets,
  13778. (phys_ctx->num_listening_sockets + 1)
  13779. * sizeof(phys_ctx->listening_sockets[0]),
  13780. phys_ctx))
  13781. == NULL) {
  13782. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13783. closesocket(so.sock);
  13784. so.sock = INVALID_SOCKET;
  13785. continue;
  13786. }
  13787. if ((pfd = (struct mg_pollfd *)
  13788. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13789. (phys_ctx->num_listening_sockets + 1)
  13790. * sizeof(phys_ctx->listening_socket_fds[0]),
  13791. phys_ctx))
  13792. == NULL) {
  13793. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13794. closesocket(so.sock);
  13795. so.sock = INVALID_SOCKET;
  13796. mg_free(ptr);
  13797. continue;
  13798. }
  13799. set_close_on_exec(so.sock, NULL, phys_ctx);
  13800. phys_ctx->listening_sockets = ptr;
  13801. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13802. phys_ctx->listening_socket_fds = pfd;
  13803. phys_ctx->num_listening_sockets++;
  13804. portsOk++;
  13805. }
  13806. if (portsOk != portsTotal) {
  13807. close_all_listening_sockets(phys_ctx);
  13808. portsOk = 0;
  13809. }
  13810. return portsOk;
  13811. }
  13812. static const char *
  13813. header_val(const struct mg_connection *conn, const char *header)
  13814. {
  13815. const char *header_value;
  13816. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13817. return "-";
  13818. } else {
  13819. return header_value;
  13820. }
  13821. }
  13822. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13823. #include "external_log_access.inl"
  13824. #elif !defined(NO_FILESYSTEMS)
  13825. static void
  13826. log_access(const struct mg_connection *conn)
  13827. {
  13828. const struct mg_request_info *ri;
  13829. struct mg_file fi;
  13830. char date[64], src_addr[IP_ADDR_STR_LEN];
  13831. #if defined(REENTRANT_TIME)
  13832. struct tm _tm;
  13833. struct tm *tm = &_tm;
  13834. #else
  13835. struct tm *tm;
  13836. #endif
  13837. const char *referer;
  13838. const char *user_agent;
  13839. char log_buf[4096];
  13840. if (!conn || !conn->dom_ctx) {
  13841. return;
  13842. }
  13843. /* Set log message to "empty" */
  13844. log_buf[0] = 0;
  13845. #if defined(USE_LUA)
  13846. if (conn->phys_ctx->lua_bg_log_available) {
  13847. int ret;
  13848. struct mg_context *ctx = conn->phys_ctx;
  13849. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13850. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13851. /* call "log()" in Lua */
  13852. lua_getglobal(lstate, "log");
  13853. prepare_lua_request_info_inner(conn, lstate);
  13854. push_lua_response_log_data(conn, lstate);
  13855. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13856. if (ret == 0) {
  13857. int t = lua_type(lstate, -1);
  13858. if (t == LUA_TBOOLEAN) {
  13859. if (lua_toboolean(lstate, -1) == 0) {
  13860. /* log() returned false: do not log */
  13861. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13862. return;
  13863. }
  13864. /* log returned true: continue logging */
  13865. } else if (t == LUA_TSTRING) {
  13866. size_t len;
  13867. const char *txt = lua_tolstring(lstate, -1, &len);
  13868. if ((len == 0) || (*txt == 0)) {
  13869. /* log() returned empty string: do not log */
  13870. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13871. return;
  13872. }
  13873. /* Copy test from Lua into log_buf */
  13874. if (len >= sizeof(log_buf)) {
  13875. len = sizeof(log_buf) - 1;
  13876. }
  13877. memcpy(log_buf, txt, len);
  13878. log_buf[len] = 0;
  13879. }
  13880. } else {
  13881. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13882. }
  13883. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13884. }
  13885. #endif
  13886. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13887. if (mg_fopen(conn,
  13888. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13889. MG_FOPEN_MODE_APPEND,
  13890. &fi)
  13891. == 0) {
  13892. fi.access.fp = NULL;
  13893. }
  13894. } else {
  13895. fi.access.fp = NULL;
  13896. }
  13897. /* Log is written to a file and/or a callback. If both are not set,
  13898. * executing the rest of the function is pointless. */
  13899. if ((fi.access.fp == NULL)
  13900. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13901. return;
  13902. }
  13903. /* If we did not get a log message from Lua, create it here. */
  13904. if (!log_buf[0]) {
  13905. #if defined(REENTRANT_TIME)
  13906. localtime_r(&conn->conn_birth_time, tm);
  13907. #else
  13908. tm = localtime(&conn->conn_birth_time);
  13909. #endif
  13910. if (tm != NULL) {
  13911. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13912. } else {
  13913. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13914. }
  13915. ri = &conn->request_info;
  13916. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13917. referer = header_val(conn, "Referer");
  13918. user_agent = header_val(conn, "User-Agent");
  13919. mg_snprintf(conn,
  13920. NULL, /* Ignore truncation in access log */
  13921. log_buf,
  13922. sizeof(log_buf),
  13923. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13924. " %s %s",
  13925. src_addr,
  13926. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13927. date,
  13928. ri->request_method ? ri->request_method : "-",
  13929. ri->request_uri ? ri->request_uri : "-",
  13930. ri->query_string ? "?" : "",
  13931. ri->query_string ? ri->query_string : "",
  13932. ri->http_version,
  13933. conn->status_code,
  13934. conn->num_bytes_sent,
  13935. referer,
  13936. user_agent);
  13937. }
  13938. /* Here we have a log message in log_buf. Call the callback */
  13939. if (conn->phys_ctx->callbacks.log_access) {
  13940. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13941. /* do not log if callback returns non-zero */
  13942. if (fi.access.fp) {
  13943. mg_fclose(&fi.access);
  13944. }
  13945. return;
  13946. }
  13947. }
  13948. /* Store in file */
  13949. if (fi.access.fp) {
  13950. int ok = 1;
  13951. flockfile(fi.access.fp);
  13952. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13953. ok = 0;
  13954. }
  13955. if (fflush(fi.access.fp) != 0) {
  13956. ok = 0;
  13957. }
  13958. funlockfile(fi.access.fp);
  13959. if (mg_fclose(&fi.access) != 0) {
  13960. ok = 0;
  13961. }
  13962. if (!ok) {
  13963. mg_cry_internal(conn,
  13964. "Error writing log file %s",
  13965. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13966. }
  13967. }
  13968. }
  13969. #else
  13970. #error "Either enable filesystems or provide a custom log_access implementation"
  13971. #endif /* Externally provided function */
  13972. /* Verify given socket address against the ACL.
  13973. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13974. */
  13975. static int
  13976. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13977. {
  13978. int allowed, flag, matched;
  13979. struct vec vec;
  13980. if (phys_ctx) {
  13981. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13982. /* If any ACL is set, deny by default */
  13983. allowed = (list == NULL) ? '+' : '-';
  13984. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13985. flag = vec.ptr[0];
  13986. matched = -1;
  13987. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13988. vec.ptr++;
  13989. vec.len--;
  13990. matched = parse_match_net(&vec, sa, 1);
  13991. }
  13992. if (matched < 0) {
  13993. mg_cry_ctx_internal(phys_ctx,
  13994. "%s: subnet must be [+|-]IP-addr[/x]",
  13995. __func__);
  13996. return -1;
  13997. }
  13998. if (matched) {
  13999. allowed = flag;
  14000. }
  14001. }
  14002. return allowed == '+';
  14003. }
  14004. return -1;
  14005. }
  14006. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14007. static int
  14008. set_uid_option(struct mg_context *phys_ctx)
  14009. {
  14010. int success = 0;
  14011. if (phys_ctx) {
  14012. /* We are currently running as curr_uid. */
  14013. const uid_t curr_uid = getuid();
  14014. /* If set, we want to run as run_as_user. */
  14015. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14016. const struct passwd *to_pw = NULL;
  14017. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14018. /* run_as_user does not exist on the system. We can't proceed
  14019. * further. */
  14020. mg_cry_ctx_internal(phys_ctx,
  14021. "%s: unknown user [%s]",
  14022. __func__,
  14023. run_as_user);
  14024. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14025. /* There was either no request to change user, or we're already
  14026. * running as run_as_user. Nothing else to do.
  14027. */
  14028. success = 1;
  14029. } else {
  14030. /* Valid change request. */
  14031. if (setgid(to_pw->pw_gid) == -1) {
  14032. mg_cry_ctx_internal(phys_ctx,
  14033. "%s: setgid(%s): %s",
  14034. __func__,
  14035. run_as_user,
  14036. strerror(errno));
  14037. } else if (setgroups(0, NULL) == -1) {
  14038. mg_cry_ctx_internal(phys_ctx,
  14039. "%s: setgroups(): %s",
  14040. __func__,
  14041. strerror(errno));
  14042. } else if (setuid(to_pw->pw_uid) == -1) {
  14043. mg_cry_ctx_internal(phys_ctx,
  14044. "%s: setuid(%s): %s",
  14045. __func__,
  14046. run_as_user,
  14047. strerror(errno));
  14048. } else {
  14049. success = 1;
  14050. }
  14051. }
  14052. }
  14053. return success;
  14054. }
  14055. #endif /* !_WIN32 */
  14056. static void
  14057. tls_dtor(void *key)
  14058. {
  14059. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14060. /* key == pthread_getspecific(sTlsKey); */
  14061. if (tls) {
  14062. if (tls->is_master == 2) {
  14063. tls->is_master = -3; /* Mark memory as dead */
  14064. mg_free(tls);
  14065. }
  14066. }
  14067. pthread_setspecific(sTlsKey, NULL);
  14068. }
  14069. #if defined(USE_MBEDTLS)
  14070. /* Check if SSL is required.
  14071. * If so, set up ctx->ssl_ctx pointer. */
  14072. static int
  14073. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14074. {
  14075. if (!phys_ctx) {
  14076. return 0;
  14077. }
  14078. if (!dom_ctx) {
  14079. dom_ctx = &(phys_ctx->dd);
  14080. }
  14081. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14082. /* No SSL port is set. No need to setup SSL. */
  14083. return 1;
  14084. }
  14085. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14086. if (dom_ctx->ssl_ctx == NULL) {
  14087. fprintf(stderr, "ssl_ctx malloc failed\n");
  14088. return 0;
  14089. }
  14090. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14091. == 0
  14092. ? 1
  14093. : 0;
  14094. }
  14095. #elif !defined(NO_SSL)
  14096. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14097. struct mg_domain_context *dom_ctx,
  14098. const char *pem,
  14099. const char *chain);
  14100. static const char *ssl_error(void);
  14101. static int
  14102. refresh_trust(struct mg_connection *conn)
  14103. {
  14104. struct stat cert_buf;
  14105. int64_t t = 0;
  14106. const char *pem;
  14107. const char *chain;
  14108. int should_verify_peer;
  14109. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14110. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14111. * refresh_trust still can not work. */
  14112. return 0;
  14113. }
  14114. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14115. if (chain == NULL) {
  14116. /* pem is not NULL here */
  14117. chain = pem;
  14118. }
  14119. if (*chain == 0) {
  14120. chain = NULL;
  14121. }
  14122. if (stat(pem, &cert_buf) != -1) {
  14123. t = (int64_t)cert_buf.st_mtime;
  14124. }
  14125. mg_lock_context(conn->phys_ctx);
  14126. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14127. conn->dom_ctx->ssl_cert_last_mtime = t;
  14128. should_verify_peer = 0;
  14129. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14130. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14131. == 0) {
  14132. should_verify_peer = 1;
  14133. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14134. "optional")
  14135. == 0) {
  14136. should_verify_peer = 1;
  14137. }
  14138. }
  14139. if (should_verify_peer) {
  14140. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14141. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14142. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14143. ca_file,
  14144. ca_path)
  14145. != 1) {
  14146. mg_unlock_context(conn->phys_ctx);
  14147. mg_cry_ctx_internal(
  14148. conn->phys_ctx,
  14149. "SSL_CTX_load_verify_locations error: %s "
  14150. "ssl_verify_peer requires setting "
  14151. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14152. "present in "
  14153. "the .conf file?",
  14154. ssl_error());
  14155. return 0;
  14156. }
  14157. }
  14158. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14159. mg_unlock_context(conn->phys_ctx);
  14160. return 0;
  14161. }
  14162. }
  14163. mg_unlock_context(conn->phys_ctx);
  14164. return 1;
  14165. }
  14166. #if defined(OPENSSL_API_1_1)
  14167. #else
  14168. static pthread_mutex_t *ssl_mutexes;
  14169. #endif /* OPENSSL_API_1_1 */
  14170. static int
  14171. sslize(struct mg_connection *conn,
  14172. int (*func)(SSL *),
  14173. const struct mg_client_options *client_options)
  14174. {
  14175. int ret, err;
  14176. int short_trust;
  14177. unsigned timeout = 1024;
  14178. unsigned i;
  14179. if (!conn) {
  14180. return 0;
  14181. }
  14182. short_trust =
  14183. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14184. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14185. if (short_trust) {
  14186. int trust_ret = refresh_trust(conn);
  14187. if (!trust_ret) {
  14188. return trust_ret;
  14189. }
  14190. }
  14191. mg_lock_context(conn->phys_ctx);
  14192. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14193. mg_unlock_context(conn->phys_ctx);
  14194. if (conn->ssl == NULL) {
  14195. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14196. OPENSSL_REMOVE_THREAD_STATE();
  14197. return 0;
  14198. }
  14199. SSL_set_app_data(conn->ssl, (char *)conn);
  14200. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14201. if (ret != 1) {
  14202. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14203. SSL_free(conn->ssl);
  14204. conn->ssl = NULL;
  14205. OPENSSL_REMOVE_THREAD_STATE();
  14206. return 0;
  14207. }
  14208. if (client_options) {
  14209. if (client_options->host_name) {
  14210. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14211. }
  14212. }
  14213. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14214. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14215. /* NOTE: The loop below acts as a back-off, so we can end
  14216. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14217. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14218. if (to >= 0) {
  14219. timeout = (unsigned)to;
  14220. }
  14221. }
  14222. /* SSL functions may fail and require to be called again:
  14223. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14224. * Here "func" could be SSL_connect or SSL_accept. */
  14225. for (i = 0; i <= timeout; i += 50) {
  14226. ERR_clear_error();
  14227. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14228. ret = func(conn->ssl);
  14229. if (ret != 1) {
  14230. err = SSL_get_error(conn->ssl, ret);
  14231. if ((err == SSL_ERROR_WANT_CONNECT)
  14232. || (err == SSL_ERROR_WANT_ACCEPT)
  14233. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14234. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14235. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14236. /* Don't wait if the server is going to be stopped. */
  14237. break;
  14238. }
  14239. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14240. /* Simply retry the function call. */
  14241. mg_sleep(50);
  14242. } else {
  14243. /* Need to retry the function call "later".
  14244. * See https://linux.die.net/man/3/ssl_get_error
  14245. * This is typical for non-blocking sockets. */
  14246. struct mg_pollfd pfd;
  14247. int pollres;
  14248. pfd.fd = conn->client.sock;
  14249. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14250. || (err == SSL_ERROR_WANT_WRITE))
  14251. ? POLLOUT
  14252. : POLLIN;
  14253. pollres =
  14254. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14255. if (pollres < 0) {
  14256. /* Break if error occurred (-1)
  14257. * or server shutdown (-2) */
  14258. break;
  14259. }
  14260. }
  14261. } else if (err == SSL_ERROR_SYSCALL) {
  14262. /* This is an IO error. Look at errno. */
  14263. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14264. break;
  14265. } else {
  14266. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14267. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14268. break;
  14269. }
  14270. } else {
  14271. /* success */
  14272. break;
  14273. }
  14274. }
  14275. ERR_clear_error();
  14276. if (ret != 1) {
  14277. SSL_free(conn->ssl);
  14278. conn->ssl = NULL;
  14279. OPENSSL_REMOVE_THREAD_STATE();
  14280. return 0;
  14281. }
  14282. return 1;
  14283. }
  14284. /* Return OpenSSL error message (from CRYPTO lib) */
  14285. static const char *
  14286. ssl_error(void)
  14287. {
  14288. unsigned long err;
  14289. err = ERR_get_error();
  14290. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14291. }
  14292. static int
  14293. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14294. {
  14295. int i;
  14296. const char hexdigit[] = "0123456789abcdef";
  14297. if ((memlen <= 0) || (buflen <= 0)) {
  14298. return 0;
  14299. }
  14300. if (buflen < (3 * memlen)) {
  14301. return 0;
  14302. }
  14303. for (i = 0; i < memlen; i++) {
  14304. if (i > 0) {
  14305. buf[3 * i - 1] = ' ';
  14306. }
  14307. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14308. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14309. }
  14310. buf[3 * memlen - 1] = 0;
  14311. return 1;
  14312. }
  14313. static int
  14314. ssl_get_client_cert_info(const struct mg_connection *conn,
  14315. struct mg_client_cert *client_cert)
  14316. {
  14317. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14318. if (cert) {
  14319. char str_buf[1024];
  14320. unsigned char buf[256];
  14321. char *str_serial = NULL;
  14322. unsigned int ulen;
  14323. int ilen;
  14324. unsigned char *tmp_buf;
  14325. unsigned char *tmp_p;
  14326. /* Handle to algorithm used for fingerprint */
  14327. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14328. /* Get Subject and issuer */
  14329. X509_NAME *subj = X509_get_subject_name(cert);
  14330. X509_NAME *iss = X509_get_issuer_name(cert);
  14331. /* Get serial number */
  14332. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14333. /* Translate serial number to a hex string */
  14334. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14335. if (serial_bn) {
  14336. str_serial = BN_bn2hex(serial_bn);
  14337. BN_free(serial_bn);
  14338. }
  14339. client_cert->serial =
  14340. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14341. /* Translate subject and issuer to a string */
  14342. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14343. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14344. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14345. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14346. /* Calculate SHA1 fingerprint and store as a hex string */
  14347. ulen = 0;
  14348. /* ASN1_digest is deprecated. Do the calculation manually,
  14349. * using EVP_Digest. */
  14350. ilen = i2d_X509(cert, NULL);
  14351. tmp_buf = (ilen > 0)
  14352. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14353. conn->phys_ctx)
  14354. : NULL;
  14355. if (tmp_buf) {
  14356. tmp_p = tmp_buf;
  14357. (void)i2d_X509(cert, &tmp_p);
  14358. if (!EVP_Digest(
  14359. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14360. ulen = 0;
  14361. }
  14362. mg_free(tmp_buf);
  14363. }
  14364. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14365. *str_buf = 0;
  14366. }
  14367. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14368. client_cert->peer_cert = (void *)cert;
  14369. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14370. * see https://linux.die.net/man/3/bn_bn2hex */
  14371. OPENSSL_free(str_serial);
  14372. return 1;
  14373. }
  14374. return 0;
  14375. }
  14376. #if defined(OPENSSL_API_1_1)
  14377. #else
  14378. static void
  14379. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14380. {
  14381. (void)line;
  14382. (void)file;
  14383. if (mode & 1) {
  14384. /* 1 is CRYPTO_LOCK */
  14385. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14386. } else {
  14387. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14388. }
  14389. }
  14390. #endif /* OPENSSL_API_1_1 */
  14391. #if !defined(NO_SSL_DL)
  14392. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14393. static void *
  14394. load_tls_dll(char *ebuf,
  14395. size_t ebuf_len,
  14396. const char *dll_name,
  14397. struct ssl_func *sw,
  14398. int *feature_missing)
  14399. {
  14400. union {
  14401. void *p;
  14402. void (*fp)(void);
  14403. } u;
  14404. void *dll_handle;
  14405. struct ssl_func *fp;
  14406. int ok;
  14407. int truncated = 0;
  14408. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14409. mg_snprintf(NULL,
  14410. NULL, /* No truncation check for ebuf */
  14411. ebuf,
  14412. ebuf_len,
  14413. "%s: cannot load %s",
  14414. __func__,
  14415. dll_name);
  14416. return NULL;
  14417. }
  14418. ok = 1;
  14419. for (fp = sw; fp->name != NULL; fp++) {
  14420. #if defined(_WIN32)
  14421. /* GetProcAddress() returns pointer to function */
  14422. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14423. #else
  14424. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14425. * pointers to function pointers. We need to use a union to make a
  14426. * cast. */
  14427. u.p = dlsym(dll_handle, fp->name);
  14428. #endif /* _WIN32 */
  14429. /* Set pointer (might be NULL) */
  14430. fp->ptr = u.fp;
  14431. if (u.fp == NULL) {
  14432. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14433. if (feature_missing) {
  14434. feature_missing[fp->required]++;
  14435. }
  14436. if (fp->required == TLS_Mandatory) {
  14437. /* Mandatory function is missing */
  14438. if (ok) {
  14439. /* This is the first missing function.
  14440. * Create a new error message. */
  14441. mg_snprintf(NULL,
  14442. &truncated,
  14443. ebuf,
  14444. ebuf_len,
  14445. "%s: %s: cannot find %s",
  14446. __func__,
  14447. dll_name,
  14448. fp->name);
  14449. ok = 0;
  14450. } else {
  14451. /* This is yet anothermissing function.
  14452. * Append existing error message. */
  14453. size_t cur_len = strlen(ebuf);
  14454. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14455. mg_snprintf(NULL,
  14456. &truncated,
  14457. ebuf + cur_len,
  14458. ebuf_len - cur_len - 3,
  14459. ", %s",
  14460. fp->name);
  14461. if (truncated) {
  14462. /* If truncated, add "..." */
  14463. strcat(ebuf, "...");
  14464. }
  14465. }
  14466. }
  14467. }
  14468. }
  14469. }
  14470. if (!ok) {
  14471. (void)dlclose(dll_handle);
  14472. return NULL;
  14473. }
  14474. return dll_handle;
  14475. }
  14476. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14477. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14478. #endif /* NO_SSL_DL */
  14479. #if defined(SSL_ALREADY_INITIALIZED)
  14480. static volatile ptrdiff_t cryptolib_users =
  14481. 1; /* Reference counter for crypto library. */
  14482. #else
  14483. static volatile ptrdiff_t cryptolib_users =
  14484. 0; /* Reference counter for crypto library. */
  14485. #endif
  14486. static int
  14487. initialize_openssl(char *ebuf, size_t ebuf_len)
  14488. {
  14489. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14490. int i, num_locks;
  14491. size_t size;
  14492. #endif
  14493. if (ebuf_len > 0) {
  14494. ebuf[0] = 0;
  14495. }
  14496. #if !defined(NO_SSL_DL)
  14497. if (!cryptolib_dll_handle) {
  14498. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14499. cryptolib_dll_handle = load_tls_dll(
  14500. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14501. if (!cryptolib_dll_handle) {
  14502. mg_snprintf(NULL,
  14503. NULL, /* No truncation check for ebuf */
  14504. ebuf,
  14505. ebuf_len,
  14506. "%s: error loading library %s",
  14507. __func__,
  14508. CRYPTO_LIB);
  14509. DEBUG_TRACE("%s", ebuf);
  14510. return 0;
  14511. }
  14512. }
  14513. #endif /* NO_SSL_DL */
  14514. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14515. return 1;
  14516. }
  14517. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14518. /* Initialize locking callbacks, needed for thread safety.
  14519. * http://www.openssl.org/support/faq.html#PROG1
  14520. */
  14521. num_locks = CRYPTO_num_locks();
  14522. if (num_locks < 0) {
  14523. num_locks = 0;
  14524. }
  14525. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14526. /* allocate mutex array, if required */
  14527. if (num_locks == 0) {
  14528. /* No mutex array required */
  14529. ssl_mutexes = NULL;
  14530. } else {
  14531. /* Mutex array required - allocate it */
  14532. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14533. /* Check OOM */
  14534. if (ssl_mutexes == NULL) {
  14535. mg_snprintf(NULL,
  14536. NULL, /* No truncation check for ebuf */
  14537. ebuf,
  14538. ebuf_len,
  14539. "%s: cannot allocate mutexes: %s",
  14540. __func__,
  14541. ssl_error());
  14542. DEBUG_TRACE("%s", ebuf);
  14543. return 0;
  14544. }
  14545. /* initialize mutex array */
  14546. for (i = 0; i < num_locks; i++) {
  14547. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14548. mg_snprintf(NULL,
  14549. NULL, /* No truncation check for ebuf */
  14550. ebuf,
  14551. ebuf_len,
  14552. "%s: error initializing mutex %i of %i",
  14553. __func__,
  14554. i,
  14555. num_locks);
  14556. DEBUG_TRACE("%s", ebuf);
  14557. mg_free(ssl_mutexes);
  14558. return 0;
  14559. }
  14560. }
  14561. }
  14562. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14563. CRYPTO_set_id_callback(&mg_current_thread_id);
  14564. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14565. #if !defined(NO_SSL_DL)
  14566. if (!ssllib_dll_handle) {
  14567. ssllib_dll_handle =
  14568. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14569. if (!ssllib_dll_handle) {
  14570. #if !defined(OPENSSL_API_1_1)
  14571. mg_free(ssl_mutexes);
  14572. #endif
  14573. DEBUG_TRACE("%s", ebuf);
  14574. return 0;
  14575. }
  14576. }
  14577. #endif /* NO_SSL_DL */
  14578. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14579. && !defined(NO_SSL_DL)
  14580. /* Initialize SSL library */
  14581. OPENSSL_init_ssl(0, NULL);
  14582. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14583. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14584. NULL);
  14585. #else
  14586. /* Initialize SSL library */
  14587. SSL_library_init();
  14588. SSL_load_error_strings();
  14589. #endif
  14590. return 1;
  14591. }
  14592. static int
  14593. ssl_use_pem_file(struct mg_context *phys_ctx,
  14594. struct mg_domain_context *dom_ctx,
  14595. const char *pem,
  14596. const char *chain)
  14597. {
  14598. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14599. mg_cry_ctx_internal(phys_ctx,
  14600. "%s: cannot open certificate file %s: %s",
  14601. __func__,
  14602. pem,
  14603. ssl_error());
  14604. return 0;
  14605. }
  14606. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14607. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14608. mg_cry_ctx_internal(phys_ctx,
  14609. "%s: cannot open private key file %s: %s",
  14610. __func__,
  14611. pem,
  14612. ssl_error());
  14613. return 0;
  14614. }
  14615. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14616. mg_cry_ctx_internal(phys_ctx,
  14617. "%s: certificate and private key do not match: %s",
  14618. __func__,
  14619. pem);
  14620. return 0;
  14621. }
  14622. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14623. * chain files that contain private keys and certificates in
  14624. * SSL_CTX_use_certificate_chain_file.
  14625. * The CivetWeb-Server used pem-Files that contained both information.
  14626. * In order to make wolfSSL work, it is split in two files.
  14627. * One file that contains key and certificate used by the server and
  14628. * an optional chain file for the ssl stack.
  14629. */
  14630. if (chain) {
  14631. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14632. mg_cry_ctx_internal(phys_ctx,
  14633. "%s: cannot use certificate chain file %s: %s",
  14634. __func__,
  14635. chain,
  14636. ssl_error());
  14637. return 0;
  14638. }
  14639. }
  14640. return 1;
  14641. }
  14642. #if defined(OPENSSL_API_1_1)
  14643. static unsigned long
  14644. ssl_get_protocol(int version_id)
  14645. {
  14646. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14647. if (version_id > 0)
  14648. ret |= SSL_OP_NO_SSLv2;
  14649. if (version_id > 1)
  14650. ret |= SSL_OP_NO_SSLv3;
  14651. if (version_id > 2)
  14652. ret |= SSL_OP_NO_TLSv1;
  14653. if (version_id > 3)
  14654. ret |= SSL_OP_NO_TLSv1_1;
  14655. if (version_id > 4)
  14656. ret |= SSL_OP_NO_TLSv1_2;
  14657. #if defined(SSL_OP_NO_TLSv1_3)
  14658. if (version_id > 5)
  14659. ret |= SSL_OP_NO_TLSv1_3;
  14660. #endif
  14661. return ret;
  14662. }
  14663. #else
  14664. static long
  14665. ssl_get_protocol(int version_id)
  14666. {
  14667. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14668. if (version_id > 0)
  14669. ret |= SSL_OP_NO_SSLv2;
  14670. if (version_id > 1)
  14671. ret |= SSL_OP_NO_SSLv3;
  14672. if (version_id > 2)
  14673. ret |= SSL_OP_NO_TLSv1;
  14674. if (version_id > 3)
  14675. ret |= SSL_OP_NO_TLSv1_1;
  14676. if (version_id > 4)
  14677. ret |= SSL_OP_NO_TLSv1_2;
  14678. #if defined(SSL_OP_NO_TLSv1_3)
  14679. if (version_id > 5)
  14680. ret |= SSL_OP_NO_TLSv1_3;
  14681. #endif
  14682. return (long)ret;
  14683. }
  14684. #endif /* OPENSSL_API_1_1 */
  14685. /* SSL callback documentation:
  14686. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14687. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14688. * https://linux.die.net/man/3/ssl_set_info_callback */
  14689. /* Note: There is no "const" for the first argument in the documentation
  14690. * examples, however some (maybe most, but not all) headers of OpenSSL
  14691. * versions / OpenSSL compatibility layers have it. Having a different
  14692. * definition will cause a warning in C and an error in C++. Use "const SSL
  14693. * *", while automatic conversion from "SSL *" works for all compilers,
  14694. * but not other way around */
  14695. static void
  14696. ssl_info_callback(const SSL *ssl, int what, int ret)
  14697. {
  14698. (void)ret;
  14699. if (what & SSL_CB_HANDSHAKE_START) {
  14700. SSL_get_app_data(ssl);
  14701. }
  14702. if (what & SSL_CB_HANDSHAKE_DONE) {
  14703. /* TODO: check for openSSL 1.1 */
  14704. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14705. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14706. }
  14707. }
  14708. static int
  14709. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14710. {
  14711. #if defined(GCC_DIAGNOSTIC)
  14712. #pragma GCC diagnostic push
  14713. #pragma GCC diagnostic ignored "-Wcast-align"
  14714. #endif /* defined(GCC_DIAGNOSTIC) */
  14715. /* We used an aligned pointer in SSL_set_app_data */
  14716. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14717. #if defined(GCC_DIAGNOSTIC)
  14718. #pragma GCC diagnostic pop
  14719. #endif /* defined(GCC_DIAGNOSTIC) */
  14720. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14721. (void)ad;
  14722. (void)arg;
  14723. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14724. DEBUG_ASSERT(0);
  14725. return SSL_TLSEXT_ERR_NOACK;
  14726. }
  14727. conn->dom_ctx = &(conn->phys_ctx->dd);
  14728. /* Old clients (Win XP) will not support SNI. Then, there
  14729. * is no server name available in the request - we can
  14730. * only work with the default certificate.
  14731. * Multiple HTTPS hosts on one IP+port are only possible
  14732. * with a certificate containing all alternative names.
  14733. */
  14734. if ((servername == NULL) || (*servername == 0)) {
  14735. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14736. mg_lock_context(conn->phys_ctx);
  14737. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14738. mg_unlock_context(conn->phys_ctx);
  14739. return SSL_TLSEXT_ERR_NOACK;
  14740. }
  14741. DEBUG_TRACE("TLS connection to host %s", servername);
  14742. while (conn->dom_ctx) {
  14743. if (!mg_strcasecmp(servername,
  14744. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14745. /* Found matching domain */
  14746. DEBUG_TRACE("TLS domain %s found",
  14747. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14748. break;
  14749. }
  14750. mg_lock_context(conn->phys_ctx);
  14751. conn->dom_ctx = conn->dom_ctx->next;
  14752. mg_unlock_context(conn->phys_ctx);
  14753. }
  14754. if (conn->dom_ctx == NULL) {
  14755. /* Default domain */
  14756. DEBUG_TRACE("TLS default domain %s used",
  14757. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14758. conn->dom_ctx = &(conn->phys_ctx->dd);
  14759. }
  14760. mg_lock_context(conn->phys_ctx);
  14761. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14762. mg_unlock_context(conn->phys_ctx);
  14763. return SSL_TLSEXT_ERR_OK;
  14764. }
  14765. #if defined(USE_ALPN)
  14766. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14767. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14768. alpn_proto_list + 3 + 8,
  14769. NULL};
  14770. #if defined(USE_HTTP2)
  14771. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14772. alpn_proto_list + 3,
  14773. alpn_proto_list + 3 + 8,
  14774. NULL};
  14775. #endif
  14776. static int
  14777. alpn_select_cb(SSL *ssl,
  14778. const unsigned char **out,
  14779. unsigned char *outlen,
  14780. const unsigned char *in,
  14781. unsigned int inlen,
  14782. void *arg)
  14783. {
  14784. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14785. unsigned int i, j, enable_http2 = 0;
  14786. const char **alpn_proto_order = alpn_proto_order_http1;
  14787. struct mg_workerTLS *tls =
  14788. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14789. (void)ssl;
  14790. if (tls == NULL) {
  14791. /* Need to store protocol in Thread Local Storage */
  14792. /* If there is no Thread Local Storage, don't use ALPN */
  14793. return SSL_TLSEXT_ERR_NOACK;
  14794. }
  14795. #if defined(USE_HTTP2)
  14796. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14797. if (enable_http2) {
  14798. alpn_proto_order = alpn_proto_order_http2;
  14799. }
  14800. #endif
  14801. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14802. /* check all accepted protocols in this order */
  14803. const char *alpn_proto = alpn_proto_order[j];
  14804. /* search input for matching protocol */
  14805. for (i = 0; i < inlen; i++) {
  14806. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14807. *out = in + i + 1;
  14808. *outlen = in[i];
  14809. tls->alpn_proto = alpn_proto;
  14810. return SSL_TLSEXT_ERR_OK;
  14811. }
  14812. }
  14813. }
  14814. /* Nothing found */
  14815. return SSL_TLSEXT_ERR_NOACK;
  14816. }
  14817. static int
  14818. next_protos_advertised_cb(SSL *ssl,
  14819. const unsigned char **data,
  14820. unsigned int *len,
  14821. void *arg)
  14822. {
  14823. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14824. *data = (const unsigned char *)alpn_proto_list;
  14825. *len = (unsigned int)strlen((const char *)data);
  14826. (void)ssl;
  14827. (void)dom_ctx;
  14828. return SSL_TLSEXT_ERR_OK;
  14829. }
  14830. static int
  14831. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14832. {
  14833. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14834. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14835. (const unsigned char *)alpn_proto_list,
  14836. alpn_len);
  14837. if (ret != 0) {
  14838. mg_cry_ctx_internal(phys_ctx,
  14839. "SSL_CTX_set_alpn_protos error: %s",
  14840. ssl_error());
  14841. }
  14842. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14843. alpn_select_cb,
  14844. (void *)dom_ctx);
  14845. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14846. next_protos_advertised_cb,
  14847. (void *)dom_ctx);
  14848. return ret;
  14849. }
  14850. #endif
  14851. /* Setup SSL CTX as required by CivetWeb */
  14852. static int
  14853. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14854. struct mg_domain_context *dom_ctx,
  14855. const char *pem,
  14856. const char *chain)
  14857. {
  14858. int callback_ret;
  14859. int should_verify_peer;
  14860. int peer_certificate_optional;
  14861. const char *ca_path;
  14862. const char *ca_file;
  14863. int use_default_verify_paths;
  14864. int verify_depth;
  14865. struct timespec now_mt;
  14866. md5_byte_t ssl_context_id[16];
  14867. md5_state_t md5state;
  14868. int protocol_ver;
  14869. int ssl_cache_timeout;
  14870. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14871. && !defined(NO_SSL_DL)
  14872. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14873. mg_cry_ctx_internal(phys_ctx,
  14874. "SSL_CTX_new (server) error: %s",
  14875. ssl_error());
  14876. return 0;
  14877. }
  14878. #else
  14879. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14880. mg_cry_ctx_internal(phys_ctx,
  14881. "SSL_CTX_new (server) error: %s",
  14882. ssl_error());
  14883. return 0;
  14884. }
  14885. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14886. #if defined(SSL_OP_NO_TLSv1_3)
  14887. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14888. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14889. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14890. | SSL_OP_NO_TLSv1_3);
  14891. #else
  14892. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14893. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14894. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14895. #endif
  14896. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14897. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14898. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14899. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14900. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14901. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14902. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14903. #if defined(SSL_OP_NO_RENEGOTIATION)
  14904. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14905. #endif
  14906. #if !defined(NO_SSL_DL)
  14907. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14908. #endif /* NO_SSL_DL */
  14909. /* In SSL documentation examples callback defined without const
  14910. * specifier 'void (*)(SSL *, int, int)' See:
  14911. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14912. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14913. * But in the source code const SSL is used:
  14914. * 'void (*)(const SSL *, int, int)' See:
  14915. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14916. * Problem about wrong documentation described, but not resolved:
  14917. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14918. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14919. * But when compiled with modern C++ compiler, correct const should be
  14920. * provided
  14921. */
  14922. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14923. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14924. ssl_servername_callback);
  14925. /* If a callback has been specified, call it. */
  14926. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14927. ? 0
  14928. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14929. phys_ctx->user_data));
  14930. /* If callback returns 0, civetweb sets up the SSL certificate.
  14931. * If it returns 1, civetweb assumes the callback already did this.
  14932. * If it returns -1, initializing ssl fails. */
  14933. if (callback_ret < 0) {
  14934. mg_cry_ctx_internal(phys_ctx,
  14935. "SSL callback returned error: %i",
  14936. callback_ret);
  14937. return 0;
  14938. }
  14939. if (callback_ret > 0) {
  14940. /* Callback did everything. */
  14941. return 1;
  14942. }
  14943. /* If a domain callback has been specified, call it. */
  14944. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14945. ? 0
  14946. : (phys_ctx->callbacks.init_ssl_domain(
  14947. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14948. dom_ctx->ssl_ctx,
  14949. phys_ctx->user_data));
  14950. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14951. * If it returns 1, civetweb assumes the callback already did this.
  14952. * If it returns -1, initializing ssl fails. */
  14953. if (callback_ret < 0) {
  14954. mg_cry_ctx_internal(phys_ctx,
  14955. "Domain SSL callback returned error: %i",
  14956. callback_ret);
  14957. return 0;
  14958. }
  14959. if (callback_ret > 0) {
  14960. /* Domain callback did everything. */
  14961. return 1;
  14962. }
  14963. /* Use some combination of start time, domain and port as a SSL
  14964. * context ID. This should be unique on the current machine. */
  14965. md5_init(&md5state);
  14966. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14967. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14968. md5_append(&md5state,
  14969. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14970. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14971. md5_append(&md5state,
  14972. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14973. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14974. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14975. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14976. md5_finish(&md5state, ssl_context_id);
  14977. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14978. (unsigned char *)ssl_context_id,
  14979. sizeof(ssl_context_id));
  14980. if (pem != NULL) {
  14981. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14982. return 0;
  14983. }
  14984. }
  14985. /* Should we support client certificates? */
  14986. /* Default is "no". */
  14987. should_verify_peer = 0;
  14988. peer_certificate_optional = 0;
  14989. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14990. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14991. /* Yes, they are mandatory */
  14992. should_verify_peer = 1;
  14993. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14994. "optional")
  14995. == 0) {
  14996. /* Yes, they are optional */
  14997. should_verify_peer = 1;
  14998. peer_certificate_optional = 1;
  14999. }
  15000. }
  15001. use_default_verify_paths =
  15002. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15003. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15004. == 0);
  15005. if (should_verify_peer) {
  15006. ca_path = dom_ctx->config[SSL_CA_PATH];
  15007. ca_file = dom_ctx->config[SSL_CA_FILE];
  15008. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15009. != 1) {
  15010. mg_cry_ctx_internal(phys_ctx,
  15011. "SSL_CTX_load_verify_locations error: %s "
  15012. "ssl_verify_peer requires setting "
  15013. "either ssl_ca_path or ssl_ca_file. "
  15014. "Is any of them present in the "
  15015. ".conf file?",
  15016. ssl_error());
  15017. return 0;
  15018. }
  15019. if (peer_certificate_optional) {
  15020. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15021. } else {
  15022. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15023. SSL_VERIFY_PEER
  15024. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15025. NULL);
  15026. }
  15027. if (use_default_verify_paths
  15028. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15029. mg_cry_ctx_internal(phys_ctx,
  15030. "SSL_CTX_set_default_verify_paths error: %s",
  15031. ssl_error());
  15032. return 0;
  15033. }
  15034. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15035. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15036. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15037. }
  15038. }
  15039. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15040. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15041. dom_ctx->config[SSL_CIPHER_LIST])
  15042. != 1) {
  15043. mg_cry_ctx_internal(phys_ctx,
  15044. "SSL_CTX_set_cipher_list error: %s",
  15045. ssl_error());
  15046. }
  15047. }
  15048. /* SSL session caching */
  15049. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15050. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15051. : 0);
  15052. if (ssl_cache_timeout > 0) {
  15053. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15054. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15055. * default */
  15056. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15057. }
  15058. #if defined(USE_ALPN)
  15059. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15060. #if !defined(NO_SSL_DL)
  15061. if (!tls_feature_missing[TLS_ALPN])
  15062. #endif
  15063. {
  15064. init_alpn(phys_ctx, dom_ctx);
  15065. }
  15066. #endif
  15067. return 1;
  15068. }
  15069. /* Check if SSL is required.
  15070. * If so, dynamically load SSL library
  15071. * and set up ctx->ssl_ctx pointer. */
  15072. static int
  15073. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15074. {
  15075. void *ssl_ctx = 0;
  15076. int callback_ret;
  15077. const char *pem;
  15078. const char *chain;
  15079. char ebuf[128];
  15080. if (!phys_ctx) {
  15081. return 0;
  15082. }
  15083. if (!dom_ctx) {
  15084. dom_ctx = &(phys_ctx->dd);
  15085. }
  15086. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15087. /* No SSL port is set. No need to setup SSL. */
  15088. return 1;
  15089. }
  15090. /* Check for external SSL_CTX */
  15091. callback_ret =
  15092. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15093. ? 0
  15094. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15095. phys_ctx->user_data));
  15096. if (callback_ret < 0) {
  15097. /* Callback exists and returns <0: Initializing failed. */
  15098. mg_cry_ctx_internal(phys_ctx,
  15099. "external_ssl_ctx callback returned error: %i",
  15100. callback_ret);
  15101. return 0;
  15102. } else if (callback_ret > 0) {
  15103. /* Callback exists and returns >0: Initializing complete,
  15104. * civetweb should not modify the SSL context. */
  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. /* If the callback does not exist or return 0, civetweb must initialize
  15113. * the SSL context. Handle "domain" callback next. */
  15114. /* Check for external domain SSL_CTX callback. */
  15115. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15116. ? 0
  15117. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15118. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15119. &ssl_ctx,
  15120. phys_ctx->user_data));
  15121. if (callback_ret < 0) {
  15122. /* Callback < 0: Error. Abort init. */
  15123. mg_cry_ctx_internal(
  15124. phys_ctx,
  15125. "external_ssl_ctx_domain callback returned error: %i",
  15126. callback_ret);
  15127. return 0;
  15128. } else if (callback_ret > 0) {
  15129. /* Callback > 0: Consider init done. */
  15130. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15131. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15132. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15133. return 0;
  15134. }
  15135. return 1;
  15136. }
  15137. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15138. * 0, CivetWeb should continue initializing SSL */
  15139. /* If PEM file is not specified and the init_ssl callbacks
  15140. * are not specified, setup will fail. */
  15141. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15142. && (phys_ctx->callbacks.init_ssl == NULL)
  15143. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15144. /* No certificate and no init_ssl callbacks:
  15145. * Essential data to set up TLS is missing.
  15146. */
  15147. mg_cry_ctx_internal(phys_ctx,
  15148. "Initializing SSL failed: -%s is not set",
  15149. config_options[SSL_CERTIFICATE].name);
  15150. return 0;
  15151. }
  15152. /* If a certificate chain is configured, use it. */
  15153. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15154. if (chain == NULL) {
  15155. /* Default: certificate chain in PEM file */
  15156. chain = pem;
  15157. }
  15158. if ((chain != NULL) && (*chain == 0)) {
  15159. /* If the chain is an empty string, don't use it. */
  15160. chain = NULL;
  15161. }
  15162. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15163. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15164. return 0;
  15165. }
  15166. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15167. }
  15168. static void
  15169. uninitialize_openssl(void)
  15170. {
  15171. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15172. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15173. /* Shutdown according to
  15174. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15175. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15176. */
  15177. CONF_modules_unload(1);
  15178. #else
  15179. int i;
  15180. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15181. /* Shutdown according to
  15182. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15183. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15184. */
  15185. CRYPTO_set_locking_callback(NULL);
  15186. CRYPTO_set_id_callback(NULL);
  15187. ENGINE_cleanup();
  15188. CONF_modules_unload(1);
  15189. ERR_free_strings();
  15190. EVP_cleanup();
  15191. CRYPTO_cleanup_all_ex_data();
  15192. OPENSSL_REMOVE_THREAD_STATE();
  15193. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15194. pthread_mutex_destroy(&ssl_mutexes[i]);
  15195. }
  15196. mg_free(ssl_mutexes);
  15197. ssl_mutexes = NULL;
  15198. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15199. }
  15200. }
  15201. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15202. #if !defined(NO_FILESYSTEMS)
  15203. static int
  15204. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15205. {
  15206. if (phys_ctx) {
  15207. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15208. const char *path;
  15209. struct mg_connection fc;
  15210. if (!dom_ctx) {
  15211. dom_ctx = &(phys_ctx->dd);
  15212. }
  15213. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15214. if ((path != NULL)
  15215. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15216. mg_cry_ctx_internal(phys_ctx,
  15217. "Cannot open %s: %s",
  15218. path,
  15219. strerror(ERRNO));
  15220. return 0;
  15221. }
  15222. return 1;
  15223. }
  15224. return 0;
  15225. }
  15226. #endif /* NO_FILESYSTEMS */
  15227. static int
  15228. set_acl_option(struct mg_context *phys_ctx)
  15229. {
  15230. union usa sa;
  15231. memset(&sa, 0, sizeof(sa));
  15232. #if defined(USE_IPV6)
  15233. sa.sin6.sin6_family = AF_INET6;
  15234. #else
  15235. sa.sin.sin_family = AF_INET;
  15236. #endif
  15237. return check_acl(phys_ctx, &sa) != -1;
  15238. }
  15239. static void
  15240. reset_per_request_attributes(struct mg_connection *conn)
  15241. {
  15242. if (!conn) {
  15243. return;
  15244. }
  15245. conn->num_bytes_sent = conn->consumed_content = 0;
  15246. conn->path_info = NULL;
  15247. conn->status_code = -1;
  15248. conn->content_len = -1;
  15249. conn->is_chunked = 0;
  15250. conn->must_close = 0;
  15251. conn->request_len = 0;
  15252. conn->request_state = 0;
  15253. conn->throttle = 0;
  15254. conn->accept_gzip = 0;
  15255. conn->response_info.content_length = conn->request_info.content_length = -1;
  15256. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15257. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15258. conn->response_info.status_text = NULL;
  15259. conn->response_info.status_code = 0;
  15260. conn->request_info.remote_user = NULL;
  15261. conn->request_info.request_method = NULL;
  15262. conn->request_info.request_uri = NULL;
  15263. /* Free cleaned local URI (if any) */
  15264. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15265. mg_free((void *)conn->request_info.local_uri);
  15266. conn->request_info.local_uri = NULL;
  15267. }
  15268. conn->request_info.local_uri = NULL;
  15269. #if defined(USE_SERVER_STATS)
  15270. conn->processing_time = 0;
  15271. #endif
  15272. }
  15273. static int
  15274. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15275. {
  15276. if ((so->lsa.sa.sa_family == AF_INET)
  15277. || (so->lsa.sa.sa_family == AF_INET6)) {
  15278. /* Only for TCP sockets */
  15279. if (setsockopt(so->sock,
  15280. IPPROTO_TCP,
  15281. TCP_NODELAY,
  15282. (SOCK_OPT_TYPE)&nodelay_on,
  15283. sizeof(nodelay_on))
  15284. != 0) {
  15285. /* Error */
  15286. return 1;
  15287. }
  15288. }
  15289. /* OK */
  15290. return 0;
  15291. }
  15292. #if !defined(__ZEPHYR__)
  15293. static void
  15294. close_socket_gracefully(struct mg_connection *conn)
  15295. {
  15296. #if defined(_WIN32)
  15297. char buf[MG_BUF_LEN];
  15298. int n;
  15299. #endif
  15300. struct linger linger;
  15301. int error_code = 0;
  15302. int linger_timeout = -2;
  15303. socklen_t opt_len = sizeof(error_code);
  15304. if (!conn) {
  15305. return;
  15306. }
  15307. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15308. * "Note that enabling a nonzero timeout on a nonblocking socket
  15309. * is not recommended.", so set it to blocking now */
  15310. set_blocking_mode(conn->client.sock);
  15311. /* Send FIN to the client */
  15312. shutdown(conn->client.sock, SHUTDOWN_WR);
  15313. #if defined(_WIN32)
  15314. /* Read and discard pending incoming data. If we do not do that and
  15315. * close
  15316. * the socket, the data in the send buffer may be discarded. This
  15317. * behaviour is seen on Windows, when client keeps sending data
  15318. * when server decides to close the connection; then when client
  15319. * does recv() it gets no data back. */
  15320. do {
  15321. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15322. } while (n > 0);
  15323. #endif
  15324. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15325. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15326. }
  15327. /* Set linger option according to configuration */
  15328. if (linger_timeout >= 0) {
  15329. /* Set linger option to avoid socket hanging out after close. This
  15330. * prevent ephemeral port exhaust problem under high QPS. */
  15331. linger.l_onoff = 1;
  15332. #if defined(_MSC_VER)
  15333. #pragma warning(push)
  15334. #pragma warning(disable : 4244)
  15335. #endif
  15336. #if defined(GCC_DIAGNOSTIC)
  15337. #pragma GCC diagnostic push
  15338. #pragma GCC diagnostic ignored "-Wconversion"
  15339. #endif
  15340. /* Data type of linger structure elements may differ,
  15341. * so we don't know what cast we need here.
  15342. * Disable type conversion warnings. */
  15343. linger.l_linger = (linger_timeout + 999) / 1000;
  15344. #if defined(GCC_DIAGNOSTIC)
  15345. #pragma GCC diagnostic pop
  15346. #endif
  15347. #if defined(_MSC_VER)
  15348. #pragma warning(pop)
  15349. #endif
  15350. } else {
  15351. linger.l_onoff = 0;
  15352. linger.l_linger = 0;
  15353. }
  15354. if (linger_timeout < -1) {
  15355. /* Default: don't configure any linger */
  15356. } else if (getsockopt(conn->client.sock,
  15357. SOL_SOCKET,
  15358. SO_ERROR,
  15359. #if defined(_WIN32) /* WinSock uses different data type here */
  15360. (char *)&error_code,
  15361. #else
  15362. &error_code,
  15363. #endif
  15364. &opt_len)
  15365. != 0) {
  15366. /* Cannot determine if socket is already closed. This should
  15367. * not occur and never did in a test. Log an error message
  15368. * and continue. */
  15369. mg_cry_internal(conn,
  15370. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15371. __func__,
  15372. strerror(ERRNO));
  15373. #if defined(_WIN32)
  15374. } else if (error_code == WSAECONNRESET) {
  15375. #else
  15376. } else if (error_code == ECONNRESET) {
  15377. #endif
  15378. /* Socket already closed by client/peer, close socket without linger
  15379. */
  15380. } else {
  15381. /* Set linger timeout */
  15382. if (setsockopt(conn->client.sock,
  15383. SOL_SOCKET,
  15384. SO_LINGER,
  15385. (char *)&linger,
  15386. sizeof(linger))
  15387. != 0) {
  15388. mg_cry_internal(
  15389. conn,
  15390. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15391. __func__,
  15392. linger.l_onoff,
  15393. linger.l_linger,
  15394. strerror(ERRNO));
  15395. }
  15396. }
  15397. /* Now we know that our FIN is ACK-ed, safe to close */
  15398. closesocket(conn->client.sock);
  15399. conn->client.sock = INVALID_SOCKET;
  15400. }
  15401. #endif
  15402. static void
  15403. close_connection(struct mg_connection *conn)
  15404. {
  15405. #if defined(USE_SERVER_STATS)
  15406. conn->conn_state = 6; /* to close */
  15407. #endif
  15408. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15409. if (conn->lua_websocket_state) {
  15410. lua_websocket_close(conn, conn->lua_websocket_state);
  15411. conn->lua_websocket_state = NULL;
  15412. }
  15413. #endif
  15414. mg_lock_connection(conn);
  15415. /* Set close flag, so keep-alive loops will stop */
  15416. conn->must_close = 1;
  15417. /* call the connection_close callback if assigned */
  15418. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15419. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15420. conn->phys_ctx->callbacks.connection_close(conn);
  15421. }
  15422. }
  15423. /* Reset user data, after close callback is called.
  15424. * Do not reuse it. If the user needs a destructor,
  15425. * it must be done in the connection_close callback. */
  15426. mg_set_user_connection_data(conn, NULL);
  15427. #if defined(USE_SERVER_STATS)
  15428. conn->conn_state = 7; /* closing */
  15429. #endif
  15430. #if defined(USE_MBEDTLS)
  15431. if (conn->ssl != NULL) {
  15432. mbed_ssl_close(conn->ssl);
  15433. conn->ssl = NULL;
  15434. }
  15435. #elif !defined(NO_SSL)
  15436. if (conn->ssl != NULL) {
  15437. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15438. */
  15439. SSL_shutdown(conn->ssl);
  15440. SSL_free(conn->ssl);
  15441. OPENSSL_REMOVE_THREAD_STATE();
  15442. conn->ssl = NULL;
  15443. }
  15444. #endif
  15445. if (conn->client.sock != INVALID_SOCKET) {
  15446. #if defined(__ZEPHYR__)
  15447. closesocket(conn->client.sock);
  15448. #else
  15449. close_socket_gracefully(conn);
  15450. #endif
  15451. conn->client.sock = INVALID_SOCKET;
  15452. }
  15453. /* call the connection_closed callback if assigned */
  15454. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15455. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15456. conn->phys_ctx->callbacks.connection_closed(conn);
  15457. }
  15458. }
  15459. mg_unlock_connection(conn);
  15460. #if defined(USE_SERVER_STATS)
  15461. conn->conn_state = 8; /* closed */
  15462. #endif
  15463. }
  15464. CIVETWEB_API void
  15465. mg_close_connection(struct mg_connection *conn)
  15466. {
  15467. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15468. return;
  15469. }
  15470. #if defined(USE_WEBSOCKET)
  15471. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15472. if (conn->in_websocket_handling) {
  15473. /* Set close flag, so the server thread can exit. */
  15474. conn->must_close = 1;
  15475. return;
  15476. }
  15477. }
  15478. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15479. unsigned int i;
  15480. /* client context: loops must end */
  15481. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15482. conn->must_close = 1;
  15483. /* We need to get the client thread out of the select/recv call
  15484. * here. */
  15485. /* Since we use a sleep quantum of some seconds to check for recv
  15486. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15487. /* join worker thread */
  15488. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15489. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15490. }
  15491. }
  15492. #endif /* defined(USE_WEBSOCKET) */
  15493. close_connection(conn);
  15494. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15495. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15496. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15497. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15498. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15499. }
  15500. #endif
  15501. #if defined(USE_WEBSOCKET)
  15502. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15503. mg_free(conn->phys_ctx->worker_threadids);
  15504. (void)pthread_mutex_destroy(&conn->mutex);
  15505. mg_free(conn);
  15506. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15507. (void)pthread_mutex_destroy(&conn->mutex);
  15508. mg_free(conn);
  15509. }
  15510. #else
  15511. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15512. (void)pthread_mutex_destroy(&conn->mutex);
  15513. mg_free(conn);
  15514. }
  15515. #endif /* defined(USE_WEBSOCKET) */
  15516. }
  15517. static struct mg_connection *
  15518. mg_connect_client_impl(const struct mg_client_options *client_options,
  15519. int use_ssl,
  15520. struct mg_init_data *init,
  15521. struct mg_error_data *error)
  15522. {
  15523. struct mg_connection *conn = NULL;
  15524. SOCKET sock;
  15525. union usa sa;
  15526. struct sockaddr *psa;
  15527. socklen_t len;
  15528. unsigned max_req_size =
  15529. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15530. /* Size of structures, aligned to 8 bytes */
  15531. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15532. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15533. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15534. (void)init; /* TODO: Implement required options */
  15535. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15536. if (error != NULL) {
  15537. error->code = MG_ERROR_DATA_CODE_OK;
  15538. error->code_sub = 0;
  15539. if (error->text_buffer_size > 0) {
  15540. error->text[0] = 0;
  15541. }
  15542. }
  15543. if (conn == NULL) {
  15544. if (error != NULL) {
  15545. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15546. error->code_sub = (unsigned)alloc_size;
  15547. mg_snprintf(NULL,
  15548. NULL, /* No truncation check for ebuf */
  15549. error->text,
  15550. error->text_buffer_size,
  15551. "calloc(): %s",
  15552. strerror(ERRNO));
  15553. }
  15554. return NULL;
  15555. }
  15556. #if defined(GCC_DIAGNOSTIC)
  15557. #pragma GCC diagnostic push
  15558. #pragma GCC diagnostic ignored "-Wcast-align"
  15559. #endif /* defined(GCC_DIAGNOSTIC) */
  15560. /* conn_size is aligned to 8 bytes */
  15561. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15562. #if defined(GCC_DIAGNOSTIC)
  15563. #pragma GCC diagnostic pop
  15564. #endif /* defined(GCC_DIAGNOSTIC) */
  15565. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15566. conn->buf_size = (int)max_req_size;
  15567. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15568. conn->dom_ctx = &(conn->phys_ctx->dd);
  15569. if (!connect_socket(conn->phys_ctx,
  15570. client_options->host,
  15571. client_options->port,
  15572. use_ssl,
  15573. error,
  15574. &sock,
  15575. &sa)) {
  15576. /* "error" will be set by connect_socket. */
  15577. /* free all memory and return NULL; */
  15578. mg_free(conn);
  15579. return NULL;
  15580. }
  15581. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15582. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15583. && !defined(NO_SSL_DL)
  15584. if (use_ssl
  15585. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15586. == NULL) {
  15587. if (error != NULL) {
  15588. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15589. mg_snprintf(NULL,
  15590. NULL, /* No truncation check for ebuf */
  15591. error->text,
  15592. error->text_buffer_size,
  15593. "SSL_CTX_new error: %s",
  15594. ssl_error());
  15595. }
  15596. closesocket(sock);
  15597. mg_free(conn);
  15598. return NULL;
  15599. }
  15600. #else
  15601. if (use_ssl
  15602. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15603. == NULL) {
  15604. if (error != NULL) {
  15605. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15606. mg_snprintf(NULL,
  15607. NULL, /* No truncation check for ebuf */
  15608. error->text,
  15609. error->text_buffer_size,
  15610. "SSL_CTX_new error: %s",
  15611. ssl_error());
  15612. }
  15613. closesocket(sock);
  15614. mg_free(conn);
  15615. return NULL;
  15616. }
  15617. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15618. #endif /* NO_SSL */
  15619. #if defined(USE_IPV6)
  15620. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15621. : sizeof(conn->client.rsa.sin6);
  15622. psa = (sa.sa.sa_family == AF_INET)
  15623. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15624. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15625. #else
  15626. len = sizeof(conn->client.rsa.sin);
  15627. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15628. #endif
  15629. conn->client.sock = sock;
  15630. conn->client.lsa = sa;
  15631. if (getsockname(sock, psa, &len) != 0) {
  15632. mg_cry_internal(conn,
  15633. "%s: getsockname() failed: %s",
  15634. __func__,
  15635. strerror(ERRNO));
  15636. }
  15637. conn->client.is_ssl = use_ssl ? 1 : 0;
  15638. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15639. if (error != NULL) {
  15640. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15641. error->code_sub = (unsigned)ERRNO;
  15642. mg_snprintf(NULL,
  15643. NULL, /* No truncation check for ebuf */
  15644. error->text,
  15645. error->text_buffer_size,
  15646. "Can not create mutex");
  15647. }
  15648. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15649. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15650. #endif
  15651. closesocket(sock);
  15652. mg_free(conn);
  15653. return NULL;
  15654. }
  15655. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15656. if (use_ssl) {
  15657. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15658. * SSL_CTX_set_verify call is needed to switch off server
  15659. * certificate checking, which is off by default in OpenSSL and
  15660. * on in yaSSL. */
  15661. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15662. * SSL_VERIFY_PEER, verify_ssl_server); */
  15663. if (client_options->client_cert) {
  15664. if (!ssl_use_pem_file(conn->phys_ctx,
  15665. conn->dom_ctx,
  15666. client_options->client_cert,
  15667. NULL)) {
  15668. if (error != NULL) {
  15669. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15670. mg_snprintf(NULL,
  15671. NULL, /* No truncation check for ebuf */
  15672. error->text,
  15673. error->text_buffer_size,
  15674. "Can not use SSL client certificate");
  15675. }
  15676. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15677. closesocket(sock);
  15678. mg_free(conn);
  15679. return NULL;
  15680. }
  15681. }
  15682. if (client_options->server_cert) {
  15683. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15684. client_options->server_cert,
  15685. NULL)
  15686. != 1) {
  15687. if (error != NULL) {
  15688. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15689. mg_snprintf(NULL,
  15690. NULL, /* No truncation check for ebuf */
  15691. error->text,
  15692. error->text_buffer_size,
  15693. "SSL_CTX_load_verify_locations error: %s",
  15694. ssl_error());
  15695. }
  15696. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15697. closesocket(sock);
  15698. mg_free(conn);
  15699. return NULL;
  15700. }
  15701. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15702. } else {
  15703. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15704. }
  15705. if (!sslize(conn, SSL_connect, client_options)) {
  15706. if (error != NULL) {
  15707. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15708. mg_snprintf(NULL,
  15709. NULL, /* No truncation check for ebuf */
  15710. error->text,
  15711. error->text_buffer_size,
  15712. "SSL connection error");
  15713. }
  15714. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15715. closesocket(sock);
  15716. mg_free(conn);
  15717. return NULL;
  15718. }
  15719. }
  15720. #endif
  15721. return conn;
  15722. }
  15723. CIVETWEB_API struct mg_connection *
  15724. mg_connect_client_secure(const struct mg_client_options *client_options,
  15725. char *error_buffer,
  15726. size_t error_buffer_size)
  15727. {
  15728. struct mg_init_data init;
  15729. struct mg_error_data error;
  15730. memset(&init, 0, sizeof(init));
  15731. memset(&error, 0, sizeof(error));
  15732. error.text_buffer_size = error_buffer_size;
  15733. error.text = error_buffer;
  15734. return mg_connect_client_impl(client_options, 1, &init, &error);
  15735. }
  15736. CIVETWEB_API struct mg_connection *
  15737. mg_connect_client(const char *host,
  15738. int port,
  15739. int use_ssl,
  15740. char *error_buffer,
  15741. size_t error_buffer_size)
  15742. {
  15743. struct mg_client_options opts;
  15744. struct mg_init_data init;
  15745. struct mg_error_data error;
  15746. memset(&init, 0, sizeof(init));
  15747. memset(&error, 0, sizeof(error));
  15748. error.text_buffer_size = error_buffer_size;
  15749. error.text = error_buffer;
  15750. memset(&opts, 0, sizeof(opts));
  15751. opts.host = host;
  15752. opts.port = port;
  15753. if (use_ssl) {
  15754. opts.host_name = host;
  15755. }
  15756. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  15757. }
  15758. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15759. CIVETWEB_API struct mg_connection *
  15760. mg_connect_client2(const char *host,
  15761. const char *protocol,
  15762. int port,
  15763. const char *path,
  15764. struct mg_init_data *init,
  15765. struct mg_error_data *error)
  15766. {
  15767. (void)path;
  15768. int is_ssl, is_ws;
  15769. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15770. if (error != NULL) {
  15771. error->code = MG_ERROR_DATA_CODE_OK;
  15772. error->code_sub = 0;
  15773. if (error->text_buffer_size > 0) {
  15774. *error->text = 0;
  15775. }
  15776. }
  15777. if ((host == NULL) || (protocol == NULL)) {
  15778. if (error != NULL) {
  15779. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15780. mg_snprintf(NULL,
  15781. NULL, /* No truncation check for error buffers */
  15782. error->text,
  15783. error->text_buffer_size,
  15784. "%s",
  15785. "Invalid parameters");
  15786. }
  15787. return NULL;
  15788. }
  15789. /* check all known protocols */
  15790. if (!mg_strcasecmp(protocol, "http")) {
  15791. is_ssl = 0;
  15792. is_ws = 0;
  15793. } else if (!mg_strcasecmp(protocol, "https")) {
  15794. is_ssl = 1;
  15795. is_ws = 0;
  15796. #if defined(USE_WEBSOCKET)
  15797. } else if (!mg_strcasecmp(protocol, "ws")) {
  15798. is_ssl = 0;
  15799. is_ws = 1;
  15800. } else if (!mg_strcasecmp(protocol, "wss")) {
  15801. is_ssl = 1;
  15802. is_ws = 1;
  15803. #endif
  15804. } else {
  15805. if (error != NULL) {
  15806. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15807. mg_snprintf(NULL,
  15808. NULL, /* No truncation check for error buffers */
  15809. error->text,
  15810. error->text_buffer_size,
  15811. "Protocol %s not supported",
  15812. protocol);
  15813. }
  15814. return NULL;
  15815. }
  15816. /* TODO: The current implementation here just calls the old
  15817. * implementations, without using any new options. This is just a first
  15818. * step to test the new interfaces. */
  15819. #if defined(USE_WEBSOCKET)
  15820. if (is_ws) {
  15821. /* TODO: implement all options */
  15822. return mg_connect_websocket_client(
  15823. host,
  15824. port,
  15825. is_ssl,
  15826. ((error != NULL) ? error->text : NULL),
  15827. ((error != NULL) ? error->text_buffer_size : 0),
  15828. (path ? path : ""),
  15829. NULL /* TODO: origin */,
  15830. experimental_websocket_client_data_wrapper,
  15831. experimental_websocket_client_close_wrapper,
  15832. (void *)init->callbacks);
  15833. }
  15834. #else
  15835. (void)is_ws;
  15836. #endif
  15837. /* TODO: all additional options */
  15838. struct mg_client_options opts;
  15839. memset(&opts, 0, sizeof(opts));
  15840. opts.host = host;
  15841. opts.port = port;
  15842. return mg_connect_client_impl(&opts, is_ssl, init, error);
  15843. }
  15844. #endif
  15845. static const struct {
  15846. const char *proto;
  15847. size_t proto_len;
  15848. unsigned default_port;
  15849. } abs_uri_protocols[] = {{"http://", 7, 80},
  15850. {"https://", 8, 443},
  15851. {"ws://", 5, 80},
  15852. {"wss://", 6, 443},
  15853. {NULL, 0, 0}};
  15854. /* Check if the uri is valid.
  15855. * return 0 for invalid uri,
  15856. * return 1 for *,
  15857. * return 2 for relative uri,
  15858. * return 3 for absolute uri without port,
  15859. * return 4 for absolute uri with port */
  15860. static int
  15861. get_uri_type(const char *uri)
  15862. {
  15863. int i;
  15864. const char *hostend, *portbegin;
  15865. char *portend;
  15866. unsigned long port;
  15867. /* According to the HTTP standard
  15868. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15869. * URI can be an asterisk (*) or should start with slash (relative uri),
  15870. * or it should start with the protocol (absolute uri). */
  15871. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15872. /* asterisk */
  15873. return 1;
  15874. }
  15875. /* Valid URIs according to RFC 3986
  15876. * (https://www.ietf.org/rfc/rfc3986.txt)
  15877. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15878. * and unreserved characters A-Z a-z 0-9 and -._~
  15879. * and % encoded symbols.
  15880. */
  15881. for (i = 0; uri[i] != 0; i++) {
  15882. if (uri[i] < 33) {
  15883. /* control characters and spaces are invalid */
  15884. return 0;
  15885. }
  15886. /* Allow everything else here (See #894) */
  15887. }
  15888. /* A relative uri starts with a / character */
  15889. if (uri[0] == '/') {
  15890. /* relative uri */
  15891. return 2;
  15892. }
  15893. /* It could be an absolute uri: */
  15894. /* This function only checks if the uri is valid, not if it is
  15895. * addressing the current server. So civetweb can also be used
  15896. * as a proxy server. */
  15897. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15898. if (mg_strncasecmp(uri,
  15899. abs_uri_protocols[i].proto,
  15900. abs_uri_protocols[i].proto_len)
  15901. == 0) {
  15902. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15903. if (!hostend) {
  15904. return 0;
  15905. }
  15906. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15907. if (!portbegin) {
  15908. return 3;
  15909. }
  15910. port = strtoul(portbegin + 1, &portend, 10);
  15911. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15912. return 0;
  15913. }
  15914. return 4;
  15915. }
  15916. }
  15917. return 0;
  15918. }
  15919. /* Return NULL or the relative uri at the current server */
  15920. static const char *
  15921. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15922. {
  15923. const char *server_domain;
  15924. size_t server_domain_len;
  15925. size_t request_domain_len = 0;
  15926. unsigned long port = 0;
  15927. int i, auth_domain_check_enabled;
  15928. const char *hostbegin = NULL;
  15929. const char *hostend = NULL;
  15930. const char *portbegin;
  15931. char *portend;
  15932. auth_domain_check_enabled =
  15933. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15934. /* DNS is case insensitive, so use case insensitive string compare here
  15935. */
  15936. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15937. if (mg_strncasecmp(uri,
  15938. abs_uri_protocols[i].proto,
  15939. abs_uri_protocols[i].proto_len)
  15940. == 0) {
  15941. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15942. hostend = strchr(hostbegin, '/');
  15943. if (!hostend) {
  15944. return 0;
  15945. }
  15946. portbegin = strchr(hostbegin, ':');
  15947. if ((!portbegin) || (portbegin > hostend)) {
  15948. port = abs_uri_protocols[i].default_port;
  15949. request_domain_len = (size_t)(hostend - hostbegin);
  15950. } else {
  15951. port = strtoul(portbegin + 1, &portend, 10);
  15952. if ((portend != hostend) || (port <= 0)
  15953. || !is_valid_port(port)) {
  15954. return 0;
  15955. }
  15956. request_domain_len = (size_t)(portbegin - hostbegin);
  15957. }
  15958. /* protocol found, port set */
  15959. break;
  15960. }
  15961. }
  15962. if (!port) {
  15963. /* port remains 0 if the protocol is not found */
  15964. return 0;
  15965. }
  15966. /* Check if the request is directed to a different server. */
  15967. /* First check if the port is the same. */
  15968. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15969. /* Request is directed to a different port */
  15970. return 0;
  15971. }
  15972. /* Finally check if the server corresponds to the authentication
  15973. * domain of the server (the server domain).
  15974. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15975. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15976. * but do not allow substrings (like
  15977. * http://notmydomain.com/path/file.ext
  15978. * or http://mydomain.com.fake/path/file.ext).
  15979. */
  15980. if (auth_domain_check_enabled) {
  15981. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15982. server_domain_len = strlen(server_domain);
  15983. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15984. return 0;
  15985. }
  15986. if ((request_domain_len == server_domain_len)
  15987. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15988. /* Request is directed to this server - full name match. */
  15989. } else {
  15990. if (request_domain_len < (server_domain_len + 2)) {
  15991. /* Request is directed to another server: The server name
  15992. * is longer than the request name.
  15993. * Drop this case here to avoid overflows in the
  15994. * following checks. */
  15995. return 0;
  15996. }
  15997. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15998. /* Request is directed to another server: It could be a
  15999. * substring
  16000. * like notmyserver.com */
  16001. return 0;
  16002. }
  16003. if (0
  16004. != memcmp(server_domain,
  16005. hostbegin + request_domain_len - server_domain_len,
  16006. server_domain_len)) {
  16007. /* Request is directed to another server:
  16008. * The server name is different. */
  16009. return 0;
  16010. }
  16011. }
  16012. }
  16013. return hostend;
  16014. }
  16015. static int
  16016. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16017. {
  16018. if (ebuf_len > 0) {
  16019. ebuf[0] = '\0';
  16020. }
  16021. *err = 0;
  16022. reset_per_request_attributes(conn);
  16023. if (!conn) {
  16024. mg_snprintf(conn,
  16025. NULL, /* No truncation check for ebuf */
  16026. ebuf,
  16027. ebuf_len,
  16028. "%s",
  16029. "Internal error");
  16030. *err = 500;
  16031. return 0;
  16032. }
  16033. /* Set the time the request was received. This value should be used for
  16034. * timeouts. */
  16035. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16036. conn->request_len =
  16037. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16038. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16039. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16040. mg_snprintf(conn,
  16041. NULL, /* No truncation check for ebuf */
  16042. ebuf,
  16043. ebuf_len,
  16044. "%s",
  16045. "Invalid message size");
  16046. *err = 500;
  16047. return 0;
  16048. }
  16049. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16050. mg_snprintf(conn,
  16051. NULL, /* No truncation check for ebuf */
  16052. ebuf,
  16053. ebuf_len,
  16054. "%s",
  16055. "Message too large");
  16056. *err = 413;
  16057. return 0;
  16058. }
  16059. if (conn->request_len <= 0) {
  16060. if (conn->data_len > 0) {
  16061. mg_snprintf(conn,
  16062. NULL, /* No truncation check for ebuf */
  16063. ebuf,
  16064. ebuf_len,
  16065. "%s",
  16066. "Malformed message");
  16067. *err = 400;
  16068. } else {
  16069. /* Server did not recv anything -> just close the connection */
  16070. conn->must_close = 1;
  16071. mg_snprintf(conn,
  16072. NULL, /* No truncation check for ebuf */
  16073. ebuf,
  16074. ebuf_len,
  16075. "%s",
  16076. "No data received");
  16077. *err = 0;
  16078. }
  16079. return 0;
  16080. }
  16081. return 1;
  16082. }
  16083. static int
  16084. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16085. {
  16086. const char *cl;
  16087. conn->connection_type =
  16088. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16089. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16090. return 0;
  16091. }
  16092. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16093. <= 0) {
  16094. mg_snprintf(conn,
  16095. NULL, /* No truncation check for ebuf */
  16096. ebuf,
  16097. ebuf_len,
  16098. "%s",
  16099. "Bad request");
  16100. *err = 400;
  16101. return 0;
  16102. }
  16103. /* Message is a valid request */
  16104. if (!switch_domain_context(conn)) {
  16105. mg_snprintf(conn,
  16106. NULL, /* No truncation check for ebuf */
  16107. ebuf,
  16108. ebuf_len,
  16109. "%s",
  16110. "Bad request: Host mismatch");
  16111. *err = 400;
  16112. return 0;
  16113. }
  16114. #if USE_ZLIB
  16115. if (((cl = get_header(conn->request_info.http_headers,
  16116. conn->request_info.num_headers,
  16117. "Accept-Encoding"))
  16118. != NULL)
  16119. && strstr(cl, "gzip")) {
  16120. conn->accept_gzip = 1;
  16121. }
  16122. #endif
  16123. if (((cl = get_header(conn->request_info.http_headers,
  16124. conn->request_info.num_headers,
  16125. "Transfer-Encoding"))
  16126. != NULL)
  16127. && mg_strcasecmp(cl, "identity")) {
  16128. if (mg_strcasecmp(cl, "chunked")) {
  16129. mg_snprintf(conn,
  16130. NULL, /* No truncation check for ebuf */
  16131. ebuf,
  16132. ebuf_len,
  16133. "%s",
  16134. "Bad request");
  16135. *err = 400;
  16136. return 0;
  16137. }
  16138. conn->is_chunked = 1;
  16139. conn->content_len = 0; /* not yet read */
  16140. } else if ((cl = get_header(conn->request_info.http_headers,
  16141. conn->request_info.num_headers,
  16142. "Content-Length"))
  16143. != NULL) {
  16144. /* Request has content length set */
  16145. char *endptr = NULL;
  16146. conn->content_len = strtoll(cl, &endptr, 10);
  16147. if ((endptr == cl) || (conn->content_len < 0)) {
  16148. mg_snprintf(conn,
  16149. NULL, /* No truncation check for ebuf */
  16150. ebuf,
  16151. ebuf_len,
  16152. "%s",
  16153. "Bad request");
  16154. *err = 411;
  16155. return 0;
  16156. }
  16157. /* Publish the content length back to the request info. */
  16158. conn->request_info.content_length = conn->content_len;
  16159. } else {
  16160. /* There is no exception, see RFC7230. */
  16161. conn->content_len = 0;
  16162. }
  16163. return 1;
  16164. }
  16165. /* conn is assumed to be valid in this internal function */
  16166. static int
  16167. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16168. {
  16169. const char *cl;
  16170. conn->connection_type =
  16171. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16172. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16173. return 0;
  16174. }
  16175. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16176. <= 0) {
  16177. mg_snprintf(conn,
  16178. NULL, /* No truncation check for ebuf */
  16179. ebuf,
  16180. ebuf_len,
  16181. "%s",
  16182. "Bad response");
  16183. *err = 400;
  16184. return 0;
  16185. }
  16186. /* Message is a valid response */
  16187. if (((cl = get_header(conn->response_info.http_headers,
  16188. conn->response_info.num_headers,
  16189. "Transfer-Encoding"))
  16190. != NULL)
  16191. && mg_strcasecmp(cl, "identity")) {
  16192. if (mg_strcasecmp(cl, "chunked")) {
  16193. mg_snprintf(conn,
  16194. NULL, /* No truncation check for ebuf */
  16195. ebuf,
  16196. ebuf_len,
  16197. "%s",
  16198. "Bad request");
  16199. *err = 400;
  16200. return 0;
  16201. }
  16202. conn->is_chunked = 1;
  16203. conn->content_len = 0; /* not yet read */
  16204. } else if ((cl = get_header(conn->response_info.http_headers,
  16205. conn->response_info.num_headers,
  16206. "Content-Length"))
  16207. != NULL) {
  16208. char *endptr = NULL;
  16209. conn->content_len = strtoll(cl, &endptr, 10);
  16210. if ((endptr == cl) || (conn->content_len < 0)) {
  16211. mg_snprintf(conn,
  16212. NULL, /* No truncation check for ebuf */
  16213. ebuf,
  16214. ebuf_len,
  16215. "%s",
  16216. "Bad request");
  16217. *err = 411;
  16218. return 0;
  16219. }
  16220. /* Publish the content length back to the response info. */
  16221. conn->response_info.content_length = conn->content_len;
  16222. /* TODO: check if it is still used in response_info */
  16223. conn->request_info.content_length = conn->content_len;
  16224. /* TODO: we should also consider HEAD method */
  16225. if (conn->response_info.status_code == 304) {
  16226. conn->content_len = 0;
  16227. }
  16228. } else {
  16229. /* TODO: we should also consider HEAD method */
  16230. if (((conn->response_info.status_code >= 100)
  16231. && (conn->response_info.status_code <= 199))
  16232. || (conn->response_info.status_code == 204)
  16233. || (conn->response_info.status_code == 304)) {
  16234. conn->content_len = 0;
  16235. } else {
  16236. conn->content_len = -1; /* unknown content length */
  16237. }
  16238. }
  16239. return 1;
  16240. }
  16241. CIVETWEB_API int
  16242. mg_get_response(struct mg_connection *conn,
  16243. char *ebuf,
  16244. size_t ebuf_len,
  16245. int timeout)
  16246. {
  16247. int err, ret;
  16248. char txt[32]; /* will not overflow */
  16249. char *save_timeout;
  16250. char *new_timeout;
  16251. if (ebuf_len > 0) {
  16252. ebuf[0] = '\0';
  16253. }
  16254. if (!conn) {
  16255. mg_snprintf(conn,
  16256. NULL, /* No truncation check for ebuf */
  16257. ebuf,
  16258. ebuf_len,
  16259. "%s",
  16260. "Parameter error");
  16261. return -1;
  16262. }
  16263. /* Reset the previous responses */
  16264. conn->data_len = 0;
  16265. /* Implementation of API function for HTTP clients */
  16266. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16267. if (timeout >= 0) {
  16268. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16269. new_timeout = txt;
  16270. } else {
  16271. new_timeout = NULL;
  16272. }
  16273. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16274. ret = get_response(conn, ebuf, ebuf_len, &err);
  16275. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16276. /* TODO: here, the URI is the http response code */
  16277. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16278. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16279. /* TODO (mid): Define proper return values - maybe return length?
  16280. * For the first test use <0 for error and >0 for OK */
  16281. return (ret == 0) ? -1 : +1;
  16282. }
  16283. CIVETWEB_API struct mg_connection *
  16284. mg_download(const char *host,
  16285. int port,
  16286. int use_ssl,
  16287. char *ebuf,
  16288. size_t ebuf_len,
  16289. const char *fmt,
  16290. ...)
  16291. {
  16292. struct mg_connection *conn;
  16293. va_list ap;
  16294. int i;
  16295. int reqerr;
  16296. if (ebuf_len > 0) {
  16297. ebuf[0] = '\0';
  16298. }
  16299. va_start(ap, fmt);
  16300. /* open a connection */
  16301. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16302. if (conn != NULL) {
  16303. i = mg_vprintf(conn, fmt, ap);
  16304. if (i <= 0) {
  16305. mg_snprintf(conn,
  16306. NULL, /* No truncation check for ebuf */
  16307. ebuf,
  16308. ebuf_len,
  16309. "%s",
  16310. "Error sending request");
  16311. } else {
  16312. /* make sure the buffer is clear */
  16313. conn->data_len = 0;
  16314. get_response(conn, ebuf, ebuf_len, &reqerr);
  16315. /* TODO: here, the URI is the http response code */
  16316. conn->request_info.local_uri = conn->request_info.request_uri;
  16317. }
  16318. }
  16319. /* if an error occurred, close the connection */
  16320. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16321. mg_close_connection(conn);
  16322. conn = NULL;
  16323. }
  16324. va_end(ap);
  16325. return conn;
  16326. }
  16327. struct websocket_client_thread_data {
  16328. struct mg_connection *conn;
  16329. mg_websocket_data_handler data_handler;
  16330. mg_websocket_close_handler close_handler;
  16331. void *callback_data;
  16332. };
  16333. #if defined(USE_WEBSOCKET)
  16334. #if defined(_WIN32)
  16335. static unsigned __stdcall websocket_client_thread(void *data)
  16336. #else
  16337. static void *
  16338. websocket_client_thread(void *data)
  16339. #endif
  16340. {
  16341. struct websocket_client_thread_data *cdata =
  16342. (struct websocket_client_thread_data *)data;
  16343. void *user_thread_ptr = NULL;
  16344. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16345. struct sigaction sa;
  16346. /* Ignore SIGPIPE */
  16347. memset(&sa, 0, sizeof(sa));
  16348. sa.sa_handler = SIG_IGN;
  16349. sigaction(SIGPIPE, &sa, NULL);
  16350. #endif
  16351. mg_set_thread_name("ws-clnt");
  16352. if (cdata->conn->phys_ctx) {
  16353. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16354. /* 3 indicates a websocket client thread */
  16355. /* TODO: check if conn->phys_ctx can be set */
  16356. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16357. cdata->conn->phys_ctx, 3);
  16358. }
  16359. }
  16360. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16361. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16362. if (cdata->close_handler != NULL) {
  16363. cdata->close_handler(cdata->conn, cdata->callback_data);
  16364. }
  16365. /* The websocket_client context has only this thread. If it runs out,
  16366. set the stop_flag to 2 (= "stopped"). */
  16367. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16368. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16369. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16370. 3,
  16371. user_thread_ptr);
  16372. }
  16373. mg_free((void *)cdata);
  16374. #if defined(_WIN32)
  16375. return 0;
  16376. #else
  16377. return NULL;
  16378. #endif
  16379. }
  16380. #endif
  16381. static struct mg_connection *
  16382. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16383. int use_ssl,
  16384. char *error_buffer,
  16385. size_t error_buffer_size,
  16386. const char *path,
  16387. const char *origin,
  16388. const char *extensions,
  16389. mg_websocket_data_handler data_func,
  16390. mg_websocket_close_handler close_func,
  16391. void *user_data)
  16392. {
  16393. struct mg_connection *conn = NULL;
  16394. #if defined(USE_WEBSOCKET)
  16395. struct websocket_client_thread_data *thread_data;
  16396. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16397. const char *host = client_options->host;
  16398. int i;
  16399. struct mg_init_data init;
  16400. struct mg_error_data error;
  16401. memset(&init, 0, sizeof(init));
  16402. memset(&error, 0, sizeof(error));
  16403. error.text_buffer_size = error_buffer_size;
  16404. error.text = error_buffer;
  16405. #if defined(__clang__)
  16406. #pragma clang diagnostic push
  16407. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16408. #endif
  16409. /* Establish the client connection and request upgrade */
  16410. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16411. /* Connection object will be null if something goes wrong */
  16412. if (conn == NULL) {
  16413. /* error_buffer should be already filled ... */
  16414. if (!error_buffer[0]) {
  16415. /* ... if not add an error message */
  16416. mg_snprintf(conn,
  16417. NULL, /* No truncation check for ebuf */
  16418. error_buffer,
  16419. error_buffer_size,
  16420. "Unexpected error");
  16421. }
  16422. return NULL;
  16423. }
  16424. if (origin != NULL) {
  16425. if (extensions != NULL) {
  16426. i = mg_printf(conn,
  16427. "GET %s HTTP/1.1\r\n"
  16428. "Host: %s\r\n"
  16429. "Upgrade: websocket\r\n"
  16430. "Connection: Upgrade\r\n"
  16431. "Sec-WebSocket-Key: %s\r\n"
  16432. "Sec-WebSocket-Version: 13\r\n"
  16433. "Sec-WebSocket-Extensions: %s\r\n"
  16434. "Origin: %s\r\n"
  16435. "\r\n",
  16436. path,
  16437. host,
  16438. magic,
  16439. extensions,
  16440. origin);
  16441. } else {
  16442. i = mg_printf(conn,
  16443. "GET %s HTTP/1.1\r\n"
  16444. "Host: %s\r\n"
  16445. "Upgrade: websocket\r\n"
  16446. "Connection: Upgrade\r\n"
  16447. "Sec-WebSocket-Key: %s\r\n"
  16448. "Sec-WebSocket-Version: 13\r\n"
  16449. "Origin: %s\r\n"
  16450. "\r\n",
  16451. path,
  16452. host,
  16453. magic,
  16454. origin);
  16455. }
  16456. } else {
  16457. if (extensions != NULL) {
  16458. i = mg_printf(conn,
  16459. "GET %s HTTP/1.1\r\n"
  16460. "Host: %s\r\n"
  16461. "Upgrade: websocket\r\n"
  16462. "Connection: Upgrade\r\n"
  16463. "Sec-WebSocket-Key: %s\r\n"
  16464. "Sec-WebSocket-Version: 13\r\n"
  16465. "Sec-WebSocket-Extensions: %s\r\n"
  16466. "\r\n",
  16467. path,
  16468. host,
  16469. magic,
  16470. extensions);
  16471. } else {
  16472. i = mg_printf(conn,
  16473. "GET %s HTTP/1.1\r\n"
  16474. "Host: %s\r\n"
  16475. "Upgrade: websocket\r\n"
  16476. "Connection: Upgrade\r\n"
  16477. "Sec-WebSocket-Key: %s\r\n"
  16478. "Sec-WebSocket-Version: 13\r\n"
  16479. "\r\n",
  16480. path,
  16481. host,
  16482. magic);
  16483. }
  16484. }
  16485. if (i <= 0) {
  16486. mg_snprintf(conn,
  16487. NULL, /* No truncation check for ebuf */
  16488. error_buffer,
  16489. error_buffer_size,
  16490. "%s",
  16491. "Error sending request");
  16492. mg_close_connection(conn);
  16493. return NULL;
  16494. }
  16495. conn->data_len = 0;
  16496. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16497. mg_close_connection(conn);
  16498. return NULL;
  16499. }
  16500. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16501. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16502. #if defined(__clang__)
  16503. #pragma clang diagnostic pop
  16504. #endif
  16505. if (conn->response_info.status_code != 101) {
  16506. /* We sent an "upgrade" request. For a correct websocket
  16507. * protocol handshake, we expect a "101 Continue" response.
  16508. * Otherwise it is a protocol violation. Maybe the HTTP
  16509. * Server does not know websockets. */
  16510. if (!*error_buffer) {
  16511. /* set an error, if not yet set */
  16512. mg_snprintf(conn,
  16513. NULL, /* No truncation check for ebuf */
  16514. error_buffer,
  16515. error_buffer_size,
  16516. "Unexpected server reply");
  16517. }
  16518. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16519. mg_close_connection(conn);
  16520. return NULL;
  16521. }
  16522. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16523. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16524. if (!thread_data) {
  16525. DEBUG_TRACE("%s\r\n", "Out of memory");
  16526. mg_close_connection(conn);
  16527. return NULL;
  16528. }
  16529. thread_data->conn = conn;
  16530. thread_data->data_handler = data_func;
  16531. thread_data->close_handler = close_func;
  16532. thread_data->callback_data = user_data;
  16533. conn->phys_ctx->worker_threadids =
  16534. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16535. if (!conn->phys_ctx->worker_threadids) {
  16536. DEBUG_TRACE("%s\r\n", "Out of memory");
  16537. mg_free(thread_data);
  16538. mg_close_connection(conn);
  16539. return NULL;
  16540. }
  16541. /* Now upgrade to ws/wss client context */
  16542. conn->phys_ctx->user_data = user_data;
  16543. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16544. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16545. /* Start a thread to read the websocket client connection
  16546. * This thread will automatically stop when mg_disconnect is
  16547. * called on the client connection */
  16548. if (mg_start_thread_with_id(websocket_client_thread,
  16549. thread_data,
  16550. conn->phys_ctx->worker_threadids)
  16551. != 0) {
  16552. conn->phys_ctx->cfg_worker_threads = 0;
  16553. mg_free(thread_data);
  16554. mg_close_connection(conn);
  16555. conn = NULL;
  16556. DEBUG_TRACE("%s",
  16557. "Websocket client connect thread could not be started\r\n");
  16558. }
  16559. #else
  16560. /* Appease "unused parameter" warnings */
  16561. (void)client_options;
  16562. (void)use_ssl;
  16563. (void)error_buffer;
  16564. (void)error_buffer_size;
  16565. (void)path;
  16566. (void)origin;
  16567. (void)extensions;
  16568. (void)user_data;
  16569. (void)data_func;
  16570. (void)close_func;
  16571. #endif
  16572. return conn;
  16573. }
  16574. CIVETWEB_API struct mg_connection *
  16575. mg_connect_websocket_client(const char *host,
  16576. int port,
  16577. int use_ssl,
  16578. char *error_buffer,
  16579. size_t error_buffer_size,
  16580. const char *path,
  16581. const char *origin,
  16582. mg_websocket_data_handler data_func,
  16583. mg_websocket_close_handler close_func,
  16584. void *user_data)
  16585. {
  16586. struct mg_client_options client_options;
  16587. memset(&client_options, 0, sizeof(client_options));
  16588. client_options.host = host;
  16589. client_options.port = port;
  16590. return mg_connect_websocket_client_impl(&client_options,
  16591. use_ssl,
  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_secure(
  16603. const struct mg_client_options *client_options,
  16604. char *error_buffer,
  16605. size_t error_buffer_size,
  16606. const char *path,
  16607. const char *origin,
  16608. mg_websocket_data_handler data_func,
  16609. mg_websocket_close_handler close_func,
  16610. void *user_data)
  16611. {
  16612. if (!client_options) {
  16613. return NULL;
  16614. }
  16615. return mg_connect_websocket_client_impl(client_options,
  16616. 1,
  16617. error_buffer,
  16618. error_buffer_size,
  16619. path,
  16620. origin,
  16621. NULL,
  16622. data_func,
  16623. close_func,
  16624. user_data);
  16625. }
  16626. CIVETWEB_API struct mg_connection *
  16627. mg_connect_websocket_client_extensions(const char *host,
  16628. int port,
  16629. int use_ssl,
  16630. char *error_buffer,
  16631. size_t error_buffer_size,
  16632. const char *path,
  16633. const char *origin,
  16634. const char *extensions,
  16635. mg_websocket_data_handler data_func,
  16636. mg_websocket_close_handler close_func,
  16637. void *user_data)
  16638. {
  16639. struct mg_client_options client_options;
  16640. memset(&client_options, 0, sizeof(client_options));
  16641. client_options.host = host;
  16642. client_options.port = port;
  16643. return mg_connect_websocket_client_impl(&client_options,
  16644. use_ssl,
  16645. error_buffer,
  16646. error_buffer_size,
  16647. path,
  16648. origin,
  16649. extensions,
  16650. data_func,
  16651. close_func,
  16652. user_data);
  16653. }
  16654. CIVETWEB_API struct mg_connection *
  16655. mg_connect_websocket_client_secure_extensions(
  16656. const struct mg_client_options *client_options,
  16657. char *error_buffer,
  16658. size_t error_buffer_size,
  16659. const char *path,
  16660. const char *origin,
  16661. const char *extensions,
  16662. mg_websocket_data_handler data_func,
  16663. mg_websocket_close_handler close_func,
  16664. void *user_data)
  16665. {
  16666. if (!client_options) {
  16667. return NULL;
  16668. }
  16669. return mg_connect_websocket_client_impl(client_options,
  16670. 1,
  16671. error_buffer,
  16672. error_buffer_size,
  16673. path,
  16674. origin,
  16675. extensions,
  16676. data_func,
  16677. close_func,
  16678. user_data);
  16679. }
  16680. /* Prepare connection data structure */
  16681. static void
  16682. init_connection(struct mg_connection *conn)
  16683. {
  16684. /* Is keep alive allowed by the server */
  16685. int keep_alive_enabled =
  16686. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16687. if (!keep_alive_enabled) {
  16688. conn->must_close = 1;
  16689. }
  16690. /* Important: on new connection, reset the receiving buffer. Credit
  16691. * goes to crule42. */
  16692. conn->data_len = 0;
  16693. conn->handled_requests = 0;
  16694. conn->connection_type = CONNECTION_TYPE_INVALID;
  16695. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  16696. mg_set_user_connection_data(conn, NULL);
  16697. #if defined(USE_SERVER_STATS)
  16698. conn->conn_state = 2; /* init */
  16699. #endif
  16700. /* call the init_connection callback if assigned */
  16701. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16702. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16703. void *conn_data = NULL;
  16704. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16705. mg_set_user_connection_data(conn, conn_data);
  16706. }
  16707. }
  16708. }
  16709. /* Process a connection - may handle multiple requests
  16710. * using the same connection.
  16711. * Must be called with a valid connection (conn and
  16712. * conn->phys_ctx must be valid).
  16713. */
  16714. static void
  16715. process_new_connection(struct mg_connection *conn)
  16716. {
  16717. struct mg_request_info *ri = &conn->request_info;
  16718. int keep_alive, discard_len;
  16719. char ebuf[100];
  16720. const char *hostend;
  16721. int reqerr, uri_type;
  16722. #if defined(USE_SERVER_STATS)
  16723. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16724. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16725. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16726. #endif
  16727. DEBUG_TRACE("Start processing connection from %s",
  16728. conn->request_info.remote_addr);
  16729. /* Loop over multiple requests sent using the same connection
  16730. * (while "keep alive"). */
  16731. do {
  16732. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16733. conn->handled_requests + 1);
  16734. #if defined(USE_SERVER_STATS)
  16735. conn->conn_state = 3; /* ready */
  16736. #endif
  16737. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16738. /* The request sent by the client could not be understood by
  16739. * the server, or it was incomplete or a timeout. Send an
  16740. * error message and close the connection. */
  16741. if (reqerr > 0) {
  16742. DEBUG_ASSERT(ebuf[0] != '\0');
  16743. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16744. }
  16745. } else if (strcmp(ri->http_version, "1.0")
  16746. && strcmp(ri->http_version, "1.1")) {
  16747. /* HTTP/2 is not allowed here */
  16748. mg_snprintf(conn,
  16749. NULL, /* No truncation check for ebuf */
  16750. ebuf,
  16751. sizeof(ebuf),
  16752. "Bad HTTP version: [%s]",
  16753. ri->http_version);
  16754. mg_send_http_error(conn, 505, "%s", ebuf);
  16755. }
  16756. if (ebuf[0] == '\0') {
  16757. uri_type = get_uri_type(conn->request_info.request_uri);
  16758. switch (uri_type) {
  16759. case 1:
  16760. /* Asterisk */
  16761. conn->request_info.local_uri_raw = 0;
  16762. /* TODO: Deal with '*'. */
  16763. break;
  16764. case 2:
  16765. /* relative uri */
  16766. conn->request_info.local_uri_raw =
  16767. conn->request_info.request_uri;
  16768. break;
  16769. case 3:
  16770. case 4:
  16771. /* absolute uri (with/without port) */
  16772. hostend = get_rel_url_at_current_server(
  16773. conn->request_info.request_uri, conn);
  16774. if (hostend) {
  16775. conn->request_info.local_uri_raw = hostend;
  16776. } else {
  16777. conn->request_info.local_uri_raw = NULL;
  16778. }
  16779. break;
  16780. default:
  16781. mg_snprintf(conn,
  16782. NULL, /* No truncation check for ebuf */
  16783. ebuf,
  16784. sizeof(ebuf),
  16785. "Invalid URI");
  16786. mg_send_http_error(conn, 400, "%s", ebuf);
  16787. conn->request_info.local_uri_raw = NULL;
  16788. break;
  16789. }
  16790. conn->request_info.local_uri =
  16791. (char *)conn->request_info.local_uri_raw;
  16792. }
  16793. if (ebuf[0] != '\0') {
  16794. conn->protocol_type = -1;
  16795. } else {
  16796. /* HTTP/1 allows protocol upgrade */
  16797. conn->protocol_type = should_switch_to_protocol(conn);
  16798. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16799. /* This will occur, if a HTTP/1.1 request should be upgraded
  16800. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16801. * Since most (all?) major browsers only support HTTP/2 using
  16802. * ALPN, this is hard to test and very low priority.
  16803. * Deactivate it (at least for now).
  16804. */
  16805. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16806. }
  16807. }
  16808. DEBUG_TRACE("http: %s, error: %s",
  16809. (ri->http_version ? ri->http_version : "none"),
  16810. (ebuf[0] ? ebuf : "none"));
  16811. if (ebuf[0] == '\0') {
  16812. if (conn->request_info.local_uri) {
  16813. /* handle request to local server */
  16814. handle_request_stat_log(conn);
  16815. } else {
  16816. /* TODO: handle non-local request (PROXY) */
  16817. conn->must_close = 1;
  16818. }
  16819. } else {
  16820. conn->must_close = 1;
  16821. }
  16822. /* Response complete. Free header buffer */
  16823. free_buffered_response_header_list(conn);
  16824. if (ri->remote_user != NULL) {
  16825. mg_free((void *)ri->remote_user);
  16826. /* Important! When having connections with and without auth
  16827. * would cause double free and then crash */
  16828. ri->remote_user = NULL;
  16829. }
  16830. /* NOTE(lsm): order is important here. should_keep_alive() call
  16831. * is using parsed request, which will be invalid after
  16832. * memmove's below.
  16833. * Therefore, memorize should_keep_alive() result now for later
  16834. * use in loop exit condition. */
  16835. /* Enable it only if this request is completely discardable. */
  16836. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16837. && should_keep_alive(conn) && (conn->content_len >= 0)
  16838. && (conn->request_len > 0)
  16839. && ((conn->is_chunked == 4)
  16840. || (!conn->is_chunked
  16841. && ((conn->consumed_content == conn->content_len)
  16842. || ((conn->request_len + conn->content_len)
  16843. <= conn->data_len))))
  16844. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16845. if (keep_alive) {
  16846. /* Discard all buffered data for this request */
  16847. discard_len =
  16848. ((conn->request_len + conn->content_len) < conn->data_len)
  16849. ? (int)(conn->request_len + conn->content_len)
  16850. : conn->data_len;
  16851. conn->data_len -= discard_len;
  16852. if (conn->data_len > 0) {
  16853. DEBUG_TRACE("discard_len = %d", discard_len);
  16854. memmove(conn->buf,
  16855. conn->buf + discard_len,
  16856. (size_t)conn->data_len);
  16857. }
  16858. }
  16859. DEBUG_ASSERT(conn->data_len >= 0);
  16860. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16861. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16862. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16863. (long int)conn->data_len,
  16864. (long int)conn->buf_size);
  16865. break;
  16866. }
  16867. conn->handled_requests++;
  16868. } while (keep_alive);
  16869. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16870. conn->request_info.remote_addr,
  16871. difftime(time(NULL), conn->conn_birth_time));
  16872. close_connection(conn);
  16873. #if defined(USE_SERVER_STATS)
  16874. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16875. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16876. #endif
  16877. }
  16878. #if defined(ALTERNATIVE_QUEUE)
  16879. static void
  16880. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16881. {
  16882. unsigned int i;
  16883. while (!ctx->stop_flag) {
  16884. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16885. /* find a free worker slot and signal it */
  16886. if (ctx->client_socks[i].in_use == 2) {
  16887. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16888. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16889. ctx->client_socks[i] = *sp;
  16890. ctx->client_socks[i].in_use = 1;
  16891. /* socket has been moved to the consumer */
  16892. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16893. (void)event_signal(ctx->client_wait_events[i]);
  16894. return;
  16895. }
  16896. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16897. }
  16898. }
  16899. /* queue is full */
  16900. mg_sleep(1);
  16901. }
  16902. /* must consume */
  16903. set_blocking_mode(sp->sock);
  16904. closesocket(sp->sock);
  16905. }
  16906. static int
  16907. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16908. {
  16909. DEBUG_TRACE("%s", "going idle");
  16910. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16911. ctx->client_socks[thread_index].in_use = 2;
  16912. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16913. event_wait(ctx->client_wait_events[thread_index]);
  16914. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16915. *sp = ctx->client_socks[thread_index];
  16916. if (ctx->stop_flag) {
  16917. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16918. if (sp->in_use == 1) {
  16919. /* must consume */
  16920. set_blocking_mode(sp->sock);
  16921. closesocket(sp->sock);
  16922. }
  16923. return 0;
  16924. }
  16925. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16926. if (sp->in_use == 1) {
  16927. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16928. return 1;
  16929. }
  16930. /* must not reach here */
  16931. DEBUG_ASSERT(0);
  16932. return 0;
  16933. }
  16934. #else /* ALTERNATIVE_QUEUE */
  16935. /* Worker threads take accepted socket from the queue */
  16936. static int
  16937. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16938. {
  16939. (void)thread_index;
  16940. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16941. DEBUG_TRACE("%s", "going idle");
  16942. /* If the queue is empty, wait. We're idle at this point. */
  16943. while ((ctx->sq_head == ctx->sq_tail)
  16944. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16945. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16946. }
  16947. /* If we're stopping, sq_head may be equal to sq_tail. */
  16948. if (ctx->sq_head > ctx->sq_tail) {
  16949. /* Copy socket from the queue and increment tail */
  16950. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16951. ctx->sq_tail++;
  16952. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16953. /* Wrap pointers if needed */
  16954. while (ctx->sq_tail > ctx->sq_size) {
  16955. ctx->sq_tail -= ctx->sq_size;
  16956. ctx->sq_head -= ctx->sq_size;
  16957. }
  16958. }
  16959. (void)pthread_cond_signal(&ctx->sq_empty);
  16960. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16961. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16962. }
  16963. /* Master thread adds accepted socket to a queue */
  16964. static void
  16965. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16966. {
  16967. int queue_filled;
  16968. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16969. queue_filled = ctx->sq_head - ctx->sq_tail;
  16970. /* If the queue is full, wait */
  16971. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16972. && (queue_filled >= ctx->sq_size)) {
  16973. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16974. #if defined(USE_SERVER_STATS)
  16975. if (queue_filled > ctx->sq_max_fill) {
  16976. ctx->sq_max_fill = queue_filled;
  16977. }
  16978. #endif
  16979. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16980. ctx->sq_blocked = 0; /* Not blocked now */
  16981. queue_filled = ctx->sq_head - ctx->sq_tail;
  16982. }
  16983. if (queue_filled < ctx->sq_size) {
  16984. /* Copy socket to the queue and increment head */
  16985. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16986. ctx->sq_head++;
  16987. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16988. }
  16989. queue_filled = ctx->sq_head - ctx->sq_tail;
  16990. #if defined(USE_SERVER_STATS)
  16991. if (queue_filled > ctx->sq_max_fill) {
  16992. ctx->sq_max_fill = queue_filled;
  16993. }
  16994. #endif
  16995. (void)pthread_cond_signal(&ctx->sq_full);
  16996. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16997. }
  16998. #endif /* ALTERNATIVE_QUEUE */
  16999. static void
  17000. worker_thread_run(struct mg_connection *conn)
  17001. {
  17002. struct mg_context *ctx = conn->phys_ctx;
  17003. int thread_index;
  17004. struct mg_workerTLS tls;
  17005. mg_set_thread_name("worker");
  17006. tls.is_master = 0;
  17007. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17008. #if defined(_WIN32)
  17009. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17010. #endif
  17011. /* Initialize thread local storage before calling any callback */
  17012. pthread_setspecific(sTlsKey, &tls);
  17013. /* Check if there is a user callback */
  17014. if (ctx->callbacks.init_thread) {
  17015. /* call init_thread for a worker thread (type 1), and store the
  17016. * return value */
  17017. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17018. } else {
  17019. /* No callback: set user pointer to NULL */
  17020. tls.user_ptr = NULL;
  17021. }
  17022. /* Connection structure has been pre-allocated */
  17023. thread_index = (int)(conn - ctx->worker_connections);
  17024. if ((thread_index < 0)
  17025. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  17026. mg_cry_ctx_internal(ctx,
  17027. "Internal error: Invalid worker index %i",
  17028. thread_index);
  17029. return;
  17030. }
  17031. /* Request buffers are not pre-allocated. They are private to the
  17032. * request and do not contain any state information that might be
  17033. * of interest to anyone observing a server status. */
  17034. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17035. if (conn->buf == NULL) {
  17036. mg_cry_ctx_internal(
  17037. ctx,
  17038. "Out of memory: Cannot allocate buffer for worker %i",
  17039. thread_index);
  17040. return;
  17041. }
  17042. conn->buf_size = (int)ctx->max_request_size;
  17043. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17044. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17045. conn->request_info.user_data = ctx->user_data;
  17046. /* Allocate a mutex for this connection to allow communication both
  17047. * within the request handler and from elsewhere in the application
  17048. */
  17049. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17050. mg_free(conn->buf);
  17051. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17052. return;
  17053. }
  17054. #if defined(USE_SERVER_STATS)
  17055. conn->conn_state = 1; /* not consumed */
  17056. #endif
  17057. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17058. * signal sq_empty condvar to wake up the master waiting in
  17059. * produce_socket() */
  17060. while (consume_socket(ctx, &conn->client, thread_index)) {
  17061. /* New connections must start with new protocol negotiation */
  17062. tls.alpn_proto = NULL;
  17063. #if defined(USE_SERVER_STATS)
  17064. conn->conn_close_time = 0;
  17065. #endif
  17066. conn->conn_birth_time = time(NULL);
  17067. /* Fill in IP, port info early so even if SSL setup below fails,
  17068. * error handler would have the corresponding info.
  17069. * Thanks to Johannes Winkelmann for the patch.
  17070. */
  17071. conn->request_info.remote_port =
  17072. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17073. conn->request_info.server_port =
  17074. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17075. sockaddr_to_string(conn->request_info.remote_addr,
  17076. sizeof(conn->request_info.remote_addr),
  17077. &conn->client.rsa);
  17078. DEBUG_TRACE("Incoming %sconnection from %s",
  17079. (conn->client.is_ssl ? "SSL " : ""),
  17080. conn->request_info.remote_addr);
  17081. conn->request_info.is_ssl = conn->client.is_ssl;
  17082. if (conn->client.is_ssl) {
  17083. #if defined(USE_MBEDTLS)
  17084. /* HTTPS connection */
  17085. if (mbed_ssl_accept(&(conn->ssl),
  17086. conn->dom_ctx->ssl_ctx,
  17087. (int *)&(conn->client.sock),
  17088. conn->phys_ctx)
  17089. == 0) {
  17090. /* conn->dom_ctx is set in get_request */
  17091. /* process HTTPS connection */
  17092. init_connection(conn);
  17093. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17094. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17095. process_new_connection(conn);
  17096. } else {
  17097. /* make sure the connection is cleaned up on SSL failure */
  17098. close_connection(conn);
  17099. }
  17100. #elif !defined(NO_SSL)
  17101. /* HTTPS connection */
  17102. if (sslize(conn, SSL_accept, NULL)) {
  17103. /* conn->dom_ctx is set in get_request */
  17104. /* Get SSL client certificate information (if set) */
  17105. struct mg_client_cert client_cert;
  17106. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17107. conn->request_info.client_cert = &client_cert;
  17108. }
  17109. /* process HTTPS connection */
  17110. #if defined(USE_HTTP2)
  17111. if ((tls.alpn_proto != NULL)
  17112. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17113. /* process HTTPS/2 connection */
  17114. init_connection(conn);
  17115. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17116. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17117. conn->content_len =
  17118. -1; /* content length is not predefined */
  17119. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17120. process_new_http2_connection(conn);
  17121. } else
  17122. #endif
  17123. {
  17124. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17125. init_connection(conn);
  17126. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17127. /* Start with HTTP, WS will be an "upgrade" request later */
  17128. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17129. process_new_connection(conn);
  17130. }
  17131. /* Free client certificate info */
  17132. if (conn->request_info.client_cert) {
  17133. mg_free((void *)(conn->request_info.client_cert->subject));
  17134. mg_free((void *)(conn->request_info.client_cert->issuer));
  17135. mg_free((void *)(conn->request_info.client_cert->serial));
  17136. mg_free((void *)(conn->request_info.client_cert->finger));
  17137. /* Free certificate memory */
  17138. X509_free(
  17139. (X509 *)conn->request_info.client_cert->peer_cert);
  17140. conn->request_info.client_cert->peer_cert = 0;
  17141. conn->request_info.client_cert->subject = 0;
  17142. conn->request_info.client_cert->issuer = 0;
  17143. conn->request_info.client_cert->serial = 0;
  17144. conn->request_info.client_cert->finger = 0;
  17145. conn->request_info.client_cert = 0;
  17146. }
  17147. } else {
  17148. /* make sure the connection is cleaned up on SSL failure */
  17149. close_connection(conn);
  17150. }
  17151. #endif
  17152. } else {
  17153. /* process HTTP connection */
  17154. init_connection(conn);
  17155. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17156. /* Start with HTTP, WS will be an "upgrade" request later */
  17157. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17158. process_new_connection(conn);
  17159. }
  17160. DEBUG_TRACE("%s", "Connection closed");
  17161. #if defined(USE_SERVER_STATS)
  17162. conn->conn_close_time = time(NULL);
  17163. #endif
  17164. }
  17165. /* Call exit thread user callback */
  17166. if (ctx->callbacks.exit_thread) {
  17167. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17168. }
  17169. /* delete thread local storage objects */
  17170. pthread_setspecific(sTlsKey, NULL);
  17171. #if defined(_WIN32)
  17172. CloseHandle(tls.pthread_cond_helper_mutex);
  17173. #endif
  17174. pthread_mutex_destroy(&conn->mutex);
  17175. /* Free the request buffer. */
  17176. conn->buf_size = 0;
  17177. mg_free(conn->buf);
  17178. conn->buf = NULL;
  17179. /* Free cleaned URI (if any) */
  17180. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17181. mg_free((void *)conn->request_info.local_uri);
  17182. conn->request_info.local_uri = NULL;
  17183. }
  17184. #if defined(USE_SERVER_STATS)
  17185. conn->conn_state = 9; /* done */
  17186. #endif
  17187. DEBUG_TRACE("%s", "exiting");
  17188. }
  17189. /* Threads have different return types on Windows and Unix. */
  17190. #if defined(_WIN32)
  17191. static unsigned __stdcall worker_thread(void *thread_func_param)
  17192. {
  17193. worker_thread_run((struct mg_connection *)thread_func_param);
  17194. return 0;
  17195. }
  17196. #else
  17197. static void *
  17198. worker_thread(void *thread_func_param)
  17199. {
  17200. #if !defined(__ZEPHYR__)
  17201. struct sigaction sa;
  17202. /* Ignore SIGPIPE */
  17203. memset(&sa, 0, sizeof(sa));
  17204. sa.sa_handler = SIG_IGN;
  17205. sigaction(SIGPIPE, &sa, NULL);
  17206. #endif
  17207. worker_thread_run((struct mg_connection *)thread_func_param);
  17208. return NULL;
  17209. }
  17210. #endif /* _WIN32 */
  17211. /* This is an internal function, thus all arguments are expected to be
  17212. * valid - a NULL check is not required. */
  17213. static void
  17214. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17215. {
  17216. struct socket so;
  17217. char src_addr[IP_ADDR_STR_LEN];
  17218. socklen_t len = sizeof(so.rsa);
  17219. #if !defined(__ZEPHYR__)
  17220. int on = 1;
  17221. #endif
  17222. memset(&so, 0, sizeof(so));
  17223. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17224. == INVALID_SOCKET) {
  17225. } else if (check_acl(ctx, &so.rsa) != 1) {
  17226. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17227. mg_cry_ctx_internal(ctx,
  17228. "%s: %s is not allowed to connect",
  17229. __func__,
  17230. src_addr);
  17231. closesocket(so.sock);
  17232. } else {
  17233. /* Put so socket structure into the queue */
  17234. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17235. set_close_on_exec(so.sock, NULL, ctx);
  17236. so.is_ssl = listener->is_ssl;
  17237. so.ssl_redir = listener->ssl_redir;
  17238. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17239. mg_cry_ctx_internal(ctx,
  17240. "%s: getsockname() failed: %s",
  17241. __func__,
  17242. strerror(ERRNO));
  17243. }
  17244. #if !defined(__ZEPHYR__)
  17245. if ((so.lsa.sa.sa_family == AF_INET)
  17246. || (so.lsa.sa.sa_family == AF_INET6)) {
  17247. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17248. * This is needed because if HTTP-level keep-alive
  17249. * is enabled, and client resets the connection, server won't get
  17250. * TCP FIN or RST and will keep the connection open forever. With
  17251. * TCP keep-alive, next keep-alive handshake will figure out that
  17252. * the client is down and will close the server end.
  17253. * Thanks to Igor Klopov who suggested the patch. */
  17254. if (setsockopt(so.sock,
  17255. SOL_SOCKET,
  17256. SO_KEEPALIVE,
  17257. (SOCK_OPT_TYPE)&on,
  17258. sizeof(on))
  17259. != 0) {
  17260. mg_cry_ctx_internal(
  17261. ctx,
  17262. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17263. __func__,
  17264. strerror(ERRNO));
  17265. }
  17266. }
  17267. #endif
  17268. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17269. * to effectively fill up the underlying IP packet payload and
  17270. * reduce the overhead of sending lots of small buffers. However
  17271. * this hurts the server's throughput (ie. operations per second)
  17272. * when HTTP 1.1 persistent connections are used and the responses
  17273. * are relatively small (eg. less than 1400 bytes).
  17274. */
  17275. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17276. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17277. if (set_tcp_nodelay(&so, 1) != 0) {
  17278. mg_cry_ctx_internal(
  17279. ctx,
  17280. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17281. __func__,
  17282. strerror(ERRNO));
  17283. }
  17284. }
  17285. /* The "non blocking" property should already be
  17286. * inherited from the parent socket. Set it for
  17287. * non-compliant socket implementations. */
  17288. set_non_blocking_mode(so.sock);
  17289. so.in_use = 0;
  17290. produce_socket(ctx, &so);
  17291. }
  17292. }
  17293. static void
  17294. master_thread_run(struct mg_context *ctx)
  17295. {
  17296. struct mg_workerTLS tls;
  17297. struct mg_pollfd *pfd;
  17298. unsigned int i;
  17299. unsigned int workerthreadcount;
  17300. if (!ctx) {
  17301. return;
  17302. }
  17303. mg_set_thread_name("master");
  17304. /* Increase priority of the master thread */
  17305. #if defined(_WIN32)
  17306. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17307. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17308. int min_prio = sched_get_priority_min(SCHED_RR);
  17309. int max_prio = sched_get_priority_max(SCHED_RR);
  17310. if ((min_prio >= 0) && (max_prio >= 0)
  17311. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17312. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17313. struct sched_param sched_param = {0};
  17314. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17315. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17316. }
  17317. #endif
  17318. /* Initialize thread local storage */
  17319. #if defined(_WIN32)
  17320. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17321. #endif
  17322. tls.is_master = 1;
  17323. pthread_setspecific(sTlsKey, &tls);
  17324. if (ctx->callbacks.init_thread) {
  17325. /* Callback for the master thread (type 0) */
  17326. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17327. } else {
  17328. tls.user_ptr = NULL;
  17329. }
  17330. /* Lua background script "start" event */
  17331. #if defined(USE_LUA)
  17332. if (ctx->lua_background_state) {
  17333. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17334. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17335. /* call "start()" in Lua */
  17336. lua_getglobal(lstate, "start");
  17337. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17338. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17339. if (ret != 0) {
  17340. struct mg_connection fc;
  17341. lua_cry(fake_connection(&fc, ctx),
  17342. ret,
  17343. lstate,
  17344. "lua_background_script",
  17345. "start");
  17346. }
  17347. } else {
  17348. lua_pop(lstate, 1);
  17349. }
  17350. /* determine if there is a "log()" function in Lua background script */
  17351. lua_getglobal(lstate, "log");
  17352. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17353. ctx->lua_bg_log_available = 1;
  17354. }
  17355. lua_pop(lstate, 1);
  17356. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17357. }
  17358. #endif
  17359. /* Server starts *now* */
  17360. ctx->start_time = time(NULL);
  17361. /* Server accept loop */
  17362. pfd = ctx->listening_socket_fds;
  17363. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17364. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17365. pfd[i].fd = ctx->listening_sockets[i].sock;
  17366. pfd[i].events = POLLIN;
  17367. }
  17368. if (mg_poll(pfd,
  17369. ctx->num_listening_sockets,
  17370. SOCKET_TIMEOUT_QUANTUM,
  17371. &(ctx->stop_flag))
  17372. > 0) {
  17373. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17374. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17375. * successful poll, and POLLIN is defined as
  17376. * (POLLRDNORM | POLLRDBAND)
  17377. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17378. * pfd[i].revents == POLLIN. */
  17379. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17380. && (pfd[i].revents & POLLIN)) {
  17381. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17382. }
  17383. }
  17384. }
  17385. }
  17386. /* Here stop_flag is 1 - Initiate shutdown. */
  17387. DEBUG_TRACE("%s", "stopping workers");
  17388. /* Stop signal received: somebody called mg_stop. Quit. */
  17389. close_all_listening_sockets(ctx);
  17390. /* Wakeup workers that are waiting for connections to handle. */
  17391. #if defined(ALTERNATIVE_QUEUE)
  17392. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17393. event_signal(ctx->client_wait_events[i]);
  17394. }
  17395. #else
  17396. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17397. pthread_cond_broadcast(&ctx->sq_full);
  17398. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17399. #endif
  17400. /* Join all worker threads to avoid leaking threads. */
  17401. workerthreadcount = ctx->cfg_worker_threads;
  17402. for (i = 0; i < workerthreadcount; i++) {
  17403. if (ctx->worker_threadids[i] != 0) {
  17404. mg_join_thread(ctx->worker_threadids[i]);
  17405. }
  17406. }
  17407. #if defined(USE_LUA)
  17408. /* Free Lua state of lua background task */
  17409. if (ctx->lua_background_state) {
  17410. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17411. ctx->lua_bg_log_available = 0;
  17412. /* call "stop()" in Lua */
  17413. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17414. lua_getglobal(lstate, "stop");
  17415. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17416. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17417. if (ret != 0) {
  17418. struct mg_connection fc;
  17419. lua_cry(fake_connection(&fc, ctx),
  17420. ret,
  17421. lstate,
  17422. "lua_background_script",
  17423. "stop");
  17424. }
  17425. }
  17426. lua_close(lstate);
  17427. ctx->lua_background_state = 0;
  17428. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17429. }
  17430. #endif
  17431. DEBUG_TRACE("%s", "exiting");
  17432. /* call exit thread callback */
  17433. if (ctx->callbacks.exit_thread) {
  17434. /* Callback for the master thread (type 0) */
  17435. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17436. }
  17437. #if defined(_WIN32)
  17438. CloseHandle(tls.pthread_cond_helper_mutex);
  17439. #endif
  17440. pthread_setspecific(sTlsKey, NULL);
  17441. /* Signal mg_stop() that we're done.
  17442. * WARNING: This must be the very last thing this
  17443. * thread does, as ctx becomes invalid after this line. */
  17444. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17445. }
  17446. /* Threads have different return types on Windows and Unix. */
  17447. #if defined(_WIN32)
  17448. static unsigned __stdcall master_thread(void *thread_func_param)
  17449. {
  17450. master_thread_run((struct mg_context *)thread_func_param);
  17451. return 0;
  17452. }
  17453. #else
  17454. static void *
  17455. master_thread(void *thread_func_param)
  17456. {
  17457. #if !defined(__ZEPHYR__)
  17458. struct sigaction sa;
  17459. /* Ignore SIGPIPE */
  17460. memset(&sa, 0, sizeof(sa));
  17461. sa.sa_handler = SIG_IGN;
  17462. sigaction(SIGPIPE, &sa, NULL);
  17463. #endif
  17464. master_thread_run((struct mg_context *)thread_func_param);
  17465. return NULL;
  17466. }
  17467. #endif /* _WIN32 */
  17468. static void
  17469. free_context(struct mg_context *ctx)
  17470. {
  17471. int i;
  17472. struct mg_handler_info *tmp_rh;
  17473. if (ctx == NULL) {
  17474. return;
  17475. }
  17476. /* Call user callback */
  17477. if (ctx->callbacks.exit_context) {
  17478. ctx->callbacks.exit_context(ctx);
  17479. }
  17480. /* All threads exited, no sync is needed. Destroy thread mutex and
  17481. * condvars
  17482. */
  17483. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17484. #if defined(ALTERNATIVE_QUEUE)
  17485. mg_free(ctx->client_socks);
  17486. if (ctx->client_wait_events != NULL) {
  17487. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17488. event_destroy(ctx->client_wait_events[i]);
  17489. }
  17490. mg_free(ctx->client_wait_events);
  17491. }
  17492. #else
  17493. (void)pthread_cond_destroy(&ctx->sq_empty);
  17494. (void)pthread_cond_destroy(&ctx->sq_full);
  17495. mg_free(ctx->squeue);
  17496. #endif
  17497. /* Destroy other context global data structures mutex */
  17498. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17499. #if defined(USE_LUA)
  17500. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17501. #endif
  17502. /* Deallocate config parameters */
  17503. for (i = 0; i < NUM_OPTIONS; i++) {
  17504. if (ctx->dd.config[i] != NULL) {
  17505. #if defined(_MSC_VER)
  17506. #pragma warning(suppress : 6001)
  17507. #endif
  17508. mg_free(ctx->dd.config[i]);
  17509. }
  17510. }
  17511. /* Deallocate request handlers */
  17512. while (ctx->dd.handlers) {
  17513. tmp_rh = ctx->dd.handlers;
  17514. ctx->dd.handlers = tmp_rh->next;
  17515. mg_free(tmp_rh->uri);
  17516. mg_free(tmp_rh);
  17517. }
  17518. #if defined(USE_MBEDTLS)
  17519. if (ctx->dd.ssl_ctx != NULL) {
  17520. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17521. mg_free(ctx->dd.ssl_ctx);
  17522. ctx->dd.ssl_ctx = NULL;
  17523. }
  17524. #elif !defined(NO_SSL)
  17525. /* Deallocate SSL context */
  17526. if (ctx->dd.ssl_ctx != NULL) {
  17527. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17528. int callback_ret =
  17529. (ctx->callbacks.external_ssl_ctx == NULL)
  17530. ? 0
  17531. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17532. if (callback_ret == 0) {
  17533. SSL_CTX_free(ctx->dd.ssl_ctx);
  17534. }
  17535. /* else: ignore error and omit SSL_CTX_free in case
  17536. * callback_ret is 1 */
  17537. }
  17538. #endif /* !NO_SSL */
  17539. /* Deallocate worker thread ID array */
  17540. mg_free(ctx->worker_threadids);
  17541. /* Deallocate worker thread ID array */
  17542. mg_free(ctx->worker_connections);
  17543. /* deallocate system name string */
  17544. mg_free(ctx->systemName);
  17545. /* Deallocate context itself */
  17546. mg_free(ctx);
  17547. }
  17548. CIVETWEB_API void
  17549. mg_stop(struct mg_context *ctx)
  17550. {
  17551. pthread_t mt;
  17552. if (!ctx) {
  17553. return;
  17554. }
  17555. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17556. * two threads is not allowed. */
  17557. mt = ctx->masterthreadid;
  17558. if (mt == 0) {
  17559. return;
  17560. }
  17561. ctx->masterthreadid = 0;
  17562. /* Set stop flag, so all threads know they have to exit. */
  17563. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17564. /* Join timer thread */
  17565. #if defined(USE_TIMERS)
  17566. timers_exit(ctx);
  17567. #endif
  17568. /* Wait until everything has stopped. */
  17569. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17570. (void)mg_sleep(10);
  17571. }
  17572. /* Wait to stop master thread */
  17573. mg_join_thread(mt);
  17574. /* Close remaining Lua states */
  17575. #if defined(USE_LUA)
  17576. lua_ctx_exit(ctx);
  17577. #endif
  17578. /* Free memory */
  17579. free_context(ctx);
  17580. }
  17581. static void
  17582. get_system_name(char **sysName)
  17583. {
  17584. #if defined(_WIN32)
  17585. char name[128];
  17586. DWORD dwVersion = 0;
  17587. DWORD dwMajorVersion = 0;
  17588. DWORD dwMinorVersion = 0;
  17589. DWORD dwBuild = 0;
  17590. BOOL wowRet, isWoW = FALSE;
  17591. #if defined(_MSC_VER)
  17592. #pragma warning(push)
  17593. /* GetVersion was declared deprecated */
  17594. #pragma warning(disable : 4996)
  17595. #endif
  17596. dwVersion = GetVersion();
  17597. #if defined(_MSC_VER)
  17598. #pragma warning(pop)
  17599. #endif
  17600. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17601. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17602. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17603. (void)dwBuild;
  17604. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17605. sprintf(name,
  17606. "Windows %u.%u%s",
  17607. (unsigned)dwMajorVersion,
  17608. (unsigned)dwMinorVersion,
  17609. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17610. *sysName = mg_strdup(name);
  17611. #elif defined(__ZEPHYR__)
  17612. *sysName = mg_strdup("Zephyr OS");
  17613. #else
  17614. struct utsname name;
  17615. memset(&name, 0, sizeof(name));
  17616. uname(&name);
  17617. *sysName = mg_strdup(name.sysname);
  17618. #endif
  17619. }
  17620. static void
  17621. legacy_init(const char **options)
  17622. {
  17623. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17624. if (options) {
  17625. const char **run_options = options;
  17626. const char *optname = config_options[LISTENING_PORTS].name;
  17627. /* Try to find the "listening_ports" option */
  17628. while (*run_options) {
  17629. if (!strcmp(*run_options, optname)) {
  17630. ports_option = run_options[1];
  17631. }
  17632. run_options += 2;
  17633. }
  17634. }
  17635. if (is_ssl_port_used(ports_option)) {
  17636. /* Initialize with SSL support */
  17637. mg_init_library(MG_FEATURES_TLS);
  17638. } else {
  17639. /* Initialize without SSL support */
  17640. mg_init_library(MG_FEATURES_DEFAULT);
  17641. }
  17642. }
  17643. CIVETWEB_API struct mg_context *
  17644. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17645. {
  17646. struct mg_context *ctx;
  17647. const char *name, *value, *default_value;
  17648. int idx, ok, workerthreadcount;
  17649. unsigned int i;
  17650. int itmp;
  17651. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17652. const char **options =
  17653. ((init != NULL) ? (init->configuration_options) : (NULL));
  17654. struct mg_workerTLS tls;
  17655. if (error != NULL) {
  17656. error->code = MG_ERROR_DATA_CODE_OK;
  17657. error->code_sub = 0;
  17658. if (error->text_buffer_size > 0) {
  17659. *error->text = 0;
  17660. }
  17661. }
  17662. if (mg_init_library_called == 0) {
  17663. /* Legacy INIT, if mg_start is called without mg_init_library.
  17664. * Note: This will cause a memory leak when unloading the library.
  17665. */
  17666. legacy_init(options);
  17667. }
  17668. if (mg_init_library_called == 0) {
  17669. if (error != NULL) {
  17670. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  17671. mg_snprintf(NULL,
  17672. NULL, /* No truncation check for error buffers */
  17673. error->text,
  17674. error->text_buffer_size,
  17675. "%s",
  17676. "Library uninitialized");
  17677. }
  17678. return NULL;
  17679. }
  17680. /* Allocate context and initialize reasonable general case defaults. */
  17681. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  17682. if (ctx == NULL) {
  17683. if (error != NULL) {
  17684. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17685. error->code_sub = (unsigned)sizeof(*ctx);
  17686. mg_snprintf(NULL,
  17687. NULL, /* No truncation check for error buffers */
  17688. error->text,
  17689. error->text_buffer_size,
  17690. "%s",
  17691. "Out of memory");
  17692. }
  17693. return NULL;
  17694. }
  17695. /* Random number generator will initialize at the first call */
  17696. ctx->dd.auth_nonce_mask =
  17697. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17698. /* Save started thread index to reuse in other external API calls
  17699. * For the sake of thread synchronization all non-civetweb threads
  17700. * can be considered as single external thread */
  17701. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17702. tls.is_master = -1; /* Thread calling mg_start */
  17703. tls.thread_idx = ctx->starter_thread_idx;
  17704. #if defined(_WIN32)
  17705. tls.pthread_cond_helper_mutex = NULL;
  17706. #endif
  17707. pthread_setspecific(sTlsKey, &tls);
  17708. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17709. #if !defined(ALTERNATIVE_QUEUE)
  17710. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17711. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17712. ctx->sq_blocked = 0;
  17713. #endif
  17714. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17715. #if defined(USE_LUA)
  17716. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17717. #endif
  17718. if (!ok) {
  17719. unsigned error_id = (unsigned)ERRNO;
  17720. const char *err_msg =
  17721. "Cannot initialize thread synchronization objects";
  17722. /* Fatal error - abort start. However, this situation should never
  17723. * occur in practice. */
  17724. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17725. if (error != NULL) {
  17726. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  17727. error->code_sub = error_id;
  17728. mg_snprintf(NULL,
  17729. NULL, /* No truncation check for error buffers */
  17730. error->text,
  17731. error->text_buffer_size,
  17732. "%s",
  17733. err_msg);
  17734. }
  17735. mg_free(ctx);
  17736. pthread_setspecific(sTlsKey, NULL);
  17737. return NULL;
  17738. }
  17739. if ((init != NULL) && (init->callbacks != NULL)) {
  17740. /* Set all callbacks except exit_context. */
  17741. ctx->callbacks = *init->callbacks;
  17742. exit_callback = init->callbacks->exit_context;
  17743. /* The exit callback is activated once the context is successfully
  17744. * created. It should not be called, if an incomplete context object
  17745. * is deleted during a failed initialization. */
  17746. ctx->callbacks.exit_context = 0;
  17747. }
  17748. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17749. ctx->dd.handlers = NULL;
  17750. ctx->dd.next = NULL;
  17751. #if defined(USE_LUA)
  17752. lua_ctx_init(ctx);
  17753. #endif
  17754. /* Store options */
  17755. while (options && (name = *options++) != NULL) {
  17756. idx = get_option_index(name);
  17757. if (idx == -1) {
  17758. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17759. if (error != NULL) {
  17760. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17761. error->code_sub = (unsigned)-1;
  17762. mg_snprintf(NULL,
  17763. NULL, /* No truncation check for error buffers */
  17764. error->text,
  17765. error->text_buffer_size,
  17766. "Invalid configuration option: %s",
  17767. name);
  17768. }
  17769. free_context(ctx);
  17770. pthread_setspecific(sTlsKey, NULL);
  17771. return NULL;
  17772. } else if ((value = *options++) == NULL) {
  17773. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17774. if (error != NULL) {
  17775. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17776. error->code_sub = (unsigned)idx;
  17777. mg_snprintf(NULL,
  17778. NULL, /* No truncation check for error buffers */
  17779. error->text,
  17780. error->text_buffer_size,
  17781. "Invalid configuration option value: %s",
  17782. name);
  17783. }
  17784. free_context(ctx);
  17785. pthread_setspecific(sTlsKey, NULL);
  17786. return NULL;
  17787. }
  17788. if (ctx->dd.config[idx] != NULL) {
  17789. /* A duplicate configuration option is not an error - the last
  17790. * option value will be used. */
  17791. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17792. mg_free(ctx->dd.config[idx]);
  17793. }
  17794. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17795. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17796. }
  17797. /* Set default value if needed */
  17798. for (i = 0; config_options[i].name != NULL; i++) {
  17799. default_value = config_options[i].default_value;
  17800. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17801. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17802. }
  17803. }
  17804. /* Request size option */
  17805. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17806. if (itmp < 1024) {
  17807. mg_cry_ctx_internal(ctx,
  17808. "%s too small",
  17809. config_options[MAX_REQUEST_SIZE].name);
  17810. if (error != NULL) {
  17811. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17812. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  17813. mg_snprintf(NULL,
  17814. NULL, /* No truncation check for error buffers */
  17815. error->text,
  17816. error->text_buffer_size,
  17817. "Invalid configuration option value: %s",
  17818. config_options[MAX_REQUEST_SIZE].name);
  17819. }
  17820. free_context(ctx);
  17821. pthread_setspecific(sTlsKey, NULL);
  17822. return NULL;
  17823. }
  17824. ctx->max_request_size = (unsigned)itmp;
  17825. /* Queue length */
  17826. #if !defined(ALTERNATIVE_QUEUE)
  17827. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17828. if (itmp < 1) {
  17829. mg_cry_ctx_internal(ctx,
  17830. "%s too small",
  17831. config_options[CONNECTION_QUEUE_SIZE].name);
  17832. if (error != NULL) {
  17833. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17834. error->code_sub = CONNECTION_QUEUE_SIZE;
  17835. mg_snprintf(NULL,
  17836. NULL, /* No truncation check for error buffers */
  17837. error->text,
  17838. error->text_buffer_size,
  17839. "Invalid configuration option value: %s",
  17840. config_options[CONNECTION_QUEUE_SIZE].name);
  17841. }
  17842. free_context(ctx);
  17843. pthread_setspecific(sTlsKey, NULL);
  17844. return NULL;
  17845. }
  17846. ctx->squeue =
  17847. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17848. if (ctx->squeue == NULL) {
  17849. mg_cry_ctx_internal(ctx,
  17850. "Out of memory: Cannot allocate %s",
  17851. config_options[CONNECTION_QUEUE_SIZE].name);
  17852. if (error != NULL) {
  17853. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17854. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  17855. mg_snprintf(NULL,
  17856. NULL, /* No truncation check for error buffers */
  17857. error->text,
  17858. error->text_buffer_size,
  17859. "Out of memory: Cannot allocate %s",
  17860. config_options[CONNECTION_QUEUE_SIZE].name);
  17861. }
  17862. free_context(ctx);
  17863. pthread_setspecific(sTlsKey, NULL);
  17864. return NULL;
  17865. }
  17866. ctx->sq_size = itmp;
  17867. #endif
  17868. /* Worker thread count option */
  17869. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17870. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17871. if (workerthreadcount <= 0) {
  17872. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17873. } else {
  17874. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17875. }
  17876. if (error != NULL) {
  17877. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17878. error->code_sub = NUM_THREADS;
  17879. mg_snprintf(NULL,
  17880. NULL, /* No truncation check for error buffers */
  17881. error->text,
  17882. error->text_buffer_size,
  17883. "Invalid configuration option value: %s",
  17884. config_options[NUM_THREADS].name);
  17885. }
  17886. free_context(ctx);
  17887. pthread_setspecific(sTlsKey, NULL);
  17888. return NULL;
  17889. }
  17890. /* Document root */
  17891. #if defined(NO_FILES)
  17892. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17893. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17894. if (error != NULL) {
  17895. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17896. error->code_sub = (unsigned)DOCUMENT_ROOT;
  17897. mg_snprintf(NULL,
  17898. NULL, /* No truncation check for error buffers */
  17899. error->text,
  17900. error->text_buffer_size,
  17901. "Invalid configuration option value: %s",
  17902. config_options[DOCUMENT_ROOT].name);
  17903. }
  17904. free_context(ctx);
  17905. pthread_setspecific(sTlsKey, NULL);
  17906. return NULL;
  17907. }
  17908. #endif
  17909. get_system_name(&ctx->systemName);
  17910. #if defined(USE_LUA)
  17911. /* If a Lua background script has been configured, start it. */
  17912. ctx->lua_bg_log_available = 0;
  17913. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17914. char ebuf[256];
  17915. struct vec opt_vec;
  17916. struct vec eq_vec;
  17917. const char *sparams;
  17918. memset(ebuf, 0, sizeof(ebuf));
  17919. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17920. /* Create a Lua state, load all standard libraries and the mg table */
  17921. lua_State *state = mg_lua_context_script_prepare(
  17922. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17923. if (!state) {
  17924. mg_cry_ctx_internal(ctx,
  17925. "lua_background_script load error: %s",
  17926. ebuf);
  17927. if (error != NULL) {
  17928. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  17929. mg_snprintf(NULL,
  17930. NULL, /* No truncation check for error buffers */
  17931. error->text,
  17932. error->text_buffer_size,
  17933. "Error in script %s: %s",
  17934. config_options[LUA_BACKGROUND_SCRIPT].name,
  17935. ebuf);
  17936. }
  17937. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17938. free_context(ctx);
  17939. pthread_setspecific(sTlsKey, NULL);
  17940. return NULL;
  17941. }
  17942. /* Add a table with parameters into mg.params */
  17943. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17944. if (sparams && sparams[0]) {
  17945. lua_getglobal(state, "mg");
  17946. lua_pushstring(state, "params");
  17947. lua_newtable(state);
  17948. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17949. != NULL) {
  17950. reg_llstring(
  17951. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17952. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17953. break;
  17954. }
  17955. lua_rawset(state, -3);
  17956. lua_pop(state, 1);
  17957. }
  17958. /* Call script */
  17959. state = mg_lua_context_script_run(state,
  17960. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17961. ctx,
  17962. ebuf,
  17963. sizeof(ebuf));
  17964. if (!state) {
  17965. mg_cry_ctx_internal(ctx,
  17966. "lua_background_script start error: %s",
  17967. ebuf);
  17968. if (error != NULL) {
  17969. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  17970. mg_snprintf(NULL,
  17971. NULL, /* No truncation check for error buffers */
  17972. error->text,
  17973. error->text_buffer_size,
  17974. "Error in script %s: %s",
  17975. config_options[DOCUMENT_ROOT].name,
  17976. ebuf);
  17977. }
  17978. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17979. free_context(ctx);
  17980. pthread_setspecific(sTlsKey, NULL);
  17981. return NULL;
  17982. }
  17983. /* state remains valid */
  17984. ctx->lua_background_state = (void *)state;
  17985. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17986. } else {
  17987. ctx->lua_background_state = 0;
  17988. }
  17989. #endif
  17990. /* Step by step initialization of ctx - depending on build options */
  17991. #if !defined(NO_FILESYSTEMS)
  17992. if (!set_gpass_option(ctx, NULL)) {
  17993. const char *err_msg = "Invalid global password file";
  17994. /* Fatal error - abort start. */
  17995. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17996. if (error != NULL) {
  17997. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  17998. mg_snprintf(NULL,
  17999. NULL, /* No truncation check for error buffers */
  18000. error->text,
  18001. error->text_buffer_size,
  18002. "%s",
  18003. err_msg);
  18004. }
  18005. free_context(ctx);
  18006. pthread_setspecific(sTlsKey, NULL);
  18007. return NULL;
  18008. }
  18009. #endif
  18010. #if defined(USE_MBEDTLS)
  18011. if (!mg_sslctx_init(ctx, NULL)) {
  18012. const char *err_msg = "Error initializing SSL context";
  18013. /* Fatal error - abort start. */
  18014. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18015. if (error != NULL) {
  18016. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18017. mg_snprintf(NULL,
  18018. NULL, /* No truncation check for error buffers */
  18019. error->text,
  18020. error->text_buffer_size,
  18021. "%s",
  18022. err_msg);
  18023. }
  18024. free_context(ctx);
  18025. pthread_setspecific(sTlsKey, NULL);
  18026. return NULL;
  18027. }
  18028. #elif !defined(NO_SSL)
  18029. if (!init_ssl_ctx(ctx, NULL)) {
  18030. const char *err_msg = "Error initializing SSL context";
  18031. /* Fatal error - abort start. */
  18032. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18033. if (error != NULL) {
  18034. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18035. mg_snprintf(NULL,
  18036. NULL, /* No truncation check for error buffers */
  18037. error->text,
  18038. error->text_buffer_size,
  18039. "%s",
  18040. err_msg);
  18041. }
  18042. free_context(ctx);
  18043. pthread_setspecific(sTlsKey, NULL);
  18044. return NULL;
  18045. }
  18046. #endif
  18047. if (!set_ports_option(ctx)) {
  18048. const char *err_msg = "Failed to setup server ports";
  18049. /* Fatal error - abort start. */
  18050. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18051. if (error != NULL) {
  18052. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18053. mg_snprintf(NULL,
  18054. NULL, /* No truncation check for error buffers */
  18055. error->text,
  18056. error->text_buffer_size,
  18057. "%s",
  18058. err_msg);
  18059. }
  18060. free_context(ctx);
  18061. pthread_setspecific(sTlsKey, NULL);
  18062. return NULL;
  18063. }
  18064. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18065. if (!set_uid_option(ctx)) {
  18066. const char *err_msg = "Failed to run as configured user";
  18067. /* Fatal error - abort start. */
  18068. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18069. if (error != NULL) {
  18070. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18071. mg_snprintf(NULL,
  18072. NULL, /* No truncation check for error buffers */
  18073. error->text,
  18074. error->text_buffer_size,
  18075. "%s",
  18076. err_msg);
  18077. }
  18078. free_context(ctx);
  18079. pthread_setspecific(sTlsKey, NULL);
  18080. return NULL;
  18081. }
  18082. #endif
  18083. if (!set_acl_option(ctx)) {
  18084. const char *err_msg = "Failed to setup access control list";
  18085. /* Fatal error - abort start. */
  18086. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18087. if (error != NULL) {
  18088. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18089. mg_snprintf(NULL,
  18090. NULL, /* No truncation check for error buffers */
  18091. error->text,
  18092. error->text_buffer_size,
  18093. "%s",
  18094. err_msg);
  18095. }
  18096. free_context(ctx);
  18097. pthread_setspecific(sTlsKey, NULL);
  18098. return NULL;
  18099. }
  18100. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  18101. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18102. sizeof(pthread_t),
  18103. ctx);
  18104. if (ctx->worker_threadids == NULL) {
  18105. const char *err_msg = "Not enough memory for worker thread ID array";
  18106. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18107. if (error != NULL) {
  18108. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18109. error->code_sub =
  18110. (unsigned)ctx->cfg_worker_threads * (unsigned)sizeof(pthread_t);
  18111. mg_snprintf(NULL,
  18112. NULL, /* No truncation check for error buffers */
  18113. error->text,
  18114. error->text_buffer_size,
  18115. "%s",
  18116. err_msg);
  18117. }
  18118. free_context(ctx);
  18119. pthread_setspecific(sTlsKey, NULL);
  18120. return NULL;
  18121. }
  18122. ctx->worker_connections =
  18123. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18124. sizeof(struct mg_connection),
  18125. ctx);
  18126. if (ctx->worker_connections == NULL) {
  18127. const char *err_msg =
  18128. "Not enough memory for worker thread connection array";
  18129. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18130. if (error != NULL) {
  18131. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18132. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18133. * (unsigned)sizeof(struct mg_connection);
  18134. mg_snprintf(NULL,
  18135. NULL, /* No truncation check for error buffers */
  18136. error->text,
  18137. error->text_buffer_size,
  18138. "%s",
  18139. err_msg);
  18140. }
  18141. free_context(ctx);
  18142. pthread_setspecific(sTlsKey, NULL);
  18143. return NULL;
  18144. }
  18145. #if defined(ALTERNATIVE_QUEUE)
  18146. ctx->client_wait_events =
  18147. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  18148. sizeof(ctx->client_wait_events[0]),
  18149. ctx);
  18150. if (ctx->client_wait_events == NULL) {
  18151. const char *err_msg = "Not enough memory for worker event array";
  18152. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18153. mg_free(ctx->worker_threadids);
  18154. if (error != NULL) {
  18155. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18156. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18157. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18158. mg_snprintf(NULL,
  18159. NULL, /* No truncation check for error buffers */
  18160. error->text,
  18161. error->text_buffer_size,
  18162. "%s",
  18163. err_msg);
  18164. }
  18165. free_context(ctx);
  18166. pthread_setspecific(sTlsKey, NULL);
  18167. return NULL;
  18168. }
  18169. ctx->client_socks =
  18170. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18171. sizeof(ctx->client_socks[0]),
  18172. ctx);
  18173. if (ctx->client_socks == NULL) {
  18174. const char *err_msg = "Not enough memory for worker socket array";
  18175. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18176. mg_free(ctx->client_wait_events);
  18177. mg_free(ctx->worker_threadids);
  18178. if (error != NULL) {
  18179. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18180. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18181. * (unsigned)sizeof(ctx->client_socks[0]);
  18182. mg_snprintf(NULL,
  18183. NULL, /* No truncation check for error buffers */
  18184. error->text,
  18185. error->text_buffer_size,
  18186. "%s",
  18187. err_msg);
  18188. }
  18189. free_context(ctx);
  18190. pthread_setspecific(sTlsKey, NULL);
  18191. return NULL;
  18192. }
  18193. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  18194. ctx->client_wait_events[i] = event_create();
  18195. if (ctx->client_wait_events[i] == 0) {
  18196. const char *err_msg = "Error creating worker event %i";
  18197. mg_cry_ctx_internal(ctx, err_msg, i);
  18198. while (i > 0) {
  18199. i--;
  18200. event_destroy(ctx->client_wait_events[i]);
  18201. }
  18202. mg_free(ctx->client_socks);
  18203. mg_free(ctx->client_wait_events);
  18204. mg_free(ctx->worker_threadids);
  18205. if (error != NULL) {
  18206. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18207. error->code_sub = ERRNO;
  18208. mg_snprintf(NULL,
  18209. NULL, /* No truncation check for error buffers */
  18210. error->text,
  18211. error->text_buffer_size,
  18212. err_msg,
  18213. i);
  18214. }
  18215. free_context(ctx);
  18216. pthread_setspecific(sTlsKey, NULL);
  18217. return NULL;
  18218. }
  18219. }
  18220. #endif
  18221. #if defined(USE_TIMERS)
  18222. if (timers_init(ctx) != 0) {
  18223. const char *err_msg = "Error creating timers";
  18224. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18225. if (error != NULL) {
  18226. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18227. error->code_sub = ERRNO;
  18228. mg_snprintf(NULL,
  18229. NULL, /* No truncation check for error buffers */
  18230. error->text,
  18231. error->text_buffer_size,
  18232. "%s",
  18233. err_msg);
  18234. }
  18235. free_context(ctx);
  18236. pthread_setspecific(sTlsKey, NULL);
  18237. return NULL;
  18238. }
  18239. #endif
  18240. /* Context has been created - init user libraries */
  18241. if (ctx->callbacks.init_context) {
  18242. ctx->callbacks.init_context(ctx);
  18243. }
  18244. /* From now, the context is successfully created.
  18245. * When it is destroyed, the exit callback should be called. */
  18246. ctx->callbacks.exit_context = exit_callback;
  18247. ctx->context_type = CONTEXT_SERVER; /* server context */
  18248. /* Start worker threads */
  18249. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  18250. /* worker_thread sets up the other fields */
  18251. ctx->worker_connections[i].phys_ctx = ctx;
  18252. if (mg_start_thread_with_id(worker_thread,
  18253. &ctx->worker_connections[i],
  18254. &ctx->worker_threadids[i])
  18255. != 0) {
  18256. long error_no = (long)ERRNO;
  18257. /* thread was not created */
  18258. if (i > 0) {
  18259. /* If the second, third, ... thread cannot be created, set a
  18260. * warning, but keep running. */
  18261. mg_cry_ctx_internal(ctx,
  18262. "Cannot start worker thread %i: error %ld",
  18263. i + 1,
  18264. error_no);
  18265. /* If the server initialization should stop here, all
  18266. * threads that have already been created must be stopped
  18267. * first, before any free_context(ctx) call.
  18268. */
  18269. } else {
  18270. /* If the first worker thread cannot be created, stop
  18271. * initialization and free the entire server context. */
  18272. mg_cry_ctx_internal(ctx,
  18273. "Cannot create threads: error %ld",
  18274. error_no);
  18275. if (error != NULL) {
  18276. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18277. error->code_sub = (unsigned)error_no;
  18278. mg_snprintf(
  18279. NULL,
  18280. NULL, /* No truncation check for error buffers */
  18281. error->text,
  18282. error->text_buffer_size,
  18283. "Cannot create first worker thread: error %ld",
  18284. error_no);
  18285. }
  18286. free_context(ctx);
  18287. pthread_setspecific(sTlsKey, NULL);
  18288. return NULL;
  18289. }
  18290. break;
  18291. }
  18292. }
  18293. /* Start master (listening) thread */
  18294. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18295. pthread_setspecific(sTlsKey, NULL);
  18296. return ctx;
  18297. }
  18298. CIVETWEB_API struct mg_context *
  18299. mg_start(const struct mg_callbacks *callbacks,
  18300. void *user_data,
  18301. const char **options)
  18302. {
  18303. struct mg_init_data init = {0};
  18304. init.callbacks = callbacks;
  18305. init.user_data = user_data;
  18306. init.configuration_options = options;
  18307. return mg_start2(&init, NULL);
  18308. }
  18309. /* Add an additional domain to an already running web server. */
  18310. CIVETWEB_API int
  18311. mg_start_domain2(struct mg_context *ctx,
  18312. const char **options,
  18313. struct mg_error_data *error)
  18314. {
  18315. const char *name;
  18316. const char *value;
  18317. const char *default_value;
  18318. struct mg_domain_context *new_dom;
  18319. struct mg_domain_context *dom;
  18320. int idx, i;
  18321. if (error != NULL) {
  18322. error->code = MG_ERROR_DATA_CODE_OK;
  18323. error->code_sub = 0;
  18324. if (error->text_buffer_size > 0) {
  18325. *error->text = 0;
  18326. }
  18327. }
  18328. if ((ctx == NULL) || (options == NULL)) {
  18329. if (error != NULL) {
  18330. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18331. mg_snprintf(NULL,
  18332. NULL, /* No truncation check for error buffers */
  18333. error->text,
  18334. error->text_buffer_size,
  18335. "%s",
  18336. "Invalid parameters");
  18337. }
  18338. return -1;
  18339. }
  18340. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18341. if (error != NULL) {
  18342. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18343. mg_snprintf(NULL,
  18344. NULL, /* No truncation check for error buffers */
  18345. error->text,
  18346. error->text_buffer_size,
  18347. "%s",
  18348. "Server already stopped");
  18349. }
  18350. return -7;
  18351. }
  18352. new_dom = (struct mg_domain_context *)
  18353. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18354. if (!new_dom) {
  18355. /* Out of memory */
  18356. if (error != NULL) {
  18357. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18358. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18359. mg_snprintf(NULL,
  18360. NULL, /* No truncation check for error buffers */
  18361. error->text,
  18362. error->text_buffer_size,
  18363. "%s",
  18364. "Out or memory");
  18365. }
  18366. return -6;
  18367. }
  18368. /* Store options - TODO: unite duplicate code */
  18369. while (options && (name = *options++) != NULL) {
  18370. idx = get_option_index(name);
  18371. if (idx == -1) {
  18372. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18373. if (error != NULL) {
  18374. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18375. error->code_sub = (unsigned)-1;
  18376. mg_snprintf(NULL,
  18377. NULL, /* No truncation check for error buffers */
  18378. error->text,
  18379. error->text_buffer_size,
  18380. "Invalid option: %s",
  18381. name);
  18382. }
  18383. mg_free(new_dom);
  18384. return -2;
  18385. } else if ((value = *options++) == NULL) {
  18386. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18387. if (error != NULL) {
  18388. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18389. error->code_sub = idx;
  18390. mg_snprintf(NULL,
  18391. NULL, /* No truncation check for error buffers */
  18392. error->text,
  18393. error->text_buffer_size,
  18394. "Invalid option value: %s",
  18395. name);
  18396. }
  18397. mg_free(new_dom);
  18398. return -2;
  18399. }
  18400. if (new_dom->config[idx] != NULL) {
  18401. /* Duplicate option: Later values overwrite earlier ones. */
  18402. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18403. mg_free(new_dom->config[idx]);
  18404. }
  18405. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18406. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18407. }
  18408. /* Authentication domain is mandatory */
  18409. /* TODO: Maybe use a new option hostname? */
  18410. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18411. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18412. if (error != NULL) {
  18413. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18414. error->code_sub = AUTHENTICATION_DOMAIN;
  18415. mg_snprintf(NULL,
  18416. NULL, /* No truncation check for error buffers */
  18417. error->text,
  18418. error->text_buffer_size,
  18419. "Mandatory option %s missing",
  18420. config_options[AUTHENTICATION_DOMAIN].name);
  18421. }
  18422. mg_free(new_dom);
  18423. return -4;
  18424. }
  18425. /* Set default value if needed. Take the config value from
  18426. * ctx as a default value. */
  18427. for (i = 0; config_options[i].name != NULL; i++) {
  18428. default_value = ctx->dd.config[i];
  18429. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18430. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18431. }
  18432. }
  18433. new_dom->handlers = NULL;
  18434. new_dom->next = NULL;
  18435. new_dom->nonce_count = 0;
  18436. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18437. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18438. new_dom->shared_lua_websockets = NULL;
  18439. #endif
  18440. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18441. if (!init_ssl_ctx(ctx, new_dom)) {
  18442. /* Init SSL failed */
  18443. if (error != NULL) {
  18444. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18445. mg_snprintf(NULL,
  18446. NULL, /* No truncation check for error buffers */
  18447. error->text,
  18448. error->text_buffer_size,
  18449. "%s",
  18450. "Initializing SSL context failed");
  18451. }
  18452. mg_free(new_dom);
  18453. return -3;
  18454. }
  18455. #endif
  18456. /* Add element to linked list. */
  18457. mg_lock_context(ctx);
  18458. idx = 0;
  18459. dom = &(ctx->dd);
  18460. for (;;) {
  18461. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18462. dom->config[AUTHENTICATION_DOMAIN])) {
  18463. /* Domain collision */
  18464. mg_cry_ctx_internal(ctx,
  18465. "domain %s already in use",
  18466. new_dom->config[AUTHENTICATION_DOMAIN]);
  18467. if (error != NULL) {
  18468. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18469. mg_snprintf(NULL,
  18470. NULL, /* No truncation check for error buffers */
  18471. error->text,
  18472. error->text_buffer_size,
  18473. "Domain %s specified by %s is already in use",
  18474. new_dom->config[AUTHENTICATION_DOMAIN],
  18475. config_options[AUTHENTICATION_DOMAIN].name);
  18476. }
  18477. mg_free(new_dom);
  18478. mg_unlock_context(ctx);
  18479. return -5;
  18480. }
  18481. /* Count number of domains */
  18482. idx++;
  18483. if (dom->next == NULL) {
  18484. dom->next = new_dom;
  18485. break;
  18486. }
  18487. dom = dom->next;
  18488. }
  18489. mg_unlock_context(ctx);
  18490. /* Return domain number */
  18491. return idx;
  18492. }
  18493. CIVETWEB_API int
  18494. mg_start_domain(struct mg_context *ctx, const char **options)
  18495. {
  18496. return mg_start_domain2(ctx, options, NULL);
  18497. }
  18498. /* Feature check API function */
  18499. CIVETWEB_API unsigned
  18500. mg_check_feature(unsigned feature)
  18501. {
  18502. static const unsigned feature_set = 0
  18503. /* Set bits for available features according to API documentation.
  18504. * This bit mask is created at compile time, according to the active
  18505. * preprocessor defines. It is a single const value at runtime. */
  18506. #if !defined(NO_FILES)
  18507. | MG_FEATURES_FILES
  18508. #endif
  18509. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18510. | MG_FEATURES_SSL
  18511. #endif
  18512. #if !defined(NO_CGI)
  18513. | MG_FEATURES_CGI
  18514. #endif
  18515. #if defined(USE_IPV6)
  18516. | MG_FEATURES_IPV6
  18517. #endif
  18518. #if defined(USE_WEBSOCKET)
  18519. | MG_FEATURES_WEBSOCKET
  18520. #endif
  18521. #if defined(USE_LUA)
  18522. | MG_FEATURES_LUA
  18523. #endif
  18524. #if defined(USE_DUKTAPE)
  18525. | MG_FEATURES_SSJS
  18526. #endif
  18527. #if !defined(NO_CACHING)
  18528. | MG_FEATURES_CACHE
  18529. #endif
  18530. #if defined(USE_SERVER_STATS)
  18531. | MG_FEATURES_STATS
  18532. #endif
  18533. #if defined(USE_ZLIB)
  18534. | MG_FEATURES_COMPRESSION
  18535. #endif
  18536. #if defined(USE_HTTP2)
  18537. | MG_FEATURES_HTTP2
  18538. #endif
  18539. #if defined(USE_X_DOM_SOCKET)
  18540. | MG_FEATURES_X_DOMAIN_SOCKET
  18541. #endif
  18542. /* Set some extra bits not defined in the API documentation.
  18543. * These bits may change without further notice. */
  18544. #if defined(MG_LEGACY_INTERFACE)
  18545. | 0x80000000u
  18546. #endif
  18547. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18548. | 0x40000000u
  18549. #endif
  18550. #if !defined(NO_RESPONSE_BUFFERING)
  18551. | 0x20000000u
  18552. #endif
  18553. #if defined(MEMORY_DEBUGGING)
  18554. | 0x10000000u
  18555. #endif
  18556. ;
  18557. return (feature & feature_set);
  18558. }
  18559. static size_t
  18560. mg_str_append(char **dst, char *end, const char *src)
  18561. {
  18562. size_t len = strlen(src);
  18563. if (*dst != end) {
  18564. /* Append src if enough space, or close dst. */
  18565. if ((size_t)(end - *dst) > len) {
  18566. strcpy(*dst, src);
  18567. *dst += len;
  18568. } else {
  18569. *dst = end;
  18570. }
  18571. }
  18572. return len;
  18573. }
  18574. /* Get system information. It can be printed or stored by the caller.
  18575. * Return the size of available information. */
  18576. CIVETWEB_API int
  18577. mg_get_system_info(char *buffer, int buflen)
  18578. {
  18579. char *end, *append_eoobj = NULL, block[256];
  18580. size_t system_info_length = 0;
  18581. #if defined(_WIN32)
  18582. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18583. #else
  18584. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18585. #endif
  18586. if ((buffer == NULL) || (buflen < 1)) {
  18587. buflen = 0;
  18588. end = buffer;
  18589. } else {
  18590. *buffer = 0;
  18591. end = buffer + buflen;
  18592. }
  18593. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18594. /* has enough space to append eoobj */
  18595. append_eoobj = buffer;
  18596. if (end) {
  18597. end -= sizeof(eoobj) - 1;
  18598. }
  18599. }
  18600. system_info_length += mg_str_append(&buffer, end, "{");
  18601. /* Server version */
  18602. {
  18603. const char *version = mg_version();
  18604. mg_snprintf(NULL,
  18605. NULL,
  18606. block,
  18607. sizeof(block),
  18608. "%s\"version\" : \"%s\"",
  18609. eol,
  18610. version);
  18611. system_info_length += mg_str_append(&buffer, end, block);
  18612. }
  18613. /* System info */
  18614. {
  18615. #if defined(_WIN32)
  18616. DWORD dwVersion = 0;
  18617. DWORD dwMajorVersion = 0;
  18618. DWORD dwMinorVersion = 0;
  18619. SYSTEM_INFO si;
  18620. GetSystemInfo(&si);
  18621. #if defined(_MSC_VER)
  18622. #pragma warning(push)
  18623. /* GetVersion was declared deprecated */
  18624. #pragma warning(disable : 4996)
  18625. #endif
  18626. dwVersion = GetVersion();
  18627. #if defined(_MSC_VER)
  18628. #pragma warning(pop)
  18629. #endif
  18630. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18631. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18632. mg_snprintf(NULL,
  18633. NULL,
  18634. block,
  18635. sizeof(block),
  18636. ",%s\"os\" : \"Windows %u.%u\"",
  18637. eol,
  18638. (unsigned)dwMajorVersion,
  18639. (unsigned)dwMinorVersion);
  18640. system_info_length += mg_str_append(&buffer, end, block);
  18641. mg_snprintf(NULL,
  18642. NULL,
  18643. block,
  18644. sizeof(block),
  18645. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18646. eol,
  18647. (unsigned)si.wProcessorArchitecture,
  18648. (unsigned)si.dwNumberOfProcessors,
  18649. (unsigned)si.dwActiveProcessorMask);
  18650. system_info_length += mg_str_append(&buffer, end, block);
  18651. #elif defined(__ZEPHYR__)
  18652. mg_snprintf(NULL,
  18653. NULL,
  18654. block,
  18655. sizeof(block),
  18656. ",%s\"os\" : \"%s %s\"",
  18657. eol,
  18658. "Zephyr OS",
  18659. ZEPHYR_VERSION);
  18660. system_info_length += mg_str_append(&buffer, end, block);
  18661. #else
  18662. struct utsname name;
  18663. memset(&name, 0, sizeof(name));
  18664. uname(&name);
  18665. mg_snprintf(NULL,
  18666. NULL,
  18667. block,
  18668. sizeof(block),
  18669. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18670. eol,
  18671. name.sysname,
  18672. name.version,
  18673. name.release,
  18674. name.machine);
  18675. system_info_length += mg_str_append(&buffer, end, block);
  18676. #endif
  18677. }
  18678. /* Features */
  18679. {
  18680. mg_snprintf(NULL,
  18681. NULL,
  18682. block,
  18683. sizeof(block),
  18684. ",%s\"features\" : %lu"
  18685. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18686. eol,
  18687. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18688. eol,
  18689. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18690. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18691. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18692. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18693. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18694. : "",
  18695. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18696. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18697. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18698. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18699. system_info_length += mg_str_append(&buffer, end, block);
  18700. #if defined(USE_LUA)
  18701. mg_snprintf(NULL,
  18702. NULL,
  18703. block,
  18704. sizeof(block),
  18705. ",%s\"lua_version\" : \"%u (%s)\"",
  18706. eol,
  18707. (unsigned)LUA_VERSION_NUM,
  18708. LUA_RELEASE);
  18709. system_info_length += mg_str_append(&buffer, end, block);
  18710. #endif
  18711. #if defined(USE_DUKTAPE)
  18712. mg_snprintf(NULL,
  18713. NULL,
  18714. block,
  18715. sizeof(block),
  18716. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18717. eol,
  18718. (unsigned)DUK_VERSION / 10000,
  18719. ((unsigned)DUK_VERSION / 100) % 100,
  18720. (unsigned)DUK_VERSION % 100);
  18721. system_info_length += mg_str_append(&buffer, end, block);
  18722. #endif
  18723. }
  18724. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18725. {
  18726. #if defined(BUILD_DATE)
  18727. const char *bd = BUILD_DATE;
  18728. #else
  18729. #if defined(GCC_DIAGNOSTIC)
  18730. #if GCC_VERSION >= 40900
  18731. #pragma GCC diagnostic push
  18732. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18733. * does not work in some versions. If "BUILD_DATE" is defined to some
  18734. * string, it is used instead of __DATE__. */
  18735. #pragma GCC diagnostic ignored "-Wdate-time"
  18736. #endif
  18737. #endif
  18738. const char *bd = __DATE__;
  18739. #if defined(GCC_DIAGNOSTIC)
  18740. #if GCC_VERSION >= 40900
  18741. #pragma GCC diagnostic pop
  18742. #endif
  18743. #endif
  18744. #endif
  18745. mg_snprintf(
  18746. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18747. system_info_length += mg_str_append(&buffer, end, block);
  18748. }
  18749. /* Compiler information */
  18750. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18751. {
  18752. #if defined(_MSC_VER)
  18753. mg_snprintf(NULL,
  18754. NULL,
  18755. block,
  18756. sizeof(block),
  18757. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18758. eol,
  18759. (unsigned)_MSC_VER,
  18760. (unsigned)_MSC_FULL_VER);
  18761. system_info_length += mg_str_append(&buffer, end, block);
  18762. #elif defined(__MINGW64__)
  18763. mg_snprintf(NULL,
  18764. NULL,
  18765. block,
  18766. sizeof(block),
  18767. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18768. eol,
  18769. (unsigned)__MINGW64_VERSION_MAJOR,
  18770. (unsigned)__MINGW64_VERSION_MINOR);
  18771. system_info_length += mg_str_append(&buffer, end, block);
  18772. mg_snprintf(NULL,
  18773. NULL,
  18774. block,
  18775. sizeof(block),
  18776. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18777. eol,
  18778. (unsigned)__MINGW32_MAJOR_VERSION,
  18779. (unsigned)__MINGW32_MINOR_VERSION);
  18780. system_info_length += mg_str_append(&buffer, end, block);
  18781. #elif defined(__MINGW32__)
  18782. mg_snprintf(NULL,
  18783. NULL,
  18784. block,
  18785. sizeof(block),
  18786. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18787. eol,
  18788. (unsigned)__MINGW32_MAJOR_VERSION,
  18789. (unsigned)__MINGW32_MINOR_VERSION);
  18790. system_info_length += mg_str_append(&buffer, end, block);
  18791. #elif defined(__clang__)
  18792. mg_snprintf(NULL,
  18793. NULL,
  18794. block,
  18795. sizeof(block),
  18796. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18797. eol,
  18798. __clang_major__,
  18799. __clang_minor__,
  18800. __clang_patchlevel__,
  18801. __clang_version__);
  18802. system_info_length += mg_str_append(&buffer, end, block);
  18803. #elif defined(__GNUC__)
  18804. mg_snprintf(NULL,
  18805. NULL,
  18806. block,
  18807. sizeof(block),
  18808. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18809. eol,
  18810. (unsigned)__GNUC__,
  18811. (unsigned)__GNUC_MINOR__,
  18812. (unsigned)__GNUC_PATCHLEVEL__);
  18813. system_info_length += mg_str_append(&buffer, end, block);
  18814. #elif defined(__INTEL_COMPILER)
  18815. mg_snprintf(NULL,
  18816. NULL,
  18817. block,
  18818. sizeof(block),
  18819. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18820. eol,
  18821. (unsigned)__INTEL_COMPILER);
  18822. system_info_length += mg_str_append(&buffer, end, block);
  18823. #elif defined(__BORLANDC__)
  18824. mg_snprintf(NULL,
  18825. NULL,
  18826. block,
  18827. sizeof(block),
  18828. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18829. eol,
  18830. (unsigned)__BORLANDC__);
  18831. system_info_length += mg_str_append(&buffer, end, block);
  18832. #elif defined(__SUNPRO_C)
  18833. mg_snprintf(NULL,
  18834. NULL,
  18835. block,
  18836. sizeof(block),
  18837. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18838. eol,
  18839. (unsigned)__SUNPRO_C);
  18840. system_info_length += mg_str_append(&buffer, end, block);
  18841. #else
  18842. mg_snprintf(NULL,
  18843. NULL,
  18844. block,
  18845. sizeof(block),
  18846. ",%s\"compiler\" : \"other\"",
  18847. eol);
  18848. system_info_length += mg_str_append(&buffer, end, block);
  18849. #endif
  18850. }
  18851. /* Determine 32/64 bit data mode.
  18852. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18853. {
  18854. mg_snprintf(NULL,
  18855. NULL,
  18856. block,
  18857. sizeof(block),
  18858. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18859. "char:%u/%u, "
  18860. "ptr:%u, size:%u, time:%u\"",
  18861. eol,
  18862. (unsigned)sizeof(short),
  18863. (unsigned)sizeof(int),
  18864. (unsigned)sizeof(long),
  18865. (unsigned)sizeof(long long),
  18866. (unsigned)sizeof(float),
  18867. (unsigned)sizeof(double),
  18868. (unsigned)sizeof(long double),
  18869. (unsigned)sizeof(char),
  18870. (unsigned)sizeof(wchar_t),
  18871. (unsigned)sizeof(void *),
  18872. (unsigned)sizeof(size_t),
  18873. (unsigned)sizeof(time_t));
  18874. system_info_length += mg_str_append(&buffer, end, block);
  18875. }
  18876. /* Terminate string */
  18877. if (append_eoobj) {
  18878. strcat(append_eoobj, eoobj);
  18879. }
  18880. system_info_length += sizeof(eoobj) - 1;
  18881. return (int)system_info_length;
  18882. }
  18883. /* Get context information. It can be printed or stored by the caller.
  18884. * Return the size of available information. */
  18885. CIVETWEB_API int
  18886. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18887. {
  18888. #if defined(USE_SERVER_STATS)
  18889. char *end, *append_eoobj = NULL, block[256];
  18890. size_t context_info_length = 0;
  18891. #if defined(_WIN32)
  18892. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18893. #else
  18894. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18895. #endif
  18896. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18897. if ((buffer == NULL) || (buflen < 1)) {
  18898. buflen = 0;
  18899. end = buffer;
  18900. } else {
  18901. *buffer = 0;
  18902. end = buffer + buflen;
  18903. }
  18904. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18905. /* has enough space to append eoobj */
  18906. append_eoobj = buffer;
  18907. end -= sizeof(eoobj) - 1;
  18908. }
  18909. context_info_length += mg_str_append(&buffer, end, "{");
  18910. if (ms) { /* <-- should be always true */
  18911. /* Memory information */
  18912. int blockCount = (int)ms->blockCount;
  18913. int64_t totalMemUsed = ms->totalMemUsed;
  18914. int64_t maxMemUsed = ms->maxMemUsed;
  18915. if (totalMemUsed > maxMemUsed) {
  18916. maxMemUsed = totalMemUsed;
  18917. }
  18918. mg_snprintf(NULL,
  18919. NULL,
  18920. block,
  18921. sizeof(block),
  18922. "%s\"memory\" : {%s"
  18923. "\"blocks\" : %i,%s"
  18924. "\"used\" : %" INT64_FMT ",%s"
  18925. "\"maxUsed\" : %" INT64_FMT "%s"
  18926. "}",
  18927. eol,
  18928. eol,
  18929. blockCount,
  18930. eol,
  18931. totalMemUsed,
  18932. eol,
  18933. maxMemUsed,
  18934. eol);
  18935. context_info_length += mg_str_append(&buffer, end, block);
  18936. }
  18937. if (ctx) {
  18938. /* Declare all variables at begin of the block, to comply
  18939. * with old C standards. */
  18940. char start_time_str[64] = {0};
  18941. char now_str[64] = {0};
  18942. time_t start_time = ctx->start_time;
  18943. time_t now = time(NULL);
  18944. int64_t total_data_read, total_data_written;
  18945. int active_connections = (int)ctx->active_connections;
  18946. int max_active_connections = (int)ctx->max_active_connections;
  18947. int total_connections = (int)ctx->total_connections;
  18948. if (active_connections > max_active_connections) {
  18949. max_active_connections = active_connections;
  18950. }
  18951. if (active_connections > total_connections) {
  18952. total_connections = active_connections;
  18953. }
  18954. /* Connections information */
  18955. mg_snprintf(NULL,
  18956. NULL,
  18957. block,
  18958. sizeof(block),
  18959. ",%s\"connections\" : {%s"
  18960. "\"active\" : %i,%s"
  18961. "\"maxActive\" : %i,%s"
  18962. "\"total\" : %i%s"
  18963. "}",
  18964. eol,
  18965. eol,
  18966. active_connections,
  18967. eol,
  18968. max_active_connections,
  18969. eol,
  18970. total_connections,
  18971. eol);
  18972. context_info_length += mg_str_append(&buffer, end, block);
  18973. /* Queue information */
  18974. #if !defined(ALTERNATIVE_QUEUE)
  18975. mg_snprintf(NULL,
  18976. NULL,
  18977. block,
  18978. sizeof(block),
  18979. ",%s\"queue\" : {%s"
  18980. "\"length\" : %i,%s"
  18981. "\"filled\" : %i,%s"
  18982. "\"maxFilled\" : %i,%s"
  18983. "\"full\" : %s%s"
  18984. "}",
  18985. eol,
  18986. eol,
  18987. ctx->sq_size,
  18988. eol,
  18989. ctx->sq_head - ctx->sq_tail,
  18990. eol,
  18991. ctx->sq_max_fill,
  18992. eol,
  18993. (ctx->sq_blocked ? "true" : "false"),
  18994. eol);
  18995. context_info_length += mg_str_append(&buffer, end, block);
  18996. #endif
  18997. /* Requests information */
  18998. mg_snprintf(NULL,
  18999. NULL,
  19000. block,
  19001. sizeof(block),
  19002. ",%s\"requests\" : {%s"
  19003. "\"total\" : %lu%s"
  19004. "}",
  19005. eol,
  19006. eol,
  19007. (unsigned long)ctx->total_requests,
  19008. eol);
  19009. context_info_length += mg_str_append(&buffer, end, block);
  19010. /* Data information */
  19011. total_data_read =
  19012. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19013. total_data_written =
  19014. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19015. mg_snprintf(NULL,
  19016. NULL,
  19017. block,
  19018. sizeof(block),
  19019. ",%s\"data\" : {%s"
  19020. "\"read\" : %" INT64_FMT ",%s"
  19021. "\"written\" : %" INT64_FMT "%s"
  19022. "}",
  19023. eol,
  19024. eol,
  19025. total_data_read,
  19026. eol,
  19027. total_data_written,
  19028. eol);
  19029. context_info_length += mg_str_append(&buffer, end, block);
  19030. /* Execution time information */
  19031. gmt_time_string(start_time_str,
  19032. sizeof(start_time_str) - 1,
  19033. &start_time);
  19034. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19035. mg_snprintf(NULL,
  19036. NULL,
  19037. block,
  19038. sizeof(block),
  19039. ",%s\"time\" : {%s"
  19040. "\"uptime\" : %.0f,%s"
  19041. "\"start\" : \"%s\",%s"
  19042. "\"now\" : \"%s\"%s"
  19043. "}",
  19044. eol,
  19045. eol,
  19046. difftime(now, start_time),
  19047. eol,
  19048. start_time_str,
  19049. eol,
  19050. now_str,
  19051. eol);
  19052. context_info_length += mg_str_append(&buffer, end, block);
  19053. }
  19054. /* Terminate string */
  19055. if (append_eoobj) {
  19056. strcat(append_eoobj, eoobj);
  19057. }
  19058. context_info_length += sizeof(eoobj) - 1;
  19059. return (int)context_info_length;
  19060. #else
  19061. (void)ctx;
  19062. if ((buffer != NULL) && (buflen > 0)) {
  19063. *buffer = 0;
  19064. }
  19065. return 0;
  19066. #endif
  19067. }
  19068. CIVETWEB_API void
  19069. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19070. {
  19071. /* https://github.com/civetweb/civetweb/issues/727 */
  19072. if (conn != NULL) {
  19073. conn->must_close = 1;
  19074. }
  19075. }
  19076. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19077. /* Get connection information. It can be printed or stored by the caller.
  19078. * Return the size of available information. */
  19079. CIVETWEB_API int
  19080. mg_get_connection_info(const struct mg_context *ctx,
  19081. int idx,
  19082. char *buffer,
  19083. int buflen)
  19084. {
  19085. const struct mg_connection *conn;
  19086. const struct mg_request_info *ri;
  19087. char *end, *append_eoobj = NULL, block[256];
  19088. size_t connection_info_length = 0;
  19089. int state = 0;
  19090. const char *state_str = "unknown";
  19091. #if defined(_WIN32)
  19092. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19093. #else
  19094. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19095. #endif
  19096. if ((buffer == NULL) || (buflen < 1)) {
  19097. buflen = 0;
  19098. end = buffer;
  19099. } else {
  19100. *buffer = 0;
  19101. end = buffer + buflen;
  19102. }
  19103. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19104. /* has enough space to append eoobj */
  19105. append_eoobj = buffer;
  19106. end -= sizeof(eoobj) - 1;
  19107. }
  19108. if ((ctx == NULL) || (idx < 0)) {
  19109. /* Parameter error */
  19110. return 0;
  19111. }
  19112. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  19113. /* Out of range */
  19114. return 0;
  19115. }
  19116. /* Take connection [idx]. This connection is not locked in
  19117. * any way, so some other thread might use it. */
  19118. conn = (ctx->worker_connections) + idx;
  19119. /* Initialize output string */
  19120. connection_info_length += mg_str_append(&buffer, end, "{");
  19121. /* Init variables */
  19122. ri = &(conn->request_info);
  19123. #if defined(USE_SERVER_STATS)
  19124. state = conn->conn_state;
  19125. /* State as string */
  19126. switch (state) {
  19127. case 0:
  19128. state_str = "undefined";
  19129. break;
  19130. case 1:
  19131. state_str = "not used";
  19132. break;
  19133. case 2:
  19134. state_str = "init";
  19135. break;
  19136. case 3:
  19137. state_str = "ready";
  19138. break;
  19139. case 4:
  19140. state_str = "processing";
  19141. break;
  19142. case 5:
  19143. state_str = "processed";
  19144. break;
  19145. case 6:
  19146. state_str = "to close";
  19147. break;
  19148. case 7:
  19149. state_str = "closing";
  19150. break;
  19151. case 8:
  19152. state_str = "closed";
  19153. break;
  19154. case 9:
  19155. state_str = "done";
  19156. break;
  19157. }
  19158. #endif
  19159. /* Connection info */
  19160. if ((state >= 3) && (state < 9)) {
  19161. mg_snprintf(NULL,
  19162. NULL,
  19163. block,
  19164. sizeof(block),
  19165. "%s\"connection\" : {%s"
  19166. "\"remote\" : {%s"
  19167. "\"protocol\" : \"%s\",%s"
  19168. "\"addr\" : \"%s\",%s"
  19169. "\"port\" : %u%s"
  19170. "},%s"
  19171. "\"handled_requests\" : %u%s"
  19172. "}",
  19173. eol,
  19174. eol,
  19175. eol,
  19176. get_proto_name(conn),
  19177. eol,
  19178. ri->remote_addr,
  19179. eol,
  19180. ri->remote_port,
  19181. eol,
  19182. eol,
  19183. conn->handled_requests,
  19184. eol);
  19185. connection_info_length += mg_str_append(&buffer, end, block);
  19186. }
  19187. /* Request info */
  19188. if ((state >= 4) && (state < 6)) {
  19189. mg_snprintf(NULL,
  19190. NULL,
  19191. block,
  19192. sizeof(block),
  19193. "%s%s\"request_info\" : {%s"
  19194. "\"method\" : \"%s\",%s"
  19195. "\"uri\" : \"%s\",%s"
  19196. "\"query\" : %s%s%s%s"
  19197. "}",
  19198. (connection_info_length > 1 ? "," : ""),
  19199. eol,
  19200. eol,
  19201. ri->request_method,
  19202. eol,
  19203. ri->request_uri,
  19204. eol,
  19205. ri->query_string ? "\"" : "",
  19206. ri->query_string ? ri->query_string : "null",
  19207. ri->query_string ? "\"" : "",
  19208. eol);
  19209. connection_info_length += mg_str_append(&buffer, end, block);
  19210. }
  19211. /* Execution time information */
  19212. if ((state >= 2) && (state < 9)) {
  19213. char start_time_str[64] = {0};
  19214. char close_time_str[64] = {0};
  19215. time_t start_time = conn->conn_birth_time;
  19216. time_t close_time = 0;
  19217. double time_diff;
  19218. gmt_time_string(start_time_str,
  19219. sizeof(start_time_str) - 1,
  19220. &start_time);
  19221. #if defined(USE_SERVER_STATS)
  19222. close_time = conn->conn_close_time;
  19223. #endif
  19224. if (close_time != 0) {
  19225. time_diff = difftime(close_time, start_time);
  19226. gmt_time_string(close_time_str,
  19227. sizeof(close_time_str) - 1,
  19228. &close_time);
  19229. } else {
  19230. time_t now = time(NULL);
  19231. time_diff = difftime(now, start_time);
  19232. close_time_str[0] = 0; /* or use "now" ? */
  19233. }
  19234. mg_snprintf(NULL,
  19235. NULL,
  19236. block,
  19237. sizeof(block),
  19238. "%s%s\"time\" : {%s"
  19239. "\"uptime\" : %.0f,%s"
  19240. "\"start\" : \"%s\",%s"
  19241. "\"closed\" : \"%s\"%s"
  19242. "}",
  19243. (connection_info_length > 1 ? "," : ""),
  19244. eol,
  19245. eol,
  19246. time_diff,
  19247. eol,
  19248. start_time_str,
  19249. eol,
  19250. close_time_str,
  19251. eol);
  19252. connection_info_length += mg_str_append(&buffer, end, block);
  19253. }
  19254. /* Remote user name */
  19255. if ((ri->remote_user) && (state < 9)) {
  19256. mg_snprintf(NULL,
  19257. NULL,
  19258. block,
  19259. sizeof(block),
  19260. "%s%s\"user\" : {%s"
  19261. "\"name\" : \"%s\",%s"
  19262. "}",
  19263. (connection_info_length > 1 ? "," : ""),
  19264. eol,
  19265. eol,
  19266. ri->remote_user,
  19267. eol);
  19268. connection_info_length += mg_str_append(&buffer, end, block);
  19269. }
  19270. /* Data block */
  19271. if (state >= 3) {
  19272. mg_snprintf(NULL,
  19273. NULL,
  19274. block,
  19275. sizeof(block),
  19276. "%s%s\"data\" : {%s"
  19277. "\"read\" : %" INT64_FMT ",%s"
  19278. "\"written\" : %" INT64_FMT "%s"
  19279. "}",
  19280. (connection_info_length > 1 ? "," : ""),
  19281. eol,
  19282. eol,
  19283. conn->consumed_content,
  19284. eol,
  19285. conn->num_bytes_sent,
  19286. eol);
  19287. connection_info_length += mg_str_append(&buffer, end, block);
  19288. }
  19289. /* State */
  19290. mg_snprintf(NULL,
  19291. NULL,
  19292. block,
  19293. sizeof(block),
  19294. "%s%s\"state\" : \"%s\"",
  19295. (connection_info_length > 1 ? "," : ""),
  19296. eol,
  19297. state_str);
  19298. connection_info_length += mg_str_append(&buffer, end, block);
  19299. /* Terminate string */
  19300. if (append_eoobj) {
  19301. strcat(append_eoobj, eoobj);
  19302. }
  19303. connection_info_length += sizeof(eoobj) - 1;
  19304. return (int)connection_info_length;
  19305. }
  19306. #if 0
  19307. /* Get handler information. It can be printed or stored by the caller.
  19308. * Return the size of available information. */
  19309. CIVETWEB_API int
  19310. mg_get_handler_info(struct mg_context *ctx,
  19311. char *buffer,
  19312. int buflen)
  19313. {
  19314. int handler_info_len = 0;
  19315. struct mg_handler_info *tmp_rh;
  19316. mg_lock_context(ctx);
  19317. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19318. if (buflen > handler_info_len+ tmp_rh->uri_len) {
  19319. memcpy(buffer+handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19320. }
  19321. handler_info_len += tmp_rh->uri_len;
  19322. switch (tmp_rh->handler_type) {
  19323. case REQUEST_HANDLER:
  19324. (void)tmp_rh->handler;
  19325. break;
  19326. case WEBSOCKET_HANDLER:
  19327. (void)tmp_rh->connect_handler;
  19328. (void) tmp_rh->ready_handler;
  19329. (void) tmp_rh->data_handler;
  19330. (void) tmp_rh->close_handler;
  19331. break;
  19332. case AUTH_HANDLER:
  19333. (void) tmp_rh->auth_handler;
  19334. break;
  19335. }
  19336. (void)cbdata;
  19337. }
  19338. mg_unlock_context(ctx);
  19339. return handler_info_len;
  19340. }
  19341. #endif
  19342. #endif
  19343. /* Initialize this library. This function does not need to be thread safe.
  19344. */
  19345. CIVETWEB_API unsigned
  19346. mg_init_library(unsigned features)
  19347. {
  19348. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19349. unsigned features_inited = features_to_init;
  19350. if (mg_init_library_called <= 0) {
  19351. /* Not initialized yet */
  19352. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19353. return 0;
  19354. }
  19355. }
  19356. mg_global_lock();
  19357. if (mg_init_library_called <= 0) {
  19358. int i, len;
  19359. #if defined(_WIN32)
  19360. int file_mutex_init = 1;
  19361. int wsa = 1;
  19362. #else
  19363. int mutexattr_init = 1;
  19364. #endif
  19365. int failed = 1;
  19366. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19367. if (key_create == 0) {
  19368. #if defined(_WIN32)
  19369. file_mutex_init =
  19370. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19371. if (file_mutex_init == 0) {
  19372. /* Start WinSock */
  19373. WSADATA data;
  19374. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19375. }
  19376. #else
  19377. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19378. if (mutexattr_init == 0) {
  19379. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19380. PTHREAD_MUTEX_RECURSIVE);
  19381. }
  19382. #endif
  19383. }
  19384. if (failed) {
  19385. #if defined(_WIN32)
  19386. if (wsa == 0) {
  19387. (void)WSACleanup();
  19388. }
  19389. if (file_mutex_init == 0) {
  19390. (void)pthread_mutex_destroy(&global_log_file_lock);
  19391. }
  19392. #else
  19393. if (mutexattr_init == 0) {
  19394. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19395. }
  19396. #endif
  19397. if (key_create == 0) {
  19398. (void)pthread_key_delete(sTlsKey);
  19399. }
  19400. mg_global_unlock();
  19401. (void)pthread_mutex_destroy(&global_lock_mutex);
  19402. return 0;
  19403. }
  19404. len = 1;
  19405. for (i = 0; http_methods[i].name != NULL; i++) {
  19406. size_t sl = strlen(http_methods[i].name);
  19407. len += (int)sl;
  19408. if (i > 0) {
  19409. len += 2;
  19410. }
  19411. }
  19412. all_methods = mg_malloc(len);
  19413. if (!all_methods) {
  19414. /* Must never happen */
  19415. mg_global_unlock();
  19416. (void)pthread_mutex_destroy(&global_lock_mutex);
  19417. return 0;
  19418. }
  19419. all_methods[0] = 0;
  19420. for (i = 0; http_methods[i].name != NULL; i++) {
  19421. if (i > 0) {
  19422. strcat(all_methods, ", ");
  19423. strcat(all_methods, http_methods[i].name);
  19424. } else {
  19425. strcpy(all_methods, http_methods[i].name);
  19426. }
  19427. }
  19428. }
  19429. #if defined(USE_LUA)
  19430. lua_init_optional_libraries();
  19431. #endif
  19432. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19433. || defined(OPENSSL_API_3_0)) \
  19434. && !defined(NO_SSL)
  19435. if (features_to_init & MG_FEATURES_SSL) {
  19436. if (!mg_openssl_initialized) {
  19437. char ebuf[128];
  19438. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19439. mg_openssl_initialized = 1;
  19440. } else {
  19441. (void)ebuf;
  19442. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19443. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19444. }
  19445. } else {
  19446. /* ssl already initialized */
  19447. }
  19448. }
  19449. #endif
  19450. if (mg_init_library_called <= 0) {
  19451. mg_init_library_called = 1;
  19452. } else {
  19453. mg_init_library_called++;
  19454. }
  19455. mg_global_unlock();
  19456. return features_inited;
  19457. }
  19458. /* Un-initialize this library. */
  19459. CIVETWEB_API unsigned
  19460. mg_exit_library(void)
  19461. {
  19462. if (mg_init_library_called <= 0) {
  19463. return 0;
  19464. }
  19465. mg_global_lock();
  19466. mg_init_library_called--;
  19467. if (mg_init_library_called == 0) {
  19468. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19469. if (mg_openssl_initialized) {
  19470. uninitialize_openssl();
  19471. mg_openssl_initialized = 0;
  19472. }
  19473. #endif
  19474. #if defined(_WIN32)
  19475. (void)WSACleanup();
  19476. (void)pthread_mutex_destroy(&global_log_file_lock);
  19477. #else
  19478. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19479. #endif
  19480. (void)pthread_key_delete(sTlsKey);
  19481. #if defined(USE_LUA)
  19482. lua_exit_optional_libraries();
  19483. #endif
  19484. mg_free(all_methods);
  19485. all_methods = NULL;
  19486. mg_global_unlock();
  19487. (void)pthread_mutex_destroy(&global_lock_mutex);
  19488. return 1;
  19489. }
  19490. mg_global_unlock();
  19491. return 1;
  19492. }
  19493. /* End of civetweb.c */