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__) /* Apple OSX section */
  305. #if defined(__clang__)
  306. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  307. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  308. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  309. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  310. #endif
  311. #endif
  312. #ifndef CLOCK_MONOTONIC
  313. #define CLOCK_MONOTONIC (1)
  314. #endif
  315. #ifndef CLOCK_REALTIME
  316. #define CLOCK_REALTIME (2)
  317. #endif
  318. #include <mach/clock.h>
  319. #include <mach/mach.h>
  320. #include <mach/mach_time.h>
  321. #include <sys/errno.h>
  322. #include <sys/time.h>
  323. /* clock_gettime is not implemented on OSX prior to 10.12 */
  324. static int
  325. _civet_clock_gettime(int clk_id, struct timespec *t)
  326. {
  327. memset(t, 0, sizeof(*t));
  328. if (clk_id == CLOCK_REALTIME) {
  329. struct timeval now;
  330. int rv = gettimeofday(&now, NULL);
  331. if (rv) {
  332. return rv;
  333. }
  334. t->tv_sec = now.tv_sec;
  335. t->tv_nsec = now.tv_usec * 1000;
  336. return 0;
  337. } else if (clk_id == CLOCK_MONOTONIC) {
  338. static uint64_t clock_start_time = 0;
  339. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  340. uint64_t now = mach_absolute_time();
  341. if (clock_start_time == 0) {
  342. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  343. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  344. /* appease "unused variable" warning for release builds */
  345. (void)mach_status;
  346. clock_start_time = now;
  347. }
  348. now = (uint64_t)((double)(now - clock_start_time)
  349. * (double)timebase_ifo.numer
  350. / (double)timebase_ifo.denom);
  351. t->tv_sec = now / 1000000000;
  352. t->tv_nsec = now % 1000000000;
  353. return 0;
  354. }
  355. return -1; /* EINVAL - Clock ID is unknown */
  356. }
  357. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  358. #if defined(__CLOCK_AVAILABILITY)
  359. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  360. * declared but it may be NULL at runtime. So we need to check before using
  361. * it. */
  362. static int
  363. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  364. {
  365. if (clock_gettime) {
  366. return clock_gettime(clk_id, t);
  367. }
  368. return _civet_clock_gettime(clk_id, t);
  369. }
  370. #define clock_gettime _civet_safe_clock_gettime
  371. #else
  372. #define clock_gettime _civet_clock_gettime
  373. #endif
  374. #endif
  375. #if !defined(_WIN32)
  376. /* Unix might return different error codes indicating to try again.
  377. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  378. * decades ago, but better check both and let the compile optimize it. */
  379. #define ERROR_TRY_AGAIN(err) \
  380. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  381. #endif
  382. #if defined(USE_ZLIB)
  383. #include "zconf.h"
  384. #include "zlib.h"
  385. #endif
  386. /********************************************************************/
  387. /* CivetWeb configuration defines */
  388. /********************************************************************/
  389. /* Maximum number of threads that can be configured.
  390. * The number of threads actually created depends on the "num_threads"
  391. * configuration parameter, but this is the upper limit. */
  392. #if !defined(MAX_WORKER_THREADS)
  393. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  394. #endif
  395. /* Timeout interval for select/poll calls.
  396. * The timeouts depend on "*_timeout_ms" configuration values, but long
  397. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  398. * This reduces the time required to stop the server. */
  399. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  400. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  401. #endif
  402. /* Do not try to compress files smaller than this limit. */
  403. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  404. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  405. #endif
  406. #if !defined(PASSWORDS_FILE_NAME)
  407. #define PASSWORDS_FILE_NAME ".htpasswd"
  408. #endif
  409. /* Initial buffer size for all CGI environment variables. In case there is
  410. * not enough space, another block is allocated. */
  411. #if !defined(CGI_ENVIRONMENT_SIZE)
  412. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  413. #endif
  414. /* Maximum number of environment variables. */
  415. #if !defined(MAX_CGI_ENVIR_VARS)
  416. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  417. #endif
  418. /* General purpose buffer size. */
  419. #if !defined(MG_BUF_LEN) /* in bytes */
  420. #define MG_BUF_LEN (1024 * 8)
  421. #endif
  422. /********************************************************************/
  423. /* Helper makros */
  424. #if !defined(ARRAY_SIZE)
  425. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  426. #endif
  427. #include <stdint.h>
  428. /* Standard defines */
  429. #if !defined(INT64_MAX)
  430. #define INT64_MAX (9223372036854775807)
  431. #endif
  432. #define SHUTDOWN_RD (0)
  433. #define SHUTDOWN_WR (1)
  434. #define SHUTDOWN_BOTH (2)
  435. mg_static_assert(MAX_WORKER_THREADS >= 1,
  436. "worker threads must be a positive number");
  437. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  438. "size_t data type size check");
  439. #if defined(_WIN32) /* WINDOWS include block */
  440. #include <malloc.h> /* *alloc( */
  441. #include <stdlib.h> /* *alloc( */
  442. #include <time.h> /* struct timespec */
  443. #include <windows.h>
  444. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  445. #include <ws2tcpip.h>
  446. typedef const char *SOCK_OPT_TYPE;
  447. /* For a detailed description of these *_PATH_MAX defines, see
  448. * https://github.com/civetweb/civetweb/issues/937. */
  449. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  450. * null termination, rounded up to the next 4 bytes boundary */
  451. #define UTF8_PATH_MAX (3 * 260)
  452. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  453. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  454. #define UTF16_PATH_MAX (260)
  455. #if !defined(_IN_PORT_T)
  456. #if !defined(in_port_t)
  457. #define in_port_t u_short
  458. #endif
  459. #endif
  460. #if defined(_WIN32_WCE)
  461. #error "WinCE support has ended"
  462. #endif
  463. #include <direct.h>
  464. #include <io.h>
  465. #include <process.h>
  466. #define MAKEUQUAD(lo, hi) \
  467. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  468. #define RATE_DIFF (10000000) /* 100 nsecs */
  469. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  470. #define SYS2UNIX_TIME(lo, hi) \
  471. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  472. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  473. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  474. * Also use _strtoui64 on modern M$ compilers */
  475. #if defined(_MSC_VER)
  476. #if (_MSC_VER < 1300)
  477. #define STRX(x) #x
  478. #define STR(x) STRX(x)
  479. #define __func__ __FILE__ ":" STR(__LINE__)
  480. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  481. #define strtoll(x, y, z) (_atoi64(x))
  482. #else
  483. #define __func__ __FUNCTION__
  484. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  485. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  486. #endif
  487. #endif /* _MSC_VER */
  488. #define ERRNO ((int)(GetLastError()))
  489. #define NO_SOCKLEN_T
  490. #if defined(_WIN64) || defined(__MINGW64__)
  491. #if !defined(SSL_LIB)
  492. #if defined(OPENSSL_API_3_0)
  493. #define SSL_LIB "libssl-3-x64.dll"
  494. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  495. #endif
  496. #if defined(OPENSSL_API_1_1)
  497. #define SSL_LIB "libssl-1_1-x64.dll"
  498. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  499. #endif /* OPENSSL_API_1_1 */
  500. #if defined(OPENSSL_API_1_0)
  501. #define SSL_LIB "ssleay64.dll"
  502. #define CRYPTO_LIB "libeay64.dll"
  503. #endif /* OPENSSL_API_1_0 */
  504. #endif
  505. #else /* defined(_WIN64) || defined(__MINGW64__) */
  506. #if !defined(SSL_LIB)
  507. #if defined(OPENSSL_API_3_0)
  508. #define SSL_LIB "libssl-3.dll"
  509. #define CRYPTO_LIB "libcrypto-3.dll"
  510. #endif
  511. #if defined(OPENSSL_API_1_1)
  512. #define SSL_LIB "libssl-1_1.dll"
  513. #define CRYPTO_LIB "libcrypto-1_1.dll"
  514. #endif /* OPENSSL_API_1_1 */
  515. #if defined(OPENSSL_API_1_0)
  516. #define SSL_LIB "ssleay32.dll"
  517. #define CRYPTO_LIB "libeay32.dll"
  518. #endif /* OPENSSL_API_1_0 */
  519. #endif /* SSL_LIB */
  520. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  521. #define O_NONBLOCK (0)
  522. #if !defined(W_OK)
  523. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  524. #endif
  525. #define _POSIX_
  526. #define INT64_FMT "I64d"
  527. #define UINT64_FMT "I64u"
  528. #define WINCDECL __cdecl
  529. #define vsnprintf_impl _vsnprintf
  530. #define access _access
  531. #define mg_sleep(x) (Sleep(x))
  532. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  533. #if !defined(popen)
  534. #define popen(x, y) (_popen(x, y))
  535. #endif
  536. #if !defined(pclose)
  537. #define pclose(x) (_pclose(x))
  538. #endif
  539. #define close(x) (_close(x))
  540. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  541. #define RTLD_LAZY (0)
  542. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  543. #define fdopen(x, y) (_fdopen((x), (y)))
  544. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  545. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  546. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  547. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  548. #define sleep(x) (Sleep((x)*1000))
  549. #define rmdir(x) (_rmdir(x))
  550. #if defined(_WIN64) || !defined(__MINGW32__)
  551. /* Only MinGW 32 bit is missing this function */
  552. #define timegm(x) (_mkgmtime(x))
  553. #else
  554. time_t timegm(struct tm *tm);
  555. #define NEED_TIMEGM
  556. #endif
  557. #if !defined(fileno)
  558. #define fileno(x) (_fileno(x))
  559. #endif /* !fileno MINGW #defines fileno */
  560. typedef struct {
  561. CRITICAL_SECTION sec; /* Immovable */
  562. } pthread_mutex_t;
  563. typedef DWORD pthread_key_t;
  564. typedef HANDLE pthread_t;
  565. typedef struct {
  566. pthread_mutex_t threadIdSec;
  567. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  568. } pthread_cond_t;
  569. #if !defined(__clockid_t_defined)
  570. typedef DWORD clockid_t;
  571. #endif
  572. #if !defined(CLOCK_MONOTONIC)
  573. #define CLOCK_MONOTONIC (1)
  574. #endif
  575. #if !defined(CLOCK_REALTIME)
  576. #define CLOCK_REALTIME (2)
  577. #endif
  578. #if !defined(CLOCK_THREAD)
  579. #define CLOCK_THREAD (3)
  580. #endif
  581. #if !defined(CLOCK_PROCESS)
  582. #define CLOCK_PROCESS (4)
  583. #endif
  584. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  585. #define _TIMESPEC_DEFINED
  586. #endif
  587. #if !defined(_TIMESPEC_DEFINED)
  588. struct timespec {
  589. time_t tv_sec; /* seconds */
  590. long tv_nsec; /* nanoseconds */
  591. };
  592. #endif
  593. #if !defined(WIN_PTHREADS_TIME_H)
  594. #define MUST_IMPLEMENT_CLOCK_GETTIME
  595. #endif
  596. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  597. #define clock_gettime mg_clock_gettime
  598. static int
  599. clock_gettime(clockid_t clk_id, struct timespec *tp)
  600. {
  601. FILETIME ft;
  602. ULARGE_INTEGER li, li2;
  603. BOOL ok = FALSE;
  604. double d;
  605. static double perfcnt_per_sec = 0.0;
  606. static BOOL initialized = FALSE;
  607. if (!initialized) {
  608. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  609. perfcnt_per_sec = 1.0 / li.QuadPart;
  610. initialized = TRUE;
  611. }
  612. if (tp) {
  613. memset(tp, 0, sizeof(*tp));
  614. if (clk_id == CLOCK_REALTIME) {
  615. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  616. GetSystemTimeAsFileTime(&ft);
  617. li.LowPart = ft.dwLowDateTime;
  618. li.HighPart = ft.dwHighDateTime;
  619. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  620. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  621. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  622. ok = TRUE;
  623. /* END: CLOCK_REALTIME */
  624. } else if (clk_id == CLOCK_MONOTONIC) {
  625. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  626. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  627. d = li.QuadPart * perfcnt_per_sec;
  628. tp->tv_sec = (time_t)d;
  629. d -= (double)tp->tv_sec;
  630. tp->tv_nsec = (long)(d * 1.0E9);
  631. ok = TRUE;
  632. /* END: CLOCK_MONOTONIC */
  633. } else if (clk_id == CLOCK_THREAD) {
  634. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  635. FILETIME t_create, t_exit, t_kernel, t_user;
  636. if (GetThreadTimes(GetCurrentThread(),
  637. &t_create,
  638. &t_exit,
  639. &t_kernel,
  640. &t_user)) {
  641. li.LowPart = t_user.dwLowDateTime;
  642. li.HighPart = t_user.dwHighDateTime;
  643. li2.LowPart = t_kernel.dwLowDateTime;
  644. li2.HighPart = t_kernel.dwHighDateTime;
  645. li.QuadPart += li2.QuadPart;
  646. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  647. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  648. ok = TRUE;
  649. }
  650. /* END: CLOCK_THREAD */
  651. } else if (clk_id == CLOCK_PROCESS) {
  652. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  653. FILETIME t_create, t_exit, t_kernel, t_user;
  654. if (GetProcessTimes(GetCurrentProcess(),
  655. &t_create,
  656. &t_exit,
  657. &t_kernel,
  658. &t_user)) {
  659. li.LowPart = t_user.dwLowDateTime;
  660. li.HighPart = t_user.dwHighDateTime;
  661. li2.LowPart = t_kernel.dwLowDateTime;
  662. li2.HighPart = t_kernel.dwHighDateTime;
  663. li.QuadPart += li2.QuadPart;
  664. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  665. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  666. ok = TRUE;
  667. }
  668. /* END: CLOCK_PROCESS */
  669. } else {
  670. /* BEGIN: unknown clock */
  671. /* ok = FALSE; already set by init */
  672. /* END: unknown clock */
  673. }
  674. }
  675. return ok ? 0 : -1;
  676. }
  677. #endif
  678. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  679. static int pthread_mutex_lock(pthread_mutex_t *);
  680. static int pthread_mutex_unlock(pthread_mutex_t *);
  681. static void path_to_unicode(const struct mg_connection *conn,
  682. const char *path,
  683. wchar_t *wbuf,
  684. size_t wbuf_len);
  685. /* All file operations need to be rewritten to solve #246. */
  686. struct mg_file;
  687. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  688. /* POSIX dirent interface */
  689. struct dirent {
  690. char d_name[UTF8_PATH_MAX];
  691. };
  692. typedef struct DIR {
  693. HANDLE handle;
  694. WIN32_FIND_DATAW info;
  695. struct dirent result;
  696. } DIR;
  697. #if defined(HAVE_POLL)
  698. #define mg_pollfd pollfd
  699. #else
  700. struct mg_pollfd {
  701. SOCKET fd;
  702. short events;
  703. short revents;
  704. };
  705. #endif
  706. /* Mark required libraries */
  707. #if defined(_MSC_VER)
  708. #pragma comment(lib, "Ws2_32.lib")
  709. #endif
  710. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  711. #include <inttypes.h>
  712. /* Linux & co. internally use UTF8 */
  713. #define UTF8_PATH_MAX (PATH_MAX)
  714. typedef const void *SOCK_OPT_TYPE;
  715. #if defined(ANDROID)
  716. typedef unsigned short int in_port_t;
  717. #endif
  718. #if !defined(__ZEPHYR__)
  719. #include <arpa/inet.h>
  720. #include <ctype.h>
  721. #include <dirent.h>
  722. #include <grp.h>
  723. #include <limits.h>
  724. #include <netdb.h>
  725. #include <netinet/in.h>
  726. #include <netinet/tcp.h>
  727. #include <pthread.h>
  728. #include <pwd.h>
  729. #include <stdarg.h>
  730. #include <stddef.h>
  731. #include <stdio.h>
  732. #include <stdlib.h>
  733. #include <string.h>
  734. #include <sys/poll.h>
  735. #include <sys/socket.h>
  736. #include <sys/time.h>
  737. #include <sys/utsname.h>
  738. #include <sys/wait.h>
  739. #include <time.h>
  740. #include <unistd.h>
  741. #if defined(USE_X_DOM_SOCKET)
  742. #include <sys/un.h>
  743. #endif
  744. #endif
  745. #define vsnprintf_impl vsnprintf
  746. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  747. #include <dlfcn.h>
  748. #endif
  749. #if defined(__MACH__)
  750. #define SSL_LIB "libssl.dylib"
  751. #define CRYPTO_LIB "libcrypto.dylib"
  752. #else
  753. #if !defined(SSL_LIB)
  754. #define SSL_LIB "libssl.so"
  755. #endif
  756. #if !defined(CRYPTO_LIB)
  757. #define CRYPTO_LIB "libcrypto.so"
  758. #endif
  759. #endif
  760. #if !defined(O_BINARY)
  761. #define O_BINARY (0)
  762. #endif /* O_BINARY */
  763. #define closesocket(a) (close(a))
  764. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  765. #define mg_remove(conn, x) (remove(x))
  766. #define mg_sleep(x) (usleep((x)*1000))
  767. #define mg_opendir(conn, x) (opendir(x))
  768. #define mg_closedir(x) (closedir(x))
  769. #define mg_readdir(x) (readdir(x))
  770. #define ERRNO (errno)
  771. #define INVALID_SOCKET (-1)
  772. #define INT64_FMT PRId64
  773. #define UINT64_FMT PRIu64
  774. typedef int SOCKET;
  775. #define WINCDECL
  776. #if defined(__hpux)
  777. /* HPUX 11 does not have monotonic, fall back to realtime */
  778. #if !defined(CLOCK_MONOTONIC)
  779. #define CLOCK_MONOTONIC CLOCK_REALTIME
  780. #endif
  781. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  782. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  783. * the prototypes use int* rather than socklen_t* which matches the
  784. * actual library expectation. When called with the wrong size arg
  785. * accept() returns a zero client inet addr and check_acl() always
  786. * fails. Since socklen_t is widely used below, just force replace
  787. * their typedef with int. - DTL
  788. */
  789. #define socklen_t int
  790. #endif /* hpux */
  791. #define mg_pollfd pollfd
  792. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  793. /* In case our C library is missing "timegm", provide an implementation */
  794. #if defined(NEED_TIMEGM)
  795. static inline int
  796. is_leap(int y)
  797. {
  798. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  799. }
  800. static inline int
  801. count_leap(int y)
  802. {
  803. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  804. }
  805. time_t
  806. timegm(struct tm *tm)
  807. {
  808. static const unsigned short ydays[] = {
  809. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  810. int year = tm->tm_year + 1900;
  811. int mon = tm->tm_mon;
  812. int mday = tm->tm_mday - 1;
  813. int hour = tm->tm_hour;
  814. int min = tm->tm_min;
  815. int sec = tm->tm_sec;
  816. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  817. || (mday >= ydays[mon + 1] - ydays[mon]
  818. + (mon == 1 && is_leap(year) ? 1 : 0))
  819. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  820. return -1;
  821. time_t res = year - 1970;
  822. res *= 365;
  823. res += mday;
  824. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  825. res += count_leap(year);
  826. res *= 24;
  827. res += hour;
  828. res *= 60;
  829. res += min;
  830. res *= 60;
  831. res += sec;
  832. return res;
  833. }
  834. #endif /* NEED_TIMEGM */
  835. /* va_copy should always be a macro, C99 and C++11 - DTL */
  836. #if !defined(va_copy)
  837. #define va_copy(x, y) ((x) = (y))
  838. #endif
  839. #if defined(_WIN32)
  840. /* Create substitutes for POSIX functions in Win32. */
  841. #if defined(GCC_DIAGNOSTIC)
  842. /* Show no warning in case system functions are not used. */
  843. #pragma GCC diagnostic push
  844. #pragma GCC diagnostic ignored "-Wunused-function"
  845. #endif
  846. static pthread_mutex_t global_log_file_lock;
  847. FUNCTION_MAY_BE_UNUSED
  848. static DWORD
  849. pthread_self(void)
  850. {
  851. return GetCurrentThreadId();
  852. }
  853. FUNCTION_MAY_BE_UNUSED
  854. static int
  855. pthread_key_create(
  856. pthread_key_t *key,
  857. void (*_ignored)(void *) /* destructor not supported for Windows */
  858. )
  859. {
  860. (void)_ignored;
  861. if ((key != 0)) {
  862. *key = TlsAlloc();
  863. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  864. }
  865. return -2;
  866. }
  867. FUNCTION_MAY_BE_UNUSED
  868. static int
  869. pthread_key_delete(pthread_key_t key)
  870. {
  871. return TlsFree(key) ? 0 : 1;
  872. }
  873. FUNCTION_MAY_BE_UNUSED
  874. static int
  875. pthread_setspecific(pthread_key_t key, void *value)
  876. {
  877. return TlsSetValue(key, value) ? 0 : 1;
  878. }
  879. FUNCTION_MAY_BE_UNUSED
  880. static void *
  881. pthread_getspecific(pthread_key_t key)
  882. {
  883. return TlsGetValue(key);
  884. }
  885. #if defined(GCC_DIAGNOSTIC)
  886. /* Enable unused function warning again */
  887. #pragma GCC diagnostic pop
  888. #endif
  889. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  890. #else
  891. static pthread_mutexattr_t pthread_mutex_attr;
  892. #endif /* _WIN32 */
  893. #if defined(GCC_DIAGNOSTIC)
  894. /* Show no warning in case system functions are not used. */
  895. #pragma GCC diagnostic push
  896. #pragma GCC diagnostic ignored "-Wunused-function"
  897. #endif /* defined(GCC_DIAGNOSTIC) */
  898. #if defined(__clang__)
  899. /* Show no warning in case system functions are not used. */
  900. #pragma clang diagnostic push
  901. #pragma clang diagnostic ignored "-Wunused-function"
  902. #endif
  903. static pthread_mutex_t global_lock_mutex;
  904. FUNCTION_MAY_BE_UNUSED
  905. static void
  906. mg_global_lock(void)
  907. {
  908. (void)pthread_mutex_lock(&global_lock_mutex);
  909. }
  910. FUNCTION_MAY_BE_UNUSED
  911. static void
  912. mg_global_unlock(void)
  913. {
  914. (void)pthread_mutex_unlock(&global_lock_mutex);
  915. }
  916. #if defined(_WIN64)
  917. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  918. #elif defined(_WIN32)
  919. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  920. #endif
  921. /* Atomic functions working on ptrdiff_t ("signed size_t").
  922. * Operations: Increment, Decrement, Add, Maximum.
  923. * Up to size_t, they do not an atomic "load" operation.
  924. */
  925. FUNCTION_MAY_BE_UNUSED
  926. static ptrdiff_t
  927. mg_atomic_inc(volatile ptrdiff_t *addr)
  928. {
  929. ptrdiff_t ret;
  930. #if defined(_WIN64) && !defined(NO_ATOMICS)
  931. ret = InterlockedIncrement64(addr);
  932. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  933. ret = InterlockedIncrement(addr);
  934. #elif defined(__GNUC__) \
  935. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  936. && !defined(NO_ATOMICS)
  937. ret = __sync_add_and_fetch(addr, 1);
  938. #else
  939. mg_global_lock();
  940. ret = (++(*addr));
  941. mg_global_unlock();
  942. #endif
  943. return ret;
  944. }
  945. FUNCTION_MAY_BE_UNUSED
  946. static ptrdiff_t
  947. mg_atomic_dec(volatile ptrdiff_t *addr)
  948. {
  949. ptrdiff_t ret;
  950. #if defined(_WIN64) && !defined(NO_ATOMICS)
  951. ret = InterlockedDecrement64(addr);
  952. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  953. ret = InterlockedDecrement(addr);
  954. #elif defined(__GNUC__) \
  955. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  956. && !defined(NO_ATOMICS)
  957. ret = __sync_sub_and_fetch(addr, 1);
  958. #else
  959. mg_global_lock();
  960. ret = (--(*addr));
  961. mg_global_unlock();
  962. #endif
  963. return ret;
  964. }
  965. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  966. static ptrdiff_t
  967. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  968. {
  969. ptrdiff_t ret;
  970. #if defined(_WIN64) && !defined(NO_ATOMICS)
  971. ret = InterlockedAdd64(addr, value);
  972. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  973. ret = InterlockedExchangeAdd(addr, value) + value;
  974. #elif defined(__GNUC__) \
  975. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  976. && !defined(NO_ATOMICS)
  977. ret = __sync_add_and_fetch(addr, value);
  978. #else
  979. mg_global_lock();
  980. *addr += value;
  981. ret = (*addr);
  982. mg_global_unlock();
  983. #endif
  984. return ret;
  985. }
  986. FUNCTION_MAY_BE_UNUSED
  987. static ptrdiff_t
  988. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  989. ptrdiff_t oldval,
  990. ptrdiff_t newval)
  991. {
  992. ptrdiff_t ret;
  993. #if defined(_WIN64) && !defined(NO_ATOMICS)
  994. ret = InterlockedCompareExchange64(addr, newval, oldval);
  995. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  996. ret = InterlockedCompareExchange(addr, newval, oldval);
  997. #elif defined(__GNUC__) \
  998. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  999. && !defined(NO_ATOMICS)
  1000. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1001. #else
  1002. mg_global_lock();
  1003. ret = *addr;
  1004. if ((ret != newval) && (ret == oldval)) {
  1005. *addr = newval;
  1006. }
  1007. mg_global_unlock();
  1008. #endif
  1009. return ret;
  1010. }
  1011. static void
  1012. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1013. {
  1014. register ptrdiff_t tmp = *addr;
  1015. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1016. while (tmp < value) {
  1017. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1018. }
  1019. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1020. while (tmp < value) {
  1021. tmp = InterlockedCompareExchange(addr, value, tmp);
  1022. }
  1023. #elif defined(__GNUC__) \
  1024. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1025. && !defined(NO_ATOMICS)
  1026. while (tmp < value) {
  1027. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1028. }
  1029. #else
  1030. mg_global_lock();
  1031. if (*addr < value) {
  1032. *addr = value;
  1033. }
  1034. mg_global_unlock();
  1035. #endif
  1036. }
  1037. static int64_t
  1038. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1039. {
  1040. int64_t ret;
  1041. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1042. ret = InterlockedAdd64(addr, value);
  1043. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1044. ret = InterlockedExchangeAdd64(addr, value) + value;
  1045. #elif defined(__GNUC__) \
  1046. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1047. && !defined(NO_ATOMICS)
  1048. ret = __sync_add_and_fetch(addr, value);
  1049. #else
  1050. mg_global_lock();
  1051. *addr += value;
  1052. ret = (*addr);
  1053. mg_global_unlock();
  1054. #endif
  1055. return ret;
  1056. }
  1057. #endif
  1058. #if defined(GCC_DIAGNOSTIC)
  1059. /* Show no warning in case system functions are not used. */
  1060. #pragma GCC diagnostic pop
  1061. #endif /* defined(GCC_DIAGNOSTIC) */
  1062. #if defined(__clang__)
  1063. /* Show no warning in case system functions are not used. */
  1064. #pragma clang diagnostic pop
  1065. #endif
  1066. #if defined(USE_SERVER_STATS)
  1067. struct mg_memory_stat {
  1068. volatile ptrdiff_t totalMemUsed;
  1069. volatile ptrdiff_t maxMemUsed;
  1070. volatile ptrdiff_t blockCount;
  1071. };
  1072. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1073. static void *
  1074. mg_malloc_ex(size_t size,
  1075. struct mg_context *ctx,
  1076. const char *file,
  1077. unsigned line)
  1078. {
  1079. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1080. void *memory = 0;
  1081. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1082. #if defined(MEMORY_DEBUGGING)
  1083. char mallocStr[256];
  1084. #else
  1085. (void)file;
  1086. (void)line;
  1087. #endif
  1088. if (data) {
  1089. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1090. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1091. mg_atomic_inc(&mstat->blockCount);
  1092. ((uintptr_t *)data)[0] = size;
  1093. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1094. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1095. }
  1096. #if defined(MEMORY_DEBUGGING)
  1097. sprintf(mallocStr,
  1098. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1099. memory,
  1100. (unsigned long)size,
  1101. (unsigned long)mstat->totalMemUsed,
  1102. (unsigned long)mstat->blockCount,
  1103. file,
  1104. line);
  1105. DEBUG_TRACE("%s", mallocStr);
  1106. #endif
  1107. return memory;
  1108. }
  1109. static void *
  1110. mg_calloc_ex(size_t count,
  1111. size_t size,
  1112. struct mg_context *ctx,
  1113. const char *file,
  1114. unsigned line)
  1115. {
  1116. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1117. if (data) {
  1118. memset(data, 0, size * count);
  1119. }
  1120. return data;
  1121. }
  1122. static void
  1123. mg_free_ex(void *memory, const char *file, unsigned line)
  1124. {
  1125. #if defined(MEMORY_DEBUGGING)
  1126. char mallocStr[256];
  1127. #else
  1128. (void)file;
  1129. (void)line;
  1130. #endif
  1131. if (memory) {
  1132. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1133. uintptr_t size = ((uintptr_t *)data)[0];
  1134. struct mg_memory_stat *mstat =
  1135. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1136. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1137. mg_atomic_dec(&mstat->blockCount);
  1138. #if defined(MEMORY_DEBUGGING)
  1139. sprintf(mallocStr,
  1140. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1141. memory,
  1142. (unsigned long)size,
  1143. (unsigned long)mstat->totalMemUsed,
  1144. (unsigned long)mstat->blockCount,
  1145. file,
  1146. line);
  1147. DEBUG_TRACE("%s", mallocStr);
  1148. #endif
  1149. free(data);
  1150. }
  1151. }
  1152. static void *
  1153. mg_realloc_ex(void *memory,
  1154. size_t newsize,
  1155. struct mg_context *ctx,
  1156. const char *file,
  1157. unsigned line)
  1158. {
  1159. void *data;
  1160. void *_realloc;
  1161. uintptr_t oldsize;
  1162. #if defined(MEMORY_DEBUGGING)
  1163. char mallocStr[256];
  1164. #else
  1165. (void)file;
  1166. (void)line;
  1167. #endif
  1168. if (newsize) {
  1169. if (memory) {
  1170. /* Reallocate existing block */
  1171. struct mg_memory_stat *mstat;
  1172. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1173. oldsize = ((uintptr_t *)data)[0];
  1174. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1175. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1176. if (_realloc) {
  1177. data = _realloc;
  1178. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1179. #if defined(MEMORY_DEBUGGING)
  1180. sprintf(mallocStr,
  1181. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1182. memory,
  1183. (unsigned long)oldsize,
  1184. (unsigned long)mstat->totalMemUsed,
  1185. (unsigned long)mstat->blockCount,
  1186. file,
  1187. line);
  1188. DEBUG_TRACE("%s", mallocStr);
  1189. #endif
  1190. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1191. #if defined(MEMORY_DEBUGGING)
  1192. sprintf(mallocStr,
  1193. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1194. memory,
  1195. (unsigned long)newsize,
  1196. (unsigned long)mstat->totalMemUsed,
  1197. (unsigned long)mstat->blockCount,
  1198. file,
  1199. line);
  1200. DEBUG_TRACE("%s", mallocStr);
  1201. #endif
  1202. *(uintptr_t *)data = newsize;
  1203. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1204. } else {
  1205. #if defined(MEMORY_DEBUGGING)
  1206. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1207. #endif
  1208. return _realloc;
  1209. }
  1210. } else {
  1211. /* Allocate new block */
  1212. data = mg_malloc_ex(newsize, ctx, file, line);
  1213. }
  1214. } else {
  1215. /* Free existing block */
  1216. data = 0;
  1217. mg_free_ex(memory, file, line);
  1218. }
  1219. return data;
  1220. }
  1221. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1222. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1223. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1224. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1225. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1226. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1227. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1228. #else /* USE_SERVER_STATS */
  1229. static __inline void *
  1230. mg_malloc(size_t a)
  1231. {
  1232. return malloc(a);
  1233. }
  1234. static __inline void *
  1235. mg_calloc(size_t a, size_t b)
  1236. {
  1237. return calloc(a, b);
  1238. }
  1239. static __inline void *
  1240. mg_realloc(void *a, size_t b)
  1241. {
  1242. return realloc(a, b);
  1243. }
  1244. static __inline void
  1245. mg_free(void *a)
  1246. {
  1247. free(a);
  1248. }
  1249. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1250. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1251. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1252. #define mg_free_ctx(a, c) mg_free(a)
  1253. #endif /* USE_SERVER_STATS */
  1254. static void mg_vsnprintf(const struct mg_connection *conn,
  1255. int *truncated,
  1256. char *buf,
  1257. size_t buflen,
  1258. const char *fmt,
  1259. va_list ap);
  1260. static void mg_snprintf(const struct mg_connection *conn,
  1261. int *truncated,
  1262. char *buf,
  1263. size_t buflen,
  1264. PRINTF_FORMAT_STRING(const char *fmt),
  1265. ...) PRINTF_ARGS(5, 6);
  1266. /* This following lines are just meant as a reminder to use the mg-functions
  1267. * for memory management */
  1268. #if defined(malloc)
  1269. #undef malloc
  1270. #endif
  1271. #if defined(calloc)
  1272. #undef calloc
  1273. #endif
  1274. #if defined(realloc)
  1275. #undef realloc
  1276. #endif
  1277. #if defined(free)
  1278. #undef free
  1279. #endif
  1280. #if defined(snprintf)
  1281. #undef snprintf
  1282. #endif
  1283. #if defined(vsnprintf)
  1284. #undef vsnprintf
  1285. #endif
  1286. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1287. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1288. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1289. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1290. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1291. #if defined(_WIN32)
  1292. /* vsnprintf must not be used in any system,
  1293. * but this define only works well for Windows. */
  1294. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1295. #endif
  1296. /* mg_init_library counter */
  1297. static int mg_init_library_called = 0;
  1298. #if !defined(NO_SSL)
  1299. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1300. || defined(OPENSSL_API_3_0)
  1301. static int mg_openssl_initialized = 0;
  1302. #endif
  1303. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1304. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1305. #error "Please define OPENSSL_API_#_# 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; /* Procesing 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__)
  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. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2790. buf[len] = 0;
  2791. }
  2792. #endif
  2793. }
  2794. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2795. * included in all responses other than 100, 101, 5xx. */
  2796. static void
  2797. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2798. {
  2799. #if !defined(REENTRANT_TIME)
  2800. struct tm *tm;
  2801. tm = ((t != NULL) ? gmtime(t) : NULL);
  2802. if (tm != NULL) {
  2803. #else
  2804. struct tm _tm;
  2805. struct tm *tm = &_tm;
  2806. if (t != NULL) {
  2807. gmtime_r(t, tm);
  2808. #endif
  2809. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2810. } else {
  2811. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2812. buf[buf_len - 1] = '\0';
  2813. }
  2814. }
  2815. /* difftime for struct timespec. Return value is in seconds. */
  2816. static double
  2817. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2818. {
  2819. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2820. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2821. }
  2822. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2823. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2824. const char *func,
  2825. unsigned line,
  2826. const char *fmt,
  2827. va_list ap);
  2828. #include "external_mg_cry_internal_impl.inl"
  2829. #elif !defined(NO_FILESYSTEMS)
  2830. /* Print error message to the opened error log stream. */
  2831. static void
  2832. mg_cry_internal_impl(const struct mg_connection *conn,
  2833. const char *func,
  2834. unsigned line,
  2835. const char *fmt,
  2836. va_list ap)
  2837. {
  2838. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2839. struct mg_file fi;
  2840. time_t timestamp;
  2841. /* Unused, in the RELEASE build */
  2842. (void)func;
  2843. (void)line;
  2844. #if defined(GCC_DIAGNOSTIC)
  2845. #pragma GCC diagnostic push
  2846. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2847. #endif
  2848. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2849. #if defined(GCC_DIAGNOSTIC)
  2850. #pragma GCC diagnostic pop
  2851. #endif
  2852. buf[sizeof(buf) - 1] = 0;
  2853. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2854. if (!conn) {
  2855. puts(buf);
  2856. return;
  2857. }
  2858. /* Do not lock when getting the callback value, here and below.
  2859. * I suppose this is fine, since function cannot disappear in the
  2860. * same way string option can. */
  2861. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2862. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2863. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2864. if (mg_fopen(conn,
  2865. conn->dom_ctx->config[ERROR_LOG_FILE],
  2866. MG_FOPEN_MODE_APPEND,
  2867. &fi)
  2868. == 0) {
  2869. fi.access.fp = NULL;
  2870. }
  2871. } else {
  2872. fi.access.fp = NULL;
  2873. }
  2874. if (fi.access.fp != NULL) {
  2875. flockfile(fi.access.fp);
  2876. timestamp = time(NULL);
  2877. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2878. fprintf(fi.access.fp,
  2879. "[%010lu] [error] [client %s] ",
  2880. (unsigned long)timestamp,
  2881. src_addr);
  2882. if (conn->request_info.request_method != NULL) {
  2883. fprintf(fi.access.fp,
  2884. "%s %s: ",
  2885. conn->request_info.request_method,
  2886. conn->request_info.request_uri
  2887. ? conn->request_info.request_uri
  2888. : "");
  2889. }
  2890. fprintf(fi.access.fp, "%s", buf);
  2891. fputc('\n', fi.access.fp);
  2892. fflush(fi.access.fp);
  2893. funlockfile(fi.access.fp);
  2894. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2895. * mg_cry here anyway ;-) */
  2896. }
  2897. }
  2898. }
  2899. #else
  2900. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2901. #endif /* Externally provided function */
  2902. /* Construct fake connection structure. Used for logging, if connection
  2903. * is not applicable at the moment of logging. */
  2904. static struct mg_connection *
  2905. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2906. {
  2907. static const struct mg_connection conn_zero = {0};
  2908. *fc = conn_zero;
  2909. fc->phys_ctx = ctx;
  2910. fc->dom_ctx = &(ctx->dd);
  2911. return fc;
  2912. }
  2913. static void
  2914. mg_cry_internal_wrap(const struct mg_connection *conn,
  2915. struct mg_context *ctx,
  2916. const char *func,
  2917. unsigned line,
  2918. const char *fmt,
  2919. ...)
  2920. {
  2921. va_list ap;
  2922. va_start(ap, fmt);
  2923. if (!conn && ctx) {
  2924. struct mg_connection fc;
  2925. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2926. } else {
  2927. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2928. }
  2929. va_end(ap);
  2930. }
  2931. CIVETWEB_API void
  2932. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2933. {
  2934. va_list ap;
  2935. va_start(ap, fmt);
  2936. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2937. va_end(ap);
  2938. }
  2939. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2940. CIVETWEB_API const char *
  2941. mg_version(void)
  2942. {
  2943. return CIVETWEB_VERSION;
  2944. }
  2945. CIVETWEB_API const struct mg_request_info *
  2946. mg_get_request_info(const struct mg_connection *conn)
  2947. {
  2948. if (!conn) {
  2949. return NULL;
  2950. }
  2951. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2952. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2953. char txt[16];
  2954. struct mg_workerTLS *tls =
  2955. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2956. sprintf(txt, "%03i", conn->response_info.status_code);
  2957. if (strlen(txt) == 3) {
  2958. memcpy(tls->txtbuf, txt, 4);
  2959. } else {
  2960. strcpy(tls->txtbuf, "ERR");
  2961. }
  2962. ((struct mg_connection *)conn)->request_info.local_uri =
  2963. tls->txtbuf; /* use thread safe buffer */
  2964. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2965. tls->txtbuf; /* use the same thread safe buffer */
  2966. ((struct mg_connection *)conn)->request_info.request_uri =
  2967. tls->txtbuf; /* use the same thread safe buffer */
  2968. ((struct mg_connection *)conn)->request_info.num_headers =
  2969. conn->response_info.num_headers;
  2970. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2971. conn->response_info.http_headers,
  2972. sizeof(conn->response_info.http_headers));
  2973. } else
  2974. #endif
  2975. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2976. return NULL;
  2977. }
  2978. return &conn->request_info;
  2979. }
  2980. CIVETWEB_API const struct mg_response_info *
  2981. mg_get_response_info(const struct mg_connection *conn)
  2982. {
  2983. if (!conn) {
  2984. return NULL;
  2985. }
  2986. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2987. return NULL;
  2988. }
  2989. return &conn->response_info;
  2990. }
  2991. static const char *
  2992. get_proto_name(const struct mg_connection *conn)
  2993. {
  2994. #if defined(__clang__)
  2995. #pragma clang diagnostic push
  2996. #pragma clang diagnostic ignored "-Wunreachable-code"
  2997. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2998. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2999. * unreachable, but splitting into four different #ifdef clauses here is
  3000. * more complicated.
  3001. */
  3002. #endif
  3003. const struct mg_request_info *ri = &conn->request_info;
  3004. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3005. ? (ri->is_ssl ? "wss" : "ws")
  3006. : (ri->is_ssl ? "https" : "http"));
  3007. return proto;
  3008. #if defined(__clang__)
  3009. #pragma clang diagnostic pop
  3010. #endif
  3011. }
  3012. static int
  3013. mg_construct_local_link(const struct mg_connection *conn,
  3014. char *buf,
  3015. size_t buflen,
  3016. const char *define_proto,
  3017. int define_port,
  3018. const char *define_uri)
  3019. {
  3020. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3021. return -1;
  3022. } else {
  3023. int i, j;
  3024. int truncated = 0;
  3025. const struct mg_request_info *ri = &conn->request_info;
  3026. const char *proto =
  3027. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3028. const char *uri =
  3029. (define_uri != NULL)
  3030. ? define_uri
  3031. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3032. int port = (define_port > 0) ? define_port : ri->server_port;
  3033. int default_port = 80;
  3034. char *uri_encoded;
  3035. size_t uri_encoded_len;
  3036. if (uri == NULL) {
  3037. return -1;
  3038. }
  3039. uri_encoded_len = strlen(uri) * 3 + 1;
  3040. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3041. if (uri_encoded == NULL) {
  3042. return -1;
  3043. }
  3044. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3045. /* Directory separator should be preserved. */
  3046. for (i = j = 0; uri_encoded[i]; j++) {
  3047. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3048. uri_encoded[j] = '/';
  3049. i += 3;
  3050. } else {
  3051. uri_encoded[j] = uri_encoded[i++];
  3052. }
  3053. }
  3054. uri_encoded[j] = '\0';
  3055. #if defined(USE_X_DOM_SOCKET)
  3056. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3057. /* TODO: Define and document a link for UNIX domain sockets. */
  3058. /* There seems to be no official standard for this.
  3059. * Common uses seem to be "httpunix://", "http.unix://" or
  3060. * "http+unix://" as a protocol definition string, followed by
  3061. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3062. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3063. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3064. * "" (completely skipping the server name part). In any case, the
  3065. * last part is the server local path. */
  3066. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3067. mg_snprintf(conn,
  3068. &truncated,
  3069. buf,
  3070. buflen,
  3071. "%s.unix://%s%s",
  3072. proto,
  3073. server_name,
  3074. ri->local_uri);
  3075. default_port = 0;
  3076. mg_free(uri_encoded);
  3077. return 0;
  3078. }
  3079. #endif
  3080. if (define_proto) {
  3081. /* If we got a protocol name, use the default port accordingly. */
  3082. if ((0 == strcmp(define_proto, "https"))
  3083. || (0 == strcmp(define_proto, "wss"))) {
  3084. default_port = 443;
  3085. }
  3086. } else if (ri->is_ssl) {
  3087. /* If we did not get a protocol name, use TLS as default if it is
  3088. * already used. */
  3089. default_port = 443;
  3090. }
  3091. {
  3092. #if defined(USE_IPV6)
  3093. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3094. #endif
  3095. int auth_domain_check_enabled =
  3096. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3097. && (!mg_strcasecmp(
  3098. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3099. const char *server_domain =
  3100. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3101. char portstr[16];
  3102. char server_ip[48];
  3103. if (port != default_port) {
  3104. sprintf(portstr, ":%u", (unsigned)port);
  3105. } else {
  3106. portstr[0] = 0;
  3107. }
  3108. if (!auth_domain_check_enabled || !server_domain) {
  3109. sockaddr_to_string(server_ip,
  3110. sizeof(server_ip),
  3111. &conn->client.lsa);
  3112. server_domain = server_ip;
  3113. }
  3114. mg_snprintf(conn,
  3115. &truncated,
  3116. buf,
  3117. buflen,
  3118. #if defined(USE_IPV6)
  3119. "%s://%s%s%s%s%s",
  3120. proto,
  3121. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3122. server_domain,
  3123. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3124. #else
  3125. "%s://%s%s%s",
  3126. proto,
  3127. server_domain,
  3128. #endif
  3129. portstr,
  3130. uri_encoded);
  3131. mg_free(uri_encoded);
  3132. if (truncated) {
  3133. return -1;
  3134. }
  3135. return 0;
  3136. }
  3137. }
  3138. }
  3139. CIVETWEB_API int
  3140. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3141. {
  3142. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3143. }
  3144. /* Skip the characters until one of the delimiters characters found.
  3145. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3146. * Advance pointer to buffer to the next word. Return found 0-terminated
  3147. * word.
  3148. * Delimiters can be quoted with quotechar. */
  3149. static char *
  3150. skip_quoted(char **buf,
  3151. const char *delimiters,
  3152. const char *whitespace,
  3153. char quotechar)
  3154. {
  3155. char *p, *begin_word, *end_word, *end_whitespace;
  3156. begin_word = *buf;
  3157. end_word = begin_word + strcspn(begin_word, delimiters);
  3158. /* Check for quotechar */
  3159. if (end_word > begin_word) {
  3160. p = end_word - 1;
  3161. while (*p == quotechar) {
  3162. /* While the delimiter is quoted, look for the next delimiter. */
  3163. /* This happens, e.g., in calls from parse_auth_header,
  3164. * if the user name contains a " character. */
  3165. /* If there is anything beyond end_word, copy it. */
  3166. if (*end_word != '\0') {
  3167. size_t end_off = strcspn(end_word + 1, delimiters);
  3168. memmove(p, end_word, end_off + 1);
  3169. p += end_off; /* p must correspond to end_word - 1 */
  3170. end_word += end_off + 1;
  3171. } else {
  3172. *p = '\0';
  3173. break;
  3174. }
  3175. }
  3176. for (p++; p < end_word; p++) {
  3177. *p = '\0';
  3178. }
  3179. }
  3180. if (*end_word == '\0') {
  3181. *buf = end_word;
  3182. } else {
  3183. #if defined(GCC_DIAGNOSTIC)
  3184. /* Disable spurious conversion warning for GCC */
  3185. #pragma GCC diagnostic push
  3186. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3187. #endif /* defined(GCC_DIAGNOSTIC) */
  3188. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3189. #if defined(GCC_DIAGNOSTIC)
  3190. #pragma GCC diagnostic pop
  3191. #endif /* defined(GCC_DIAGNOSTIC) */
  3192. for (p = end_word; p < end_whitespace; p++) {
  3193. *p = '\0';
  3194. }
  3195. *buf = end_whitespace;
  3196. }
  3197. return begin_word;
  3198. }
  3199. /* Return HTTP header value, or NULL if not found. */
  3200. static const char *
  3201. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3202. {
  3203. int i;
  3204. for (i = 0; i < num_hdr; i++) {
  3205. if (!mg_strcasecmp(name, hdr[i].name)) {
  3206. return hdr[i].value;
  3207. }
  3208. }
  3209. return NULL;
  3210. }
  3211. /* Retrieve requested HTTP header multiple values, and return the number of
  3212. * found occurrences */
  3213. static int
  3214. get_req_headers(const struct mg_request_info *ri,
  3215. const char *name,
  3216. const char **output,
  3217. int output_max_size)
  3218. {
  3219. int i;
  3220. int cnt = 0;
  3221. if (ri) {
  3222. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3223. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3224. output[cnt++] = ri->http_headers[i].value;
  3225. }
  3226. }
  3227. }
  3228. return cnt;
  3229. }
  3230. CIVETWEB_API const char *
  3231. mg_get_header(const struct mg_connection *conn, const char *name)
  3232. {
  3233. if (!conn) {
  3234. return NULL;
  3235. }
  3236. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3237. return get_header(conn->request_info.http_headers,
  3238. conn->request_info.num_headers,
  3239. name);
  3240. }
  3241. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3242. return get_header(conn->response_info.http_headers,
  3243. conn->response_info.num_headers,
  3244. name);
  3245. }
  3246. return NULL;
  3247. }
  3248. static const char *
  3249. get_http_version(const struct mg_connection *conn)
  3250. {
  3251. if (!conn) {
  3252. return NULL;
  3253. }
  3254. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3255. return conn->request_info.http_version;
  3256. }
  3257. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3258. return conn->response_info.http_version;
  3259. }
  3260. return NULL;
  3261. }
  3262. /* A helper function for traversing a comma separated list of values.
  3263. * It returns a list pointer shifted to the next value, or NULL if the end
  3264. * of the list found.
  3265. * Value is stored in val vector. If value has form "x=y", then eq_val
  3266. * vector is initialized to point to the "y" part, and val vector length
  3267. * is adjusted to point only to "x". */
  3268. static const char *
  3269. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3270. {
  3271. int end;
  3272. reparse:
  3273. if (val == NULL || list == NULL || *list == '\0') {
  3274. /* End of the list */
  3275. return NULL;
  3276. }
  3277. /* Skip over leading LWS */
  3278. while (*list == ' ' || *list == '\t')
  3279. list++;
  3280. val->ptr = list;
  3281. if ((list = strchr(val->ptr, ',')) != NULL) {
  3282. /* Comma found. Store length and shift the list ptr */
  3283. val->len = ((size_t)(list - val->ptr));
  3284. list++;
  3285. } else {
  3286. /* This value is the last one */
  3287. list = val->ptr + strlen(val->ptr);
  3288. val->len = ((size_t)(list - val->ptr));
  3289. }
  3290. /* Adjust length for trailing LWS */
  3291. end = (int)val->len - 1;
  3292. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3293. end--;
  3294. val->len = (size_t)(end) + (size_t)(1);
  3295. if (val->len == 0) {
  3296. /* Ignore any empty entries. */
  3297. goto reparse;
  3298. }
  3299. if (eq_val != NULL) {
  3300. /* Value has form "x=y", adjust pointers and lengths
  3301. * so that val points to "x", and eq_val points to "y". */
  3302. eq_val->len = 0;
  3303. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3304. if (eq_val->ptr != NULL) {
  3305. eq_val->ptr++; /* Skip over '=' character */
  3306. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3307. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3308. }
  3309. }
  3310. return list;
  3311. }
  3312. /* A helper function for checking if a comma separated list of values
  3313. * contains
  3314. * the given option (case insensitvely).
  3315. * 'header' can be NULL, in which case false is returned. */
  3316. static int
  3317. header_has_option(const char *header, const char *option)
  3318. {
  3319. struct vec opt_vec;
  3320. struct vec eq_vec;
  3321. DEBUG_ASSERT(option != NULL);
  3322. DEBUG_ASSERT(option[0] != '\0');
  3323. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3324. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3325. return 1;
  3326. }
  3327. return 0;
  3328. }
  3329. /* Sorting function implemented in a separate file */
  3330. #include "sort.inl"
  3331. /* Pattern matching has been reimplemented in a new file */
  3332. #include "match.inl"
  3333. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3334. * This function must tolerate situations when connection info is not
  3335. * set up, for example if request parsing failed. */
  3336. static int
  3337. should_keep_alive(const struct mg_connection *conn)
  3338. {
  3339. const char *http_version;
  3340. const char *header;
  3341. /* First satisfy needs of the server */
  3342. if ((conn == NULL) || conn->must_close) {
  3343. /* Close, if civetweb framework needs to close */
  3344. return 0;
  3345. }
  3346. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3347. /* Close, if keep alive is not enabled */
  3348. return 0;
  3349. }
  3350. /* Check explicit wish of the client */
  3351. header = mg_get_header(conn, "Connection");
  3352. if (header) {
  3353. /* If there is a connection header from the client, obey */
  3354. if (header_has_option(header, "keep-alive")) {
  3355. return 1;
  3356. }
  3357. return 0;
  3358. }
  3359. /* Use default of the standard */
  3360. http_version = get_http_version(conn);
  3361. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3362. /* HTTP 1.1 default is keep alive */
  3363. return 1;
  3364. }
  3365. /* HTTP 1.0 (and earlier) default is to close the connection */
  3366. return 0;
  3367. }
  3368. static int
  3369. should_decode_url(const struct mg_connection *conn)
  3370. {
  3371. if (!conn || !conn->dom_ctx) {
  3372. return 0;
  3373. }
  3374. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3375. }
  3376. static int
  3377. should_decode_query_string(const struct mg_connection *conn)
  3378. {
  3379. if (!conn || !conn->dom_ctx) {
  3380. return 0;
  3381. }
  3382. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3383. == 0);
  3384. }
  3385. static const char *
  3386. suggest_connection_header(const struct mg_connection *conn)
  3387. {
  3388. return should_keep_alive(conn) ? "keep-alive" : "close";
  3389. }
  3390. #include "response.inl"
  3391. static void
  3392. send_no_cache_header(struct mg_connection *conn)
  3393. {
  3394. /* Send all current and obsolete cache opt-out directives. */
  3395. mg_response_header_add(conn,
  3396. "Cache-Control",
  3397. "no-cache, no-store, "
  3398. "must-revalidate, private, max-age=0",
  3399. -1);
  3400. mg_response_header_add(conn, "Expires", "0", -1);
  3401. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3402. /* Obsolete, but still send it for HTTP/1.0 */
  3403. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3404. }
  3405. }
  3406. static void
  3407. send_static_cache_header(struct mg_connection *conn)
  3408. {
  3409. #if !defined(NO_CACHING)
  3410. int max_age;
  3411. char val[64];
  3412. const char *cache_control =
  3413. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3414. /* If there is a full cache-control option configured,0 use it */
  3415. if (cache_control != NULL) {
  3416. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3417. return;
  3418. }
  3419. /* Read the server config to check how long a file may be cached.
  3420. * The configuration is in seconds. */
  3421. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3422. if (max_age <= 0) {
  3423. /* 0 means "do not cache". All values <0 are reserved
  3424. * and may be used differently in the future. */
  3425. /* If a file should not be cached, do not only send
  3426. * max-age=0, but also pragmas and Expires headers. */
  3427. send_no_cache_header(conn);
  3428. return;
  3429. }
  3430. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3431. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3432. /* See also https://www.mnot.net/cache_docs/ */
  3433. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3434. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3435. * leap
  3436. * year to 31622400 seconds. For the moment, we just send whatever has
  3437. * been configured, still the behavior for >1 year should be considered
  3438. * as undefined. */
  3439. mg_snprintf(
  3440. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3441. mg_response_header_add(conn, "Cache-Control", val, -1);
  3442. #else /* NO_CACHING */
  3443. send_no_cache_header(conn);
  3444. #endif /* !NO_CACHING */
  3445. }
  3446. static void
  3447. send_additional_header(struct mg_connection *conn)
  3448. {
  3449. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3450. #if !defined(NO_SSL)
  3451. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3452. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3453. if (max_age >= 0) {
  3454. char val[64];
  3455. mg_snprintf(conn,
  3456. NULL,
  3457. val,
  3458. sizeof(val),
  3459. "max-age=%lu",
  3460. (unsigned long)max_age);
  3461. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3462. }
  3463. }
  3464. #endif
  3465. if (header && header[0]) {
  3466. mg_response_header_add_lines(conn, header);
  3467. }
  3468. }
  3469. static void
  3470. send_cors_header(struct mg_connection *conn)
  3471. {
  3472. const char *origin_hdr = mg_get_header(conn, "Origin");
  3473. const char *cors_orig_cfg =
  3474. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3475. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3476. /* Cross-origin resource sharing (CORS), see
  3477. * http://www.html5rocks.com/en/tutorials/cors/,
  3478. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3479. * CORS preflight is not supported for files. */
  3480. mg_response_header_add(conn,
  3481. "Access-Control-Allow-Origin",
  3482. cors_orig_cfg,
  3483. -1);
  3484. }
  3485. }
  3486. #if !defined(NO_FILESYSTEMS)
  3487. static void handle_file_based_request(struct mg_connection *conn,
  3488. const char *path,
  3489. struct mg_file *filep);
  3490. #endif /* NO_FILESYSTEMS */
  3491. CIVETWEB_API const char *
  3492. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3493. {
  3494. /* See IANA HTTP status code assignment:
  3495. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3496. */
  3497. switch (response_code) {
  3498. /* RFC2616 Section 10.1 - Informational 1xx */
  3499. case 100:
  3500. return "Continue"; /* RFC2616 Section 10.1.1 */
  3501. case 101:
  3502. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3503. case 102:
  3504. return "Processing"; /* RFC2518 Section 10.1 */
  3505. /* RFC2616 Section 10.2 - Successful 2xx */
  3506. case 200:
  3507. return "OK"; /* RFC2616 Section 10.2.1 */
  3508. case 201:
  3509. return "Created"; /* RFC2616 Section 10.2.2 */
  3510. case 202:
  3511. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3512. case 203:
  3513. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3514. case 204:
  3515. return "No Content"; /* RFC2616 Section 10.2.5 */
  3516. case 205:
  3517. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3518. case 206:
  3519. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3520. case 207:
  3521. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3522. */
  3523. case 208:
  3524. return "Already Reported"; /* RFC5842 Section 7.1 */
  3525. case 226:
  3526. return "IM used"; /* RFC3229 Section 10.4.1 */
  3527. /* RFC2616 Section 10.3 - Redirection 3xx */
  3528. case 300:
  3529. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3530. case 301:
  3531. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3532. case 302:
  3533. return "Found"; /* RFC2616 Section 10.3.3 */
  3534. case 303:
  3535. return "See Other"; /* RFC2616 Section 10.3.4 */
  3536. case 304:
  3537. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3538. case 305:
  3539. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3540. case 307:
  3541. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3542. case 308:
  3543. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3544. /* RFC2616 Section 10.4 - Client Error 4xx */
  3545. case 400:
  3546. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3547. case 401:
  3548. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3549. case 402:
  3550. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3551. case 403:
  3552. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3553. case 404:
  3554. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3555. case 405:
  3556. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3557. case 406:
  3558. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3559. case 407:
  3560. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3561. case 408:
  3562. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3563. case 409:
  3564. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3565. case 410:
  3566. return "Gone"; /* RFC2616 Section 10.4.11 */
  3567. case 411:
  3568. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3569. case 412:
  3570. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3571. case 413:
  3572. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3573. case 414:
  3574. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3575. case 415:
  3576. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3577. case 416:
  3578. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3579. */
  3580. case 417:
  3581. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3582. case 421:
  3583. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3584. case 422:
  3585. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3586. * Section 11.2 */
  3587. case 423:
  3588. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3589. case 424:
  3590. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3591. * Section 11.4 */
  3592. case 426:
  3593. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3594. case 428:
  3595. return "Precondition Required"; /* RFC 6585, Section 3 */
  3596. case 429:
  3597. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3598. case 431:
  3599. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3600. case 451:
  3601. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3602. * Section 3 */
  3603. /* RFC2616 Section 10.5 - Server Error 5xx */
  3604. case 500:
  3605. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3606. case 501:
  3607. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3608. case 502:
  3609. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3610. case 503:
  3611. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3612. case 504:
  3613. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3614. case 505:
  3615. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3616. case 506:
  3617. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3618. case 507:
  3619. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3620. * Section 11.5 */
  3621. case 508:
  3622. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3623. case 510:
  3624. return "Not Extended"; /* RFC 2774, Section 7 */
  3625. case 511:
  3626. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3627. /* Other status codes, not shown in the IANA HTTP status code
  3628. * assignment.
  3629. * E.g., "de facto" standards due to common use, ... */
  3630. case 418:
  3631. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3632. case 419:
  3633. return "Authentication Timeout"; /* common use */
  3634. case 420:
  3635. return "Enhance Your Calm"; /* common use */
  3636. case 440:
  3637. return "Login Timeout"; /* common use */
  3638. case 509:
  3639. return "Bandwidth Limit Exceeded"; /* common use */
  3640. default:
  3641. /* This error code is unknown. This should not happen. */
  3642. if (conn) {
  3643. mg_cry_internal(conn,
  3644. "Unknown HTTP response code: %u",
  3645. response_code);
  3646. }
  3647. /* Return at least a category according to RFC 2616 Section 10. */
  3648. if (response_code >= 100 && response_code < 200) {
  3649. /* Unknown informational status code */
  3650. return "Information";
  3651. }
  3652. if (response_code >= 200 && response_code < 300) {
  3653. /* Unknown success code */
  3654. return "Success";
  3655. }
  3656. if (response_code >= 300 && response_code < 400) {
  3657. /* Unknown redirection code */
  3658. return "Redirection";
  3659. }
  3660. if (response_code >= 400 && response_code < 500) {
  3661. /* Unknown request error code */
  3662. return "Client Error";
  3663. }
  3664. if (response_code >= 500 && response_code < 600) {
  3665. /* Unknown server error code */
  3666. return "Server Error";
  3667. }
  3668. /* Response code not even within reasonable range */
  3669. return "";
  3670. }
  3671. }
  3672. static int
  3673. mg_send_http_error_impl(struct mg_connection *conn,
  3674. int status,
  3675. const char *fmt,
  3676. va_list args)
  3677. {
  3678. char errmsg_buf[MG_BUF_LEN];
  3679. va_list ap;
  3680. int has_body;
  3681. #if !defined(NO_FILESYSTEMS)
  3682. char path_buf[UTF8_PATH_MAX];
  3683. int len, i, page_handler_found, scope, truncated;
  3684. const char *error_handler = NULL;
  3685. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3686. const char *error_page_file_ext, *tstr;
  3687. #endif /* NO_FILESYSTEMS */
  3688. int handled_by_callback = 0;
  3689. if ((conn == NULL) || (fmt == NULL)) {
  3690. return -2;
  3691. }
  3692. /* Set status (for log) */
  3693. conn->status_code = status;
  3694. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3695. has_body = ((status > 199) && (status != 204) && (status != 304));
  3696. /* Prepare message in buf, if required */
  3697. if (has_body
  3698. || (!conn->in_error_handler
  3699. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3700. /* Store error message in errmsg_buf */
  3701. va_copy(ap, args);
  3702. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3703. va_end(ap);
  3704. /* In a debug build, print all html errors */
  3705. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3706. }
  3707. /* If there is a http_error callback, call it.
  3708. * But don't do it recursively, if callback calls mg_send_http_error again.
  3709. */
  3710. if (!conn->in_error_handler
  3711. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3712. /* Mark in_error_handler to avoid recursion and call user callback. */
  3713. conn->in_error_handler = 1;
  3714. handled_by_callback =
  3715. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3716. == 0);
  3717. conn->in_error_handler = 0;
  3718. }
  3719. if (!handled_by_callback) {
  3720. /* Check for recursion */
  3721. if (conn->in_error_handler) {
  3722. DEBUG_TRACE(
  3723. "Recursion when handling error %u - fall back to default",
  3724. status);
  3725. #if !defined(NO_FILESYSTEMS)
  3726. } else {
  3727. /* Send user defined error pages, if defined */
  3728. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3729. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3730. page_handler_found = 0;
  3731. if (error_handler != NULL) {
  3732. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3733. switch (scope) {
  3734. case 1: /* Handler for specific error, e.g. 404 error */
  3735. mg_snprintf(conn,
  3736. &truncated,
  3737. path_buf,
  3738. sizeof(path_buf) - 32,
  3739. "%serror%03u.",
  3740. error_handler,
  3741. status);
  3742. break;
  3743. case 2: /* Handler for error group, e.g., 5xx error
  3744. * handler
  3745. * for all server errors (500-599) */
  3746. mg_snprintf(conn,
  3747. &truncated,
  3748. path_buf,
  3749. sizeof(path_buf) - 32,
  3750. "%serror%01uxx.",
  3751. error_handler,
  3752. status / 100);
  3753. break;
  3754. default: /* Handler for all errors */
  3755. mg_snprintf(conn,
  3756. &truncated,
  3757. path_buf,
  3758. sizeof(path_buf) - 32,
  3759. "%serror.",
  3760. error_handler);
  3761. break;
  3762. }
  3763. /* String truncation in buf may only occur if
  3764. * error_handler is too long. This string is
  3765. * from the config, not from a client. */
  3766. (void)truncated;
  3767. /* The following code is redundant, but it should avoid
  3768. * false positives in static source code analyzers and
  3769. * vulnerability scanners.
  3770. */
  3771. path_buf[sizeof(path_buf) - 32] = 0;
  3772. len = (int)strlen(path_buf);
  3773. if (len > (int)sizeof(path_buf) - 32) {
  3774. len = (int)sizeof(path_buf) - 32;
  3775. }
  3776. /* Start with the file extenstion from the configuration. */
  3777. tstr = strchr(error_page_file_ext, '.');
  3778. while (tstr) {
  3779. for (i = 1;
  3780. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3781. i++) {
  3782. /* buffer overrun is not possible here, since
  3783. * (i < 32) && (len < sizeof(path_buf) - 32)
  3784. * ==> (i + len) < sizeof(path_buf) */
  3785. path_buf[len + i - 1] = tstr[i];
  3786. }
  3787. /* buffer overrun is not possible here, since
  3788. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3789. * ==> (i + len) <= sizeof(path_buf) */
  3790. path_buf[len + i - 1] = 0;
  3791. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3792. DEBUG_TRACE("Check error page %s - found",
  3793. path_buf);
  3794. page_handler_found = 1;
  3795. break;
  3796. }
  3797. DEBUG_TRACE("Check error page %s - not found",
  3798. path_buf);
  3799. /* Continue with the next file extenstion from the
  3800. * configuration (if there is a next one). */
  3801. tstr = strchr(tstr + i, '.');
  3802. }
  3803. }
  3804. }
  3805. if (page_handler_found) {
  3806. conn->in_error_handler = 1;
  3807. handle_file_based_request(conn, path_buf, &error_page_file);
  3808. conn->in_error_handler = 0;
  3809. return 0;
  3810. }
  3811. #endif /* NO_FILESYSTEMS */
  3812. }
  3813. /* No custom error page. Send default error page. */
  3814. conn->must_close = 1;
  3815. mg_response_header_start(conn, status);
  3816. send_no_cache_header(conn);
  3817. send_additional_header(conn);
  3818. send_cors_header(conn);
  3819. if (has_body) {
  3820. mg_response_header_add(conn,
  3821. "Content-Type",
  3822. "text/plain; charset=utf-8",
  3823. -1);
  3824. }
  3825. mg_response_header_send(conn);
  3826. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3827. if (has_body) {
  3828. /* For other errors, send a generic error message. */
  3829. const char *status_text = mg_get_response_code_text(conn, status);
  3830. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3831. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3832. } else {
  3833. /* No body allowed. Close the connection. */
  3834. DEBUG_TRACE("Error %i", status);
  3835. }
  3836. }
  3837. return 0;
  3838. }
  3839. CIVETWEB_API int
  3840. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3841. {
  3842. va_list ap;
  3843. int ret;
  3844. va_start(ap, fmt);
  3845. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3846. va_end(ap);
  3847. return ret;
  3848. }
  3849. CIVETWEB_API int
  3850. mg_send_http_ok(struct mg_connection *conn,
  3851. const char *mime_type,
  3852. long long content_length)
  3853. {
  3854. if ((mime_type == NULL) || (*mime_type == 0)) {
  3855. /* No content type defined: default to text/html */
  3856. mime_type = "text/html";
  3857. }
  3858. mg_response_header_start(conn, 200);
  3859. send_no_cache_header(conn);
  3860. send_additional_header(conn);
  3861. send_cors_header(conn);
  3862. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3863. if (content_length < 0) {
  3864. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3865. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3866. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3867. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3868. }
  3869. } else {
  3870. char len[32];
  3871. int trunc = 0;
  3872. mg_snprintf(conn,
  3873. &trunc,
  3874. len,
  3875. sizeof(len),
  3876. "%" UINT64_FMT,
  3877. (uint64_t)content_length);
  3878. if (!trunc) {
  3879. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3880. * !trunc is always true */
  3881. mg_response_header_add(conn, "Content-Length", len, -1);
  3882. }
  3883. }
  3884. mg_response_header_send(conn);
  3885. return 0;
  3886. }
  3887. CIVETWEB_API int
  3888. mg_send_http_redirect(struct mg_connection *conn,
  3889. const char *target_url,
  3890. int redirect_code)
  3891. {
  3892. /* Send a 30x redirect response.
  3893. *
  3894. * Redirect types (status codes):
  3895. *
  3896. * Status | Perm/Temp | Method | Version
  3897. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3898. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3899. * 303 | temporary | always use GET | HTTP/1.1
  3900. * 307 | temporary | always keep method | HTTP/1.1
  3901. * 308 | permanent | always keep method | HTTP/1.1
  3902. */
  3903. #if defined(MG_SEND_REDIRECT_BODY)
  3904. char redirect_body[MG_BUF_LEN];
  3905. size_t content_len = 0;
  3906. char content_len_text[32];
  3907. #endif
  3908. /* In case redirect_code=0, use 307. */
  3909. if (redirect_code == 0) {
  3910. redirect_code = 307;
  3911. }
  3912. /* In case redirect_code is none of the above, return error. */
  3913. if ((redirect_code != 301) && (redirect_code != 302)
  3914. && (redirect_code != 303) && (redirect_code != 307)
  3915. && (redirect_code != 308)) {
  3916. /* Parameter error */
  3917. return -2;
  3918. }
  3919. /* If target_url is not defined, redirect to "/". */
  3920. if ((target_url == NULL) || (*target_url == 0)) {
  3921. target_url = "/";
  3922. }
  3923. #if defined(MG_SEND_REDIRECT_BODY)
  3924. /* TODO: condition name? */
  3925. /* Prepare a response body with a hyperlink.
  3926. *
  3927. * According to RFC2616 (and RFC1945 before):
  3928. * Unless the request method was HEAD, the entity of the
  3929. * response SHOULD contain a short hypertext note with a hyperlink to
  3930. * the new URI(s).
  3931. *
  3932. * However, this response body is not useful in M2M communication.
  3933. * Probably the original reason in the RFC was, clients not supporting
  3934. * a 30x HTTP redirect could still show the HTML page and let the user
  3935. * press the link. Since current browsers support 30x HTTP, the additional
  3936. * HTML body does not seem to make sense anymore.
  3937. *
  3938. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3939. * but it only notes:
  3940. * The server's response payload usually contains a short
  3941. * hypertext note with a hyperlink to the new URI(s).
  3942. *
  3943. * Deactivated by default. If you need the 30x body, set the define.
  3944. */
  3945. mg_snprintf(
  3946. conn,
  3947. NULL /* ignore truncation */,
  3948. redirect_body,
  3949. sizeof(redirect_body),
  3950. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3951. redirect_text,
  3952. target_url,
  3953. target_url);
  3954. content_len = strlen(reply);
  3955. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  3956. #endif
  3957. /* Send all required headers */
  3958. mg_response_header_start(conn, redirect_code);
  3959. mg_response_header_add(conn, "Location", target_url, -1);
  3960. if ((redirect_code == 301) || (redirect_code == 308)) {
  3961. /* Permanent redirect */
  3962. send_static_cache_header(conn);
  3963. } else {
  3964. /* Temporary redirect */
  3965. send_no_cache_header(conn);
  3966. }
  3967. send_additional_header(conn);
  3968. send_cors_header(conn);
  3969. #if defined(MG_SEND_REDIRECT_BODY)
  3970. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  3971. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  3972. #else
  3973. mg_response_header_add(conn, "Content-Length", "0", 1);
  3974. #endif
  3975. mg_response_header_send(conn);
  3976. #if defined(MG_SEND_REDIRECT_BODY)
  3977. /* Send response body */
  3978. /* ... unless it is a HEAD request */
  3979. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  3980. ret = mg_write(conn, redirect_body, content_len);
  3981. }
  3982. #endif
  3983. return 1;
  3984. }
  3985. #if defined(_WIN32)
  3986. /* Create substitutes for POSIX functions in Win32. */
  3987. #if defined(GCC_DIAGNOSTIC)
  3988. /* Show no warning in case system functions are not used. */
  3989. #pragma GCC diagnostic push
  3990. #pragma GCC diagnostic ignored "-Wunused-function"
  3991. #endif
  3992. static int
  3993. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3994. {
  3995. (void)unused;
  3996. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  3997. InitializeCriticalSection(&mutex->sec);
  3998. return 0;
  3999. }
  4000. static int
  4001. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4002. {
  4003. DeleteCriticalSection(&mutex->sec);
  4004. return 0;
  4005. }
  4006. static int
  4007. pthread_mutex_lock(pthread_mutex_t *mutex)
  4008. {
  4009. EnterCriticalSection(&mutex->sec);
  4010. return 0;
  4011. }
  4012. static int
  4013. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4014. {
  4015. LeaveCriticalSection(&mutex->sec);
  4016. return 0;
  4017. }
  4018. FUNCTION_MAY_BE_UNUSED
  4019. static int
  4020. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4021. {
  4022. (void)unused;
  4023. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4024. cv->waiting_thread = NULL;
  4025. return 0;
  4026. }
  4027. FUNCTION_MAY_BE_UNUSED
  4028. static int
  4029. pthread_cond_timedwait(pthread_cond_t *cv,
  4030. pthread_mutex_t *mutex,
  4031. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4032. {
  4033. struct mg_workerTLS **ptls,
  4034. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4035. int ok;
  4036. uint64_t nsnow, nswaitabs;
  4037. int64_t nswaitrel;
  4038. DWORD mswaitrel;
  4039. pthread_mutex_lock(&cv->threadIdSec);
  4040. /* Add this thread to cv's waiting list */
  4041. ptls = &cv->waiting_thread;
  4042. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4043. ;
  4044. tls->next_waiting_thread = NULL;
  4045. *ptls = tls;
  4046. pthread_mutex_unlock(&cv->threadIdSec);
  4047. if (abstime) {
  4048. nsnow = mg_get_current_time_ns();
  4049. nswaitabs =
  4050. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4051. nswaitrel = nswaitabs - nsnow;
  4052. if (nswaitrel < 0) {
  4053. nswaitrel = 0;
  4054. }
  4055. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4056. } else {
  4057. mswaitrel = (DWORD)INFINITE;
  4058. }
  4059. pthread_mutex_unlock(mutex);
  4060. ok = (WAIT_OBJECT_0
  4061. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4062. if (!ok) {
  4063. ok = 1;
  4064. pthread_mutex_lock(&cv->threadIdSec);
  4065. ptls = &cv->waiting_thread;
  4066. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4067. if (*ptls == tls) {
  4068. *ptls = tls->next_waiting_thread;
  4069. ok = 0;
  4070. break;
  4071. }
  4072. }
  4073. pthread_mutex_unlock(&cv->threadIdSec);
  4074. if (ok) {
  4075. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4076. (DWORD)INFINITE);
  4077. }
  4078. }
  4079. /* This thread has been removed from cv's waiting list */
  4080. pthread_mutex_lock(mutex);
  4081. return ok ? 0 : -1;
  4082. }
  4083. FUNCTION_MAY_BE_UNUSED
  4084. static int
  4085. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4086. {
  4087. return pthread_cond_timedwait(cv, mutex, NULL);
  4088. }
  4089. FUNCTION_MAY_BE_UNUSED
  4090. static int
  4091. pthread_cond_signal(pthread_cond_t *cv)
  4092. {
  4093. HANDLE wkup = NULL;
  4094. BOOL ok = FALSE;
  4095. pthread_mutex_lock(&cv->threadIdSec);
  4096. if (cv->waiting_thread) {
  4097. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4098. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4099. ok = SetEvent(wkup);
  4100. DEBUG_ASSERT(ok);
  4101. }
  4102. pthread_mutex_unlock(&cv->threadIdSec);
  4103. return ok ? 0 : 1;
  4104. }
  4105. FUNCTION_MAY_BE_UNUSED
  4106. static int
  4107. pthread_cond_broadcast(pthread_cond_t *cv)
  4108. {
  4109. pthread_mutex_lock(&cv->threadIdSec);
  4110. while (cv->waiting_thread) {
  4111. pthread_cond_signal(cv);
  4112. }
  4113. pthread_mutex_unlock(&cv->threadIdSec);
  4114. return 0;
  4115. }
  4116. FUNCTION_MAY_BE_UNUSED
  4117. static int
  4118. pthread_cond_destroy(pthread_cond_t *cv)
  4119. {
  4120. pthread_mutex_lock(&cv->threadIdSec);
  4121. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4122. pthread_mutex_unlock(&cv->threadIdSec);
  4123. pthread_mutex_destroy(&cv->threadIdSec);
  4124. return 0;
  4125. }
  4126. #if defined(ALTERNATIVE_QUEUE)
  4127. FUNCTION_MAY_BE_UNUSED
  4128. static void *
  4129. event_create(void)
  4130. {
  4131. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4132. }
  4133. FUNCTION_MAY_BE_UNUSED
  4134. static int
  4135. event_wait(void *eventhdl)
  4136. {
  4137. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4138. return (res == WAIT_OBJECT_0);
  4139. }
  4140. FUNCTION_MAY_BE_UNUSED
  4141. static int
  4142. event_signal(void *eventhdl)
  4143. {
  4144. return (int)SetEvent((HANDLE)eventhdl);
  4145. }
  4146. FUNCTION_MAY_BE_UNUSED
  4147. static void
  4148. event_destroy(void *eventhdl)
  4149. {
  4150. CloseHandle((HANDLE)eventhdl);
  4151. }
  4152. #endif
  4153. #if defined(GCC_DIAGNOSTIC)
  4154. /* Enable unused function warning again */
  4155. #pragma GCC diagnostic pop
  4156. #endif
  4157. /* For Windows, change all slashes to backslashes in path names. */
  4158. static void
  4159. change_slashes_to_backslashes(char *path)
  4160. {
  4161. int i;
  4162. for (i = 0; path[i] != '\0'; i++) {
  4163. if (path[i] == '/') {
  4164. path[i] = '\\';
  4165. }
  4166. /* remove double backslash (check i > 0 to preserve UNC paths,
  4167. * like \\server\file.txt) */
  4168. if ((i > 0) && (path[i] == '\\')) {
  4169. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4170. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4171. }
  4172. }
  4173. }
  4174. }
  4175. static int
  4176. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4177. {
  4178. int diff;
  4179. do {
  4180. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4181. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4182. s1++;
  4183. s2++;
  4184. } while ((diff == 0) && (s1[-1] != L'\0'));
  4185. return diff;
  4186. }
  4187. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4188. * wbuf and wbuf_len is a target buffer and its length. */
  4189. static void
  4190. path_to_unicode(const struct mg_connection *conn,
  4191. const char *path,
  4192. wchar_t *wbuf,
  4193. size_t wbuf_len)
  4194. {
  4195. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4196. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4197. DWORD long_len, err;
  4198. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4199. mg_strlcpy(buf, path, sizeof(buf));
  4200. change_slashes_to_backslashes(buf);
  4201. /* Convert to Unicode and back. If doubly-converted string does not
  4202. * match the original, something is fishy, reject. */
  4203. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4204. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4205. WideCharToMultiByte(
  4206. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4207. if (strcmp(buf, buf2) != 0) {
  4208. wbuf[0] = L'\0';
  4209. }
  4210. /* Windows file systems are not case sensitive, but you can still use
  4211. * uppercase and lowercase letters (on all modern file systems).
  4212. * The server can check if the URI uses the same upper/lowercase
  4213. * letters an the file system, effectively making Windows servers
  4214. * case sensitive (like Linux servers are). It is still not possible
  4215. * to use two files with the same name in different cases on Windows
  4216. * (like /a and /A) - this would be possible in Linux.
  4217. * As a default, Windows is not case sensitive, but the case sensitive
  4218. * file name check can be activated by an additional configuration. */
  4219. if (conn) {
  4220. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4221. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4222. "yes")) {
  4223. /* Use case sensitive compare function */
  4224. fcompare = wcscmp;
  4225. }
  4226. }
  4227. (void)conn; /* conn is currently unused */
  4228. /* Only accept a full file path, not a Windows short (8.3) path. */
  4229. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4230. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4231. if (long_len == 0) {
  4232. err = GetLastError();
  4233. if (err == ERROR_FILE_NOT_FOUND) {
  4234. /* File does not exist. This is not always a problem here. */
  4235. return;
  4236. }
  4237. }
  4238. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4239. /* Short name is used. */
  4240. wbuf[0] = L'\0';
  4241. }
  4242. }
  4243. #if !defined(NO_FILESYSTEMS)
  4244. /* Get file information, return 1 if file exists, 0 if not */
  4245. static int
  4246. mg_stat(const struct mg_connection *conn,
  4247. const char *path,
  4248. struct mg_file_stat *filep)
  4249. {
  4250. wchar_t wbuf[UTF16_PATH_MAX];
  4251. WIN32_FILE_ATTRIBUTE_DATA info;
  4252. time_t creation_time;
  4253. size_t len;
  4254. if (!filep) {
  4255. return 0;
  4256. }
  4257. memset(filep, 0, sizeof(*filep));
  4258. if (mg_path_suspicious(conn, path)) {
  4259. return 0;
  4260. }
  4261. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4262. /* Windows happily opens files with some garbage at the end of file name.
  4263. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4264. * "a.cgi", despite one would expect an error back. */
  4265. len = strlen(path);
  4266. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4267. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4268. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4269. filep->last_modified =
  4270. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4271. info.ftLastWriteTime.dwHighDateTime);
  4272. /* On Windows, the file creation time can be higher than the
  4273. * modification time, e.g. when a file is copied.
  4274. * Since the Last-Modified timestamp is used for caching
  4275. * it should be based on the most recent timestamp. */
  4276. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4277. info.ftCreationTime.dwHighDateTime);
  4278. if (creation_time > filep->last_modified) {
  4279. filep->last_modified = creation_time;
  4280. }
  4281. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4282. return 1;
  4283. }
  4284. return 0;
  4285. }
  4286. #endif
  4287. static int
  4288. mg_remove(const struct mg_connection *conn, const char *path)
  4289. {
  4290. wchar_t wbuf[UTF16_PATH_MAX];
  4291. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4292. return DeleteFileW(wbuf) ? 0 : -1;
  4293. }
  4294. static int
  4295. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4296. {
  4297. wchar_t wbuf[UTF16_PATH_MAX];
  4298. (void)mode;
  4299. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4300. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4301. }
  4302. /* Create substitutes for POSIX functions in Win32. */
  4303. #if defined(GCC_DIAGNOSTIC)
  4304. /* Show no warning in case system functions are not used. */
  4305. #pragma GCC diagnostic push
  4306. #pragma GCC diagnostic ignored "-Wunused-function"
  4307. #endif
  4308. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4309. FUNCTION_MAY_BE_UNUSED
  4310. static DIR *
  4311. mg_opendir(const struct mg_connection *conn, const char *name)
  4312. {
  4313. DIR *dir = NULL;
  4314. wchar_t wpath[UTF16_PATH_MAX];
  4315. DWORD attrs;
  4316. if (name == NULL) {
  4317. SetLastError(ERROR_BAD_ARGUMENTS);
  4318. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4319. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4320. } else {
  4321. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4322. attrs = GetFileAttributesW(wpath);
  4323. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4324. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4325. (void)wcscat(wpath, L"\\*");
  4326. dir->handle = FindFirstFileW(wpath, &dir->info);
  4327. dir->result.d_name[0] = '\0';
  4328. } else {
  4329. mg_free(dir);
  4330. dir = NULL;
  4331. }
  4332. }
  4333. return dir;
  4334. }
  4335. FUNCTION_MAY_BE_UNUSED
  4336. static int
  4337. mg_closedir(DIR *dir)
  4338. {
  4339. int result = 0;
  4340. if (dir != NULL) {
  4341. if (dir->handle != INVALID_HANDLE_VALUE)
  4342. result = FindClose(dir->handle) ? 0 : -1;
  4343. mg_free(dir);
  4344. } else {
  4345. result = -1;
  4346. SetLastError(ERROR_BAD_ARGUMENTS);
  4347. }
  4348. return result;
  4349. }
  4350. FUNCTION_MAY_BE_UNUSED
  4351. static struct dirent *
  4352. mg_readdir(DIR *dir)
  4353. {
  4354. struct dirent *result = 0;
  4355. if (dir) {
  4356. if (dir->handle != INVALID_HANDLE_VALUE) {
  4357. result = &dir->result;
  4358. (void)WideCharToMultiByte(CP_UTF8,
  4359. 0,
  4360. dir->info.cFileName,
  4361. -1,
  4362. result->d_name,
  4363. sizeof(result->d_name),
  4364. NULL,
  4365. NULL);
  4366. if (!FindNextFileW(dir->handle, &dir->info)) {
  4367. (void)FindClose(dir->handle);
  4368. dir->handle = INVALID_HANDLE_VALUE;
  4369. }
  4370. } else {
  4371. SetLastError(ERROR_FILE_NOT_FOUND);
  4372. }
  4373. } else {
  4374. SetLastError(ERROR_BAD_ARGUMENTS);
  4375. }
  4376. return result;
  4377. }
  4378. #if !defined(HAVE_POLL)
  4379. #undef POLLIN
  4380. #undef POLLPRI
  4381. #undef POLLOUT
  4382. #undef POLLERR
  4383. #define POLLIN (1) /* Data ready - read will not block. */
  4384. #define POLLPRI (2) /* Priority data ready. */
  4385. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4386. #define POLLERR (8) /* Error event */
  4387. FUNCTION_MAY_BE_UNUSED
  4388. static int
  4389. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4390. {
  4391. struct timeval tv;
  4392. fd_set rset;
  4393. fd_set wset;
  4394. fd_set eset;
  4395. unsigned int i;
  4396. int result;
  4397. SOCKET maxfd = 0;
  4398. memset(&tv, 0, sizeof(tv));
  4399. tv.tv_sec = milliseconds / 1000;
  4400. tv.tv_usec = (milliseconds % 1000) * 1000;
  4401. FD_ZERO(&rset);
  4402. FD_ZERO(&wset);
  4403. FD_ZERO(&eset);
  4404. for (i = 0; i < n; i++) {
  4405. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4406. if (pfd[i].events & POLLIN) {
  4407. FD_SET(pfd[i].fd, &rset);
  4408. }
  4409. if (pfd[i].events & POLLOUT) {
  4410. FD_SET(pfd[i].fd, &wset);
  4411. }
  4412. /* Check for errors for any FD in the set */
  4413. FD_SET(pfd[i].fd, &eset);
  4414. }
  4415. pfd[i].revents = 0;
  4416. if (pfd[i].fd > maxfd) {
  4417. maxfd = pfd[i].fd;
  4418. }
  4419. }
  4420. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4421. for (i = 0; i < n; i++) {
  4422. if (FD_ISSET(pfd[i].fd, &rset)) {
  4423. pfd[i].revents |= POLLIN;
  4424. }
  4425. if (FD_ISSET(pfd[i].fd, &wset)) {
  4426. pfd[i].revents |= POLLOUT;
  4427. }
  4428. if (FD_ISSET(pfd[i].fd, &eset)) {
  4429. pfd[i].revents |= POLLERR;
  4430. }
  4431. }
  4432. }
  4433. /* We should subtract the time used in select from remaining
  4434. * "milliseconds", in particular if called from mg_poll with a
  4435. * timeout quantum.
  4436. * Unfortunately, the remaining time is not stored in "tv" in all
  4437. * implementations, so the result in "tv" must be considered undefined.
  4438. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4439. return result;
  4440. }
  4441. #endif /* HAVE_POLL */
  4442. #if defined(GCC_DIAGNOSTIC)
  4443. /* Enable unused function warning again */
  4444. #pragma GCC diagnostic pop
  4445. #endif
  4446. static void
  4447. set_close_on_exec(SOCKET sock,
  4448. const struct mg_connection *conn /* may be null */,
  4449. struct mg_context *ctx /* may be null */)
  4450. {
  4451. (void)conn; /* Unused. */
  4452. (void)ctx;
  4453. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4454. }
  4455. CIVETWEB_API int
  4456. mg_start_thread(mg_thread_func_t f, void *p)
  4457. {
  4458. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4459. /* Compile-time option to control stack size, e.g.
  4460. * -DUSE_STACK_SIZE=16384
  4461. */
  4462. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4463. == ((uintptr_t)(-1L)))
  4464. ? -1
  4465. : 0);
  4466. #else
  4467. return (
  4468. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4469. ? -1
  4470. : 0);
  4471. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4472. }
  4473. /* Start a thread storing the thread context. */
  4474. static int
  4475. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4476. void *p,
  4477. pthread_t *threadidptr)
  4478. {
  4479. uintptr_t uip;
  4480. HANDLE threadhandle;
  4481. int result = -1;
  4482. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4483. threadhandle = (HANDLE)uip;
  4484. if ((uip != 0) && (threadidptr != NULL)) {
  4485. *threadidptr = threadhandle;
  4486. result = 0;
  4487. }
  4488. return result;
  4489. }
  4490. /* Wait for a thread to finish. */
  4491. static int
  4492. mg_join_thread(pthread_t threadid)
  4493. {
  4494. int result;
  4495. DWORD dwevent;
  4496. result = -1;
  4497. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4498. if (dwevent == WAIT_FAILED) {
  4499. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4500. } else {
  4501. if (dwevent == WAIT_OBJECT_0) {
  4502. CloseHandle(threadid);
  4503. result = 0;
  4504. }
  4505. }
  4506. return result;
  4507. }
  4508. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4509. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4510. /* Create substitutes for POSIX functions in Win32. */
  4511. #if defined(GCC_DIAGNOSTIC)
  4512. /* Show no warning in case system functions are not used. */
  4513. #pragma GCC diagnostic push
  4514. #pragma GCC diagnostic ignored "-Wunused-function"
  4515. #endif
  4516. FUNCTION_MAY_BE_UNUSED
  4517. static HANDLE
  4518. dlopen(const char *dll_name, int flags)
  4519. {
  4520. wchar_t wbuf[UTF16_PATH_MAX];
  4521. (void)flags;
  4522. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4523. return LoadLibraryW(wbuf);
  4524. }
  4525. FUNCTION_MAY_BE_UNUSED
  4526. static int
  4527. dlclose(void *handle)
  4528. {
  4529. int result;
  4530. if (FreeLibrary((HMODULE)handle) != 0) {
  4531. result = 0;
  4532. } else {
  4533. result = -1;
  4534. }
  4535. return result;
  4536. }
  4537. #if defined(GCC_DIAGNOSTIC)
  4538. /* Enable unused function warning again */
  4539. #pragma GCC diagnostic pop
  4540. #endif
  4541. #endif
  4542. #if !defined(NO_CGI)
  4543. #define SIGKILL (0)
  4544. static int
  4545. kill(pid_t pid, int sig_num)
  4546. {
  4547. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4548. (void)CloseHandle((HANDLE)pid);
  4549. return 0;
  4550. }
  4551. #if !defined(WNOHANG)
  4552. #define WNOHANG (1)
  4553. #endif
  4554. static pid_t
  4555. waitpid(pid_t pid, int *status, int flags)
  4556. {
  4557. DWORD timeout = INFINITE;
  4558. DWORD waitres;
  4559. (void)status; /* Currently not used by any client here */
  4560. if ((flags | WNOHANG) == WNOHANG) {
  4561. timeout = 0;
  4562. }
  4563. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4564. if (waitres == WAIT_OBJECT_0) {
  4565. return pid;
  4566. }
  4567. if (waitres == WAIT_TIMEOUT) {
  4568. return 0;
  4569. }
  4570. return (pid_t)-1;
  4571. }
  4572. static void
  4573. trim_trailing_whitespaces(char *s)
  4574. {
  4575. char *e = s + strlen(s);
  4576. while ((e > s) && isspace((unsigned char)e[-1])) {
  4577. *(--e) = '\0';
  4578. }
  4579. }
  4580. static pid_t
  4581. spawn_process(struct mg_connection *conn,
  4582. const char *prog,
  4583. char *envblk,
  4584. char *envp[],
  4585. int fdin[2],
  4586. int fdout[2],
  4587. int fderr[2],
  4588. const char *dir,
  4589. unsigned char cgi_config_idx)
  4590. {
  4591. HANDLE me;
  4592. char *interp;
  4593. char *interp_arg = 0;
  4594. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4595. int truncated;
  4596. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4597. STARTUPINFOA si;
  4598. PROCESS_INFORMATION pi = {0};
  4599. (void)envp;
  4600. memset(&si, 0, sizeof(si));
  4601. si.cb = sizeof(si);
  4602. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4603. si.wShowWindow = SW_HIDE;
  4604. me = GetCurrentProcess();
  4605. DuplicateHandle(me,
  4606. (HANDLE)_get_osfhandle(fdin[0]),
  4607. me,
  4608. &si.hStdInput,
  4609. 0,
  4610. TRUE,
  4611. DUPLICATE_SAME_ACCESS);
  4612. DuplicateHandle(me,
  4613. (HANDLE)_get_osfhandle(fdout[1]),
  4614. me,
  4615. &si.hStdOutput,
  4616. 0,
  4617. TRUE,
  4618. DUPLICATE_SAME_ACCESS);
  4619. DuplicateHandle(me,
  4620. (HANDLE)_get_osfhandle(fderr[1]),
  4621. me,
  4622. &si.hStdError,
  4623. 0,
  4624. TRUE,
  4625. DUPLICATE_SAME_ACCESS);
  4626. /* Mark handles that should not be inherited. See
  4627. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4628. */
  4629. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4630. HANDLE_FLAG_INHERIT,
  4631. 0);
  4632. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4633. HANDLE_FLAG_INHERIT,
  4634. 0);
  4635. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4636. HANDLE_FLAG_INHERIT,
  4637. 0);
  4638. /* First check, if there is a CGI interpreter configured for all CGI
  4639. * scripts. */
  4640. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4641. if (interp != NULL) {
  4642. /* If there is a configured interpreter, check for additional arguments
  4643. */
  4644. interp_arg =
  4645. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4646. } else {
  4647. /* Otherwise, the interpreter must be stated in the first line of the
  4648. * CGI script file, after a #! (shebang) mark. */
  4649. buf[0] = buf[1] = '\0';
  4650. /* Get the full script path */
  4651. mg_snprintf(
  4652. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4653. if (truncated) {
  4654. pi.hProcess = (pid_t)-1;
  4655. goto spawn_cleanup;
  4656. }
  4657. /* Open the script file, to read the first line */
  4658. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4659. /* Read the first line of the script into the buffer */
  4660. mg_fgets(buf, sizeof(buf), &file);
  4661. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4662. buf[sizeof(buf) - 1] = '\0';
  4663. }
  4664. if ((buf[0] == '#') && (buf[1] == '!')) {
  4665. trim_trailing_whitespaces(buf + 2);
  4666. } else {
  4667. buf[2] = '\0';
  4668. }
  4669. interp = buf + 2;
  4670. }
  4671. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4672. if (interp[0] != '\0') {
  4673. /* This is an interpreted script file. We must call the interpreter. */
  4674. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4675. mg_snprintf(conn,
  4676. &truncated,
  4677. cmdline,
  4678. sizeof(cmdline),
  4679. "\"%s\" %s \"%s\\%s\"",
  4680. interp,
  4681. interp_arg,
  4682. full_dir,
  4683. prog);
  4684. } else {
  4685. mg_snprintf(conn,
  4686. &truncated,
  4687. cmdline,
  4688. sizeof(cmdline),
  4689. "\"%s\" \"%s\\%s\"",
  4690. interp,
  4691. full_dir,
  4692. prog);
  4693. }
  4694. } else {
  4695. /* This is (probably) a compiled program. We call it directly. */
  4696. mg_snprintf(conn,
  4697. &truncated,
  4698. cmdline,
  4699. sizeof(cmdline),
  4700. "\"%s\\%s\"",
  4701. full_dir,
  4702. prog);
  4703. }
  4704. if (truncated) {
  4705. pi.hProcess = (pid_t)-1;
  4706. goto spawn_cleanup;
  4707. }
  4708. DEBUG_TRACE("Running [%s]", cmdline);
  4709. if (CreateProcessA(NULL,
  4710. cmdline,
  4711. NULL,
  4712. NULL,
  4713. TRUE,
  4714. CREATE_NEW_PROCESS_GROUP,
  4715. envblk,
  4716. NULL,
  4717. &si,
  4718. &pi)
  4719. == 0) {
  4720. mg_cry_internal(
  4721. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4722. pi.hProcess = (pid_t)-1;
  4723. /* goto spawn_cleanup; */
  4724. }
  4725. spawn_cleanup:
  4726. (void)CloseHandle(si.hStdOutput);
  4727. (void)CloseHandle(si.hStdError);
  4728. (void)CloseHandle(si.hStdInput);
  4729. if (pi.hThread != NULL) {
  4730. (void)CloseHandle(pi.hThread);
  4731. }
  4732. return (pid_t)pi.hProcess;
  4733. }
  4734. #endif /* !NO_CGI */
  4735. static int
  4736. set_blocking_mode(SOCKET sock)
  4737. {
  4738. unsigned long non_blocking = 0;
  4739. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4740. }
  4741. static int
  4742. set_non_blocking_mode(SOCKET sock)
  4743. {
  4744. unsigned long non_blocking = 1;
  4745. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4746. }
  4747. #else
  4748. #if !defined(NO_FILESYSTEMS)
  4749. static int
  4750. mg_stat(const struct mg_connection *conn,
  4751. const char *path,
  4752. struct mg_file_stat *filep)
  4753. {
  4754. struct stat st;
  4755. if (!filep) {
  4756. return 0;
  4757. }
  4758. memset(filep, 0, sizeof(*filep));
  4759. if (mg_path_suspicious(conn, path)) {
  4760. return 0;
  4761. }
  4762. if (0 == stat(path, &st)) {
  4763. filep->size = (uint64_t)(st.st_size);
  4764. filep->last_modified = st.st_mtime;
  4765. filep->is_directory = S_ISDIR(st.st_mode);
  4766. return 1;
  4767. }
  4768. return 0;
  4769. }
  4770. #endif /* NO_FILESYSTEMS */
  4771. static void
  4772. set_close_on_exec(int fd,
  4773. const struct mg_connection *conn /* may be null */,
  4774. struct mg_context *ctx /* may be null */)
  4775. {
  4776. #if defined(__ZEPHYR__)
  4777. (void)fd;
  4778. (void)conn;
  4779. (void)ctx;
  4780. #else
  4781. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4782. if (conn || ctx) {
  4783. struct mg_connection fc;
  4784. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4785. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4786. __func__,
  4787. strerror(ERRNO));
  4788. }
  4789. }
  4790. #endif
  4791. }
  4792. CIVETWEB_API int
  4793. mg_start_thread(mg_thread_func_t func, void *param)
  4794. {
  4795. pthread_t thread_id;
  4796. pthread_attr_t attr;
  4797. int result;
  4798. (void)pthread_attr_init(&attr);
  4799. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4800. #if defined(__ZEPHYR__)
  4801. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4802. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4803. /* Compile-time option to control stack size,
  4804. * e.g. -DUSE_STACK_SIZE=16384 */
  4805. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4806. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4807. result = pthread_create(&thread_id, &attr, func, param);
  4808. pthread_attr_destroy(&attr);
  4809. return result;
  4810. }
  4811. /* Start a thread storing the thread context. */
  4812. static int
  4813. mg_start_thread_with_id(mg_thread_func_t func,
  4814. void *param,
  4815. pthread_t *threadidptr)
  4816. {
  4817. pthread_t thread_id;
  4818. pthread_attr_t attr;
  4819. int result;
  4820. (void)pthread_attr_init(&attr);
  4821. #if defined(__ZEPHYR__)
  4822. pthread_attr_setstack(&attr,
  4823. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4824. ZEPHYR_STACK_SIZE);
  4825. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4826. /* Compile-time option to control stack size,
  4827. * e.g. -DUSE_STACK_SIZE=16384 */
  4828. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4829. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4830. result = pthread_create(&thread_id, &attr, func, param);
  4831. pthread_attr_destroy(&attr);
  4832. if ((result == 0) && (threadidptr != NULL)) {
  4833. *threadidptr = thread_id;
  4834. }
  4835. return result;
  4836. }
  4837. /* Wait for a thread to finish. */
  4838. static int
  4839. mg_join_thread(pthread_t threadid)
  4840. {
  4841. int result;
  4842. result = pthread_join(threadid, NULL);
  4843. return result;
  4844. }
  4845. #if !defined(NO_CGI)
  4846. static pid_t
  4847. spawn_process(struct mg_connection *conn,
  4848. const char *prog,
  4849. char *envblk,
  4850. char *envp[],
  4851. int fdin[2],
  4852. int fdout[2],
  4853. int fderr[2],
  4854. const char *dir,
  4855. unsigned char cgi_config_idx)
  4856. {
  4857. pid_t pid;
  4858. const char *interp;
  4859. (void)envblk;
  4860. if ((pid = fork()) == -1) {
  4861. /* Parent */
  4862. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4863. } else if (pid != 0) {
  4864. /* Make sure children close parent-side descriptors.
  4865. * The caller will close the child-side immediately. */
  4866. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4867. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4868. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4869. } else {
  4870. /* Child */
  4871. if (chdir(dir) != 0) {
  4872. mg_cry_internal(
  4873. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4874. } else if (dup2(fdin[0], 0) == -1) {
  4875. mg_cry_internal(conn,
  4876. "%s: dup2(%d, 0): %s",
  4877. __func__,
  4878. fdin[0],
  4879. strerror(ERRNO));
  4880. } else if (dup2(fdout[1], 1) == -1) {
  4881. mg_cry_internal(conn,
  4882. "%s: dup2(%d, 1): %s",
  4883. __func__,
  4884. fdout[1],
  4885. strerror(ERRNO));
  4886. } else if (dup2(fderr[1], 2) == -1) {
  4887. mg_cry_internal(conn,
  4888. "%s: dup2(%d, 2): %s",
  4889. __func__,
  4890. fderr[1],
  4891. strerror(ERRNO));
  4892. } else {
  4893. struct sigaction sa;
  4894. /* Keep stderr and stdout in two different pipes.
  4895. * Stdout will be sent back to the client,
  4896. * stderr should go into a server error log. */
  4897. (void)close(fdin[0]);
  4898. (void)close(fdout[1]);
  4899. (void)close(fderr[1]);
  4900. /* Close write end fdin and read end fdout and fderr */
  4901. (void)close(fdin[1]);
  4902. (void)close(fdout[0]);
  4903. (void)close(fderr[0]);
  4904. /* After exec, all signal handlers are restored to their default
  4905. * values, with one exception of SIGCHLD. According to
  4906. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4907. * will leave unchanged after exec if it was set to be ignored.
  4908. * Restore it to default action. */
  4909. memset(&sa, 0, sizeof(sa));
  4910. sa.sa_handler = SIG_DFL;
  4911. sigaction(SIGCHLD, &sa, NULL);
  4912. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4913. if (interp == NULL) {
  4914. /* no interpreter configured, call the programm directly */
  4915. (void)execle(prog, prog, NULL, envp);
  4916. mg_cry_internal(conn,
  4917. "%s: execle(%s): %s",
  4918. __func__,
  4919. prog,
  4920. strerror(ERRNO));
  4921. } else {
  4922. /* call the configured interpreter */
  4923. const char *interp_args =
  4924. conn->dom_ctx
  4925. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4926. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4927. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4928. } else {
  4929. (void)execle(interp, interp, prog, NULL, envp);
  4930. }
  4931. mg_cry_internal(conn,
  4932. "%s: execle(%s %s): %s",
  4933. __func__,
  4934. interp,
  4935. prog,
  4936. strerror(ERRNO));
  4937. }
  4938. }
  4939. exit(EXIT_FAILURE);
  4940. }
  4941. return pid;
  4942. }
  4943. #endif /* !NO_CGI */
  4944. static int
  4945. set_non_blocking_mode(SOCKET sock)
  4946. {
  4947. int flags = fcntl(sock, F_GETFL, 0);
  4948. if (flags < 0) {
  4949. return -1;
  4950. }
  4951. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4952. return -1;
  4953. }
  4954. return 0;
  4955. }
  4956. static int
  4957. set_blocking_mode(SOCKET sock)
  4958. {
  4959. int flags = fcntl(sock, F_GETFL, 0);
  4960. if (flags < 0) {
  4961. return -1;
  4962. }
  4963. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4964. return -1;
  4965. }
  4966. return 0;
  4967. }
  4968. #endif /* _WIN32 / else */
  4969. /* End of initial operating system specific define block. */
  4970. /* Get a random number (independent of C rand function) */
  4971. static uint64_t
  4972. get_random(void)
  4973. {
  4974. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4975. static uint64_t lcg = 0; /* Linear congruential generator */
  4976. uint64_t now = mg_get_current_time_ns();
  4977. if (lfsr == 0) {
  4978. /* lfsr will be only 0 if has not been initialized,
  4979. * so this code is called only once. */
  4980. lfsr = mg_get_current_time_ns();
  4981. lcg = mg_get_current_time_ns();
  4982. } else {
  4983. /* Get the next step of both random number generators. */
  4984. lfsr = (lfsr >> 1)
  4985. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4986. << 63);
  4987. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4988. }
  4989. /* Combining two pseudo-random number generators and a high resolution
  4990. * part
  4991. * of the current server time will make it hard (impossible?) to guess
  4992. * the
  4993. * next number. */
  4994. return (lfsr ^ lcg ^ now);
  4995. }
  4996. static int
  4997. mg_poll(struct mg_pollfd *pfd,
  4998. unsigned int n,
  4999. int milliseconds,
  5000. const stop_flag_t *stop_flag)
  5001. {
  5002. /* Call poll, but only for a maximum time of a few seconds.
  5003. * This will allow to stop the server after some seconds, instead
  5004. * of having to wait for a long socket timeout. */
  5005. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5006. int check_pollerr = 0;
  5007. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5008. /* If we wait for only one file descriptor, wait on error as well */
  5009. pfd[0].events |= POLLERR;
  5010. check_pollerr = 1;
  5011. }
  5012. do {
  5013. int result;
  5014. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5015. /* Shut down signal */
  5016. return -2;
  5017. }
  5018. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5019. ms_now = milliseconds;
  5020. }
  5021. result = poll(pfd, n, ms_now);
  5022. if (result != 0) {
  5023. /* Poll returned either success (1) or error (-1).
  5024. * Forward both to the caller. */
  5025. if ((check_pollerr)
  5026. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5027. == POLLERR)) {
  5028. /* One and only file descriptor returned error */
  5029. return -1;
  5030. }
  5031. return result;
  5032. }
  5033. /* Poll returned timeout (0). */
  5034. if (milliseconds > 0) {
  5035. milliseconds -= ms_now;
  5036. }
  5037. } while (milliseconds > 0);
  5038. /* timeout: return 0 */
  5039. return 0;
  5040. }
  5041. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5042. * descriptor.
  5043. * Return value:
  5044. * >=0 .. number of bytes successfully written
  5045. * -1 .. timeout
  5046. * -2 .. error
  5047. */
  5048. static int
  5049. push_inner(struct mg_context *ctx,
  5050. FILE *fp,
  5051. SOCKET sock,
  5052. SSL *ssl,
  5053. const char *buf,
  5054. int len,
  5055. double timeout)
  5056. {
  5057. uint64_t start = 0, now = 0, timeout_ns = 0;
  5058. int n, err;
  5059. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5060. #if defined(_WIN32)
  5061. typedef int len_t;
  5062. #else
  5063. typedef size_t len_t;
  5064. #endif
  5065. if (timeout > 0) {
  5066. now = mg_get_current_time_ns();
  5067. start = now;
  5068. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5069. }
  5070. if (ctx == NULL) {
  5071. return -2;
  5072. }
  5073. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5074. if (ssl) {
  5075. return -2;
  5076. }
  5077. #endif
  5078. /* Try to read until it succeeds, fails, times out, or the server
  5079. * shuts down. */
  5080. for (;;) {
  5081. #if defined(USE_MBEDTLS)
  5082. if (ssl != NULL) {
  5083. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5084. if (n <= 0) {
  5085. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5086. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5087. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5088. n = 0;
  5089. } else {
  5090. fprintf(stderr, "SSL write failed, error %d\n", n);
  5091. return -2;
  5092. }
  5093. } else {
  5094. err = 0;
  5095. }
  5096. } else
  5097. #elif !defined(NO_SSL)
  5098. if (ssl != NULL) {
  5099. ERR_clear_error();
  5100. n = SSL_write(ssl, buf, len);
  5101. if (n <= 0) {
  5102. err = SSL_get_error(ssl, n);
  5103. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5104. err = ERRNO;
  5105. } else if ((err == SSL_ERROR_WANT_READ)
  5106. || (err == SSL_ERROR_WANT_WRITE)) {
  5107. n = 0;
  5108. } else {
  5109. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5110. ERR_clear_error();
  5111. return -2;
  5112. }
  5113. ERR_clear_error();
  5114. } else {
  5115. err = 0;
  5116. }
  5117. } else
  5118. #endif
  5119. if (fp != NULL) {
  5120. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5121. if (ferror(fp)) {
  5122. n = -1;
  5123. err = ERRNO;
  5124. } else {
  5125. err = 0;
  5126. }
  5127. } else {
  5128. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5129. err = (n < 0) ? ERRNO : 0;
  5130. #if defined(_WIN32)
  5131. if (err == WSAEWOULDBLOCK) {
  5132. err = 0;
  5133. n = 0;
  5134. }
  5135. #else
  5136. if (ERROR_TRY_AGAIN(err)) {
  5137. err = 0;
  5138. n = 0;
  5139. }
  5140. #endif
  5141. if (n < 0) {
  5142. /* shutdown of the socket at client side */
  5143. return -2;
  5144. }
  5145. }
  5146. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5147. return -2;
  5148. }
  5149. if ((n > 0) || ((n == 0) && (len == 0))) {
  5150. /* some data has been read, or no data was requested */
  5151. return n;
  5152. }
  5153. if (n < 0) {
  5154. /* socket error - check errno */
  5155. DEBUG_TRACE("send() failed, error %d", err);
  5156. /* TODO (mid): error handling depending on the error code.
  5157. * These codes are different between Windows and Linux.
  5158. * Currently there is no problem with failing send calls,
  5159. * if there is a reproducible situation, it should be
  5160. * investigated in detail.
  5161. */
  5162. return -2;
  5163. }
  5164. /* Only in case n=0 (timeout), repeat calling the write function */
  5165. /* If send failed, wait before retry */
  5166. if (fp != NULL) {
  5167. /* For files, just wait a fixed time.
  5168. * Maybe it helps, maybe not. */
  5169. mg_sleep(5);
  5170. } else {
  5171. /* For sockets, wait for the socket using poll */
  5172. struct mg_pollfd pfd[1];
  5173. int pollres;
  5174. pfd[0].fd = sock;
  5175. pfd[0].events = POLLOUT;
  5176. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5177. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5178. return -2;
  5179. }
  5180. if (pollres > 0) {
  5181. continue;
  5182. }
  5183. }
  5184. if (timeout > 0) {
  5185. now = mg_get_current_time_ns();
  5186. if ((now - start) > timeout_ns) {
  5187. /* Timeout */
  5188. break;
  5189. }
  5190. }
  5191. }
  5192. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5193. used */
  5194. return -1;
  5195. }
  5196. static int
  5197. push_all(struct mg_context *ctx,
  5198. FILE *fp,
  5199. SOCKET sock,
  5200. SSL *ssl,
  5201. const char *buf,
  5202. int len)
  5203. {
  5204. double timeout = -1.0;
  5205. int n, nwritten = 0;
  5206. if (ctx == NULL) {
  5207. return -1;
  5208. }
  5209. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5210. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5211. }
  5212. if (timeout <= 0.0) {
  5213. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5214. / 1000.0;
  5215. }
  5216. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5217. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5218. if (n < 0) {
  5219. if (nwritten == 0) {
  5220. nwritten = -1; /* Propagate the error */
  5221. }
  5222. break;
  5223. } else if (n == 0) {
  5224. break; /* No more data to write */
  5225. } else {
  5226. nwritten += n;
  5227. len -= n;
  5228. }
  5229. }
  5230. return nwritten;
  5231. }
  5232. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5233. * Return value:
  5234. * >=0 .. number of bytes successfully read
  5235. * -1 .. timeout
  5236. * -2 .. error
  5237. */
  5238. static int
  5239. pull_inner(FILE *fp,
  5240. struct mg_connection *conn,
  5241. char *buf,
  5242. int len,
  5243. double timeout)
  5244. {
  5245. int nread, err = 0;
  5246. #if defined(_WIN32)
  5247. typedef int len_t;
  5248. #else
  5249. typedef size_t len_t;
  5250. #endif
  5251. /* We need an additional wait loop around this, because in some cases
  5252. * with TLSwe may get data from the socket but not from SSL_read.
  5253. * In this case we need to repeat at least once.
  5254. */
  5255. if (fp != NULL) {
  5256. /* Use read() instead of fread(), because if we're reading from the
  5257. * CGI pipe, fread() may block until IO buffer is filled up. We
  5258. * cannot afford to block and must pass all read bytes immediately
  5259. * to the client. */
  5260. nread = (int)read(fileno(fp), buf, (size_t)len);
  5261. err = (nread < 0) ? ERRNO : 0;
  5262. if ((nread == 0) && (len > 0)) {
  5263. /* Should get data, but got EOL */
  5264. return -2;
  5265. }
  5266. #if defined(USE_MBEDTLS)
  5267. } else if (conn->ssl != NULL) {
  5268. struct mg_pollfd pfd[1];
  5269. int to_read;
  5270. int pollres;
  5271. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5272. if (to_read > 0) {
  5273. /* We already know there is no more data buffered in conn->buf
  5274. * but there is more available in the SSL layer. So don't poll
  5275. * conn->client.sock yet. */
  5276. pollres = 1;
  5277. if (to_read > len)
  5278. to_read = len;
  5279. } else {
  5280. pfd[0].fd = conn->client.sock;
  5281. pfd[0].events = POLLIN;
  5282. to_read = len;
  5283. pollres = mg_poll(pfd,
  5284. 1,
  5285. (int)(timeout * 1000.0),
  5286. &(conn->phys_ctx->stop_flag));
  5287. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5288. return -2;
  5289. }
  5290. }
  5291. if (pollres > 0) {
  5292. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5293. if (nread <= 0) {
  5294. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5295. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5296. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5297. nread = 0;
  5298. } else {
  5299. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5300. return -2;
  5301. }
  5302. } else {
  5303. err = 0;
  5304. }
  5305. } else if (pollres < 0) {
  5306. /* Error */
  5307. return -2;
  5308. } else {
  5309. /* pollres = 0 means timeout */
  5310. nread = 0;
  5311. }
  5312. #elif !defined(NO_SSL)
  5313. } else if (conn->ssl != NULL) {
  5314. int ssl_pending;
  5315. struct mg_pollfd pfd[1];
  5316. int pollres;
  5317. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5318. /* We already know there is no more data buffered in conn->buf
  5319. * but there is more available in the SSL layer. So don't poll
  5320. * conn->client.sock yet. */
  5321. if (ssl_pending > len) {
  5322. ssl_pending = len;
  5323. }
  5324. pollres = 1;
  5325. } else {
  5326. pfd[0].fd = conn->client.sock;
  5327. pfd[0].events = POLLIN;
  5328. pollres = mg_poll(pfd,
  5329. 1,
  5330. (int)(timeout * 1000.0),
  5331. &(conn->phys_ctx->stop_flag));
  5332. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5333. return -2;
  5334. }
  5335. }
  5336. if (pollres > 0) {
  5337. ERR_clear_error();
  5338. nread =
  5339. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5340. if (nread <= 0) {
  5341. err = SSL_get_error(conn->ssl, nread);
  5342. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5343. err = ERRNO;
  5344. } else if ((err == SSL_ERROR_WANT_READ)
  5345. || (err == SSL_ERROR_WANT_WRITE)) {
  5346. nread = 0;
  5347. } else {
  5348. /* All errors should return -2 */
  5349. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5350. ERR_clear_error();
  5351. return -2;
  5352. }
  5353. ERR_clear_error();
  5354. } else {
  5355. err = 0;
  5356. }
  5357. } else if (pollres < 0) {
  5358. /* Error */
  5359. return -2;
  5360. } else {
  5361. /* pollres = 0 means timeout */
  5362. nread = 0;
  5363. }
  5364. #endif
  5365. } else {
  5366. struct mg_pollfd pfd[1];
  5367. int pollres;
  5368. pfd[0].fd = conn->client.sock;
  5369. pfd[0].events = POLLIN;
  5370. pollres = mg_poll(pfd,
  5371. 1,
  5372. (int)(timeout * 1000.0),
  5373. &(conn->phys_ctx->stop_flag));
  5374. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5375. return -2;
  5376. }
  5377. if (pollres > 0) {
  5378. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5379. err = (nread < 0) ? ERRNO : 0;
  5380. if (nread <= 0) {
  5381. /* shutdown of the socket at client side */
  5382. return -2;
  5383. }
  5384. } else if (pollres < 0) {
  5385. /* error callint poll */
  5386. return -2;
  5387. } else {
  5388. /* pollres = 0 means timeout */
  5389. nread = 0;
  5390. }
  5391. }
  5392. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5393. return -2;
  5394. }
  5395. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5396. /* some data has been read, or no data was requested */
  5397. return nread;
  5398. }
  5399. if (nread < 0) {
  5400. /* socket error - check errno */
  5401. #if defined(_WIN32)
  5402. if (err == WSAEWOULDBLOCK) {
  5403. /* TODO (low): check if this is still required */
  5404. /* standard case if called from close_socket_gracefully */
  5405. return -2;
  5406. } else if (err == WSAETIMEDOUT) {
  5407. /* TODO (low): check if this is still required */
  5408. /* timeout is handled by the while loop */
  5409. return 0;
  5410. } else if (err == WSAECONNABORTED) {
  5411. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5412. return -2;
  5413. } else {
  5414. DEBUG_TRACE("recv() failed, error %d", err);
  5415. return -2;
  5416. }
  5417. #else
  5418. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5419. * if the timeout is reached and if the socket was set to non-
  5420. * blocking in close_socket_gracefully, so we can not distinguish
  5421. * here. We have to wait for the timeout in both cases for now.
  5422. */
  5423. if (ERROR_TRY_AGAIN(err)) {
  5424. /* TODO (low): check if this is still required */
  5425. /* EAGAIN/EWOULDBLOCK:
  5426. * standard case if called from close_socket_gracefully
  5427. * => should return -1 */
  5428. /* or timeout occurred
  5429. * => the code must stay in the while loop */
  5430. /* EINTR can be generated on a socket with a timeout set even
  5431. * when SA_RESTART is effective for all relevant signals
  5432. * (see signal(7)).
  5433. * => stay in the while loop */
  5434. } else {
  5435. DEBUG_TRACE("recv() failed, error %d", err);
  5436. return -2;
  5437. }
  5438. #endif
  5439. }
  5440. /* Timeout occurred, but no data available. */
  5441. return -1;
  5442. }
  5443. static int
  5444. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5445. {
  5446. int n, nread = 0;
  5447. double timeout = -1.0;
  5448. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5449. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5450. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5451. }
  5452. if (timeout <= 0.0) {
  5453. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5454. / 1000.0;
  5455. }
  5456. start_time = mg_get_current_time_ns();
  5457. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5458. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5459. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5460. if (n == -2) {
  5461. if (nread == 0) {
  5462. nread = -1; /* Propagate the error */
  5463. }
  5464. break;
  5465. } else if (n == -1) {
  5466. /* timeout */
  5467. if (timeout >= 0.0) {
  5468. now = mg_get_current_time_ns();
  5469. if ((now - start_time) <= timeout_ns) {
  5470. continue;
  5471. }
  5472. }
  5473. break;
  5474. } else if (n == 0) {
  5475. break; /* No more data to read */
  5476. } else {
  5477. nread += n;
  5478. len -= n;
  5479. }
  5480. }
  5481. return nread;
  5482. }
  5483. static void
  5484. discard_unread_request_data(struct mg_connection *conn)
  5485. {
  5486. char buf[MG_BUF_LEN];
  5487. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5488. ;
  5489. }
  5490. static int
  5491. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5492. {
  5493. int64_t content_len, n, buffered_len, nread;
  5494. int64_t len64 =
  5495. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5496. * int, we may not read more
  5497. * bytes */
  5498. const char *body;
  5499. if (conn == NULL) {
  5500. return 0;
  5501. }
  5502. /* If Content-Length is not set for a response with body data,
  5503. * we do not know in advance how much data should be read. */
  5504. content_len = conn->content_len;
  5505. if (content_len < 0) {
  5506. /* The body data is completed when the connection is closed. */
  5507. content_len = INT64_MAX;
  5508. }
  5509. nread = 0;
  5510. if (conn->consumed_content < content_len) {
  5511. /* Adjust number of bytes to read. */
  5512. int64_t left_to_read = content_len - conn->consumed_content;
  5513. if (left_to_read < len64) {
  5514. /* Do not read more than the total content length of the
  5515. * request.
  5516. */
  5517. len64 = left_to_read;
  5518. }
  5519. /* Return buffered data */
  5520. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5521. - conn->consumed_content;
  5522. if (buffered_len > 0) {
  5523. if (len64 < buffered_len) {
  5524. buffered_len = len64;
  5525. }
  5526. body = conn->buf + conn->request_len + conn->consumed_content;
  5527. memcpy(buf, body, (size_t)buffered_len);
  5528. len64 -= buffered_len;
  5529. conn->consumed_content += buffered_len;
  5530. nread += buffered_len;
  5531. buf = (char *)buf + buffered_len;
  5532. }
  5533. /* We have returned all buffered data. Read new data from the remote
  5534. * socket.
  5535. */
  5536. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5537. conn->consumed_content += n;
  5538. nread += n;
  5539. } else {
  5540. nread = ((nread > 0) ? nread : n);
  5541. }
  5542. }
  5543. return (int)nread;
  5544. }
  5545. /* Forward declarations */
  5546. static void handle_request(struct mg_connection *);
  5547. static void log_access(const struct mg_connection *);
  5548. /* Handle request, update statistics and call access log */
  5549. static void
  5550. handle_request_stat_log(struct mg_connection *conn)
  5551. {
  5552. #if defined(USE_SERVER_STATS)
  5553. struct timespec tnow;
  5554. conn->conn_state = 4; /* processing */
  5555. #endif
  5556. handle_request(conn);
  5557. #if defined(USE_SERVER_STATS)
  5558. conn->conn_state = 5; /* processed */
  5559. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5560. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5561. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5562. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5563. conn->num_bytes_sent);
  5564. #endif
  5565. DEBUG_TRACE("%s", "handle_request done");
  5566. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5567. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5568. DEBUG_TRACE("%s", "end_request callback done");
  5569. }
  5570. log_access(conn);
  5571. }
  5572. #if defined(USE_HTTP2)
  5573. #if defined(NO_SSL)
  5574. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5575. #endif
  5576. #define USE_ALPN
  5577. #include "http2.inl"
  5578. /* Not supported with HTTP/2 */
  5579. #define HTTP1_only \
  5580. { \
  5581. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5582. http2_must_use_http1(conn); \
  5583. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5584. return; \
  5585. } \
  5586. }
  5587. #else
  5588. #define HTTP1_only
  5589. #endif
  5590. CIVETWEB_API int
  5591. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5592. {
  5593. if (len > INT_MAX) {
  5594. len = INT_MAX;
  5595. }
  5596. if (conn == NULL) {
  5597. return 0;
  5598. }
  5599. if (conn->is_chunked) {
  5600. size_t all_read = 0;
  5601. while (len > 0) {
  5602. if (conn->is_chunked >= 3) {
  5603. /* No more data left to read */
  5604. return 0;
  5605. }
  5606. if (conn->is_chunked != 1) {
  5607. /* Has error */
  5608. return -1;
  5609. }
  5610. if (conn->consumed_content != conn->content_len) {
  5611. /* copy from the current chunk */
  5612. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5613. if (read_ret < 1) {
  5614. /* read error */
  5615. conn->is_chunked = 2;
  5616. return -1;
  5617. }
  5618. all_read += (size_t)read_ret;
  5619. len -= (size_t)read_ret;
  5620. if (conn->consumed_content == conn->content_len) {
  5621. /* Add data bytes in the current chunk have been read,
  5622. * so we are expecting \r\n now. */
  5623. char x[2];
  5624. conn->content_len += 2;
  5625. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5626. || (x[1] != '\n')) {
  5627. /* Protocol violation */
  5628. conn->is_chunked = 2;
  5629. return -1;
  5630. }
  5631. }
  5632. } else {
  5633. /* fetch a new chunk */
  5634. size_t i;
  5635. char lenbuf[64];
  5636. char *end = NULL;
  5637. unsigned long chunkSize = 0;
  5638. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5639. conn->content_len++;
  5640. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5641. lenbuf[i] = 0;
  5642. }
  5643. if ((i > 0) && (lenbuf[i] == '\r')
  5644. && (lenbuf[i - 1] != '\r')) {
  5645. continue;
  5646. }
  5647. if ((i > 1) && (lenbuf[i] == '\n')
  5648. && (lenbuf[i - 1] == '\r')) {
  5649. lenbuf[i + 1] = 0;
  5650. chunkSize = strtoul(lenbuf, &end, 16);
  5651. if (chunkSize == 0) {
  5652. /* regular end of content */
  5653. conn->is_chunked = 3;
  5654. }
  5655. break;
  5656. }
  5657. if (!isxdigit((unsigned char)lenbuf[i])) {
  5658. /* illegal character for chunk length */
  5659. conn->is_chunked = 2;
  5660. return -1;
  5661. }
  5662. }
  5663. if ((end == NULL) || (*end != '\r')) {
  5664. /* chunksize not set correctly */
  5665. conn->is_chunked = 2;
  5666. return -1;
  5667. }
  5668. if (chunkSize == 0) {
  5669. /* try discarding trailer for keep-alive */
  5670. conn->content_len += 2;
  5671. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5672. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5673. conn->is_chunked = 4;
  5674. }
  5675. break;
  5676. }
  5677. /* append a new chunk */
  5678. conn->content_len += (int64_t)chunkSize;
  5679. }
  5680. }
  5681. return (int)all_read;
  5682. }
  5683. return mg_read_inner(conn, buf, len);
  5684. }
  5685. CIVETWEB_API int
  5686. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5687. {
  5688. time_t now;
  5689. int n, total, allowed;
  5690. if (conn == NULL) {
  5691. return 0;
  5692. }
  5693. if (len > INT_MAX) {
  5694. return -1;
  5695. }
  5696. /* Mark connection as "data sent" */
  5697. conn->request_state = 10;
  5698. #if defined(USE_HTTP2)
  5699. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5700. http2_data_frame_head(conn, len, 0);
  5701. }
  5702. #endif
  5703. if (conn->throttle > 0) {
  5704. if ((now = time(NULL)) != conn->last_throttle_time) {
  5705. conn->last_throttle_time = now;
  5706. conn->last_throttle_bytes = 0;
  5707. }
  5708. allowed = conn->throttle - conn->last_throttle_bytes;
  5709. if (allowed > (int)len) {
  5710. allowed = (int)len;
  5711. }
  5712. total = push_all(conn->phys_ctx,
  5713. NULL,
  5714. conn->client.sock,
  5715. conn->ssl,
  5716. (const char *)buf,
  5717. allowed);
  5718. if (total == allowed) {
  5719. buf = (const char *)buf + total;
  5720. conn->last_throttle_bytes += total;
  5721. while ((total < (int)len)
  5722. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5723. allowed = (conn->throttle > ((int)len - total))
  5724. ? (int)len - total
  5725. : conn->throttle;
  5726. n = push_all(conn->phys_ctx,
  5727. NULL,
  5728. conn->client.sock,
  5729. conn->ssl,
  5730. (const char *)buf,
  5731. allowed);
  5732. if (n != allowed) {
  5733. break;
  5734. }
  5735. sleep(1);
  5736. conn->last_throttle_bytes = allowed;
  5737. conn->last_throttle_time = time(NULL);
  5738. buf = (const char *)buf + n;
  5739. total += n;
  5740. }
  5741. }
  5742. } else {
  5743. total = push_all(conn->phys_ctx,
  5744. NULL,
  5745. conn->client.sock,
  5746. conn->ssl,
  5747. (const char *)buf,
  5748. (int)len);
  5749. }
  5750. if (total > 0) {
  5751. conn->num_bytes_sent += total;
  5752. }
  5753. return total;
  5754. }
  5755. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5756. CIVETWEB_API int
  5757. mg_send_chunk(struct mg_connection *conn,
  5758. const char *chunk,
  5759. unsigned int chunk_len)
  5760. {
  5761. char lenbuf[16];
  5762. size_t lenbuf_len;
  5763. int ret;
  5764. int t;
  5765. /* First store the length information in a text buffer. */
  5766. sprintf(lenbuf, "%x\r\n", chunk_len);
  5767. lenbuf_len = strlen(lenbuf);
  5768. /* Then send length information, chunk and terminating \r\n. */
  5769. ret = mg_write(conn, lenbuf, lenbuf_len);
  5770. if (ret != (int)lenbuf_len) {
  5771. return -1;
  5772. }
  5773. t = ret;
  5774. ret = mg_write(conn, chunk, chunk_len);
  5775. if (ret != (int)chunk_len) {
  5776. return -1;
  5777. }
  5778. t += ret;
  5779. ret = mg_write(conn, "\r\n", 2);
  5780. if (ret != 2) {
  5781. return -1;
  5782. }
  5783. t += ret;
  5784. return t;
  5785. }
  5786. #if defined(GCC_DIAGNOSTIC)
  5787. /* This block forwards format strings to printf implementations,
  5788. * so we need to disable the format-nonliteral warning. */
  5789. #pragma GCC diagnostic push
  5790. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5791. #endif
  5792. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5793. static int
  5794. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5795. {
  5796. va_list ap_copy;
  5797. size_t size = MG_BUF_LEN / 4;
  5798. int len = -1;
  5799. *buf = NULL;
  5800. while (len < 0) {
  5801. if (*buf) {
  5802. mg_free(*buf);
  5803. }
  5804. size *= 4;
  5805. *buf = (char *)mg_malloc(size);
  5806. if (!*buf) {
  5807. break;
  5808. }
  5809. va_copy(ap_copy, ap);
  5810. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5811. va_end(ap_copy);
  5812. (*buf)[size - 1] = 0;
  5813. }
  5814. return len;
  5815. }
  5816. /* Print message to buffer. If buffer is large enough to hold the message,
  5817. * return buffer. If buffer is to small, allocate large enough buffer on
  5818. * heap,
  5819. * and return allocated buffer. */
  5820. static int
  5821. alloc_vprintf(char **out_buf,
  5822. char *prealloc_buf,
  5823. size_t prealloc_size,
  5824. const char *fmt,
  5825. va_list ap)
  5826. {
  5827. va_list ap_copy;
  5828. int len;
  5829. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5830. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5831. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5832. * Therefore, we make two passes: on first pass, get required message
  5833. * length.
  5834. * On second pass, actually print the message. */
  5835. va_copy(ap_copy, ap);
  5836. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5837. va_end(ap_copy);
  5838. if (len < 0) {
  5839. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5840. * Switch to alternative code path that uses incremental
  5841. * allocations.
  5842. */
  5843. va_copy(ap_copy, ap);
  5844. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5845. va_end(ap_copy);
  5846. } else if ((size_t)(len) >= prealloc_size) {
  5847. /* The pre-allocated buffer not large enough. */
  5848. /* Allocate a new buffer. */
  5849. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5850. if (!*out_buf) {
  5851. /* Allocation failed. Return -1 as "out of memory" error. */
  5852. return -1;
  5853. }
  5854. /* Buffer allocation successful. Store the string there. */
  5855. va_copy(ap_copy, ap);
  5856. IGNORE_UNUSED_RESULT(
  5857. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5858. va_end(ap_copy);
  5859. } else {
  5860. /* The pre-allocated buffer is large enough.
  5861. * Use it to store the string and return the address. */
  5862. va_copy(ap_copy, ap);
  5863. IGNORE_UNUSED_RESULT(
  5864. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5865. va_end(ap_copy);
  5866. *out_buf = prealloc_buf;
  5867. }
  5868. return len;
  5869. }
  5870. static int
  5871. alloc_printf(char **out_buf, const char *fmt, ...)
  5872. {
  5873. va_list ap;
  5874. int result;
  5875. va_start(ap, fmt);
  5876. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  5877. va_end(ap);
  5878. return result;
  5879. }
  5880. #if defined(GCC_DIAGNOSTIC)
  5881. /* Enable format-nonliteral warning again. */
  5882. #pragma GCC diagnostic pop
  5883. #endif
  5884. static int
  5885. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5886. {
  5887. char mem[MG_BUF_LEN];
  5888. char *buf = NULL;
  5889. int len;
  5890. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5891. len = mg_write(conn, buf, (size_t)len);
  5892. }
  5893. if (buf != mem) {
  5894. mg_free(buf);
  5895. }
  5896. return len;
  5897. }
  5898. CIVETWEB_API int
  5899. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5900. {
  5901. va_list ap;
  5902. int result;
  5903. va_start(ap, fmt);
  5904. result = mg_vprintf(conn, fmt, ap);
  5905. va_end(ap);
  5906. return result;
  5907. }
  5908. CIVETWEB_API int
  5909. mg_url_decode(const char *src,
  5910. int src_len,
  5911. char *dst,
  5912. int dst_len,
  5913. int is_form_url_encoded)
  5914. {
  5915. int i, j, a, b;
  5916. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5917. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5918. if ((i < src_len - 2) && (src[i] == '%')
  5919. && isxdigit((unsigned char)src[i + 1])
  5920. && isxdigit((unsigned char)src[i + 2])) {
  5921. a = tolower((unsigned char)src[i + 1]);
  5922. b = tolower((unsigned char)src[i + 2]);
  5923. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5924. i += 2;
  5925. } else if (is_form_url_encoded && (src[i] == '+')) {
  5926. dst[j] = ' ';
  5927. } else {
  5928. dst[j] = src[i];
  5929. }
  5930. }
  5931. dst[j] = '\0'; /* Null-terminate the destination */
  5932. return (i >= src_len) ? j : -1;
  5933. }
  5934. /* form url decoding of an entire string */
  5935. static void
  5936. url_decode_in_place(char *buf)
  5937. {
  5938. int len = (int)strlen(buf);
  5939. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5940. }
  5941. CIVETWEB_API int
  5942. mg_get_var(const char *data,
  5943. size_t data_len,
  5944. const char *name,
  5945. char *dst,
  5946. size_t dst_len)
  5947. {
  5948. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5949. }
  5950. CIVETWEB_API int
  5951. mg_get_var2(const char *data,
  5952. size_t data_len,
  5953. const char *name,
  5954. char *dst,
  5955. size_t dst_len,
  5956. size_t occurrence)
  5957. {
  5958. const char *p, *e, *s;
  5959. size_t name_len;
  5960. int len;
  5961. if ((dst == NULL) || (dst_len == 0)) {
  5962. len = -2;
  5963. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5964. len = -1;
  5965. dst[0] = '\0';
  5966. } else {
  5967. name_len = strlen(name);
  5968. e = data + data_len;
  5969. len = -1;
  5970. dst[0] = '\0';
  5971. /* data is "var1=val1&var2=val2...". Find variable first */
  5972. for (p = data; p + name_len < e; p++) {
  5973. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5974. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5975. /* Point p to variable value */
  5976. p += name_len + 1;
  5977. /* Point s to the end of the value */
  5978. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5979. if (s == NULL) {
  5980. s = e;
  5981. }
  5982. DEBUG_ASSERT(s >= p);
  5983. if (s < p) {
  5984. return -3;
  5985. }
  5986. /* Decode variable into destination buffer */
  5987. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5988. /* Redirect error code from -1 to -2 (destination buffer too
  5989. * small). */
  5990. if (len == -1) {
  5991. len = -2;
  5992. }
  5993. break;
  5994. }
  5995. }
  5996. }
  5997. return len;
  5998. }
  5999. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6000. CIVETWEB_API int
  6001. mg_split_form_urlencoded(char *data,
  6002. struct mg_header *form_fields,
  6003. unsigned num_form_fields)
  6004. {
  6005. char *b;
  6006. int i;
  6007. int num = 0;
  6008. if (data == NULL) {
  6009. /* parameter error */
  6010. return -1;
  6011. }
  6012. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6013. /* determine the number of expected fields */
  6014. if (data[0] == 0) {
  6015. return 0;
  6016. }
  6017. /* count number of & to return the number of key-value-pairs */
  6018. num = 1;
  6019. while (*data) {
  6020. if (*data == '&') {
  6021. num++;
  6022. }
  6023. data++;
  6024. }
  6025. return num;
  6026. }
  6027. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6028. /* parameter error */
  6029. return -1;
  6030. }
  6031. for (i = 0; i < (int)num_form_fields; i++) {
  6032. /* extract key-value pairs from input data */
  6033. while ((*data == ' ') || (*data == '\t')) {
  6034. /* skip initial spaces */
  6035. data++;
  6036. }
  6037. if (*data == 0) {
  6038. /* end of string reached */
  6039. break;
  6040. }
  6041. form_fields[num].name = data;
  6042. /* find & or = */
  6043. b = data;
  6044. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6045. b++;
  6046. }
  6047. if (*b == 0) {
  6048. /* last key without value */
  6049. form_fields[num].value = NULL;
  6050. } else if (*b == '&') {
  6051. /* mid key without value */
  6052. form_fields[num].value = NULL;
  6053. } else {
  6054. /* terminate string */
  6055. *b = 0;
  6056. /* value starts after '=' */
  6057. data = b + 1;
  6058. form_fields[num].value = data;
  6059. }
  6060. /* new field is stored */
  6061. num++;
  6062. /* find a next key */
  6063. b = strchr(data, '&');
  6064. if (b == 0) {
  6065. /* no more data */
  6066. break;
  6067. } else {
  6068. /* terminate value of last field at '&' */
  6069. *b = 0;
  6070. /* next key-value-pairs starts after '&' */
  6071. data = b + 1;
  6072. }
  6073. }
  6074. /* Decode all values */
  6075. for (i = 0; i < num; i++) {
  6076. if (form_fields[i].name) {
  6077. url_decode_in_place((char *)form_fields[i].name);
  6078. }
  6079. if (form_fields[i].value) {
  6080. url_decode_in_place((char *)form_fields[i].value);
  6081. }
  6082. }
  6083. /* return number of fields found */
  6084. return num;
  6085. }
  6086. /* HCP24: some changes to compare whole var_name */
  6087. CIVETWEB_API int
  6088. mg_get_cookie(const char *cookie_header,
  6089. const char *var_name,
  6090. char *dst,
  6091. size_t dst_size)
  6092. {
  6093. const char *s, *p, *end;
  6094. int name_len, len = -1;
  6095. if ((dst == NULL) || (dst_size == 0)) {
  6096. return -2;
  6097. }
  6098. dst[0] = '\0';
  6099. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6100. return -1;
  6101. }
  6102. name_len = (int)strlen(var_name);
  6103. end = s + strlen(s);
  6104. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6105. if (s[name_len] == '=') {
  6106. /* HCP24: now check is it a substring or a full cookie name */
  6107. if ((s == cookie_header) || (s[-1] == ' ')) {
  6108. s += name_len + 1;
  6109. if ((p = strchr(s, ' ')) == NULL) {
  6110. p = end;
  6111. }
  6112. if (p[-1] == ';') {
  6113. p--;
  6114. }
  6115. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6116. s++;
  6117. p--;
  6118. }
  6119. if ((size_t)(p - s) < dst_size) {
  6120. len = (int)(p - s);
  6121. mg_strlcpy(dst, s, (size_t)len + 1);
  6122. } else {
  6123. len = -3;
  6124. }
  6125. break;
  6126. }
  6127. }
  6128. }
  6129. return len;
  6130. }
  6131. CIVETWEB_API int
  6132. mg_base64_encode(const unsigned char *src,
  6133. size_t src_len,
  6134. char *dst,
  6135. size_t *dst_len)
  6136. {
  6137. static const char *b64 =
  6138. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6139. size_t i, j;
  6140. int a, b, c;
  6141. if (dst_len != NULL) {
  6142. /* Expected length including 0 termination: */
  6143. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6144. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6145. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6146. if (*dst_len < expected_len) {
  6147. if (*dst_len > 0) {
  6148. dst[0] = '\0';
  6149. }
  6150. *dst_len = expected_len;
  6151. return 0;
  6152. }
  6153. }
  6154. for (i = j = 0; i < src_len; i += 3) {
  6155. a = src[i];
  6156. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6157. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6158. dst[j++] = b64[a >> 2];
  6159. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6160. if (i + 1 < src_len) {
  6161. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6162. }
  6163. if (i + 2 < src_len) {
  6164. dst[j++] = b64[c & 63];
  6165. }
  6166. }
  6167. while (j % 4 != 0) {
  6168. dst[j++] = '=';
  6169. }
  6170. dst[j++] = '\0';
  6171. if (dst_len != NULL) {
  6172. *dst_len = (size_t)j;
  6173. }
  6174. /* Return -1 for "OK" */
  6175. return -1;
  6176. }
  6177. static unsigned char
  6178. b64reverse(char letter)
  6179. {
  6180. if ((letter >= 'A') && (letter <= 'Z')) {
  6181. return letter - 'A';
  6182. }
  6183. if ((letter >= 'a') && (letter <= 'z')) {
  6184. return letter - 'a' + 26;
  6185. }
  6186. if ((letter >= '0') && (letter <= '9')) {
  6187. return letter - '0' + 52;
  6188. }
  6189. if (letter == '+') {
  6190. return 62;
  6191. }
  6192. if (letter == '/') {
  6193. return 63;
  6194. }
  6195. if (letter == '=') {
  6196. return 255; /* normal end */
  6197. }
  6198. return 254; /* error */
  6199. }
  6200. CIVETWEB_API int
  6201. mg_base64_decode(const char *src,
  6202. size_t src_len,
  6203. unsigned char *dst,
  6204. size_t *dst_len)
  6205. {
  6206. size_t i;
  6207. unsigned char a, b, c, d;
  6208. size_t dst_len_limit = (size_t)-1;
  6209. size_t dst_len_used = 0;
  6210. if (dst_len != NULL) {
  6211. dst_len_limit = *dst_len;
  6212. *dst_len = 0;
  6213. }
  6214. for (i = 0; i < src_len; i += 4) {
  6215. /* Read 4 characters from BASE64 string */
  6216. a = b64reverse(src[i]);
  6217. if (a >= 254) {
  6218. return (int)i;
  6219. }
  6220. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6221. if (b >= 254) {
  6222. return (int)i + 1;
  6223. }
  6224. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6225. if (c == 254) {
  6226. return (int)i + 2;
  6227. }
  6228. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6229. if (d == 254) {
  6230. return (int)i + 3;
  6231. }
  6232. /* Add first (of 3) decoded character */
  6233. if (dst_len_used < dst_len_limit) {
  6234. dst[dst_len_used] = (a << 2) + (b >> 4);
  6235. }
  6236. dst_len_used++;
  6237. if (c != 255) {
  6238. if (dst_len_used < dst_len_limit) {
  6239. dst[dst_len_used] = (b << 4) + (c >> 2);
  6240. }
  6241. dst_len_used++;
  6242. if (d != 255) {
  6243. if (dst_len_used < dst_len_limit) {
  6244. dst[dst_len_used] = (c << 6) + d;
  6245. }
  6246. dst_len_used++;
  6247. }
  6248. }
  6249. }
  6250. /* Add terminating zero */
  6251. if (dst_len_used < dst_len_limit) {
  6252. dst[dst_len_used] = '\0';
  6253. }
  6254. dst_len_used++;
  6255. if (dst_len != NULL) {
  6256. *dst_len = dst_len_used;
  6257. }
  6258. if (dst_len_used > dst_len_limit) {
  6259. /* Out of memory */
  6260. return 0;
  6261. }
  6262. /* Return -1 for "OK" */
  6263. return -1;
  6264. }
  6265. static int
  6266. is_put_or_delete_method(const struct mg_connection *conn)
  6267. {
  6268. if (conn) {
  6269. const char *s = conn->request_info.request_method;
  6270. if (s != NULL) {
  6271. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6272. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6273. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6274. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6275. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6276. || !strcmp(s, "COPY"));
  6277. }
  6278. }
  6279. return 0;
  6280. }
  6281. static int
  6282. is_civetweb_webdav_method(const struct mg_connection *conn)
  6283. {
  6284. /* Note: Here we only have to identify the WebDav methods that need special
  6285. * handling in the CivetWeb code - not all methods used in WebDav. In
  6286. * particular, methods used on directories (when using Windows Explorer as
  6287. * WebDav client).
  6288. */
  6289. if (conn) {
  6290. const char *s = conn->request_info.request_method;
  6291. if (s != NULL) {
  6292. /* These are the civetweb builtin DAV methods */
  6293. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6294. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6295. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6296. }
  6297. }
  6298. return 0;
  6299. }
  6300. #if !defined(NO_FILES)
  6301. static int
  6302. extention_matches_script(
  6303. struct mg_connection *conn, /* in: request (must be valid) */
  6304. const char *filename /* in: filename (must be valid) */
  6305. )
  6306. {
  6307. #if !defined(NO_CGI)
  6308. unsigned char cgi_config_idx, inc, max;
  6309. #endif
  6310. #if defined(USE_LUA)
  6311. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6312. filename)
  6313. > 0) {
  6314. return 1;
  6315. }
  6316. #endif
  6317. #if defined(USE_DUKTAPE)
  6318. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6319. filename)
  6320. > 0) {
  6321. return 1;
  6322. }
  6323. #endif
  6324. #if !defined(NO_CGI)
  6325. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6326. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6327. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6328. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6329. && (match_prefix_strlen(
  6330. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6331. filename)
  6332. > 0)) {
  6333. return 1;
  6334. }
  6335. }
  6336. #endif
  6337. /* filename and conn could be unused, if all preocessor conditions
  6338. * are false (no script language supported). */
  6339. (void)filename;
  6340. (void)conn;
  6341. return 0;
  6342. }
  6343. static int
  6344. extention_matches_template_text(
  6345. struct mg_connection *conn, /* in: request (must be valid) */
  6346. const char *filename /* in: filename (must be valid) */
  6347. )
  6348. {
  6349. #if defined(USE_LUA)
  6350. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6351. filename)
  6352. > 0) {
  6353. return 1;
  6354. }
  6355. #endif
  6356. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6357. > 0) {
  6358. return 1;
  6359. }
  6360. return 0;
  6361. }
  6362. /* For given directory path, substitute it to valid index file.
  6363. * Return 1 if index file has been found, 0 if not found.
  6364. * If the file is found, it's stats is returned in stp. */
  6365. static int
  6366. substitute_index_file(struct mg_connection *conn,
  6367. char *path,
  6368. size_t path_len,
  6369. struct mg_file_stat *filestat)
  6370. {
  6371. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6372. struct vec filename_vec;
  6373. size_t n = strlen(path);
  6374. int found = 0;
  6375. /* The 'path' given to us points to the directory. Remove all trailing
  6376. * directory separator characters from the end of the path, and
  6377. * then append single directory separator character. */
  6378. while ((n > 0) && (path[n - 1] == '/')) {
  6379. n--;
  6380. }
  6381. path[n] = '/';
  6382. /* Traverse index files list. For each entry, append it to the given
  6383. * path and see if the file exists. If it exists, break the loop */
  6384. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6385. /* Ignore too long entries that may overflow path buffer */
  6386. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6387. continue;
  6388. }
  6389. /* Prepare full path to the index file */
  6390. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6391. /* Does it exist? */
  6392. if (mg_stat(conn, path, filestat)) {
  6393. /* Yes it does, break the loop */
  6394. found = 1;
  6395. break;
  6396. }
  6397. }
  6398. /* If no index file exists, restore directory path */
  6399. if (!found) {
  6400. path[n] = '\0';
  6401. }
  6402. return found;
  6403. }
  6404. #endif
  6405. static void
  6406. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6407. char *filename, /* out: filename */
  6408. size_t filename_buf_len, /* in: size of filename buffer */
  6409. struct mg_file_stat *filestat, /* out: file status structure */
  6410. int *is_found, /* out: file found (directly) */
  6411. int *is_script_resource, /* out: handled by a script? */
  6412. int *is_websocket_request, /* out: websocket connetion? */
  6413. int *is_put_or_delete_request, /* out: put/delete a file? */
  6414. int *is_webdav_request, /* out: webdav request? */
  6415. int *is_template_text /* out: SSI file or LSP file? */
  6416. )
  6417. {
  6418. char const *accept_encoding;
  6419. #if !defined(NO_FILES)
  6420. const char *uri = conn->request_info.local_uri;
  6421. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6422. const char *rewrite;
  6423. struct vec a, b;
  6424. ptrdiff_t match_len;
  6425. char gz_path[UTF8_PATH_MAX];
  6426. int truncated;
  6427. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6428. char *tmp_str;
  6429. size_t tmp_str_len, sep_pos;
  6430. int allow_substitute_script_subresources;
  6431. #endif
  6432. #else
  6433. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6434. #endif
  6435. /* Step 1: Set all initially unknown outputs to zero */
  6436. memset(filestat, 0, sizeof(*filestat));
  6437. *filename = 0;
  6438. *is_found = 0;
  6439. *is_script_resource = 0;
  6440. *is_template_text = 0;
  6441. /* Step 2: Classify the request method */
  6442. /* Step 2a: Check if the request attempts to modify the file system */
  6443. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6444. /* Step 2b: Check if the request uses WebDav method that requires special
  6445. * handling */
  6446. *is_webdav_request = is_civetweb_webdav_method(conn);
  6447. /* Step 3: Check if it is a websocket request, and modify the document
  6448. * root if required */
  6449. #if defined(USE_WEBSOCKET)
  6450. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6451. #if !defined(NO_FILES)
  6452. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6453. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6454. }
  6455. #endif /* !NO_FILES */
  6456. #else /* USE_WEBSOCKET */
  6457. *is_websocket_request = 0;
  6458. #endif /* USE_WEBSOCKET */
  6459. /* Step 4: Check if gzip encoded response is allowed */
  6460. conn->accept_gzip = 0;
  6461. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6462. if (strstr(accept_encoding, "gzip") != NULL) {
  6463. conn->accept_gzip = 1;
  6464. }
  6465. }
  6466. #if !defined(NO_FILES)
  6467. /* Step 5: If there is no root directory, don't look for files. */
  6468. /* Note that root == NULL is a regular use case here. This occurs,
  6469. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6470. * config is not required. */
  6471. if (root == NULL) {
  6472. /* all file related outputs have already been set to 0, just return
  6473. */
  6474. return;
  6475. }
  6476. /* Step 6: Determine the local file path from the root path and the
  6477. * request uri. */
  6478. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6479. * part of the path one byte on the right. */
  6480. truncated = 0;
  6481. mg_snprintf(
  6482. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6483. if (truncated) {
  6484. goto interpret_cleanup;
  6485. }
  6486. /* Step 7: URI rewriting */
  6487. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6488. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6489. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6490. mg_snprintf(conn,
  6491. &truncated,
  6492. filename,
  6493. filename_buf_len - 1,
  6494. "%.*s%s",
  6495. (int)b.len,
  6496. b.ptr,
  6497. uri + match_len);
  6498. break;
  6499. }
  6500. }
  6501. if (truncated) {
  6502. goto interpret_cleanup;
  6503. }
  6504. /* Step 8: Check if the file exists at the server */
  6505. /* Local file path and name, corresponding to requested URI
  6506. * is now stored in "filename" variable. */
  6507. if (mg_stat(conn, filename, filestat)) {
  6508. int uri_len = (int)strlen(uri);
  6509. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6510. /* 8.1: File exists. */
  6511. *is_found = 1;
  6512. /* 8.2: Check if it is a script type. */
  6513. if (extention_matches_script(conn, filename)) {
  6514. /* The request addresses a CGI resource, Lua script or
  6515. * server-side javascript.
  6516. * The URI corresponds to the script itself (like
  6517. * /path/script.cgi), and there is no additional resource
  6518. * path (like /path/script.cgi/something).
  6519. * Requests that modify (replace or delete) a resource, like
  6520. * PUT and DELETE requests, should replace/delete the script
  6521. * file.
  6522. * Requests that read or write from/to a resource, like GET and
  6523. * POST requests, should call the script and return the
  6524. * generated response. */
  6525. *is_script_resource = (!*is_put_or_delete_request);
  6526. }
  6527. /* 8.3: Check for SSI and LSP files */
  6528. if (extention_matches_template_text(conn, filename)) {
  6529. /* Same as above, but for *.lsp and *.shtml files. */
  6530. /* A "template text" is a file delivered directly to the client,
  6531. * but with some text tags replaced by dynamic content.
  6532. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6533. * (LP, LSP) file. */
  6534. *is_template_text = (!*is_put_or_delete_request);
  6535. }
  6536. /* 8.4: If the request target is a directory, there could be
  6537. * a substitute file (index.html, index.cgi, ...). */
  6538. /* But do not substitute a directory for a WebDav request */
  6539. if (filestat->is_directory && is_uri_end_slash
  6540. && (!*is_webdav_request)) {
  6541. /* Use a local copy here, since substitute_index_file will
  6542. * change the content of the file status */
  6543. struct mg_file_stat tmp_filestat;
  6544. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6545. if (substitute_index_file(
  6546. conn, filename, filename_buf_len, &tmp_filestat)) {
  6547. /* Substitute file found. Copy stat to the output, then
  6548. * check if the file is a script file */
  6549. *filestat = tmp_filestat;
  6550. if (extention_matches_script(conn, filename)) {
  6551. /* Substitute file is a script file */
  6552. *is_script_resource = 1;
  6553. } else if (extention_matches_template_text(conn, filename)) {
  6554. /* Substitute file is a LSP or SSI file */
  6555. *is_template_text = 1;
  6556. } else {
  6557. /* Substitute file is a regular file */
  6558. *is_script_resource = 0;
  6559. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6560. }
  6561. }
  6562. /* If there is no substitute file, the server could return
  6563. * a directory listing in a later step */
  6564. }
  6565. return;
  6566. }
  6567. /* Step 9: Check for zipped files: */
  6568. /* If we can't find the actual file, look for the file
  6569. * with the same name but a .gz extension. If we find it,
  6570. * use that and set the gzipped flag in the file struct
  6571. * to indicate that the response need to have the content-
  6572. * encoding: gzip header.
  6573. * We can only do this if the browser declares support. */
  6574. if (conn->accept_gzip) {
  6575. mg_snprintf(
  6576. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6577. if (truncated) {
  6578. goto interpret_cleanup;
  6579. }
  6580. if (mg_stat(conn, gz_path, filestat)) {
  6581. if (filestat) {
  6582. filestat->is_gzipped = 1;
  6583. *is_found = 1;
  6584. }
  6585. /* Currently gz files can not be scripts. */
  6586. return;
  6587. }
  6588. }
  6589. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6590. /* Step 10: Script resources may handle sub-resources */
  6591. /* Support PATH_INFO for CGI scripts. */
  6592. tmp_str_len = strlen(filename);
  6593. tmp_str =
  6594. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6595. if (!tmp_str) {
  6596. /* Out of memory */
  6597. goto interpret_cleanup;
  6598. }
  6599. memcpy(tmp_str, filename, tmp_str_len + 1);
  6600. /* Check config, if index scripts may have sub-resources */
  6601. allow_substitute_script_subresources =
  6602. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6603. "yes");
  6604. if (*is_webdav_request) {
  6605. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6606. * PROPFIND fo their subresources? */
  6607. /* allow_substitute_script_subresources = 0; */
  6608. }
  6609. sep_pos = tmp_str_len;
  6610. while (sep_pos > 0) {
  6611. sep_pos--;
  6612. if (tmp_str[sep_pos] == '/') {
  6613. int is_script = 0, does_exist = 0;
  6614. tmp_str[sep_pos] = 0;
  6615. if (tmp_str[0]) {
  6616. is_script = extention_matches_script(conn, tmp_str);
  6617. does_exist = mg_stat(conn, tmp_str, filestat);
  6618. }
  6619. if (does_exist && is_script) {
  6620. filename[sep_pos] = 0;
  6621. memmove(filename + sep_pos + 2,
  6622. filename + sep_pos + 1,
  6623. strlen(filename + sep_pos + 1) + 1);
  6624. conn->path_info = filename + sep_pos + 1;
  6625. filename[sep_pos + 1] = '/';
  6626. *is_script_resource = 1;
  6627. *is_found = 1;
  6628. break;
  6629. }
  6630. if (allow_substitute_script_subresources) {
  6631. if (substitute_index_file(
  6632. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6633. /* some intermediate directory has an index file */
  6634. if (extention_matches_script(conn, tmp_str)) {
  6635. size_t script_name_len = strlen(tmp_str);
  6636. /* subres_name read before this memory locatio will be
  6637. overwritten */
  6638. char *subres_name = filename + sep_pos;
  6639. size_t subres_name_len = strlen(subres_name);
  6640. DEBUG_TRACE("Substitute script %s serving path %s",
  6641. tmp_str,
  6642. filename);
  6643. /* this index file is a script */
  6644. if ((script_name_len + subres_name_len + 2)
  6645. >= filename_buf_len) {
  6646. mg_free(tmp_str);
  6647. goto interpret_cleanup;
  6648. }
  6649. conn->path_info =
  6650. filename + script_name_len + 1; /* new target */
  6651. memmove(conn->path_info, subres_name, subres_name_len);
  6652. conn->path_info[subres_name_len] = 0;
  6653. memcpy(filename, tmp_str, script_name_len + 1);
  6654. *is_script_resource = 1;
  6655. *is_found = 1;
  6656. break;
  6657. } else {
  6658. DEBUG_TRACE("Substitute file %s serving path %s",
  6659. tmp_str,
  6660. filename);
  6661. /* non-script files will not have sub-resources */
  6662. filename[sep_pos] = 0;
  6663. conn->path_info = 0;
  6664. *is_script_resource = 0;
  6665. *is_found = 0;
  6666. break;
  6667. }
  6668. }
  6669. }
  6670. tmp_str[sep_pos] = '/';
  6671. }
  6672. }
  6673. mg_free(tmp_str);
  6674. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6675. #endif /* !defined(NO_FILES) */
  6676. return;
  6677. #if !defined(NO_FILES)
  6678. /* Reset all outputs */
  6679. interpret_cleanup:
  6680. memset(filestat, 0, sizeof(*filestat));
  6681. *filename = 0;
  6682. *is_found = 0;
  6683. *is_script_resource = 0;
  6684. *is_websocket_request = 0;
  6685. *is_put_or_delete_request = 0;
  6686. #endif /* !defined(NO_FILES) */
  6687. }
  6688. /* Check whether full request is buffered. Return:
  6689. * -1 if request or response is malformed
  6690. * 0 if request or response is not yet fully buffered
  6691. * >0 actual request length, including last \r\n\r\n */
  6692. static int
  6693. get_http_header_len(const char *buf, int buflen)
  6694. {
  6695. int i;
  6696. for (i = 0; i < buflen; i++) {
  6697. /* Do an unsigned comparison in some conditions below */
  6698. const unsigned char c = (unsigned char)buf[i];
  6699. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6700. && !isprint(c)) {
  6701. /* abort scan as soon as one malformed character is found */
  6702. return -1;
  6703. }
  6704. if (i < buflen - 1) {
  6705. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6706. /* Two newline, no carriage return - not standard compliant,
  6707. * but it should be accepted */
  6708. return i + 2;
  6709. }
  6710. }
  6711. if (i < buflen - 3) {
  6712. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6713. && (buf[i + 3] == '\n')) {
  6714. /* Two \r\n - standard compliant */
  6715. return i + 4;
  6716. }
  6717. }
  6718. }
  6719. return 0;
  6720. }
  6721. #if !defined(NO_CACHING)
  6722. /* Convert month to the month number. Return -1 on error, or month number */
  6723. static int
  6724. get_month_index(const char *s)
  6725. {
  6726. size_t i;
  6727. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6728. if (!strcmp(s, month_names[i])) {
  6729. return (int)i;
  6730. }
  6731. }
  6732. return -1;
  6733. }
  6734. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6735. static time_t
  6736. parse_date_string(const char *datetime)
  6737. {
  6738. char month_str[32] = {0};
  6739. int second, minute, hour, day, month, year;
  6740. time_t result = (time_t)0;
  6741. struct tm tm;
  6742. if ((sscanf(datetime,
  6743. "%d/%3s/%d %d:%d:%d",
  6744. &day,
  6745. month_str,
  6746. &year,
  6747. &hour,
  6748. &minute,
  6749. &second)
  6750. == 6)
  6751. || (sscanf(datetime,
  6752. "%d %3s %d %d:%d:%d",
  6753. &day,
  6754. month_str,
  6755. &year,
  6756. &hour,
  6757. &minute,
  6758. &second)
  6759. == 6)
  6760. || (sscanf(datetime,
  6761. "%*3s, %d %3s %d %d:%d:%d",
  6762. &day,
  6763. month_str,
  6764. &year,
  6765. &hour,
  6766. &minute,
  6767. &second)
  6768. == 6)
  6769. || (sscanf(datetime,
  6770. "%d-%3s-%d %d:%d:%d",
  6771. &day,
  6772. month_str,
  6773. &year,
  6774. &hour,
  6775. &minute,
  6776. &second)
  6777. == 6)) {
  6778. month = get_month_index(month_str);
  6779. if ((month >= 0) && (year >= 1970)) {
  6780. memset(&tm, 0, sizeof(tm));
  6781. tm.tm_year = year - 1900;
  6782. tm.tm_mon = month;
  6783. tm.tm_mday = day;
  6784. tm.tm_hour = hour;
  6785. tm.tm_min = minute;
  6786. tm.tm_sec = second;
  6787. result = timegm(&tm);
  6788. }
  6789. }
  6790. return result;
  6791. }
  6792. #endif /* !NO_CACHING */
  6793. /* Pre-process URIs according to RFC + protect against directory disclosure
  6794. * attacks by removing '..', excessive '/' and '\' characters */
  6795. static void
  6796. remove_dot_segments(char *inout)
  6797. {
  6798. /* Windows backend protection
  6799. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6800. * in URI by slash */
  6801. char *out_end = inout;
  6802. char *in = inout;
  6803. if (!in) {
  6804. /* Param error. */
  6805. return;
  6806. }
  6807. while (*in) {
  6808. if (*in == '\\') {
  6809. *in = '/';
  6810. }
  6811. in++;
  6812. }
  6813. /* Algorithm "remove_dot_segments" from
  6814. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6815. /* Step 1:
  6816. * The input buffer is initialized.
  6817. * The output buffer is initialized to the empty string.
  6818. */
  6819. in = inout;
  6820. /* Step 2:
  6821. * While the input buffer is not empty, loop as follows:
  6822. */
  6823. /* Less than out_end of the inout buffer is used as output, so keep
  6824. * condition: out_end <= in */
  6825. while (*in) {
  6826. /* Step 2a:
  6827. * If the input buffer begins with a prefix of "../" or "./",
  6828. * then remove that prefix from the input buffer;
  6829. */
  6830. if (!strncmp(in, "../", 3)) {
  6831. in += 3;
  6832. } else if (!strncmp(in, "./", 2)) {
  6833. in += 2;
  6834. }
  6835. /* otherwise */
  6836. /* Step 2b:
  6837. * if the input buffer begins with a prefix of "/./" or "/.",
  6838. * where "." is a complete path segment, then replace that
  6839. * prefix with "/" in the input buffer;
  6840. */
  6841. else if (!strncmp(in, "/./", 3)) {
  6842. in += 2;
  6843. } else if (!strcmp(in, "/.")) {
  6844. in[1] = 0;
  6845. }
  6846. /* otherwise */
  6847. /* Step 2c:
  6848. * if the input buffer begins with a prefix of "/../" or "/..",
  6849. * where ".." is a complete path segment, then replace that
  6850. * prefix with "/" in the input buffer and remove the last
  6851. * segment and its preceding "/" (if any) from the output
  6852. * buffer;
  6853. */
  6854. else if (!strncmp(in, "/../", 4)) {
  6855. in += 3;
  6856. if (inout != out_end) {
  6857. /* remove last segment */
  6858. do {
  6859. out_end--;
  6860. } while ((inout != out_end) && (*out_end != '/'));
  6861. }
  6862. } else if (!strcmp(in, "/..")) {
  6863. in[1] = 0;
  6864. if (inout != out_end) {
  6865. /* remove last segment */
  6866. do {
  6867. out_end--;
  6868. } while ((inout != out_end) && (*out_end != '/'));
  6869. }
  6870. }
  6871. /* otherwise */
  6872. /* Step 2d:
  6873. * if the input buffer consists only of "." or "..", then remove
  6874. * that from the input buffer;
  6875. */
  6876. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6877. *in = 0;
  6878. }
  6879. /* otherwise */
  6880. /* Step 2e:
  6881. * move the first path segment in the input buffer to the end of
  6882. * the output buffer, including the initial "/" character (if
  6883. * any) and any subsequent characters up to, but not including,
  6884. * the next "/" character or the end of the input buffer.
  6885. */
  6886. else {
  6887. do {
  6888. *out_end = *in;
  6889. out_end++;
  6890. in++;
  6891. } while ((*in != 0) && (*in != '/'));
  6892. }
  6893. }
  6894. /* Step 3:
  6895. * Finally, the output buffer is returned as the result of
  6896. * remove_dot_segments.
  6897. */
  6898. /* Terminate output */
  6899. *out_end = 0;
  6900. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6901. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6902. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6903. * or "//" anymore.
  6904. */
  6905. out_end = in = inout;
  6906. while (*in) {
  6907. if (*in == '.') {
  6908. /* remove . at the end or preceding of / */
  6909. char *in_ahead = in;
  6910. do {
  6911. in_ahead++;
  6912. } while (*in_ahead == '.');
  6913. if (*in_ahead == '/') {
  6914. in = in_ahead;
  6915. if ((out_end != inout) && (out_end[-1] == '/')) {
  6916. /* remove generated // */
  6917. out_end--;
  6918. }
  6919. } else if (*in_ahead == 0) {
  6920. in = in_ahead;
  6921. } else {
  6922. do {
  6923. *out_end++ = '.';
  6924. in++;
  6925. } while (in != in_ahead);
  6926. }
  6927. } else if (*in == '/') {
  6928. /* replace // by / */
  6929. *out_end++ = '/';
  6930. do {
  6931. in++;
  6932. } while (*in == '/');
  6933. } else {
  6934. *out_end++ = *in;
  6935. in++;
  6936. }
  6937. }
  6938. *out_end = 0;
  6939. }
  6940. static const struct {
  6941. const char *extension;
  6942. size_t ext_len;
  6943. const char *mime_type;
  6944. } builtin_mime_types[] = {
  6945. /* IANA registered MIME types
  6946. * (http://www.iana.org/assignments/media-types)
  6947. * application types */
  6948. {".bin", 4, "application/octet-stream"},
  6949. {".deb", 4, "application/octet-stream"},
  6950. {".dmg", 4, "application/octet-stream"},
  6951. {".dll", 4, "application/octet-stream"},
  6952. {".doc", 4, "application/msword"},
  6953. {".eps", 4, "application/postscript"},
  6954. {".exe", 4, "application/octet-stream"},
  6955. {".iso", 4, "application/octet-stream"},
  6956. {".js", 3, "application/javascript"},
  6957. {".json", 5, "application/json"},
  6958. {".msi", 4, "application/octet-stream"},
  6959. {".pdf", 4, "application/pdf"},
  6960. {".ps", 3, "application/postscript"},
  6961. {".rtf", 4, "application/rtf"},
  6962. {".xhtml", 6, "application/xhtml+xml"},
  6963. {".xsl", 4, "application/xml"},
  6964. {".xslt", 5, "application/xml"},
  6965. /* fonts */
  6966. {".ttf", 4, "application/font-sfnt"},
  6967. {".cff", 4, "application/font-sfnt"},
  6968. {".otf", 4, "application/font-sfnt"},
  6969. {".aat", 4, "application/font-sfnt"},
  6970. {".sil", 4, "application/font-sfnt"},
  6971. {".pfr", 4, "application/font-tdpfr"},
  6972. {".woff", 5, "application/font-woff"},
  6973. {".woff2", 6, "application/font-woff2"},
  6974. /* audio */
  6975. {".mp3", 4, "audio/mpeg"},
  6976. {".oga", 4, "audio/ogg"},
  6977. {".ogg", 4, "audio/ogg"},
  6978. /* image */
  6979. {".gif", 4, "image/gif"},
  6980. {".ief", 4, "image/ief"},
  6981. {".jpeg", 5, "image/jpeg"},
  6982. {".jpg", 4, "image/jpeg"},
  6983. {".jpm", 4, "image/jpm"},
  6984. {".jpx", 4, "image/jpx"},
  6985. {".png", 4, "image/png"},
  6986. {".svg", 4, "image/svg+xml"},
  6987. {".tif", 4, "image/tiff"},
  6988. {".tiff", 5, "image/tiff"},
  6989. /* model */
  6990. {".wrl", 4, "model/vrml"},
  6991. /* text */
  6992. {".css", 4, "text/css"},
  6993. {".csv", 4, "text/csv"},
  6994. {".htm", 4, "text/html"},
  6995. {".html", 5, "text/html"},
  6996. {".sgm", 4, "text/sgml"},
  6997. {".shtm", 5, "text/html"},
  6998. {".shtml", 6, "text/html"},
  6999. {".txt", 4, "text/plain"},
  7000. {".xml", 4, "text/xml"},
  7001. /* video */
  7002. {".mov", 4, "video/quicktime"},
  7003. {".mp4", 4, "video/mp4"},
  7004. {".mpeg", 5, "video/mpeg"},
  7005. {".mpg", 4, "video/mpeg"},
  7006. {".ogv", 4, "video/ogg"},
  7007. {".qt", 3, "video/quicktime"},
  7008. /* not registered types
  7009. * (http://reference.sitepoint.com/html/mime-types-full,
  7010. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7011. {".arj", 4, "application/x-arj-compressed"},
  7012. {".gz", 3, "application/x-gunzip"},
  7013. {".rar", 4, "application/x-arj-compressed"},
  7014. {".swf", 4, "application/x-shockwave-flash"},
  7015. {".tar", 4, "application/x-tar"},
  7016. {".tgz", 4, "application/x-tar-gz"},
  7017. {".torrent", 8, "application/x-bittorrent"},
  7018. {".ppt", 4, "application/x-mspowerpoint"},
  7019. {".xls", 4, "application/x-msexcel"},
  7020. {".zip", 4, "application/x-zip-compressed"},
  7021. {".aac",
  7022. 4,
  7023. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7024. {".flac", 5, "audio/flac"},
  7025. {".aif", 4, "audio/x-aif"},
  7026. {".m3u", 4, "audio/x-mpegurl"},
  7027. {".mid", 4, "audio/x-midi"},
  7028. {".ra", 3, "audio/x-pn-realaudio"},
  7029. {".ram", 4, "audio/x-pn-realaudio"},
  7030. {".wav", 4, "audio/x-wav"},
  7031. {".bmp", 4, "image/bmp"},
  7032. {".ico", 4, "image/x-icon"},
  7033. {".pct", 4, "image/x-pct"},
  7034. {".pict", 5, "image/pict"},
  7035. {".rgb", 4, "image/x-rgb"},
  7036. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7037. {".asf", 4, "video/x-ms-asf"},
  7038. {".avi", 4, "video/x-msvideo"},
  7039. {".m4v", 4, "video/x-m4v"},
  7040. {NULL, 0, NULL}};
  7041. CIVETWEB_API const char *
  7042. mg_get_builtin_mime_type(const char *path)
  7043. {
  7044. const char *ext;
  7045. size_t i, path_len;
  7046. path_len = strlen(path);
  7047. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7048. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7049. if ((path_len > builtin_mime_types[i].ext_len)
  7050. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7051. return builtin_mime_types[i].mime_type;
  7052. }
  7053. }
  7054. return "text/plain";
  7055. }
  7056. /* Look at the "path" extension and figure what mime type it has.
  7057. * Store mime type in the vector. */
  7058. static void
  7059. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7060. {
  7061. struct vec ext_vec, mime_vec;
  7062. const char *list, *ext;
  7063. size_t path_len;
  7064. path_len = strlen(path);
  7065. if ((conn == NULL) || (vec == NULL)) {
  7066. if (vec != NULL) {
  7067. memset(vec, '\0', sizeof(struct vec));
  7068. }
  7069. return;
  7070. }
  7071. /* Scan user-defined mime types first, in case user wants to
  7072. * override default mime types. */
  7073. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7074. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7075. /* ext now points to the path suffix */
  7076. ext = path + path_len - ext_vec.len;
  7077. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7078. *vec = mime_vec;
  7079. return;
  7080. }
  7081. }
  7082. vec->ptr = mg_get_builtin_mime_type(path);
  7083. vec->len = strlen(vec->ptr);
  7084. }
  7085. /* Stringify binary data. Output buffer must be twice as big as input,
  7086. * because each byte takes 2 bytes in string representation */
  7087. static void
  7088. bin2str(char *to, const unsigned char *p, size_t len)
  7089. {
  7090. static const char *hex = "0123456789abcdef";
  7091. for (; len--; p++) {
  7092. *to++ = hex[p[0] >> 4];
  7093. *to++ = hex[p[0] & 0x0f];
  7094. }
  7095. *to = '\0';
  7096. }
  7097. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7098. */
  7099. CIVETWEB_API char *
  7100. mg_md5(char buf[33], ...)
  7101. {
  7102. md5_byte_t hash[16];
  7103. const char *p;
  7104. va_list ap;
  7105. md5_state_t ctx;
  7106. md5_init(&ctx);
  7107. va_start(ap, buf);
  7108. while ((p = va_arg(ap, const char *)) != NULL) {
  7109. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7110. }
  7111. va_end(ap);
  7112. md5_finish(&ctx, hash);
  7113. bin2str(buf, hash, sizeof(hash));
  7114. return buf;
  7115. }
  7116. /* Check the user's password, return 1 if OK */
  7117. static int
  7118. check_password_digest(const char *method,
  7119. const char *ha1,
  7120. const char *uri,
  7121. const char *nonce,
  7122. const char *nc,
  7123. const char *cnonce,
  7124. const char *qop,
  7125. const char *response)
  7126. {
  7127. char ha2[32 + 1], expected_response[32 + 1];
  7128. /* Some of the parameters may be NULL */
  7129. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7130. || (qop == NULL) || (response == NULL)) {
  7131. return 0;
  7132. }
  7133. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7134. if (strlen(response) != 32) {
  7135. return 0;
  7136. }
  7137. mg_md5(ha2, method, ":", uri, NULL);
  7138. mg_md5(expected_response,
  7139. ha1,
  7140. ":",
  7141. nonce,
  7142. ":",
  7143. nc,
  7144. ":",
  7145. cnonce,
  7146. ":",
  7147. qop,
  7148. ":",
  7149. ha2,
  7150. NULL);
  7151. return mg_strcasecmp(response, expected_response) == 0;
  7152. }
  7153. #if !defined(NO_FILESYSTEMS)
  7154. /* Use the global passwords file, if specified by auth_gpass option,
  7155. * or search for .htpasswd in the requested directory. */
  7156. static void
  7157. open_auth_file(struct mg_connection *conn,
  7158. const char *path,
  7159. struct mg_file *filep)
  7160. {
  7161. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7162. char name[UTF8_PATH_MAX];
  7163. const char *p, *e,
  7164. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7165. int truncated;
  7166. if (gpass != NULL) {
  7167. /* Use global passwords file */
  7168. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7169. #if defined(DEBUG)
  7170. /* Use mg_cry_internal here, since gpass has been
  7171. * configured. */
  7172. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7173. #endif
  7174. }
  7175. /* Important: using local struct mg_file to test path for
  7176. * is_directory flag. If filep is used, mg_stat() makes it
  7177. * appear as if auth file was opened.
  7178. * TODO(mid): Check if this is still required after rewriting
  7179. * mg_stat */
  7180. } else if (mg_stat(conn, path, &filep->stat)
  7181. && filep->stat.is_directory) {
  7182. mg_snprintf(conn,
  7183. &truncated,
  7184. name,
  7185. sizeof(name),
  7186. "%s/%s",
  7187. path,
  7188. PASSWORDS_FILE_NAME);
  7189. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7190. #if defined(DEBUG)
  7191. /* Don't use mg_cry_internal here, but only a trace, since
  7192. * this is a typical case. It will occur for every directory
  7193. * without a password file. */
  7194. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7195. #endif
  7196. }
  7197. } else {
  7198. /* Try to find .htpasswd in requested directory. */
  7199. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7200. if (e[0] == '/') {
  7201. break;
  7202. }
  7203. }
  7204. mg_snprintf(conn,
  7205. &truncated,
  7206. name,
  7207. sizeof(name),
  7208. "%.*s/%s",
  7209. (int)(e - p),
  7210. p,
  7211. PASSWORDS_FILE_NAME);
  7212. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7213. #if defined(DEBUG)
  7214. /* Don't use mg_cry_internal here, but only a trace, since
  7215. * this is a typical case. It will occur for every directory
  7216. * without a password file. */
  7217. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7218. #endif
  7219. }
  7220. }
  7221. }
  7222. }
  7223. #endif /* NO_FILESYSTEMS */
  7224. /* Parsed Authorization header */
  7225. struct ah {
  7226. char *user;
  7227. int type; /* 1 = basic, 2 = digest */
  7228. char *plain_password; /* Basic only */
  7229. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7230. };
  7231. /* Return 1 on success. Always initializes the ah structure. */
  7232. static int
  7233. parse_auth_header(struct mg_connection *conn,
  7234. char *buf,
  7235. size_t buf_size,
  7236. struct ah *ah)
  7237. {
  7238. char *name, *value, *s;
  7239. const char *auth_header;
  7240. uint64_t nonce;
  7241. if (!ah || !conn) {
  7242. return 0;
  7243. }
  7244. (void)memset(ah, 0, sizeof(*ah));
  7245. auth_header = mg_get_header(conn, "Authorization");
  7246. if (auth_header == NULL) {
  7247. /* No Authorization header at all */
  7248. return 0;
  7249. }
  7250. if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
  7251. /* Basic Auth (we never asked for this, but some client may send it) */
  7252. char *split;
  7253. const char *userpw_b64 = auth_header + 6;
  7254. size_t userpw_b64_len = strlen(userpw_b64);
  7255. size_t buf_len_r = buf_size;
  7256. if (mg_base64_decode(
  7257. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7258. != -1) {
  7259. return 0; /* decode error */
  7260. }
  7261. split = strchr(buf, ':');
  7262. if (!split) {
  7263. return 0; /* Format error */
  7264. }
  7265. /* Separate string at ':' */
  7266. *split = 0;
  7267. /* User name is before ':', Password is after ':' */
  7268. ah->user = buf;
  7269. ah->type = 1;
  7270. ah->plain_password = split + 1;
  7271. return 1;
  7272. } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
  7273. /* Digest Auth ... implemented below */
  7274. ah->type = 2;
  7275. } else {
  7276. /* Unknown or invalid Auth method */
  7277. return 0;
  7278. }
  7279. /* Make modifiable copy of the auth header */
  7280. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7281. s = buf;
  7282. /* Parse authorization header */
  7283. for (;;) {
  7284. /* Gobble initial spaces */
  7285. while (isspace((unsigned char)*s)) {
  7286. s++;
  7287. }
  7288. name = skip_quoted(&s, "=", " ", 0);
  7289. /* Value is either quote-delimited, or ends at first comma or space.
  7290. */
  7291. if (s[0] == '\"') {
  7292. s++;
  7293. value = skip_quoted(&s, "\"", " ", '\\');
  7294. if (s[0] == ',') {
  7295. s++;
  7296. }
  7297. } else {
  7298. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7299. * uses spaces */
  7300. }
  7301. if (*name == '\0') {
  7302. break;
  7303. }
  7304. if (!strcmp(name, "username")) {
  7305. ah->user = value;
  7306. } else if (!strcmp(name, "cnonce")) {
  7307. ah->cnonce = value;
  7308. } else if (!strcmp(name, "response")) {
  7309. ah->response = value;
  7310. } else if (!strcmp(name, "uri")) {
  7311. ah->uri = value;
  7312. } else if (!strcmp(name, "qop")) {
  7313. ah->qop = value;
  7314. } else if (!strcmp(name, "nc")) {
  7315. ah->nc = value;
  7316. } else if (!strcmp(name, "nonce")) {
  7317. ah->nonce = value;
  7318. }
  7319. }
  7320. #if !defined(NO_NONCE_CHECK)
  7321. /* Read the nonce from the response. */
  7322. if (ah->nonce == NULL) {
  7323. return 0;
  7324. }
  7325. s = NULL;
  7326. nonce = strtoull(ah->nonce, &s, 10);
  7327. if ((s == NULL) || (*s != 0)) {
  7328. return 0;
  7329. }
  7330. /* Convert the nonce from the client to a number. */
  7331. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7332. /* The converted number corresponds to the time the nounce has been
  7333. * created. This should not be earlier than the server start. */
  7334. /* Server side nonce check is valuable in all situations but one:
  7335. * if the server restarts frequently, but the client should not see
  7336. * that, so the server should accept nonces from previous starts. */
  7337. /* However, the reasonable default is to not accept a nonce from a
  7338. * previous start, so if anyone changed the access rights between
  7339. * two restarts, a new login is required. */
  7340. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7341. /* nonce is from a previous start of the server and no longer valid
  7342. * (replay attack?) */
  7343. return 0;
  7344. }
  7345. /* Check if the nonce is too high, so it has not (yet) been used by the
  7346. * server. */
  7347. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7348. + conn->dom_ctx->nonce_count)) {
  7349. return 0;
  7350. }
  7351. #else
  7352. (void)nonce;
  7353. #endif
  7354. return (ah->user != NULL);
  7355. }
  7356. static const char *
  7357. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7358. {
  7359. if (!filep) {
  7360. return NULL;
  7361. }
  7362. if (filep->access.fp != NULL) {
  7363. return fgets(buf, (int)size, filep->access.fp);
  7364. } else {
  7365. return NULL;
  7366. }
  7367. }
  7368. /* Define the initial recursion depth for procesesing htpasswd files that
  7369. * include other htpasswd
  7370. * (or even the same) files. It is not difficult to provide a file or files
  7371. * s.t. they force civetweb
  7372. * to infinitely recurse and then crash.
  7373. */
  7374. #define INITIAL_DEPTH 9
  7375. #if INITIAL_DEPTH <= 0
  7376. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7377. #endif
  7378. #if !defined(NO_FILESYSTEMS)
  7379. struct read_auth_file_struct {
  7380. struct mg_connection *conn;
  7381. struct ah ah;
  7382. const char *domain;
  7383. char buf[256 + 256 + 40];
  7384. const char *f_user;
  7385. const char *f_domain;
  7386. const char *f_ha1;
  7387. };
  7388. static int
  7389. read_auth_file(struct mg_file *filep,
  7390. struct read_auth_file_struct *workdata,
  7391. int depth)
  7392. {
  7393. int is_authorized = 0;
  7394. struct mg_file fp;
  7395. size_t l;
  7396. if (!filep || !workdata || (0 == depth)) {
  7397. return 0;
  7398. }
  7399. /* Loop over passwords file */
  7400. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7401. l = strlen(workdata->buf);
  7402. while (l > 0) {
  7403. if (isspace((unsigned char)workdata->buf[l - 1])
  7404. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7405. l--;
  7406. workdata->buf[l] = 0;
  7407. } else
  7408. break;
  7409. }
  7410. if (l < 1) {
  7411. continue;
  7412. }
  7413. workdata->f_user = workdata->buf;
  7414. if (workdata->f_user[0] == ':') {
  7415. /* user names may not contain a ':' and may not be empty,
  7416. * so lines starting with ':' may be used for a special purpose
  7417. */
  7418. if (workdata->f_user[1] == '#') {
  7419. /* :# is a comment */
  7420. continue;
  7421. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7422. if (mg_fopen(workdata->conn,
  7423. workdata->f_user + 9,
  7424. MG_FOPEN_MODE_READ,
  7425. &fp)) {
  7426. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7427. (void)mg_fclose(
  7428. &fp.access); /* ignore error on read only file */
  7429. /* No need to continue processing files once we have a
  7430. * match, since nothing will reset it back
  7431. * to 0.
  7432. */
  7433. if (is_authorized) {
  7434. return is_authorized;
  7435. }
  7436. } else {
  7437. mg_cry_internal(workdata->conn,
  7438. "%s: cannot open authorization file: %s",
  7439. __func__,
  7440. workdata->buf);
  7441. }
  7442. continue;
  7443. }
  7444. /* everything is invalid for the moment (might change in the
  7445. * future) */
  7446. mg_cry_internal(workdata->conn,
  7447. "%s: syntax error in authorization file: %s",
  7448. __func__,
  7449. workdata->buf);
  7450. continue;
  7451. }
  7452. workdata->f_domain = strchr(workdata->f_user, ':');
  7453. if (workdata->f_domain == NULL) {
  7454. mg_cry_internal(workdata->conn,
  7455. "%s: syntax error in authorization file: %s",
  7456. __func__,
  7457. workdata->buf);
  7458. continue;
  7459. }
  7460. *(char *)(workdata->f_domain) = 0;
  7461. (workdata->f_domain)++;
  7462. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7463. if (workdata->f_ha1 == NULL) {
  7464. mg_cry_internal(workdata->conn,
  7465. "%s: syntax error in authorization file: %s",
  7466. __func__,
  7467. workdata->buf);
  7468. continue;
  7469. }
  7470. *(char *)(workdata->f_ha1) = 0;
  7471. (workdata->f_ha1)++;
  7472. if (!strcmp(workdata->ah.user, workdata->f_user)
  7473. && !strcmp(workdata->domain, workdata->f_domain)) {
  7474. switch (workdata->ah.type) {
  7475. case 1: /* Basic */
  7476. {
  7477. size_t mlen = strlen(workdata->f_user)
  7478. + strlen(workdata->domain)
  7479. + strlen(workdata->ah.plain_password) + 3;
  7480. char md5[33];
  7481. mg_md5(md5,
  7482. workdata->f_user,
  7483. ":",
  7484. workdata->domain,
  7485. ":",
  7486. workdata->ah.plain_password,
  7487. NULL);
  7488. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7489. }
  7490. case 2: /* Digest */
  7491. return check_password_digest(
  7492. workdata->conn->request_info.request_method,
  7493. workdata->f_ha1,
  7494. workdata->ah.uri,
  7495. workdata->ah.nonce,
  7496. workdata->ah.nc,
  7497. workdata->ah.cnonce,
  7498. workdata->ah.qop,
  7499. workdata->ah.response);
  7500. default: /* None/Other/Unknown */
  7501. return 0;
  7502. }
  7503. }
  7504. }
  7505. return is_authorized;
  7506. }
  7507. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7508. static int
  7509. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7510. {
  7511. struct read_auth_file_struct workdata;
  7512. char buf[MG_BUF_LEN];
  7513. if (!conn || !conn->dom_ctx) {
  7514. return 0;
  7515. }
  7516. memset(&workdata, 0, sizeof(workdata));
  7517. workdata.conn = conn;
  7518. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7519. return 0;
  7520. }
  7521. /* CGI needs it as REMOTE_USER */
  7522. conn->request_info.remote_user =
  7523. mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
  7524. if (realm) {
  7525. workdata.domain = realm;
  7526. } else {
  7527. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7528. }
  7529. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7530. }
  7531. /* Public function to check http digest authentication header */
  7532. CIVETWEB_API int
  7533. mg_check_digest_access_authentication(struct mg_connection *conn,
  7534. const char *realm,
  7535. const char *filename)
  7536. {
  7537. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7538. int auth;
  7539. if (!conn || !filename) {
  7540. return -1;
  7541. }
  7542. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7543. return -2;
  7544. }
  7545. auth = authorize(conn, &file, realm);
  7546. mg_fclose(&file.access);
  7547. return auth;
  7548. }
  7549. #endif /* NO_FILESYSTEMS */
  7550. /* Return 1 if request is authorised, 0 otherwise. */
  7551. static int
  7552. check_authorization(struct mg_connection *conn, const char *path)
  7553. {
  7554. #if !defined(NO_FILESYSTEMS)
  7555. char fname[UTF8_PATH_MAX];
  7556. struct vec uri_vec, filename_vec;
  7557. const char *list;
  7558. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7559. int authorized = 1, truncated;
  7560. if (!conn || !conn->dom_ctx) {
  7561. return 0;
  7562. }
  7563. list = conn->dom_ctx->config[PROTECT_URI];
  7564. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7565. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7566. mg_snprintf(conn,
  7567. &truncated,
  7568. fname,
  7569. sizeof(fname),
  7570. "%.*s",
  7571. (int)filename_vec.len,
  7572. filename_vec.ptr);
  7573. if (truncated
  7574. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7575. mg_cry_internal(conn,
  7576. "%s: cannot open %s: %s",
  7577. __func__,
  7578. fname,
  7579. strerror(errno));
  7580. }
  7581. break;
  7582. }
  7583. }
  7584. if (!is_file_opened(&file.access)) {
  7585. open_auth_file(conn, path, &file);
  7586. }
  7587. if (is_file_opened(&file.access)) {
  7588. authorized = authorize(conn, &file, NULL);
  7589. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7590. }
  7591. return authorized;
  7592. #else
  7593. (void)conn;
  7594. (void)path;
  7595. return 1;
  7596. #endif /* NO_FILESYSTEMS */
  7597. }
  7598. /* Internal function. Assumes conn is valid */
  7599. static void
  7600. send_authorization_request(struct mg_connection *conn, const char *realm)
  7601. {
  7602. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7603. int trunc = 0;
  7604. char buf[128];
  7605. if (!realm) {
  7606. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7607. }
  7608. mg_lock_context(conn->phys_ctx);
  7609. nonce += conn->dom_ctx->nonce_count;
  7610. ++conn->dom_ctx->nonce_count;
  7611. mg_unlock_context(conn->phys_ctx);
  7612. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7613. conn->must_close = 1;
  7614. /* Create 401 response */
  7615. mg_response_header_start(conn, 401);
  7616. send_no_cache_header(conn);
  7617. send_additional_header(conn);
  7618. mg_response_header_add(conn, "Content-Length", "0", -1);
  7619. /* Content for "WWW-Authenticate" header */
  7620. mg_snprintf(conn,
  7621. &trunc,
  7622. buf,
  7623. sizeof(buf),
  7624. "Digest qop=\"auth\", realm=\"%s\", "
  7625. "nonce=\"%" UINT64_FMT "\"",
  7626. realm,
  7627. nonce);
  7628. if (!trunc) {
  7629. /* !trunc should always be true */
  7630. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7631. }
  7632. /* Send all headers */
  7633. mg_response_header_send(conn);
  7634. }
  7635. /* Interface function. Parameters are provided by the user, so do
  7636. * at least some basic checks.
  7637. */
  7638. CIVETWEB_API int
  7639. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7640. const char *realm)
  7641. {
  7642. if (conn && conn->dom_ctx) {
  7643. send_authorization_request(conn, realm);
  7644. return 0;
  7645. }
  7646. return -1;
  7647. }
  7648. #if !defined(NO_FILES)
  7649. static int
  7650. is_authorized_for_put(struct mg_connection *conn)
  7651. {
  7652. int ret = 0;
  7653. if (conn) {
  7654. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7655. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7656. if (passfile != NULL
  7657. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7658. ret = authorize(conn, &file, NULL);
  7659. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7660. }
  7661. }
  7662. DEBUG_TRACE("file write autorization: %i", ret);
  7663. return ret;
  7664. }
  7665. #endif
  7666. CIVETWEB_API int
  7667. mg_modify_passwords_file_ha1(const char *fname,
  7668. const char *domain,
  7669. const char *user,
  7670. const char *ha1)
  7671. {
  7672. int found = 0, i, result = 1;
  7673. char line[512], u[256], d[256], h[256];
  7674. struct stat st = {0};
  7675. FILE *fp = NULL;
  7676. char *temp_file = NULL;
  7677. int temp_file_offs = 0;
  7678. /* Regard empty password as no password - remove user record. */
  7679. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7680. ha1 = NULL;
  7681. }
  7682. /* Other arguments must not be empty */
  7683. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7684. return 0;
  7685. }
  7686. /* Using the given file format, user name and domain must not contain
  7687. * the ':' character */
  7688. if (strchr(user, ':') != NULL) {
  7689. return 0;
  7690. }
  7691. if (strchr(domain, ':') != NULL) {
  7692. return 0;
  7693. }
  7694. /* Do not allow control characters like newline in user name and domain.
  7695. * Do not allow excessively long names either. */
  7696. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7697. if (iscntrl((unsigned char)user[i])) {
  7698. return 0;
  7699. }
  7700. }
  7701. if (user[i]) {
  7702. return 0; /* user name too long */
  7703. }
  7704. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7705. if (iscntrl((unsigned char)domain[i])) {
  7706. return 0;
  7707. }
  7708. }
  7709. if (domain[i]) {
  7710. return 0; /* domain name too long */
  7711. }
  7712. /* The maximum length of the path to the password file is limited */
  7713. if (strlen(fname) >= UTF8_PATH_MAX) {
  7714. return 0;
  7715. }
  7716. /* Check if the file exists, and get file size */
  7717. if (0 == stat(fname, &st)) {
  7718. int temp_buf_len = (int)st.st_size + 1024;
  7719. /* Allocate memory (instead of using a temporary file) */
  7720. temp_file = (char *)mg_calloc(temp_buf_len, 1);
  7721. if (!temp_file) {
  7722. /* Out of memory */
  7723. return 0;
  7724. }
  7725. /* File exists. Read it into a memory buffer. */
  7726. fp = fopen(fname, "r");
  7727. if (fp == NULL) {
  7728. /* Cannot read file. No permission? */
  7729. mg_free(temp_file);
  7730. return 0;
  7731. }
  7732. /* Read content and store in memory */
  7733. while ((fgets(line, sizeof(line), fp) != NULL)
  7734. && ((temp_file_offs + 600) < temp_buf_len)) {
  7735. /* file format is "user:domain:hash\n" */
  7736. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7737. continue;
  7738. }
  7739. u[255] = 0;
  7740. d[255] = 0;
  7741. h[255] = 0;
  7742. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7743. /* Found the user: change the password hash or drop the user
  7744. */
  7745. if ((ha1 != NULL) && (!found)) {
  7746. i = sprintf(temp_file + temp_file_offs,
  7747. "%s:%s:%s\n",
  7748. user,
  7749. domain,
  7750. ha1);
  7751. if (i < 1) {
  7752. fclose(fp);
  7753. mg_free(temp_file);
  7754. return 0;
  7755. }
  7756. temp_file_offs += i;
  7757. }
  7758. found = 1;
  7759. } else {
  7760. /* Copy existing user, including password hash */
  7761. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7762. if (i < 1) {
  7763. fclose(fp);
  7764. mg_free(temp_file);
  7765. return 0;
  7766. }
  7767. temp_file_offs += i;
  7768. }
  7769. }
  7770. fclose(fp);
  7771. }
  7772. /* Create new file */
  7773. fp = fopen(fname, "w");
  7774. if (!fp) {
  7775. mg_free(temp_file);
  7776. return 0;
  7777. }
  7778. #if !defined(_WIN32)
  7779. /* On Linux & co., restrict file read/write permissions to the owner */
  7780. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7781. result = 0;
  7782. }
  7783. #endif
  7784. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7785. /* Store buffered content of old file */
  7786. if (fwrite(temp_file, 1, temp_file_offs, fp)
  7787. != (size_t)temp_file_offs) {
  7788. result = 0;
  7789. }
  7790. }
  7791. /* If new user, just add it */
  7792. if ((ha1 != NULL) && (!found)) {
  7793. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7794. result = 0;
  7795. }
  7796. }
  7797. /* All data written */
  7798. if (fclose(fp) != 0) {
  7799. result = 0;
  7800. }
  7801. mg_free(temp_file);
  7802. return result;
  7803. }
  7804. CIVETWEB_API int
  7805. mg_modify_passwords_file(const char *fname,
  7806. const char *domain,
  7807. const char *user,
  7808. const char *pass)
  7809. {
  7810. char ha1buf[33];
  7811. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7812. return 0;
  7813. }
  7814. if ((pass == NULL) || (pass[0] == 0)) {
  7815. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7816. }
  7817. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7818. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7819. }
  7820. static int
  7821. is_valid_port(unsigned long port)
  7822. {
  7823. return (port <= 0xffff);
  7824. }
  7825. static int
  7826. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7827. {
  7828. struct addrinfo hints, *res, *ressave;
  7829. int func_ret = 0;
  7830. int gai_ret;
  7831. memset(&hints, 0, sizeof(struct addrinfo));
  7832. hints.ai_family = af;
  7833. if (!resolve_src) {
  7834. hints.ai_flags = AI_NUMERICHOST;
  7835. }
  7836. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7837. if (gai_ret != 0) {
  7838. /* gai_strerror could be used to convert gai_ret to a string */
  7839. /* POSIX return values: see
  7840. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7841. */
  7842. /* Windows return values: see
  7843. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7844. */
  7845. return 0;
  7846. }
  7847. ressave = res;
  7848. while (res) {
  7849. if ((dstlen >= (size_t)res->ai_addrlen)
  7850. && (res->ai_addr->sa_family == af)) {
  7851. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7852. func_ret = 1;
  7853. }
  7854. res = res->ai_next;
  7855. }
  7856. freeaddrinfo(ressave);
  7857. return func_ret;
  7858. }
  7859. static int
  7860. connect_socket(
  7861. struct mg_context *ctx /* may be NULL */,
  7862. const char *host,
  7863. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7864. int use_ssl, /* 0 or 1 */
  7865. struct mg_error_data *error,
  7866. SOCKET *sock /* output: socket, must not be NULL */,
  7867. union usa *sa /* output: socket address, must not be NULL */
  7868. )
  7869. {
  7870. int ip_ver = 0;
  7871. int conn_ret = -1;
  7872. int sockerr = 0;
  7873. *sock = INVALID_SOCKET;
  7874. memset(sa, 0, sizeof(*sa));
  7875. if (host == NULL) {
  7876. if (error != NULL) {
  7877. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7878. mg_snprintf(NULL,
  7879. NULL, /* No truncation check for ebuf */
  7880. error->text,
  7881. error->text_buffer_size,
  7882. "%s",
  7883. "NULL host");
  7884. }
  7885. return 0;
  7886. }
  7887. #if defined(USE_X_DOM_SOCKET)
  7888. if (port == -99) {
  7889. /* Unix domain socket */
  7890. size_t hostlen = strlen(host);
  7891. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7892. if (error != NULL) {
  7893. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7894. mg_snprintf(NULL,
  7895. NULL, /* No truncation check for ebuf */
  7896. error->text,
  7897. error->text_buffer_size,
  7898. "%s",
  7899. "host length exceeds limit");
  7900. }
  7901. return 0;
  7902. }
  7903. } else
  7904. #endif
  7905. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7906. if (error != NULL) {
  7907. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7908. mg_snprintf(NULL,
  7909. NULL, /* No truncation check for ebuf */
  7910. error->text,
  7911. error->text_buffer_size,
  7912. "%s",
  7913. "invalid port");
  7914. }
  7915. return 0;
  7916. }
  7917. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7918. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7919. if (use_ssl && (TLS_client_method == NULL)) {
  7920. if (error != NULL) {
  7921. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  7922. mg_snprintf(NULL,
  7923. NULL, /* No truncation check for ebuf */
  7924. error->text,
  7925. error->text_buffer_size,
  7926. "%s",
  7927. "SSL is not initialized");
  7928. }
  7929. return 0;
  7930. }
  7931. #else
  7932. if (use_ssl && (SSLv23_client_method == NULL)) {
  7933. if (error != 0) {
  7934. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  7935. mg_snprintf(NULL,
  7936. NULL, /* No truncation check for ebuf */
  7937. error->text,
  7938. error->text_buffer_size,
  7939. "%s",
  7940. "SSL is not initialized");
  7941. }
  7942. return 0;
  7943. }
  7944. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7945. #else
  7946. (void)use_ssl;
  7947. #endif /* NO SSL */
  7948. #if defined(USE_X_DOM_SOCKET)
  7949. if (port == -99) {
  7950. size_t hostlen = strlen(host);
  7951. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  7952. ip_ver = -99;
  7953. sa->sun.sun_family = AF_UNIX;
  7954. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  7955. memcpy(sa->sun.sun_path, host, hostlen);
  7956. } else
  7957. #endif
  7958. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7959. sa->sin.sin_port = htons((uint16_t)port);
  7960. ip_ver = 4;
  7961. #if defined(USE_IPV6)
  7962. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7963. sa->sin6.sin6_port = htons((uint16_t)port);
  7964. ip_ver = 6;
  7965. } else if (host[0] == '[') {
  7966. /* While getaddrinfo on Windows will work with [::1],
  7967. * getaddrinfo on Linux only works with ::1 (without []). */
  7968. size_t l = strlen(host + 1);
  7969. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7970. if (h) {
  7971. h[l - 1] = 0;
  7972. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7973. sa->sin6.sin6_port = htons((uint16_t)port);
  7974. ip_ver = 6;
  7975. }
  7976. mg_free(h);
  7977. }
  7978. #endif
  7979. }
  7980. if (ip_ver == 0) {
  7981. if (error != NULL) {
  7982. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  7983. mg_snprintf(NULL,
  7984. NULL, /* No truncation check for ebuf */
  7985. error->text,
  7986. error->text_buffer_size,
  7987. "%s",
  7988. "host not found");
  7989. }
  7990. return 0;
  7991. }
  7992. if (ip_ver == 4) {
  7993. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7994. }
  7995. #if defined(USE_IPV6)
  7996. else if (ip_ver == 6) {
  7997. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7998. }
  7999. #endif
  8000. #if defined(USE_X_DOM_SOCKET)
  8001. else if (ip_ver == -99) {
  8002. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8003. }
  8004. #endif
  8005. if (*sock == INVALID_SOCKET) {
  8006. if (error != NULL) {
  8007. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8008. error->code_sub = ERRNO;
  8009. mg_snprintf(NULL,
  8010. NULL, /* No truncation check for ebuf */
  8011. error->text,
  8012. error->text_buffer_size,
  8013. "socket(): %s",
  8014. strerror(ERRNO));
  8015. }
  8016. return 0;
  8017. }
  8018. if (0 != set_non_blocking_mode(*sock)) {
  8019. if (error != NULL) {
  8020. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8021. error->code_sub = ERRNO;
  8022. mg_snprintf(NULL,
  8023. NULL, /* No truncation check for ebuf */
  8024. error->text,
  8025. error->text_buffer_size,
  8026. "Cannot set socket to non-blocking: %s",
  8027. strerror(ERRNO));
  8028. }
  8029. closesocket(*sock);
  8030. *sock = INVALID_SOCKET;
  8031. return 0;
  8032. }
  8033. set_close_on_exec(*sock, NULL, ctx);
  8034. if (ip_ver == 4) {
  8035. /* connected with IPv4 */
  8036. conn_ret = connect(*sock,
  8037. (struct sockaddr *)((void *)&sa->sin),
  8038. sizeof(sa->sin));
  8039. }
  8040. #if defined(USE_IPV6)
  8041. else if (ip_ver == 6) {
  8042. /* connected with IPv6 */
  8043. conn_ret = connect(*sock,
  8044. (struct sockaddr *)((void *)&sa->sin6),
  8045. sizeof(sa->sin6));
  8046. }
  8047. #endif
  8048. #if defined(USE_X_DOM_SOCKET)
  8049. else if (ip_ver == -99) {
  8050. /* connected to domain socket */
  8051. conn_ret = connect(*sock,
  8052. (struct sockaddr *)((void *)&sa->sun),
  8053. sizeof(sa->sun));
  8054. }
  8055. #endif
  8056. if (conn_ret != 0) {
  8057. sockerr = ERRNO;
  8058. }
  8059. #if defined(_WIN32)
  8060. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8061. #else
  8062. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8063. #endif
  8064. /* Data for getsockopt */
  8065. void *psockerr = &sockerr;
  8066. int ret;
  8067. #if defined(_WIN32)
  8068. int len = (int)sizeof(sockerr);
  8069. #else
  8070. socklen_t len = (socklen_t)sizeof(sockerr);
  8071. #endif
  8072. /* Data for poll */
  8073. struct mg_pollfd pfd[1];
  8074. int pollres;
  8075. int ms_wait = 10000; /* 10 second timeout */
  8076. stop_flag_t nonstop;
  8077. STOP_FLAG_ASSIGN(&nonstop, 0);
  8078. /* For a non-blocking socket, the connect sequence is:
  8079. * 1) call connect (will not block)
  8080. * 2) wait until the socket is ready for writing (select or poll)
  8081. * 3) check connection state with getsockopt
  8082. */
  8083. pfd[0].fd = *sock;
  8084. pfd[0].events = POLLOUT;
  8085. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8086. if (pollres != 1) {
  8087. /* Not connected */
  8088. if (error != NULL) {
  8089. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8090. mg_snprintf(NULL,
  8091. NULL, /* No truncation check for ebuf */
  8092. error->text,
  8093. error->text_buffer_size,
  8094. "connect(%s:%d): timeout",
  8095. host,
  8096. port);
  8097. }
  8098. closesocket(*sock);
  8099. *sock = INVALID_SOCKET;
  8100. return 0;
  8101. }
  8102. #if defined(_WIN32)
  8103. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8104. #else
  8105. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8106. #endif
  8107. if ((ret == 0) && (sockerr == 0)) {
  8108. conn_ret = 0;
  8109. }
  8110. }
  8111. if (conn_ret != 0) {
  8112. /* Not connected */
  8113. if (error != NULL) {
  8114. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8115. error->code_sub = ERRNO;
  8116. mg_snprintf(NULL,
  8117. NULL, /* No truncation check for ebuf */
  8118. error->text,
  8119. error->text_buffer_size,
  8120. "connect(%s:%d): error %s",
  8121. host,
  8122. port,
  8123. strerror(sockerr));
  8124. }
  8125. closesocket(*sock);
  8126. *sock = INVALID_SOCKET;
  8127. return 0;
  8128. }
  8129. return 1;
  8130. }
  8131. CIVETWEB_API int
  8132. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8133. {
  8134. static const char *dont_escape = "._-$,;~()";
  8135. static const char *hex = "0123456789abcdef";
  8136. char *pos = dst;
  8137. const char *end = dst + dst_len - 1;
  8138. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8139. if (isalnum((unsigned char)*src)
  8140. || (strchr(dont_escape, *src) != NULL)) {
  8141. *pos = *src;
  8142. } else if (pos + 2 < end) {
  8143. pos[0] = '%';
  8144. pos[1] = hex[(unsigned char)*src >> 4];
  8145. pos[2] = hex[(unsigned char)*src & 0xf];
  8146. pos += 2;
  8147. } else {
  8148. break;
  8149. }
  8150. }
  8151. *pos = '\0';
  8152. return (*src == '\0') ? (int)(pos - dst) : -1;
  8153. }
  8154. /* Return 0 on success, non-zero if an error occurs. */
  8155. static int
  8156. print_dir_entry(struct mg_connection *conn, struct de *de)
  8157. {
  8158. size_t namesize, escsize, i;
  8159. char *href, *esc, *p;
  8160. char size[64], mod[64];
  8161. #if defined(REENTRANT_TIME)
  8162. struct tm _tm;
  8163. struct tm *tm = &_tm;
  8164. #else
  8165. struct tm *tm;
  8166. #endif
  8167. /* Estimate worst case size for encoding and escaping */
  8168. namesize = strlen(de->file_name) + 1;
  8169. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8170. href = (char *)mg_malloc(namesize * 3 + escsize);
  8171. if (href == NULL) {
  8172. return -1;
  8173. }
  8174. mg_url_encode(de->file_name, href, namesize * 3);
  8175. esc = NULL;
  8176. if (escsize > 0) {
  8177. /* HTML escaping needed */
  8178. esc = href + namesize * 3;
  8179. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8180. mg_strlcpy(p, de->file_name + i, 2);
  8181. if (*p == '&') {
  8182. strcpy(p, "&amp;");
  8183. } else if (*p == '<') {
  8184. strcpy(p, "&lt;");
  8185. } else if (*p == '>') {
  8186. strcpy(p, "&gt;");
  8187. }
  8188. }
  8189. }
  8190. if (de->file.is_directory) {
  8191. mg_snprintf(conn,
  8192. NULL, /* Buffer is big enough */
  8193. size,
  8194. sizeof(size),
  8195. "%s",
  8196. "[DIRECTORY]");
  8197. } else {
  8198. /* We use (signed) cast below because MSVC 6 compiler cannot
  8199. * convert unsigned __int64 to double. Sigh. */
  8200. if (de->file.size < 1024) {
  8201. mg_snprintf(conn,
  8202. NULL, /* Buffer is big enough */
  8203. size,
  8204. sizeof(size),
  8205. "%d",
  8206. (int)de->file.size);
  8207. } else if (de->file.size < 0x100000) {
  8208. mg_snprintf(conn,
  8209. NULL, /* Buffer is big enough */
  8210. size,
  8211. sizeof(size),
  8212. "%.1fk",
  8213. (double)de->file.size / 1024.0);
  8214. } else if (de->file.size < 0x40000000) {
  8215. mg_snprintf(conn,
  8216. NULL, /* Buffer is big enough */
  8217. size,
  8218. sizeof(size),
  8219. "%.1fM",
  8220. (double)de->file.size / 1048576);
  8221. } else {
  8222. mg_snprintf(conn,
  8223. NULL, /* Buffer is big enough */
  8224. size,
  8225. sizeof(size),
  8226. "%.1fG",
  8227. (double)de->file.size / 1073741824);
  8228. }
  8229. }
  8230. /* Note: mg_snprintf will not cause a buffer overflow above.
  8231. * So, string truncation checks are not required here. */
  8232. #if defined(REENTRANT_TIME)
  8233. localtime_r(&de->file.last_modified, tm);
  8234. #else
  8235. tm = localtime(&de->file.last_modified);
  8236. #endif
  8237. if (tm != NULL) {
  8238. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8239. } else {
  8240. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8241. mod[sizeof(mod) - 1] = '\0';
  8242. }
  8243. mg_printf(conn,
  8244. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8245. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8246. href,
  8247. de->file.is_directory ? "/" : "",
  8248. esc ? esc : de->file_name,
  8249. de->file.is_directory ? "/" : "",
  8250. mod,
  8251. size);
  8252. mg_free(href);
  8253. return 0;
  8254. }
  8255. /* This function is called from send_directory() and used for
  8256. * sorting directory entries by size, name, or modification time. */
  8257. static int
  8258. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8259. {
  8260. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8261. if (p1 && p2) {
  8262. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8263. int cmp_result = 0;
  8264. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8265. query_string = "n";
  8266. }
  8267. /* Sort Directories vs Files */
  8268. if (a->file.is_directory && !b->file.is_directory) {
  8269. return -1; /* Always put directories on top */
  8270. } else if (!a->file.is_directory && b->file.is_directory) {
  8271. return 1; /* Always put directories on top */
  8272. }
  8273. /* Sort by size or date */
  8274. if (*query_string == 's') {
  8275. cmp_result = (a->file.size == b->file.size)
  8276. ? 0
  8277. : ((a->file.size > b->file.size) ? 1 : -1);
  8278. } else if (*query_string == 'd') {
  8279. cmp_result =
  8280. (a->file.last_modified == b->file.last_modified)
  8281. ? 0
  8282. : ((a->file.last_modified > b->file.last_modified) ? 1
  8283. : -1);
  8284. }
  8285. /* Sort by name:
  8286. * if (*query_string == 'n') ...
  8287. * but also sort files of same size/date by name as secondary criterion.
  8288. */
  8289. if (cmp_result == 0) {
  8290. cmp_result = strcmp(a->file_name, b->file_name);
  8291. }
  8292. /* For descending order, invert result */
  8293. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8294. }
  8295. return 0;
  8296. }
  8297. static int
  8298. must_hide_file(struct mg_connection *conn, const char *path)
  8299. {
  8300. if (conn && conn->dom_ctx) {
  8301. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8302. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8303. return (match_prefix_strlen(pw_pattern, path) > 0)
  8304. || (match_prefix_strlen(pattern, path) > 0);
  8305. }
  8306. return 0;
  8307. }
  8308. #if !defined(NO_FILESYSTEMS)
  8309. static int
  8310. scan_directory(struct mg_connection *conn,
  8311. const char *dir,
  8312. void *data,
  8313. int (*cb)(struct de *, void *))
  8314. {
  8315. char path[UTF8_PATH_MAX];
  8316. struct dirent *dp;
  8317. DIR *dirp;
  8318. struct de de;
  8319. int truncated;
  8320. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8321. return 0;
  8322. } else {
  8323. while ((dp = mg_readdir(dirp)) != NULL) {
  8324. /* Do not show current dir and hidden files */
  8325. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8326. || must_hide_file(conn, dp->d_name)) {
  8327. continue;
  8328. }
  8329. mg_snprintf(
  8330. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8331. /* If we don't memset stat structure to zero, mtime will have
  8332. * garbage and strftime() will segfault later on in
  8333. * print_dir_entry(). memset is required only if mg_stat()
  8334. * fails. For more details, see
  8335. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8336. memset(&de.file, 0, sizeof(de.file));
  8337. if (truncated) {
  8338. /* If the path is not complete, skip processing. */
  8339. continue;
  8340. }
  8341. if (!mg_stat(conn, path, &de.file)) {
  8342. mg_cry_internal(conn,
  8343. "%s: mg_stat(%s) failed: %s",
  8344. __func__,
  8345. path,
  8346. strerror(ERRNO));
  8347. }
  8348. de.file_name = dp->d_name;
  8349. if (cb(&de, data)) {
  8350. /* stopped */
  8351. break;
  8352. }
  8353. }
  8354. (void)mg_closedir(dirp);
  8355. }
  8356. return 1;
  8357. }
  8358. #endif /* NO_FILESYSTEMS */
  8359. #if !defined(NO_FILES)
  8360. static int
  8361. remove_directory(struct mg_connection *conn, const char *dir)
  8362. {
  8363. char path[UTF8_PATH_MAX];
  8364. struct dirent *dp;
  8365. DIR *dirp;
  8366. struct de de;
  8367. int truncated;
  8368. int ok = 1;
  8369. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8370. return 0;
  8371. } else {
  8372. while ((dp = mg_readdir(dirp)) != NULL) {
  8373. /* Do not show current dir (but show hidden files as they will
  8374. * also be removed) */
  8375. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8376. continue;
  8377. }
  8378. mg_snprintf(
  8379. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8380. /* If we don't memset stat structure to zero, mtime will have
  8381. * garbage and strftime() will segfault later on in
  8382. * print_dir_entry(). memset is required only if mg_stat()
  8383. * fails. For more details, see
  8384. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8385. memset(&de.file, 0, sizeof(de.file));
  8386. if (truncated) {
  8387. /* Do not delete anything shorter */
  8388. ok = 0;
  8389. continue;
  8390. }
  8391. if (!mg_stat(conn, path, &de.file)) {
  8392. mg_cry_internal(conn,
  8393. "%s: mg_stat(%s) failed: %s",
  8394. __func__,
  8395. path,
  8396. strerror(ERRNO));
  8397. ok = 0;
  8398. }
  8399. if (de.file.is_directory) {
  8400. if (remove_directory(conn, path) == 0) {
  8401. ok = 0;
  8402. }
  8403. } else {
  8404. /* This will fail file is the file is in memory */
  8405. if (mg_remove(conn, path) == 0) {
  8406. ok = 0;
  8407. }
  8408. }
  8409. }
  8410. (void)mg_closedir(dirp);
  8411. IGNORE_UNUSED_RESULT(rmdir(dir));
  8412. }
  8413. return ok;
  8414. }
  8415. #endif
  8416. struct dir_scan_data {
  8417. struct de *entries;
  8418. size_t num_entries;
  8419. size_t arr_size;
  8420. };
  8421. #if !defined(NO_FILESYSTEMS)
  8422. static int
  8423. dir_scan_callback(struct de *de, void *data)
  8424. {
  8425. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8426. struct de *entries = dsd->entries;
  8427. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8428. /* Here "entries" is a temporary pointer and can be replaced,
  8429. * "dsd->entries" is the original pointer */
  8430. entries =
  8431. (struct de *)mg_realloc(entries,
  8432. dsd->arr_size * 2 * sizeof(entries[0]));
  8433. if (entries == NULL) {
  8434. /* stop scan */
  8435. return 1;
  8436. }
  8437. dsd->entries = entries;
  8438. dsd->arr_size *= 2;
  8439. }
  8440. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8441. if (entries[dsd->num_entries].file_name == NULL) {
  8442. /* stop scan */
  8443. return 1;
  8444. }
  8445. entries[dsd->num_entries].file = de->file;
  8446. dsd->num_entries++;
  8447. return 0;
  8448. }
  8449. static void
  8450. handle_directory_request(struct mg_connection *conn, const char *dir)
  8451. {
  8452. size_t i;
  8453. int sort_direction;
  8454. struct dir_scan_data data = {NULL, 0, 128};
  8455. char date[64], *esc, *p;
  8456. const char *title;
  8457. time_t curtime = time(NULL);
  8458. if (!conn) {
  8459. return;
  8460. }
  8461. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8462. mg_send_http_error(conn,
  8463. 500,
  8464. "Error: Cannot open directory\nopendir(%s): %s",
  8465. dir,
  8466. strerror(ERRNO));
  8467. return;
  8468. }
  8469. gmt_time_string(date, sizeof(date), &curtime);
  8470. esc = NULL;
  8471. title = conn->request_info.local_uri;
  8472. if (title[strcspn(title, "&<>")]) {
  8473. /* HTML escaping needed */
  8474. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8475. if (esc) {
  8476. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8477. mg_strlcpy(p, title + i, 2);
  8478. if (*p == '&') {
  8479. strcpy(p, "&amp;");
  8480. } else if (*p == '<') {
  8481. strcpy(p, "&lt;");
  8482. } else if (*p == '>') {
  8483. strcpy(p, "&gt;");
  8484. }
  8485. }
  8486. } else {
  8487. title = "";
  8488. }
  8489. }
  8490. sort_direction = ((conn->request_info.query_string != NULL)
  8491. && (conn->request_info.query_string[0] != '\0')
  8492. && (conn->request_info.query_string[1] == 'd'))
  8493. ? 'a'
  8494. : 'd';
  8495. conn->must_close = 1;
  8496. /* Create 200 OK response */
  8497. mg_response_header_start(conn, 200);
  8498. send_static_cache_header(conn);
  8499. send_additional_header(conn);
  8500. mg_response_header_add(conn,
  8501. "Content-Type",
  8502. "text/html; charset=utf-8",
  8503. -1);
  8504. /* Send all headers */
  8505. mg_response_header_send(conn);
  8506. /* Body */
  8507. mg_printf(conn,
  8508. "<html><head><title>Index of %s</title>"
  8509. "<style>th {text-align: left;}</style></head>"
  8510. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8511. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8512. "<th><a href=\"?d%c\">Modified</a></th>"
  8513. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8514. "<tr><td colspan=\"3\"><hr></td></tr>",
  8515. esc ? esc : title,
  8516. esc ? esc : title,
  8517. sort_direction,
  8518. sort_direction,
  8519. sort_direction);
  8520. mg_free(esc);
  8521. /* Print first entry - link to a parent directory */
  8522. mg_printf(conn,
  8523. "<tr><td><a href=\"%s\">%s</a></td>"
  8524. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8525. "..",
  8526. "Parent directory",
  8527. "-",
  8528. "-");
  8529. /* Sort and print directory entries */
  8530. if (data.entries != NULL) {
  8531. mg_sort(data.entries,
  8532. data.num_entries,
  8533. sizeof(data.entries[0]),
  8534. compare_dir_entries,
  8535. (void *)conn->request_info.query_string);
  8536. for (i = 0; i < data.num_entries; i++) {
  8537. print_dir_entry(conn, &data.entries[i]);
  8538. mg_free(data.entries[i].file_name);
  8539. }
  8540. mg_free(data.entries);
  8541. }
  8542. mg_printf(conn, "%s", "</table></pre></body></html>");
  8543. conn->status_code = 200;
  8544. }
  8545. #endif /* NO_FILESYSTEMS */
  8546. /* Send len bytes from the opened file to the client. */
  8547. static void
  8548. send_file_data(struct mg_connection *conn,
  8549. struct mg_file *filep,
  8550. int64_t offset,
  8551. int64_t len,
  8552. int no_buffering)
  8553. {
  8554. char buf[MG_BUF_LEN];
  8555. int to_read, num_read, num_written;
  8556. int64_t size;
  8557. if (!filep || !conn) {
  8558. return;
  8559. }
  8560. /* Sanity check the offset */
  8561. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8562. : (int64_t)(filep->stat.size);
  8563. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8564. if (len > 0 && filep->access.fp != NULL) {
  8565. /* file stored on disk */
  8566. #if defined(__linux__)
  8567. /* sendfile is only available for Linux */
  8568. if ((conn->ssl == 0) && (conn->throttle == 0)
  8569. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8570. "yes"))) {
  8571. off_t sf_offs = (off_t)offset;
  8572. ssize_t sf_sent;
  8573. int sf_file = fileno(filep->access.fp);
  8574. int loop_cnt = 0;
  8575. do {
  8576. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8577. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8578. size_t sf_tosend =
  8579. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8580. sf_sent =
  8581. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8582. if (sf_sent > 0) {
  8583. len -= sf_sent;
  8584. offset += sf_sent;
  8585. } else if (loop_cnt == 0) {
  8586. /* This file can not be sent using sendfile.
  8587. * This might be the case for pseudo-files in the
  8588. * /sys/ and /proc/ file system.
  8589. * Use the regular user mode copy code instead. */
  8590. break;
  8591. } else if (sf_sent == 0) {
  8592. /* No error, but 0 bytes sent. May be EOF? */
  8593. return;
  8594. }
  8595. loop_cnt++;
  8596. } while ((len > 0) && (sf_sent >= 0));
  8597. if (sf_sent > 0) {
  8598. return; /* OK */
  8599. }
  8600. /* sf_sent<0 means error, thus fall back to the classic way */
  8601. /* This is always the case, if sf_file is not a "normal" file,
  8602. * e.g., for sending data from the output of a CGI process. */
  8603. offset = (int64_t)sf_offs;
  8604. }
  8605. #endif
  8606. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8607. mg_cry_internal(conn,
  8608. "%s: fseeko() failed: %s",
  8609. __func__,
  8610. strerror(ERRNO));
  8611. mg_send_http_error(
  8612. conn,
  8613. 500,
  8614. "%s",
  8615. "Error: Unable to access file at requested position.");
  8616. } else {
  8617. while (len > 0) {
  8618. /* Calculate how much to read from the file into the buffer. */
  8619. /* If no_buffering is set, we should not wait until the
  8620. * CGI->Server buffer is filled, but send everything
  8621. * immediately. In theory buffering could be turned off using
  8622. * setbuf(filep->access.fp, NULL);
  8623. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8624. * but in practice this does not work. A "Linux only" solution
  8625. * may be to use select(). The only portable way is to read byte
  8626. * by byte, but this is quite inefficient from a performance
  8627. * point of view. */
  8628. to_read = no_buffering ? 1 : sizeof(buf);
  8629. if ((int64_t)to_read > len) {
  8630. to_read = (int)len;
  8631. }
  8632. /* Read from file, exit the loop on error */
  8633. if ((num_read =
  8634. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8635. <= 0) {
  8636. break;
  8637. }
  8638. /* Send read bytes to the client, exit the loop on error */
  8639. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8640. != num_read) {
  8641. break;
  8642. }
  8643. /* Both read and were successful, adjust counters */
  8644. len -= num_written;
  8645. }
  8646. }
  8647. }
  8648. }
  8649. static int
  8650. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8651. {
  8652. return sscanf(header,
  8653. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8654. a,
  8655. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8656. // to an integer value, but function will not report
  8657. // conversion errors; consider using 'strtol' instead
  8658. }
  8659. static void
  8660. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8661. {
  8662. if ((filestat != NULL) && (buf != NULL)) {
  8663. mg_snprintf(NULL,
  8664. NULL, /* All calls to construct_etag use 64 byte buffer */
  8665. buf,
  8666. buf_len,
  8667. "\"%lx.%" INT64_FMT "\"",
  8668. (unsigned long)filestat->last_modified,
  8669. filestat->size);
  8670. }
  8671. }
  8672. static void
  8673. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8674. {
  8675. if (filep != NULL && filep->fp != NULL) {
  8676. #if defined(_WIN32)
  8677. (void)conn; /* Unused. */
  8678. #else
  8679. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8680. mg_cry_internal(conn,
  8681. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8682. __func__,
  8683. strerror(ERRNO));
  8684. }
  8685. #endif
  8686. }
  8687. }
  8688. #if defined(USE_ZLIB)
  8689. #include "mod_zlib.inl"
  8690. #endif
  8691. #if !defined(NO_FILESYSTEMS)
  8692. static void
  8693. handle_static_file_request(struct mg_connection *conn,
  8694. const char *path,
  8695. struct mg_file *filep,
  8696. const char *mime_type,
  8697. const char *additional_headers)
  8698. {
  8699. char lm[64], etag[64];
  8700. char range[128]; /* large enough, so there will be no overflow */
  8701. const char *range_hdr;
  8702. int64_t cl, r1, r2;
  8703. struct vec mime_vec;
  8704. int n, truncated;
  8705. char gz_path[UTF8_PATH_MAX];
  8706. const char *encoding = 0;
  8707. int is_head_request;
  8708. #if defined(USE_ZLIB)
  8709. /* Compression is allowed, unless there is a reason not to use
  8710. * compression. If the file is already compressed, too small or a
  8711. * "range" request was made, on the fly compression is not possible. */
  8712. int allow_on_the_fly_compression = 1;
  8713. #endif
  8714. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8715. return;
  8716. }
  8717. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8718. if (mime_type == NULL) {
  8719. get_mime_type(conn, path, &mime_vec);
  8720. } else {
  8721. mime_vec.ptr = mime_type;
  8722. mime_vec.len = strlen(mime_type);
  8723. }
  8724. if (filep->stat.size > INT64_MAX) {
  8725. mg_send_http_error(conn,
  8726. 500,
  8727. "Error: File size is too large to send\n%" INT64_FMT,
  8728. filep->stat.size);
  8729. return;
  8730. }
  8731. cl = (int64_t)filep->stat.size;
  8732. conn->status_code = 200;
  8733. range[0] = '\0';
  8734. #if defined(USE_ZLIB)
  8735. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8736. * it's important to rewrite the filename after resolving
  8737. * the mime type from it, to preserve the actual file's type */
  8738. if (!conn->accept_gzip) {
  8739. allow_on_the_fly_compression = 0;
  8740. }
  8741. #endif
  8742. /* Check if there is a range header */
  8743. range_hdr = mg_get_header(conn, "Range");
  8744. /* For gzipped files, add *.gz */
  8745. if (filep->stat.is_gzipped) {
  8746. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8747. if (truncated) {
  8748. mg_send_http_error(conn,
  8749. 500,
  8750. "Error: Path of zipped file too long (%s)",
  8751. path);
  8752. return;
  8753. }
  8754. path = gz_path;
  8755. encoding = "gzip";
  8756. #if defined(USE_ZLIB)
  8757. /* File is already compressed. No "on the fly" compression. */
  8758. allow_on_the_fly_compression = 0;
  8759. #endif
  8760. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8761. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8762. struct mg_file_stat file_stat;
  8763. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8764. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8765. && !file_stat.is_directory) {
  8766. file_stat.is_gzipped = 1;
  8767. filep->stat = file_stat;
  8768. cl = (int64_t)filep->stat.size;
  8769. path = gz_path;
  8770. encoding = "gzip";
  8771. #if defined(USE_ZLIB)
  8772. /* File is already compressed. No "on the fly" compression. */
  8773. allow_on_the_fly_compression = 0;
  8774. #endif
  8775. }
  8776. }
  8777. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8778. mg_send_http_error(conn,
  8779. 500,
  8780. "Error: Cannot open file\nfopen(%s): %s",
  8781. path,
  8782. strerror(ERRNO));
  8783. return;
  8784. }
  8785. fclose_on_exec(&filep->access, conn);
  8786. /* If "Range" request was made: parse header, send only selected part
  8787. * of the file. */
  8788. r1 = r2 = 0;
  8789. if ((range_hdr != NULL)
  8790. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8791. && (r2 >= 0)) {
  8792. /* actually, range requests don't play well with a pre-gzipped
  8793. * file (since the range is specified in the uncompressed space) */
  8794. if (filep->stat.is_gzipped) {
  8795. mg_send_http_error(
  8796. conn,
  8797. 416, /* 416 = Range Not Satisfiable */
  8798. "%s",
  8799. "Error: Range requests in gzipped files are not supported");
  8800. (void)mg_fclose(
  8801. &filep->access); /* ignore error on read only file */
  8802. return;
  8803. }
  8804. conn->status_code = 206;
  8805. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8806. mg_snprintf(conn,
  8807. NULL, /* range buffer is big enough */
  8808. range,
  8809. sizeof(range),
  8810. "bytes "
  8811. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8812. r1,
  8813. r1 + cl - 1,
  8814. filep->stat.size);
  8815. #if defined(USE_ZLIB)
  8816. /* Do not compress ranges. */
  8817. allow_on_the_fly_compression = 0;
  8818. #endif
  8819. }
  8820. /* Do not compress small files. Small files do not benefit from file
  8821. * compression, but there is still some overhead. */
  8822. #if defined(USE_ZLIB)
  8823. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8824. /* File is below the size limit. */
  8825. allow_on_the_fly_compression = 0;
  8826. }
  8827. #endif
  8828. /* Prepare Etag, and Last-Modified headers. */
  8829. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8830. construct_etag(etag, sizeof(etag), &filep->stat);
  8831. /* Create 2xx (200, 206) response */
  8832. mg_response_header_start(conn, conn->status_code);
  8833. send_static_cache_header(conn);
  8834. send_additional_header(conn);
  8835. send_cors_header(conn);
  8836. mg_response_header_add(conn,
  8837. "Content-Type",
  8838. mime_vec.ptr,
  8839. (int)mime_vec.len);
  8840. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8841. mg_response_header_add(conn, "Etag", etag, -1);
  8842. #if defined(USE_ZLIB)
  8843. /* On the fly compression allowed */
  8844. if (allow_on_the_fly_compression) {
  8845. /* For on the fly compression, we don't know the content size in
  8846. * advance, so we have to use chunked encoding */
  8847. encoding = "gzip";
  8848. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8849. /* HTTP/2 is always using "chunks" (frames) */
  8850. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8851. }
  8852. } else
  8853. #endif
  8854. {
  8855. /* Without on-the-fly compression, we know the content-length
  8856. * and we can use ranges (with on-the-fly compression we cannot).
  8857. * So we send these response headers only in this case. */
  8858. char len[32];
  8859. int trunc = 0;
  8860. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8861. if (!trunc) {
  8862. mg_response_header_add(conn, "Content-Length", len, -1);
  8863. }
  8864. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8865. }
  8866. if (encoding) {
  8867. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8868. }
  8869. if (range[0] != 0) {
  8870. mg_response_header_add(conn, "Content-Range", range, -1);
  8871. }
  8872. /* The code above does not add any header starting with X- to make
  8873. * sure no one of the additional_headers is included twice */
  8874. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8875. mg_response_header_add_lines(conn, additional_headers);
  8876. }
  8877. /* Send all headers */
  8878. mg_response_header_send(conn);
  8879. if (!is_head_request) {
  8880. #if defined(USE_ZLIB)
  8881. if (allow_on_the_fly_compression) {
  8882. /* Compress and send */
  8883. send_compressed_data(conn, filep);
  8884. } else
  8885. #endif
  8886. {
  8887. /* Send file directly */
  8888. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  8889. }
  8890. }
  8891. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8892. }
  8893. CIVETWEB_API int
  8894. mg_send_file_body(struct mg_connection *conn, const char *path)
  8895. {
  8896. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8897. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8898. return -1;
  8899. }
  8900. fclose_on_exec(&file.access, conn);
  8901. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  8902. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8903. return 0; /* >= 0 for OK */
  8904. }
  8905. #endif /* NO_FILESYSTEMS */
  8906. #if !defined(NO_CACHING)
  8907. /* Return True if we should reply 304 Not Modified. */
  8908. static int
  8909. is_not_modified(const struct mg_connection *conn,
  8910. const struct mg_file_stat *filestat)
  8911. {
  8912. char etag[64];
  8913. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8914. const char *inm = mg_get_header(conn, "If-None-Match");
  8915. construct_etag(etag, sizeof(etag), filestat);
  8916. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8917. || ((ims != NULL)
  8918. && (filestat->last_modified <= parse_date_string(ims)));
  8919. }
  8920. static void
  8921. handle_not_modified_static_file_request(struct mg_connection *conn,
  8922. struct mg_file *filep)
  8923. {
  8924. char lm[64], etag[64];
  8925. if ((conn == NULL) || (filep == NULL)) {
  8926. return;
  8927. }
  8928. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8929. construct_etag(etag, sizeof(etag), &filep->stat);
  8930. /* Create 304 "not modified" response */
  8931. mg_response_header_start(conn, 304);
  8932. send_static_cache_header(conn);
  8933. send_additional_header(conn);
  8934. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8935. mg_response_header_add(conn, "Etag", etag, -1);
  8936. /* Send all headers */
  8937. mg_response_header_send(conn);
  8938. }
  8939. #endif
  8940. #if !defined(NO_FILESYSTEMS)
  8941. CIVETWEB_API void
  8942. mg_send_file(struct mg_connection *conn, const char *path)
  8943. {
  8944. mg_send_mime_file2(conn, path, NULL, NULL);
  8945. }
  8946. CIVETWEB_API void
  8947. mg_send_mime_file(struct mg_connection *conn,
  8948. const char *path,
  8949. const char *mime_type)
  8950. {
  8951. mg_send_mime_file2(conn, path, mime_type, NULL);
  8952. }
  8953. CIVETWEB_API void
  8954. mg_send_mime_file2(struct mg_connection *conn,
  8955. const char *path,
  8956. const char *mime_type,
  8957. const char *additional_headers)
  8958. {
  8959. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8960. if (!conn) {
  8961. /* No conn */
  8962. return;
  8963. }
  8964. if (mg_stat(conn, path, &file.stat)) {
  8965. #if !defined(NO_CACHING)
  8966. if (is_not_modified(conn, &file.stat)) {
  8967. /* Send 304 "Not Modified" - this must not send any body data */
  8968. handle_not_modified_static_file_request(conn, &file);
  8969. } else
  8970. #endif /* NO_CACHING */
  8971. if (file.stat.is_directory) {
  8972. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8973. "yes")) {
  8974. handle_directory_request(conn, path);
  8975. } else {
  8976. mg_send_http_error(conn,
  8977. 403,
  8978. "%s",
  8979. "Error: Directory listing denied");
  8980. }
  8981. } else {
  8982. handle_static_file_request(
  8983. conn, path, &file, mime_type, additional_headers);
  8984. }
  8985. } else {
  8986. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8987. }
  8988. }
  8989. /* For a given PUT path, create all intermediate subdirectories.
  8990. * Return 0 if the path itself is a directory.
  8991. * Return 1 if the path leads to a file.
  8992. * Return -1 for if the path is too long.
  8993. * Return -2 if path can not be created.
  8994. */
  8995. static int
  8996. put_dir(struct mg_connection *conn, const char *path)
  8997. {
  8998. char buf[UTF8_PATH_MAX];
  8999. const char *s, *p;
  9000. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9001. size_t len;
  9002. int res = 1;
  9003. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9004. len = (size_t)(p - path);
  9005. if (len >= sizeof(buf)) {
  9006. /* path too long */
  9007. res = -1;
  9008. break;
  9009. }
  9010. memcpy(buf, path, len);
  9011. buf[len] = '\0';
  9012. /* Try to create intermediate directory */
  9013. DEBUG_TRACE("mkdir(%s)", buf);
  9014. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9015. /* path does not exixt and can not be created */
  9016. res = -2;
  9017. break;
  9018. }
  9019. /* Is path itself a directory? */
  9020. if (p[1] == '\0') {
  9021. res = 0;
  9022. }
  9023. }
  9024. return res;
  9025. }
  9026. static void
  9027. remove_bad_file(const struct mg_connection *conn, const char *path)
  9028. {
  9029. int r = mg_remove(conn, path);
  9030. if (r != 0) {
  9031. mg_cry_internal(conn,
  9032. "%s: Cannot remove invalid file %s",
  9033. __func__,
  9034. path);
  9035. }
  9036. }
  9037. CIVETWEB_API long long
  9038. mg_store_body(struct mg_connection *conn, const char *path)
  9039. {
  9040. char buf[MG_BUF_LEN];
  9041. long long len = 0;
  9042. int ret, n;
  9043. struct mg_file fi;
  9044. if (conn->consumed_content != 0) {
  9045. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9046. return -11;
  9047. }
  9048. ret = put_dir(conn, path);
  9049. if (ret < 0) {
  9050. /* -1 for path too long,
  9051. * -2 for path can not be created. */
  9052. return ret;
  9053. }
  9054. if (ret != 1) {
  9055. /* Return 0 means, path itself is a directory. */
  9056. return 0;
  9057. }
  9058. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9059. return -12;
  9060. }
  9061. ret = mg_read(conn, buf, sizeof(buf));
  9062. while (ret > 0) {
  9063. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9064. if (n != ret) {
  9065. (void)mg_fclose(
  9066. &fi.access); /* File is bad and will be removed anyway. */
  9067. remove_bad_file(conn, path);
  9068. return -13;
  9069. }
  9070. len += ret;
  9071. ret = mg_read(conn, buf, sizeof(buf));
  9072. }
  9073. /* File is open for writing. If fclose fails, there was probably an
  9074. * error flushing the buffer to disk, so the file on disk might be
  9075. * broken. Delete it and return an error to the caller. */
  9076. if (mg_fclose(&fi.access) != 0) {
  9077. remove_bad_file(conn, path);
  9078. return -14;
  9079. }
  9080. return len;
  9081. }
  9082. #endif /* NO_FILESYSTEMS */
  9083. /* Parse a buffer:
  9084. * Forward the string pointer till the end of a word, then
  9085. * terminate it and forward till the begin of the next word.
  9086. */
  9087. static int
  9088. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9089. {
  9090. /* Forward until a space is found - use isgraph here */
  9091. /* See http://www.cplusplus.com/reference/cctype/ */
  9092. while (isgraph((unsigned char)**ppw)) {
  9093. (*ppw)++;
  9094. }
  9095. /* Check end of word */
  9096. if (eol) {
  9097. /* must be a end of line */
  9098. if ((**ppw != '\r') && (**ppw != '\n')) {
  9099. return -1;
  9100. }
  9101. } else {
  9102. /* must be a end of a word, but not a line */
  9103. if (**ppw != ' ') {
  9104. return -1;
  9105. }
  9106. }
  9107. /* Terminate and forward to the next word */
  9108. do {
  9109. **ppw = 0;
  9110. (*ppw)++;
  9111. } while (isspace((unsigned char)**ppw));
  9112. /* Check after term */
  9113. if (!eol) {
  9114. /* if it's not the end of line, there must be a next word */
  9115. if (!isgraph((unsigned char)**ppw)) {
  9116. return -1;
  9117. }
  9118. }
  9119. /* ok */
  9120. return 1;
  9121. }
  9122. /* Parse HTTP headers from the given buffer, advance buf pointer
  9123. * to the point where parsing stopped.
  9124. * All parameters must be valid pointers (not NULL).
  9125. * Return <0 on error. */
  9126. static int
  9127. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9128. {
  9129. int i;
  9130. int num_headers = 0;
  9131. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9132. char *dp = *buf;
  9133. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9134. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9135. dp++;
  9136. }
  9137. if (dp == *buf) {
  9138. /* End of headers reached. */
  9139. break;
  9140. }
  9141. /* Drop all spaces after header name before : */
  9142. while (*dp == ' ') {
  9143. *dp = 0;
  9144. dp++;
  9145. }
  9146. if (*dp != ':') {
  9147. /* This is not a valid field. */
  9148. return -1;
  9149. }
  9150. /* End of header key (*dp == ':') */
  9151. /* Truncate here and set the key name */
  9152. *dp = 0;
  9153. hdr[i].name = *buf;
  9154. /* Skip all spaces */
  9155. do {
  9156. dp++;
  9157. } while ((*dp == ' ') || (*dp == '\t'));
  9158. /* The rest of the line is the value */
  9159. hdr[i].value = dp;
  9160. /* Find end of line */
  9161. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9162. dp++;
  9163. };
  9164. /* eliminate \r */
  9165. if (*dp == '\r') {
  9166. *dp = 0;
  9167. dp++;
  9168. if (*dp != '\n') {
  9169. /* This is not a valid line. */
  9170. return -1;
  9171. }
  9172. }
  9173. /* here *dp is either 0 or '\n' */
  9174. /* in any case, we have a new header */
  9175. num_headers = i + 1;
  9176. if (*dp) {
  9177. *dp = 0;
  9178. dp++;
  9179. *buf = dp;
  9180. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9181. /* This is the end of the header */
  9182. break;
  9183. }
  9184. } else {
  9185. *buf = dp;
  9186. break;
  9187. }
  9188. }
  9189. return num_headers;
  9190. }
  9191. struct mg_http_method_info {
  9192. const char *name;
  9193. int request_has_body;
  9194. int response_has_body;
  9195. int is_safe;
  9196. int is_idempotent;
  9197. int is_cacheable;
  9198. };
  9199. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9200. static const struct mg_http_method_info http_methods[] = {
  9201. /* HTTP (RFC 2616) */
  9202. {"GET", 0, 1, 1, 1, 1},
  9203. {"POST", 1, 1, 0, 0, 0},
  9204. {"PUT", 1, 0, 0, 1, 0},
  9205. {"DELETE", 0, 0, 0, 1, 0},
  9206. {"HEAD", 0, 0, 1, 1, 1},
  9207. {"OPTIONS", 0, 0, 1, 1, 0},
  9208. {"CONNECT", 1, 1, 0, 0, 0},
  9209. /* TRACE method (RFC 2616) is not supported for security reasons */
  9210. /* PATCH method (RFC 5789) */
  9211. {"PATCH", 1, 0, 0, 0, 0},
  9212. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9213. /* WEBDAV (RFC 2518) */
  9214. {"PROPFIND", 0, 1, 1, 1, 0},
  9215. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9216. * Some PROPFIND results MAY be cached, with care,
  9217. * as there is no cache validation mechanism for
  9218. * most properties. This method is both safe and
  9219. * idempotent (see Section 9.1 of [RFC2616]). */
  9220. {"MKCOL", 0, 0, 0, 1, 0},
  9221. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9222. * When MKCOL is invoked without a request body,
  9223. * the newly created collection SHOULD have no
  9224. * members. A MKCOL request message may contain
  9225. * a message body. The precise behavior of a MKCOL
  9226. * request when the body is present is undefined,
  9227. * ... ==> We do not support MKCOL with body data.
  9228. * This method is idempotent, but not safe (see
  9229. * Section 9.1 of [RFC2616]). Responses to this
  9230. * method MUST NOT be cached. */
  9231. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9232. {"LOCK", 1, 1, 0, 0, 0},
  9233. {"UNLOCK", 1, 0, 0, 0, 0},
  9234. {"PROPPATCH", 1, 1, 0, 0, 0},
  9235. {"COPY", 1, 0, 0, 0, 0},
  9236. {"MOVE", 1, 1, 0, 0, 0},
  9237. /* Unsupported WEBDAV Methods: */
  9238. /* + 11 methods from RFC 3253 */
  9239. /* ORDERPATCH (RFC 3648) */
  9240. /* ACL (RFC 3744) */
  9241. /* SEARCH (RFC 5323) */
  9242. /* + MicroSoft extensions
  9243. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9244. /* REPORT method (RFC 3253) */
  9245. {"REPORT", 1, 1, 1, 1, 1},
  9246. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9247. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9248. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9249. * to be useful for REST in case a "GET request with body" is
  9250. * required. */
  9251. {NULL, 0, 0, 0, 0, 0}
  9252. /* end of list */
  9253. };
  9254. /* All method names */
  9255. static char *all_methods = NULL; /* Built by mg_init_library */
  9256. static const struct mg_http_method_info *
  9257. get_http_method_info(const char *method)
  9258. {
  9259. /* Check if the method is known to the server. The list of all known
  9260. * HTTP methods can be found here at
  9261. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9262. */
  9263. const struct mg_http_method_info *m = http_methods;
  9264. while (m->name) {
  9265. if (!strcmp(m->name, method)) {
  9266. return m;
  9267. }
  9268. m++;
  9269. }
  9270. return NULL;
  9271. }
  9272. static int
  9273. is_valid_http_method(const char *method)
  9274. {
  9275. return (get_http_method_info(method) != NULL);
  9276. }
  9277. /* Parse HTTP request, fill in mg_request_info structure.
  9278. * This function modifies the buffer by NUL-terminating
  9279. * HTTP request components, header names and header values.
  9280. * Parameters:
  9281. * buf (in/out): pointer to the HTTP header to parse and split
  9282. * len (in): length of HTTP header buffer
  9283. * re (out): parsed header as mg_request_info
  9284. * buf and ri must be valid pointers (not NULL), len>0.
  9285. * Returns <0 on error. */
  9286. static int
  9287. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9288. {
  9289. int request_length;
  9290. int init_skip = 0;
  9291. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9292. * remote_port */
  9293. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9294. NULL;
  9295. ri->num_headers = 0;
  9296. /* RFC says that all initial whitespaces should be ignored */
  9297. /* This included all leading \r and \n (isspace) */
  9298. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9299. while ((len > 0) && isspace((unsigned char)*buf)) {
  9300. buf++;
  9301. len--;
  9302. init_skip++;
  9303. }
  9304. if (len == 0) {
  9305. /* Incomplete request */
  9306. return 0;
  9307. }
  9308. /* Control characters are not allowed, including zero */
  9309. if (iscntrl((unsigned char)*buf)) {
  9310. return -1;
  9311. }
  9312. /* Find end of HTTP header */
  9313. request_length = get_http_header_len(buf, len);
  9314. if (request_length <= 0) {
  9315. return request_length;
  9316. }
  9317. buf[request_length - 1] = '\0';
  9318. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9319. return -1;
  9320. }
  9321. /* The first word has to be the HTTP method */
  9322. ri->request_method = buf;
  9323. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9324. return -1;
  9325. }
  9326. /* The second word is the URI */
  9327. ri->request_uri = buf;
  9328. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9329. return -1;
  9330. }
  9331. /* Next would be the HTTP version */
  9332. ri->http_version = buf;
  9333. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9334. return -1;
  9335. }
  9336. /* Check for a valid HTTP version key */
  9337. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9338. /* Invalid request */
  9339. return -1;
  9340. }
  9341. ri->http_version += 5;
  9342. /* Check for a valid http method */
  9343. if (!is_valid_http_method(ri->request_method)) {
  9344. return -1;
  9345. }
  9346. /* Parse all HTTP headers */
  9347. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9348. if (ri->num_headers < 0) {
  9349. /* Error while parsing headers */
  9350. return -1;
  9351. }
  9352. return request_length + init_skip;
  9353. }
  9354. static int
  9355. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9356. {
  9357. int response_length;
  9358. int init_skip = 0;
  9359. char *tmp, *tmp2;
  9360. long l;
  9361. /* Initialize elements. */
  9362. ri->http_version = ri->status_text = NULL;
  9363. ri->num_headers = ri->status_code = 0;
  9364. /* RFC says that all initial whitespaces should be ingored */
  9365. /* This included all leading \r and \n (isspace) */
  9366. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9367. while ((len > 0) && isspace((unsigned char)*buf)) {
  9368. buf++;
  9369. len--;
  9370. init_skip++;
  9371. }
  9372. if (len == 0) {
  9373. /* Incomplete request */
  9374. return 0;
  9375. }
  9376. /* Control characters are not allowed, including zero */
  9377. if (iscntrl((unsigned char)*buf)) {
  9378. return -1;
  9379. }
  9380. /* Find end of HTTP header */
  9381. response_length = get_http_header_len(buf, len);
  9382. if (response_length <= 0) {
  9383. return response_length;
  9384. }
  9385. buf[response_length - 1] = '\0';
  9386. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9387. return -1;
  9388. }
  9389. /* The first word is the HTTP version */
  9390. /* Check for a valid HTTP version key */
  9391. if (strncmp(buf, "HTTP/", 5) != 0) {
  9392. /* Invalid request */
  9393. return -1;
  9394. }
  9395. buf += 5;
  9396. if (!isgraph((unsigned char)buf[0])) {
  9397. /* Invalid request */
  9398. return -1;
  9399. }
  9400. ri->http_version = buf;
  9401. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9402. return -1;
  9403. }
  9404. /* The second word is the status as a number */
  9405. tmp = buf;
  9406. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9407. return -1;
  9408. }
  9409. l = strtol(tmp, &tmp2, 10);
  9410. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9411. /* Everything else but a 3 digit code is invalid */
  9412. return -1;
  9413. }
  9414. ri->status_code = (int)l;
  9415. /* The rest of the line is the status text */
  9416. ri->status_text = buf;
  9417. /* Find end of status text */
  9418. /* isgraph or isspace = isprint */
  9419. while (isprint((unsigned char)*buf)) {
  9420. buf++;
  9421. }
  9422. if ((*buf != '\r') && (*buf != '\n')) {
  9423. return -1;
  9424. }
  9425. /* Terminate string and forward buf to next line */
  9426. do {
  9427. *buf = 0;
  9428. buf++;
  9429. } while (isspace((unsigned char)*buf));
  9430. /* Parse all HTTP headers */
  9431. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9432. if (ri->num_headers < 0) {
  9433. /* Error while parsing headers */
  9434. return -1;
  9435. }
  9436. return response_length + init_skip;
  9437. }
  9438. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9439. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9440. * buffer (which marks the end of HTTP request). Buffer buf may already
  9441. * have some data. The length of the data is stored in nread.
  9442. * Upon every read operation, increase nread by the number of bytes read. */
  9443. static int
  9444. read_message(FILE *fp,
  9445. struct mg_connection *conn,
  9446. char *buf,
  9447. int bufsiz,
  9448. int *nread)
  9449. {
  9450. int request_len, n = 0;
  9451. struct timespec last_action_time;
  9452. double request_timeout;
  9453. if (!conn) {
  9454. return 0;
  9455. }
  9456. memset(&last_action_time, 0, sizeof(last_action_time));
  9457. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9458. /* value of request_timeout is in seconds, config in milliseconds */
  9459. request_timeout =
  9460. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9461. } else {
  9462. request_timeout =
  9463. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9464. / 1000.0;
  9465. }
  9466. if (conn->handled_requests > 0) {
  9467. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9468. request_timeout =
  9469. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9470. / 1000.0;
  9471. }
  9472. }
  9473. request_len = get_http_header_len(buf, *nread);
  9474. while (request_len == 0) {
  9475. /* Full request not yet received */
  9476. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9477. /* Server is to be stopped. */
  9478. return -1;
  9479. }
  9480. if (*nread >= bufsiz) {
  9481. /* Request too long */
  9482. return -2;
  9483. }
  9484. n = pull_inner(
  9485. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9486. if (n == -2) {
  9487. /* Receive error */
  9488. return -1;
  9489. }
  9490. /* update clock after every read request */
  9491. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9492. if (n > 0) {
  9493. *nread += n;
  9494. request_len = get_http_header_len(buf, *nread);
  9495. }
  9496. if ((request_len == 0) && (request_timeout >= 0)) {
  9497. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9498. > request_timeout) {
  9499. /* Timeout */
  9500. return -1;
  9501. }
  9502. }
  9503. }
  9504. return request_len;
  9505. }
  9506. #if !defined(NO_CGI) || !defined(NO_FILES)
  9507. static int
  9508. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9509. {
  9510. const char *expect;
  9511. char buf[MG_BUF_LEN];
  9512. int success = 0;
  9513. if (!conn) {
  9514. return 0;
  9515. }
  9516. expect = mg_get_header(conn, "Expect");
  9517. DEBUG_ASSERT(fp != NULL);
  9518. if (!fp) {
  9519. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9520. return 0;
  9521. }
  9522. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9523. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9524. */
  9525. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9526. } else {
  9527. if (expect != NULL) {
  9528. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9529. conn->status_code = 100;
  9530. } else {
  9531. conn->status_code = 200;
  9532. }
  9533. DEBUG_ASSERT(conn->consumed_content == 0);
  9534. if (conn->consumed_content != 0) {
  9535. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9536. return 0;
  9537. }
  9538. for (;;) {
  9539. int nread = mg_read(conn, buf, sizeof(buf));
  9540. if (nread <= 0) {
  9541. success = (nread == 0);
  9542. break;
  9543. }
  9544. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9545. break;
  9546. }
  9547. }
  9548. /* Each error code path in this function must send an error */
  9549. if (!success) {
  9550. /* NOTE: Maybe some data has already been sent. */
  9551. /* TODO (low): If some data has been sent, a correct error
  9552. * reply can no longer be sent, so just close the connection */
  9553. mg_send_http_error(conn, 500, "%s", "");
  9554. }
  9555. }
  9556. return success;
  9557. }
  9558. #endif
  9559. #if defined(USE_TIMERS)
  9560. #define TIMER_API static
  9561. #include "timer.inl"
  9562. #endif /* USE_TIMERS */
  9563. #if !defined(NO_CGI)
  9564. /* This structure helps to create an environment for the spawned CGI
  9565. * program.
  9566. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9567. * last element must be NULL.
  9568. * However, on Windows there is a requirement that all these
  9569. * VARIABLE=VALUE\0
  9570. * strings must reside in a contiguous buffer. The end of the buffer is
  9571. * marked by two '\0' characters.
  9572. * We satisfy both worlds: we create an envp array (which is vars), all
  9573. * entries are actually pointers inside buf. */
  9574. struct cgi_environment {
  9575. struct mg_connection *conn;
  9576. /* Data block */
  9577. char *buf; /* Environment buffer */
  9578. size_t buflen; /* Space available in buf */
  9579. size_t bufused; /* Space taken in buf */
  9580. /* Index block */
  9581. char **var; /* char **envp */
  9582. size_t varlen; /* Number of variables available in var */
  9583. size_t varused; /* Number of variables stored in var */
  9584. };
  9585. static void addenv(struct cgi_environment *env,
  9586. PRINTF_FORMAT_STRING(const char *fmt),
  9587. ...) PRINTF_ARGS(2, 3);
  9588. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9589. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9590. static void
  9591. addenv(struct cgi_environment *env, const char *fmt, ...)
  9592. {
  9593. size_t i, n, space;
  9594. int truncated = 0;
  9595. char *added;
  9596. va_list ap;
  9597. if ((env->varlen - env->varused) < 2) {
  9598. mg_cry_internal(env->conn,
  9599. "%s: Cannot register CGI variable [%s]",
  9600. __func__,
  9601. fmt);
  9602. return;
  9603. }
  9604. /* Calculate how much space is left in the buffer */
  9605. space = (env->buflen - env->bufused);
  9606. do {
  9607. /* Space for "\0\0" is always needed. */
  9608. if (space <= 2) {
  9609. /* Allocate new buffer */
  9610. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9611. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9612. if (!added) {
  9613. /* Out of memory */
  9614. mg_cry_internal(
  9615. env->conn,
  9616. "%s: Cannot allocate memory for CGI variable [%s]",
  9617. __func__,
  9618. fmt);
  9619. return;
  9620. }
  9621. /* Retarget pointers */
  9622. env->buf = added;
  9623. env->buflen = n;
  9624. for (i = 0, n = 0; i < env->varused; i++) {
  9625. env->var[i] = added + n;
  9626. n += strlen(added + n) + 1;
  9627. }
  9628. space = (env->buflen - env->bufused);
  9629. }
  9630. /* Make a pointer to the free space int the buffer */
  9631. added = env->buf + env->bufused;
  9632. /* Copy VARIABLE=VALUE\0 string into the free space */
  9633. va_start(ap, fmt);
  9634. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9635. va_end(ap);
  9636. /* Do not add truncated strings to the environment */
  9637. if (truncated) {
  9638. /* Reallocate the buffer */
  9639. space = 0;
  9640. }
  9641. } while (truncated);
  9642. /* Calculate number of bytes added to the environment */
  9643. n = strlen(added) + 1;
  9644. env->bufused += n;
  9645. /* Append a pointer to the added string into the envp array */
  9646. env->var[env->varused] = added;
  9647. env->varused++;
  9648. }
  9649. /* Return 0 on success, non-zero if an error occurs. */
  9650. static int
  9651. prepare_cgi_environment(struct mg_connection *conn,
  9652. const char *prog,
  9653. struct cgi_environment *env,
  9654. unsigned char cgi_config_idx)
  9655. {
  9656. const char *s;
  9657. struct vec var_vec;
  9658. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9659. int i, truncated, uri_len;
  9660. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9661. return -1;
  9662. }
  9663. env->conn = conn;
  9664. env->buflen = CGI_ENVIRONMENT_SIZE;
  9665. env->bufused = 0;
  9666. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9667. if (env->buf == NULL) {
  9668. mg_cry_internal(conn,
  9669. "%s: Not enough memory for environmental buffer",
  9670. __func__);
  9671. return -1;
  9672. }
  9673. env->varlen = MAX_CGI_ENVIR_VARS;
  9674. env->varused = 0;
  9675. env->var =
  9676. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9677. if (env->var == NULL) {
  9678. mg_cry_internal(conn,
  9679. "%s: Not enough memory for environmental variables",
  9680. __func__);
  9681. mg_free(env->buf);
  9682. return -1;
  9683. }
  9684. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9685. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9686. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9687. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9688. /* Prepare the environment block */
  9689. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9690. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9691. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9692. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9693. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9694. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9695. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9696. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9697. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9698. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9699. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9700. /* SCRIPT_NAME */
  9701. uri_len = (int)strlen(conn->request_info.local_uri);
  9702. if (conn->path_info == NULL) {
  9703. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9704. /* URI: /path_to_script/script.cgi */
  9705. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9706. } else {
  9707. /* URI: /path_to_script/ ... using index.cgi */
  9708. const char *index_file = strrchr(prog, '/');
  9709. if (index_file) {
  9710. addenv(env,
  9711. "SCRIPT_NAME=%s%s",
  9712. conn->request_info.local_uri,
  9713. index_file + 1);
  9714. }
  9715. }
  9716. } else {
  9717. /* URI: /path_to_script/script.cgi/path_info */
  9718. addenv(env,
  9719. "SCRIPT_NAME=%.*s",
  9720. uri_len - (int)strlen(conn->path_info),
  9721. conn->request_info.local_uri);
  9722. }
  9723. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9724. if (conn->path_info == NULL) {
  9725. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9726. } else {
  9727. addenv(env,
  9728. "PATH_TRANSLATED=%s%s",
  9729. conn->dom_ctx->config[DOCUMENT_ROOT],
  9730. conn->path_info);
  9731. }
  9732. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9733. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9734. addenv(env, "CONTENT_TYPE=%s", s);
  9735. }
  9736. if (conn->request_info.query_string != NULL) {
  9737. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9738. }
  9739. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9740. addenv(env, "CONTENT_LENGTH=%s", s);
  9741. }
  9742. if ((s = getenv("PATH")) != NULL) {
  9743. addenv(env, "PATH=%s", s);
  9744. }
  9745. if (conn->path_info != NULL) {
  9746. addenv(env, "PATH_INFO=%s", conn->path_info);
  9747. }
  9748. if (conn->status_code > 0) {
  9749. /* CGI error handler should show the status code */
  9750. addenv(env, "STATUS=%d", conn->status_code);
  9751. }
  9752. #if defined(_WIN32)
  9753. if ((s = getenv("COMSPEC")) != NULL) {
  9754. addenv(env, "COMSPEC=%s", s);
  9755. }
  9756. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9757. addenv(env, "SYSTEMROOT=%s", s);
  9758. }
  9759. if ((s = getenv("SystemDrive")) != NULL) {
  9760. addenv(env, "SystemDrive=%s", s);
  9761. }
  9762. if ((s = getenv("ProgramFiles")) != NULL) {
  9763. addenv(env, "ProgramFiles=%s", s);
  9764. }
  9765. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9766. addenv(env, "ProgramFiles(x86)=%s", s);
  9767. }
  9768. #else
  9769. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9770. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9771. }
  9772. #endif /* _WIN32 */
  9773. if ((s = getenv("PERLLIB")) != NULL) {
  9774. addenv(env, "PERLLIB=%s", s);
  9775. }
  9776. if (conn->request_info.remote_user != NULL) {
  9777. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9778. addenv(env, "%s", "AUTH_TYPE=Digest");
  9779. }
  9780. /* Add all headers as HTTP_* variables */
  9781. for (i = 0; i < conn->request_info.num_headers; i++) {
  9782. (void)mg_snprintf(conn,
  9783. &truncated,
  9784. http_var_name,
  9785. sizeof(http_var_name),
  9786. "HTTP_%s",
  9787. conn->request_info.http_headers[i].name);
  9788. if (truncated) {
  9789. mg_cry_internal(conn,
  9790. "%s: HTTP header variable too long [%s]",
  9791. __func__,
  9792. conn->request_info.http_headers[i].name);
  9793. continue;
  9794. }
  9795. /* Convert variable name into uppercase, and change - to _ */
  9796. for (p = http_var_name; *p != '\0'; p++) {
  9797. if (*p == '-') {
  9798. *p = '_';
  9799. }
  9800. *p = (char)toupper((unsigned char)*p);
  9801. }
  9802. addenv(env,
  9803. "%s=%s",
  9804. http_var_name,
  9805. conn->request_info.http_headers[i].value);
  9806. }
  9807. /* Add user-specified variables */
  9808. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9809. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9810. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9811. }
  9812. env->var[env->varused] = NULL;
  9813. env->buf[env->bufused] = '\0';
  9814. return 0;
  9815. }
  9816. /* Data for CGI process control: PID and number of references */
  9817. struct process_control_data {
  9818. pid_t pid;
  9819. ptrdiff_t references;
  9820. };
  9821. static int
  9822. abort_cgi_process(void *data)
  9823. {
  9824. /* Waitpid checks for child status and won't work for a pid that does
  9825. * not identify a child of the current process. Thus, if the pid is
  9826. * reused, we will not affect a different process. */
  9827. struct process_control_data *proc = (struct process_control_data *)data;
  9828. int status = 0;
  9829. ptrdiff_t refs;
  9830. pid_t ret_pid;
  9831. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9832. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9833. /* Stop child process */
  9834. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9835. kill(proc->pid, SIGABRT);
  9836. /* Wait until process is terminated (don't leave zombies) */
  9837. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9838. ;
  9839. } else {
  9840. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9841. }
  9842. /* Dec reference counter */
  9843. refs = mg_atomic_dec(&proc->references);
  9844. if (refs == 0) {
  9845. /* no more references - free data */
  9846. mg_free(data);
  9847. }
  9848. return 0;
  9849. }
  9850. /* Local (static) function assumes all arguments are valid. */
  9851. static void
  9852. handle_cgi_request(struct mg_connection *conn,
  9853. const char *prog,
  9854. unsigned char cgi_config_idx)
  9855. {
  9856. char *buf;
  9857. size_t buflen;
  9858. int headers_len, data_len, i, truncated;
  9859. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9860. const char *status, *status_text;
  9861. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9862. struct mg_request_info ri;
  9863. struct cgi_environment blk;
  9864. FILE *in = NULL, *out = NULL, *err = NULL;
  9865. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9866. pid_t pid = (pid_t)-1;
  9867. struct process_control_data *proc = NULL;
  9868. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  9869. int no_buffering = 0;
  9870. #if defined(USE_TIMERS)
  9871. double cgi_timeout;
  9872. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9873. /* Get timeout in seconds */
  9874. cgi_timeout =
  9875. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9876. } else {
  9877. cgi_timeout =
  9878. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9879. }
  9880. #endif
  9881. if (cfg_buffering != NULL) {
  9882. if (!mg_strcasecmp(cfg_buffering, "no")) {
  9883. no_buffering = 1;
  9884. }
  9885. }
  9886. buf = NULL;
  9887. buflen = conn->phys_ctx->max_request_size;
  9888. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9889. if (i != 0) {
  9890. blk.buf = NULL;
  9891. blk.var = NULL;
  9892. goto done;
  9893. }
  9894. /* CGI must be executed in its own directory. 'dir' must point to the
  9895. * directory containing executable program, 'p' must point to the
  9896. * executable program name relative to 'dir'. */
  9897. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9898. if (truncated) {
  9899. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9900. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9901. goto done;
  9902. }
  9903. if ((p = strrchr(dir, '/')) != NULL) {
  9904. *p++ = '\0';
  9905. } else {
  9906. dir[0] = '.';
  9907. dir[1] = '\0';
  9908. p = (char *)prog;
  9909. }
  9910. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9911. status = strerror(ERRNO);
  9912. mg_cry_internal(
  9913. conn,
  9914. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9915. prog,
  9916. status);
  9917. mg_send_http_error(conn,
  9918. 500,
  9919. "Error: Cannot create CGI pipe: %s",
  9920. status);
  9921. goto done;
  9922. }
  9923. proc = (struct process_control_data *)
  9924. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9925. if (proc == NULL) {
  9926. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9927. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9928. goto done;
  9929. }
  9930. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9931. pid = spawn_process(
  9932. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9933. if (pid == (pid_t)-1) {
  9934. status = strerror(ERRNO);
  9935. mg_cry_internal(
  9936. conn,
  9937. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9938. prog,
  9939. status);
  9940. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9941. mg_free(proc);
  9942. proc = NULL;
  9943. goto done;
  9944. }
  9945. /* Store data in shared process_control_data */
  9946. proc->pid = pid;
  9947. proc->references = 1;
  9948. #if defined(USE_TIMERS)
  9949. if (cgi_timeout > 0.0) {
  9950. proc->references = 2;
  9951. // Start a timer for CGI
  9952. timer_add(conn->phys_ctx,
  9953. cgi_timeout /* in seconds */,
  9954. 0.0,
  9955. 1,
  9956. abort_cgi_process,
  9957. (void *)proc,
  9958. NULL);
  9959. }
  9960. #endif
  9961. /* Parent closes only one side of the pipes.
  9962. * If we don't mark them as closed, close() attempt before
  9963. * return from this function throws an exception on Windows.
  9964. * Windows does not like when closed descriptor is closed again. */
  9965. (void)close(fdin[0]);
  9966. (void)close(fdout[1]);
  9967. (void)close(fderr[1]);
  9968. fdin[0] = fdout[1] = fderr[1] = -1;
  9969. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9970. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9971. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9972. status = strerror(ERRNO);
  9973. mg_cry_internal(conn,
  9974. "Error: CGI program \"%s\": Can not open fd: %s",
  9975. prog,
  9976. status);
  9977. mg_send_http_error(conn,
  9978. 500,
  9979. "Error: CGI can not open fd\nfdopen: %s",
  9980. status);
  9981. goto done;
  9982. }
  9983. setbuf(in, NULL);
  9984. setbuf(out, NULL);
  9985. setbuf(err, NULL);
  9986. fout.access.fp = out;
  9987. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9988. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9989. conn->content_len);
  9990. /* This is a POST/PUT request, or another request with body data. */
  9991. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9992. /* Error sending the body data */
  9993. mg_cry_internal(
  9994. conn,
  9995. "Error: CGI program \"%s\": Forward body data failed",
  9996. prog);
  9997. goto done;
  9998. }
  9999. }
  10000. /* Close so child gets an EOF. */
  10001. fclose(in);
  10002. in = NULL;
  10003. fdin[1] = -1;
  10004. /* Now read CGI reply into a buffer. We need to set correct
  10005. * status code, thus we need to see all HTTP headers first.
  10006. * Do not send anything back to client, until we buffer in all
  10007. * HTTP headers. */
  10008. data_len = 0;
  10009. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10010. if (buf == NULL) {
  10011. mg_send_http_error(conn,
  10012. 500,
  10013. "Error: Not enough memory for CGI buffer (%u bytes)",
  10014. (unsigned int)buflen);
  10015. mg_cry_internal(
  10016. conn,
  10017. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10018. "bytes)",
  10019. prog,
  10020. (unsigned int)buflen);
  10021. goto done;
  10022. }
  10023. DEBUG_TRACE("CGI: %s", "wait for response");
  10024. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10025. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10026. if (headers_len <= 0) {
  10027. /* Could not parse the CGI response. Check if some error message on
  10028. * stderr. */
  10029. i = pull_all(err, conn, buf, (int)buflen);
  10030. if (i > 0) {
  10031. /* CGI program explicitly sent an error */
  10032. /* Write the error message to the internal log */
  10033. mg_cry_internal(conn,
  10034. "Error: CGI program \"%s\" sent error "
  10035. "message: [%.*s]",
  10036. prog,
  10037. i,
  10038. buf);
  10039. /* Don't send the error message back to the client */
  10040. mg_send_http_error(conn,
  10041. 500,
  10042. "Error: CGI program \"%s\" failed.",
  10043. prog);
  10044. } else {
  10045. /* CGI program did not explicitly send an error, but a broken
  10046. * respon header */
  10047. mg_cry_internal(conn,
  10048. "Error: CGI program sent malformed or too big "
  10049. "(>%u bytes) HTTP headers: [%.*s]",
  10050. (unsigned)buflen,
  10051. data_len,
  10052. buf);
  10053. mg_send_http_error(conn,
  10054. 500,
  10055. "Error: CGI program sent malformed or too big "
  10056. "(>%u bytes) HTTP headers: [%.*s]",
  10057. (unsigned)buflen,
  10058. data_len,
  10059. buf);
  10060. }
  10061. /* in both cases, abort processing CGI */
  10062. goto done;
  10063. }
  10064. pbuf = buf;
  10065. buf[headers_len - 1] = '\0';
  10066. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10067. /* Make up and send the status line */
  10068. status_text = "OK";
  10069. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10070. != NULL) {
  10071. conn->status_code = atoi(status);
  10072. status_text = status;
  10073. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10074. status_text++;
  10075. }
  10076. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10077. != NULL) {
  10078. conn->status_code = 307;
  10079. } else {
  10080. conn->status_code = 200;
  10081. }
  10082. if (!should_keep_alive(conn)) {
  10083. conn->must_close = 1;
  10084. }
  10085. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10086. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10087. /* Send headers */
  10088. for (i = 0; i < ri.num_headers; i++) {
  10089. DEBUG_TRACE("CGI header: %s: %s",
  10090. ri.http_headers[i].name,
  10091. ri.http_headers[i].value);
  10092. mg_printf(conn,
  10093. "%s: %s\r\n",
  10094. ri.http_headers[i].name,
  10095. ri.http_headers[i].value);
  10096. }
  10097. mg_write(conn, "\r\n", 2);
  10098. /* Send chunk of data that may have been read after the headers */
  10099. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10100. /* Read the rest of CGI output and send to the client */
  10101. DEBUG_TRACE("CGI: %s", "forward all data");
  10102. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10103. DEBUG_TRACE("CGI: %s", "all data sent");
  10104. done:
  10105. mg_free(blk.var);
  10106. mg_free(blk.buf);
  10107. if (pid != (pid_t)-1) {
  10108. abort_cgi_process((void *)proc);
  10109. }
  10110. if (fdin[0] != -1) {
  10111. close(fdin[0]);
  10112. }
  10113. if (fdout[1] != -1) {
  10114. close(fdout[1]);
  10115. }
  10116. if (fderr[1] != -1) {
  10117. close(fderr[1]);
  10118. }
  10119. if (in != NULL) {
  10120. fclose(in);
  10121. } else if (fdin[1] != -1) {
  10122. close(fdin[1]);
  10123. }
  10124. if (out != NULL) {
  10125. fclose(out);
  10126. } else if (fdout[0] != -1) {
  10127. close(fdout[0]);
  10128. }
  10129. if (err != NULL) {
  10130. fclose(err);
  10131. } else if (fderr[0] != -1) {
  10132. close(fderr[0]);
  10133. }
  10134. mg_free(buf);
  10135. }
  10136. #endif /* !NO_CGI */
  10137. #if !defined(NO_FILES)
  10138. static void
  10139. dav_mkcol(struct mg_connection *conn, const char *path)
  10140. {
  10141. int rc, body_len;
  10142. struct de de;
  10143. if (conn == NULL) {
  10144. return;
  10145. }
  10146. /* TODO (mid): Check the mg_send_http_error situations in this function
  10147. */
  10148. memset(&de.file, 0, sizeof(de.file));
  10149. if (!mg_stat(conn, path, &de.file)) {
  10150. mg_cry_internal(conn,
  10151. "%s: mg_stat(%s) failed: %s",
  10152. __func__,
  10153. path,
  10154. strerror(ERRNO));
  10155. }
  10156. if (de.file.last_modified) {
  10157. /* TODO (mid): This check does not seem to make any sense ! */
  10158. /* TODO (mid): Add a webdav unit test first, before changing
  10159. * anything here. */
  10160. mg_send_http_error(
  10161. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10162. return;
  10163. }
  10164. body_len = conn->data_len - conn->request_len;
  10165. if (body_len > 0) {
  10166. mg_send_http_error(
  10167. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10168. return;
  10169. }
  10170. rc = mg_mkdir(conn, path, 0755);
  10171. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10172. if (rc == 0) {
  10173. /* Create 201 "Created" response */
  10174. mg_response_header_start(conn, 201);
  10175. send_static_cache_header(conn);
  10176. send_additional_header(conn);
  10177. mg_response_header_add(conn, "Content-Length", "0", -1);
  10178. /* Send all headers - there is no body */
  10179. mg_response_header_send(conn);
  10180. } else {
  10181. int http_status = 500;
  10182. switch (errno) {
  10183. case EEXIST:
  10184. http_status = 405;
  10185. break;
  10186. case EACCES:
  10187. http_status = 403;
  10188. break;
  10189. case ENOENT:
  10190. http_status = 409;
  10191. break;
  10192. }
  10193. mg_send_http_error(conn,
  10194. http_status,
  10195. "Error processing %s: %s",
  10196. path,
  10197. strerror(ERRNO));
  10198. }
  10199. }
  10200. /* Forward decrlaration */
  10201. static int get_uri_type(const char *uri);
  10202. static const char *
  10203. get_rel_url_at_current_server(const char *uri,
  10204. const struct mg_connection *conn);
  10205. static void
  10206. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10207. {
  10208. const char *overwrite_hdr;
  10209. const char *destination_hdr;
  10210. const char *root;
  10211. int rc, dest_uri_type;
  10212. int http_status = 400;
  10213. int do_overwrite = 0;
  10214. int destination_ok = 0;
  10215. char dest_path[UTF8_PATH_MAX];
  10216. struct mg_file_stat ignored;
  10217. if (conn == NULL) {
  10218. return;
  10219. }
  10220. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10221. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10222. destination_hdr = mg_get_header(conn, "Destination");
  10223. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10224. do_overwrite = 1;
  10225. }
  10226. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10227. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10228. return;
  10229. }
  10230. if (root != NULL) {
  10231. char *local_dest = NULL;
  10232. dest_uri_type = get_uri_type(destination_hdr);
  10233. if (dest_uri_type == 2) {
  10234. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10235. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10236. const char *h =
  10237. get_rel_url_at_current_server(destination_hdr, conn);
  10238. if (h) {
  10239. int len = (int)strlen(h);
  10240. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10241. mg_url_decode(h, len, local_dest, len + 1, 0);
  10242. }
  10243. }
  10244. if (local_dest != NULL) {
  10245. remove_dot_segments(local_dest);
  10246. if (local_dest[0] == '/') {
  10247. int trunc_check = 0;
  10248. mg_snprintf(conn,
  10249. &trunc_check,
  10250. dest_path,
  10251. sizeof(dest_path),
  10252. "%s/%s",
  10253. root,
  10254. local_dest);
  10255. if (trunc_check == 0) {
  10256. destination_ok = 1;
  10257. }
  10258. }
  10259. mg_free(local_dest);
  10260. }
  10261. }
  10262. if (!destination_ok) {
  10263. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10264. return;
  10265. }
  10266. /* Check now if this file exists */
  10267. if (mg_stat(conn, dest_path, &ignored)) {
  10268. /* File exists */
  10269. if (do_overwrite) {
  10270. /* Overwrite allowed: delete the file first */
  10271. if (0 != remove(dest_path)) {
  10272. /* No overwrite: return error */
  10273. mg_send_http_error(conn,
  10274. 403,
  10275. "Cannot overwrite file: %s",
  10276. dest_path);
  10277. return;
  10278. }
  10279. } else {
  10280. /* No overwrite: return error */
  10281. mg_send_http_error(conn,
  10282. 412,
  10283. "Destination already exists: %s",
  10284. dest_path);
  10285. return;
  10286. }
  10287. }
  10288. /* Copy / Move / Rename operation. */
  10289. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10290. #if defined(_WIN32)
  10291. {
  10292. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10293. wchar_t wSource[UTF16_PATH_MAX];
  10294. wchar_t wDest[UTF16_PATH_MAX];
  10295. BOOL ok;
  10296. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10297. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10298. if (do_copy) {
  10299. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10300. } else {
  10301. ok = MoveFileExW(wSource,
  10302. wDest,
  10303. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10304. }
  10305. if (ok) {
  10306. rc = 0;
  10307. } else {
  10308. DWORD lastErr = GetLastError();
  10309. if (lastErr == ERROR_ALREADY_EXISTS) {
  10310. mg_send_http_error(conn,
  10311. 412,
  10312. "Destination already exists: %s",
  10313. dest_path);
  10314. return;
  10315. }
  10316. rc = -1;
  10317. http_status = 400;
  10318. }
  10319. }
  10320. #else
  10321. {
  10322. /* Linux uses already UTF-8, we don't need to convert file names. */
  10323. if (do_copy) {
  10324. /* TODO: COPY for Linux. */
  10325. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10326. return;
  10327. }
  10328. rc = rename(path, dest_path);
  10329. if (rc) {
  10330. switch (errno) {
  10331. case EEXIST:
  10332. http_status = 412;
  10333. break;
  10334. case EACCES:
  10335. http_status = 403;
  10336. break;
  10337. case ENOENT:
  10338. http_status = 409;
  10339. break;
  10340. }
  10341. }
  10342. }
  10343. #endif
  10344. if (rc == 0) {
  10345. /* Create 204 "No Content" response */
  10346. mg_response_header_start(conn, 204);
  10347. mg_response_header_add(conn, "Content-Length", "0", -1);
  10348. /* Send all headers - there is no body */
  10349. mg_response_header_send(conn);
  10350. } else {
  10351. mg_send_http_error(conn, http_status, "Operation failed");
  10352. }
  10353. }
  10354. static void
  10355. put_file(struct mg_connection *conn, const char *path)
  10356. {
  10357. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10358. const char *range;
  10359. int64_t r1, r2;
  10360. int rc;
  10361. if (conn == NULL) {
  10362. return;
  10363. }
  10364. DEBUG_TRACE("store %s", path);
  10365. if (mg_stat(conn, path, &file.stat)) {
  10366. /* File already exists */
  10367. conn->status_code = 200;
  10368. if (file.stat.is_directory) {
  10369. /* This is an already existing directory,
  10370. * so there is nothing to do for the server. */
  10371. rc = 0;
  10372. } else {
  10373. /* File exists and is not a directory. */
  10374. /* Can it be replaced? */
  10375. /* Check if the server may write this file */
  10376. if (access(path, W_OK) == 0) {
  10377. /* Access granted */
  10378. rc = 1;
  10379. } else {
  10380. mg_send_http_error(
  10381. conn,
  10382. 403,
  10383. "Error: Put not possible\nReplacing %s is not allowed",
  10384. path);
  10385. return;
  10386. }
  10387. }
  10388. } else {
  10389. /* File should be created */
  10390. conn->status_code = 201;
  10391. rc = put_dir(conn, path);
  10392. }
  10393. if (rc == 0) {
  10394. /* put_dir returns 0 if path is a directory */
  10395. /* Create response */
  10396. mg_response_header_start(conn, conn->status_code);
  10397. send_no_cache_header(conn);
  10398. send_additional_header(conn);
  10399. mg_response_header_add(conn, "Content-Length", "0", -1);
  10400. /* Send all headers - there is no body */
  10401. mg_response_header_send(conn);
  10402. /* Request to create a directory has been fulfilled successfully.
  10403. * No need to put a file. */
  10404. return;
  10405. }
  10406. if (rc == -1) {
  10407. /* put_dir returns -1 if the path is too long */
  10408. mg_send_http_error(conn,
  10409. 414,
  10410. "Error: Path too long\nput_dir(%s): %s",
  10411. path,
  10412. strerror(ERRNO));
  10413. return;
  10414. }
  10415. if (rc == -2) {
  10416. /* put_dir returns -2 if the directory can not be created */
  10417. mg_send_http_error(conn,
  10418. 500,
  10419. "Error: Can not create directory\nput_dir(%s): %s",
  10420. path,
  10421. strerror(ERRNO));
  10422. return;
  10423. }
  10424. /* A file should be created or overwritten. */
  10425. /* Currently CivetWeb does not nead read+write access. */
  10426. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10427. || file.access.fp == NULL) {
  10428. (void)mg_fclose(&file.access);
  10429. mg_send_http_error(conn,
  10430. 500,
  10431. "Error: Can not create file\nfopen(%s): %s",
  10432. path,
  10433. strerror(ERRNO));
  10434. return;
  10435. }
  10436. fclose_on_exec(&file.access, conn);
  10437. range = mg_get_header(conn, "Content-Range");
  10438. r1 = r2 = 0;
  10439. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10440. conn->status_code = 206; /* Partial content */
  10441. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10442. mg_send_http_error(conn,
  10443. 500,
  10444. "Error: Internal error processing file %s",
  10445. path);
  10446. return;
  10447. }
  10448. }
  10449. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10450. /* forward_body_data failed.
  10451. * The error code has already been sent to the client,
  10452. * and conn->status_code is already set. */
  10453. (void)mg_fclose(&file.access);
  10454. return;
  10455. }
  10456. if (mg_fclose(&file.access) != 0) {
  10457. /* fclose failed. This might have different reasons, but a likely
  10458. * one is "no space on disk", http 507. */
  10459. conn->status_code = 507;
  10460. }
  10461. /* Create response (status_code has been set before) */
  10462. mg_response_header_start(conn, conn->status_code);
  10463. send_no_cache_header(conn);
  10464. send_additional_header(conn);
  10465. mg_response_header_add(conn, "Content-Length", "0", -1);
  10466. /* Send all headers - there is no body */
  10467. mg_response_header_send(conn);
  10468. }
  10469. static void
  10470. delete_file(struct mg_connection *conn, const char *path)
  10471. {
  10472. struct de de;
  10473. memset(&de.file, 0, sizeof(de.file));
  10474. if (!mg_stat(conn, path, &de.file)) {
  10475. /* mg_stat returns 0 if the file does not exist */
  10476. mg_send_http_error(conn,
  10477. 404,
  10478. "Error: Cannot delete file\nFile %s not found",
  10479. path);
  10480. return;
  10481. }
  10482. DEBUG_TRACE("delete %s", path);
  10483. if (de.file.is_directory) {
  10484. if (remove_directory(conn, path)) {
  10485. /* Delete is successful: Return 204 without content. */
  10486. mg_send_http_error(conn, 204, "%s", "");
  10487. } else {
  10488. /* Delete is not successful: Return 500 (Server error). */
  10489. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10490. }
  10491. return;
  10492. }
  10493. /* This is an existing file (not a directory).
  10494. * Check if write permission is granted. */
  10495. if (access(path, W_OK) != 0) {
  10496. /* File is read only */
  10497. mg_send_http_error(
  10498. conn,
  10499. 403,
  10500. "Error: Delete not possible\nDeleting %s is not allowed",
  10501. path);
  10502. return;
  10503. }
  10504. /* Try to delete it. */
  10505. if (mg_remove(conn, path) == 0) {
  10506. /* Delete was successful: Return 204 without content. */
  10507. mg_response_header_start(conn, 204);
  10508. send_no_cache_header(conn);
  10509. send_additional_header(conn);
  10510. mg_response_header_add(conn, "Content-Length", "0", -1);
  10511. mg_response_header_send(conn);
  10512. } else {
  10513. /* Delete not successful (file locked). */
  10514. mg_send_http_error(conn,
  10515. 423,
  10516. "Error: Cannot delete file\nremove(%s): %s",
  10517. path,
  10518. strerror(ERRNO));
  10519. }
  10520. }
  10521. #endif /* !NO_FILES */
  10522. #if !defined(NO_FILESYSTEMS)
  10523. static void
  10524. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10525. static void
  10526. do_ssi_include(struct mg_connection *conn,
  10527. const char *ssi,
  10528. char *tag,
  10529. int include_level)
  10530. {
  10531. char file_name[MG_BUF_LEN], path[512], *p;
  10532. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10533. size_t len;
  10534. int truncated = 0;
  10535. if (conn == NULL) {
  10536. return;
  10537. }
  10538. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10539. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10540. * always < MG_BUF_LEN. */
  10541. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10542. /* File name is relative to the webserver root */
  10543. file_name[511] = 0;
  10544. (void)mg_snprintf(conn,
  10545. &truncated,
  10546. path,
  10547. sizeof(path),
  10548. "%s/%s",
  10549. conn->dom_ctx->config[DOCUMENT_ROOT],
  10550. file_name);
  10551. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10552. /* File name is relative to the webserver working directory
  10553. * or it is absolute system path */
  10554. file_name[511] = 0;
  10555. (void)
  10556. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10557. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10558. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10559. /* File name is relative to the currect document */
  10560. file_name[511] = 0;
  10561. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10562. if (!truncated) {
  10563. if ((p = strrchr(path, '/')) != NULL) {
  10564. p[1] = '\0';
  10565. }
  10566. len = strlen(path);
  10567. (void)mg_snprintf(conn,
  10568. &truncated,
  10569. path + len,
  10570. sizeof(path) - len,
  10571. "%s",
  10572. file_name);
  10573. }
  10574. } else {
  10575. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10576. return;
  10577. }
  10578. if (truncated) {
  10579. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10580. return;
  10581. }
  10582. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10583. mg_cry_internal(conn,
  10584. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10585. tag,
  10586. path,
  10587. strerror(ERRNO));
  10588. } else {
  10589. fclose_on_exec(&file.access, conn);
  10590. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10591. > 0) {
  10592. send_ssi_file(conn, path, &file, include_level + 1);
  10593. } else {
  10594. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10595. }
  10596. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10597. }
  10598. }
  10599. #if !defined(NO_POPEN)
  10600. static void
  10601. do_ssi_exec(struct mg_connection *conn, char *tag)
  10602. {
  10603. char cmd[1024] = "";
  10604. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10605. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10606. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10607. } else {
  10608. cmd[1023] = 0;
  10609. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10610. mg_cry_internal(conn,
  10611. "Cannot SSI #exec: [%s]: %s",
  10612. cmd,
  10613. strerror(ERRNO));
  10614. } else {
  10615. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10616. pclose(file.access.fp);
  10617. }
  10618. }
  10619. }
  10620. #endif /* !NO_POPEN */
  10621. static int
  10622. mg_fgetc(struct mg_file *filep)
  10623. {
  10624. if (filep == NULL) {
  10625. return EOF;
  10626. }
  10627. if (filep->access.fp != NULL) {
  10628. return fgetc(filep->access.fp);
  10629. } else {
  10630. return EOF;
  10631. }
  10632. }
  10633. static void
  10634. send_ssi_file(struct mg_connection *conn,
  10635. const char *path,
  10636. struct mg_file *filep,
  10637. int include_level)
  10638. {
  10639. char buf[MG_BUF_LEN];
  10640. int ch, len, in_tag, in_ssi_tag;
  10641. if (include_level > 10) {
  10642. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10643. return;
  10644. }
  10645. in_tag = in_ssi_tag = len = 0;
  10646. /* Read file, byte by byte, and look for SSI include tags */
  10647. while ((ch = mg_fgetc(filep)) != EOF) {
  10648. if (in_tag) {
  10649. /* We are in a tag, either SSI tag or html tag */
  10650. if (ch == '>') {
  10651. /* Tag is closing */
  10652. buf[len++] = '>';
  10653. if (in_ssi_tag) {
  10654. /* Handle SSI tag */
  10655. buf[len] = 0;
  10656. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10657. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10658. #if !defined(NO_POPEN)
  10659. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10660. do_ssi_exec(conn, buf + 9);
  10661. #endif /* !NO_POPEN */
  10662. } else {
  10663. mg_cry_internal(conn,
  10664. "%s: unknown SSI "
  10665. "command: \"%s\"",
  10666. path,
  10667. buf);
  10668. }
  10669. len = 0;
  10670. in_ssi_tag = in_tag = 0;
  10671. } else {
  10672. /* Not an SSI tag */
  10673. /* Flush buffer */
  10674. (void)mg_write(conn, buf, (size_t)len);
  10675. len = 0;
  10676. in_tag = 0;
  10677. }
  10678. } else {
  10679. /* Tag is still open */
  10680. buf[len++] = (char)(ch & 0xff);
  10681. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10682. /* All SSI tags start with <!--# */
  10683. in_ssi_tag = 1;
  10684. }
  10685. if ((len + 2) > (int)sizeof(buf)) {
  10686. /* Tag to long for buffer */
  10687. mg_cry_internal(conn, "%s: tag is too large", path);
  10688. return;
  10689. }
  10690. }
  10691. } else {
  10692. /* We are not in a tag yet. */
  10693. if (ch == '<') {
  10694. /* Tag is opening */
  10695. in_tag = 1;
  10696. if (len > 0) {
  10697. /* Flush current buffer.
  10698. * Buffer is filled with "len" bytes. */
  10699. (void)mg_write(conn, buf, (size_t)len);
  10700. }
  10701. /* Store the < */
  10702. len = 1;
  10703. buf[0] = '<';
  10704. } else {
  10705. /* No Tag */
  10706. /* Add data to buffer */
  10707. buf[len++] = (char)(ch & 0xff);
  10708. /* Flush if buffer is full */
  10709. if (len == (int)sizeof(buf)) {
  10710. mg_write(conn, buf, (size_t)len);
  10711. len = 0;
  10712. }
  10713. }
  10714. }
  10715. }
  10716. /* Send the rest of buffered data */
  10717. if (len > 0) {
  10718. mg_write(conn, buf, (size_t)len);
  10719. }
  10720. }
  10721. static void
  10722. handle_ssi_file_request(struct mg_connection *conn,
  10723. const char *path,
  10724. struct mg_file *filep)
  10725. {
  10726. char date[64];
  10727. time_t curtime = time(NULL);
  10728. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10729. return;
  10730. }
  10731. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10732. /* File exists (precondition for calling this function),
  10733. * but can not be opened by the server. */
  10734. mg_send_http_error(conn,
  10735. 500,
  10736. "Error: Cannot read file\nfopen(%s): %s",
  10737. path,
  10738. strerror(ERRNO));
  10739. } else {
  10740. /* Set "must_close" for HTTP/1.x, since we do not know the
  10741. * content length */
  10742. conn->must_close = 1;
  10743. gmt_time_string(date, sizeof(date), &curtime);
  10744. fclose_on_exec(&filep->access, conn);
  10745. /* 200 OK response */
  10746. mg_response_header_start(conn, 200);
  10747. send_no_cache_header(conn);
  10748. send_additional_header(conn);
  10749. send_cors_header(conn);
  10750. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10751. mg_response_header_send(conn);
  10752. /* Header sent, now send body */
  10753. send_ssi_file(conn, path, filep, 0);
  10754. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10755. }
  10756. }
  10757. #endif /* NO_FILESYSTEMS */
  10758. #if !defined(NO_FILES)
  10759. static void
  10760. send_options(struct mg_connection *conn)
  10761. {
  10762. if (!conn || !all_methods) {
  10763. return;
  10764. }
  10765. /* We do not set a "Cache-Control" header here, but leave the default.
  10766. * Since browsers do not send an OPTIONS request, we can not test the
  10767. * effect anyway. */
  10768. mg_response_header_start(conn, 200);
  10769. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10770. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10771. /* Use the same as before */
  10772. mg_response_header_add(conn, "Allow", all_methods, -1);
  10773. mg_response_header_add(conn, "DAV", "1", -1);
  10774. } else {
  10775. /* TODO: Check this later for HTTP/2 */
  10776. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10777. }
  10778. send_additional_header(conn);
  10779. mg_response_header_send(conn);
  10780. }
  10781. /* Writes PROPFIND properties for a collection element */
  10782. static int
  10783. print_props(struct mg_connection *conn,
  10784. const char *uri,
  10785. const char *name,
  10786. struct mg_file_stat *filep)
  10787. {
  10788. size_t i;
  10789. char mtime[64];
  10790. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10791. char *link_concat;
  10792. size_t link_concat_len;
  10793. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10794. return 0;
  10795. }
  10796. link_concat_len = strlen(uri) + strlen(name) + 1;
  10797. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  10798. if (!link_concat) {
  10799. return 0;
  10800. }
  10801. strcpy(link_concat, uri);
  10802. strcat(link_concat, name);
  10803. /* Get full link used in request */
  10804. mg_construct_local_link(
  10805. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  10806. /*
  10807. OutputDebugStringA("print_props:\n uri: ");
  10808. OutputDebugStringA(uri);
  10809. OutputDebugStringA("\n name: ");
  10810. OutputDebugStringA(name);
  10811. OutputDebugStringA("\n link: ");
  10812. OutputDebugStringA(link_buf);
  10813. OutputDebugStringA("\n");
  10814. */
  10815. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10816. mg_printf(conn,
  10817. "<d:response>"
  10818. "<d:href>%s</d:href>"
  10819. "<d:propstat>"
  10820. "<d:prop>"
  10821. "<d:resourcetype>%s</d:resourcetype>"
  10822. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10823. "<d:getlastmodified>%s</d:getlastmodified>"
  10824. "<d:lockdiscovery>",
  10825. link_buf,
  10826. filep->is_directory ? "<d:collection/>" : "",
  10827. filep->size,
  10828. mtime);
  10829. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10830. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10831. if (!strcmp(dav_lock[i].path, link_buf)) {
  10832. mg_printf(conn,
  10833. "<d:activelock>"
  10834. "<d:locktype><d:write/></d:locktype>"
  10835. "<d:lockscope><d:exclusive/></d:lockscope>"
  10836. "<d:depth>0</d:depth>"
  10837. "<d:owner>%s</d:owner>"
  10838. "<d:timeout>Second-%u</d:timeout>"
  10839. "<d:locktoken>"
  10840. "<d:href>%s</d:href>"
  10841. "</d:locktoken>"
  10842. "</d:activelock>\n",
  10843. dav_lock[i].user,
  10844. (unsigned)LOCK_DURATION_S,
  10845. dav_lock[i].token);
  10846. }
  10847. }
  10848. mg_printf(conn,
  10849. "</d:lockdiscovery>"
  10850. "</d:prop>"
  10851. "<d:status>HTTP/1.1 200 OK</d:status>"
  10852. "</d:propstat>"
  10853. "</d:response>\n");
  10854. mg_free(link_concat);
  10855. return 1;
  10856. }
  10857. static int
  10858. print_dav_dir_entry(struct de *de, void *data)
  10859. {
  10860. struct mg_connection *conn = (struct mg_connection *)data;
  10861. if (!de || !conn
  10862. || !print_props(
  10863. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10864. /* stop scan */
  10865. return 1;
  10866. }
  10867. return 0;
  10868. }
  10869. static void
  10870. handle_propfind(struct mg_connection *conn,
  10871. const char *path,
  10872. struct mg_file_stat *filep)
  10873. {
  10874. const char *depth = mg_get_header(conn, "Depth");
  10875. if (!conn || !path || !filep || !conn->dom_ctx) {
  10876. return;
  10877. }
  10878. /* return 207 "Multi-Status" */
  10879. conn->must_close = 1;
  10880. mg_response_header_start(conn, 207);
  10881. send_static_cache_header(conn);
  10882. send_additional_header(conn);
  10883. mg_response_header_add(conn,
  10884. "Content-Type",
  10885. "application/xml; charset=utf-8",
  10886. -1);
  10887. mg_response_header_send(conn);
  10888. /* Content */
  10889. mg_printf(conn,
  10890. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10891. "<d:multistatus xmlns:d='DAV:'>\n");
  10892. /* Print properties for the requested resource itself */
  10893. print_props(conn, conn->request_info.local_uri, "", filep);
  10894. /* If it is a directory, print directory entries too if Depth is not 0
  10895. */
  10896. if (filep->is_directory
  10897. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10898. "yes")
  10899. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10900. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10901. }
  10902. mg_printf(conn, "%s\n", "</d:multistatus>");
  10903. }
  10904. static void
  10905. dav_lock_file(struct mg_connection *conn, const char *path)
  10906. {
  10907. /* internal function - therefore conn is assumed to be valid */
  10908. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10909. uint64_t new_locktime;
  10910. int lock_index = -1;
  10911. int i;
  10912. uint64_t LOCK_DURATION_NS =
  10913. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  10914. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10915. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  10916. return;
  10917. }
  10918. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10919. /* const char *refresh = mg_get_header(conn, "If"); */
  10920. /* Link refresh should have an "If" header:
  10921. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  10922. * But it seems Windows Explorer does not send them.
  10923. */
  10924. mg_lock_context(conn->phys_ctx);
  10925. new_locktime = mg_get_current_time_ns();
  10926. /* Find a slot for a lock */
  10927. while (lock_index < 0) {
  10928. /* find existing lock */
  10929. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10930. if (!strcmp(dav_lock[i].path, link_buf)) {
  10931. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  10932. /* locked by the same user */
  10933. dav_lock[i].locktime = new_locktime;
  10934. lock_index = i;
  10935. break;
  10936. } else {
  10937. /* already locked by someone else */
  10938. if (new_locktime
  10939. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  10940. /* Lock expired */
  10941. dav_lock[i].path[0] = 0;
  10942. } else {
  10943. /* Lock still valid */
  10944. mg_unlock_context(conn->phys_ctx);
  10945. mg_send_http_error(conn, 423, "%s", "Already locked");
  10946. return;
  10947. }
  10948. }
  10949. }
  10950. }
  10951. /* create new lock token */
  10952. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10953. if (dav_lock[i].path[0] == 0) {
  10954. char s[32];
  10955. dav_lock[i].locktime = mg_get_current_time_ns();
  10956. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  10957. mg_md5(dav_lock[i].token,
  10958. link_buf,
  10959. "\x01",
  10960. s,
  10961. "\x01",
  10962. conn->request_info.remote_user,
  10963. NULL);
  10964. strncpy(dav_lock[i].path,
  10965. link_buf,
  10966. sizeof(dav_lock[i].path) - 1);
  10967. strncpy(dav_lock[i].user,
  10968. conn->request_info.remote_user,
  10969. sizeof(dav_lock[i].user) - 1);
  10970. lock_index = i;
  10971. break;
  10972. }
  10973. }
  10974. if (lock_index < 0) {
  10975. /* too many locks. Find oldest lock */
  10976. uint64_t oldest_locktime = dav_lock[0].locktime;
  10977. lock_index = 0;
  10978. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  10979. if (dav_lock[i].locktime < oldest_locktime) {
  10980. oldest_locktime = dav_lock[i].locktime;
  10981. lock_index = i;
  10982. }
  10983. }
  10984. /* invalidate oldest lock */
  10985. dav_lock[lock_index].path[0] = 0;
  10986. }
  10987. }
  10988. mg_unlock_context(conn->phys_ctx);
  10989. /* return 200 "OK" */
  10990. conn->must_close = 1;
  10991. mg_response_header_start(conn, 200);
  10992. send_static_cache_header(conn);
  10993. send_additional_header(conn);
  10994. mg_response_header_add(conn,
  10995. "Content-Type",
  10996. "application/xml; charset=utf-8",
  10997. -1);
  10998. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  10999. mg_response_header_send(conn);
  11000. /* Content */
  11001. mg_printf(conn,
  11002. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11003. "<d:prop xmlns:d=\"DAV:\">\n"
  11004. " <d:lockdiscovery>\n"
  11005. " <d:activelock>\n"
  11006. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11007. " <d:locktype><d:write/></d:locktype>\n"
  11008. " <d:owner>\n"
  11009. " <d:href>%s</d:href>\n"
  11010. " </d:owner>\n"
  11011. " <d:timeout>Second-%u</d:timeout>\n"
  11012. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11013. " <d:lockroot>\n"
  11014. " <d:href>%s</d:href>\n"
  11015. " </d:lockroot>\n"
  11016. " </d:activelock>\n"
  11017. " </d:lockdiscovery>\n"
  11018. " </d:prop>\n",
  11019. dav_lock[lock_index].user,
  11020. (LOCK_DURATION_S),
  11021. dav_lock[lock_index].token,
  11022. dav_lock[lock_index].path);
  11023. }
  11024. static void
  11025. dav_unlock_file(struct mg_connection *conn, const char *path)
  11026. {
  11027. /* internal function - therefore conn is assumed to be valid */
  11028. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11029. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11030. int lock_index;
  11031. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11032. return;
  11033. }
  11034. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11035. mg_lock_context(conn->phys_ctx);
  11036. /* find existing lock */
  11037. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11038. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11039. /* Success: return 204 "No Content" */
  11040. mg_unlock_context(conn->phys_ctx);
  11041. conn->must_close = 1;
  11042. mg_response_header_start(conn, 204);
  11043. mg_response_header_send(conn);
  11044. return;
  11045. }
  11046. }
  11047. mg_unlock_context(conn->phys_ctx);
  11048. /* Error: Cannot unlock a resource that is not locked */
  11049. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11050. }
  11051. static void
  11052. dav_proppatch(struct mg_connection *conn, const char *path)
  11053. {
  11054. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11055. if (!conn || !path || !conn->dom_ctx) {
  11056. return;
  11057. }
  11058. /* return 207 "Multi-Status" */
  11059. conn->must_close = 1;
  11060. mg_response_header_start(conn, 207);
  11061. send_static_cache_header(conn);
  11062. send_additional_header(conn);
  11063. mg_response_header_add(conn,
  11064. "Content-Type",
  11065. "application/xml; charset=utf-8",
  11066. -1);
  11067. mg_response_header_send(conn);
  11068. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11069. /* Content */
  11070. mg_printf(conn,
  11071. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11072. "<d:multistatus xmlns:d='DAV:'>\n"
  11073. "<d:response>\n<d:href>%s</d:href>\n",
  11074. link_buf);
  11075. mg_printf(conn,
  11076. "<d:propstat><d:status>HTTP/1.1 403 "
  11077. "Forbidden</d:status></d:propstat>\n");
  11078. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11079. }
  11080. #endif
  11081. CIVETWEB_API void
  11082. mg_lock_connection(struct mg_connection *conn)
  11083. {
  11084. if (conn) {
  11085. (void)pthread_mutex_lock(&conn->mutex);
  11086. }
  11087. }
  11088. CIVETWEB_API void
  11089. mg_unlock_connection(struct mg_connection *conn)
  11090. {
  11091. if (conn) {
  11092. (void)pthread_mutex_unlock(&conn->mutex);
  11093. }
  11094. }
  11095. CIVETWEB_API void
  11096. mg_lock_context(struct mg_context *ctx)
  11097. {
  11098. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11099. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11100. }
  11101. }
  11102. CIVETWEB_API void
  11103. mg_unlock_context(struct mg_context *ctx)
  11104. {
  11105. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11106. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11107. }
  11108. }
  11109. #if defined(USE_LUA)
  11110. #include "mod_lua.inl"
  11111. #endif /* USE_LUA */
  11112. #if defined(USE_DUKTAPE)
  11113. #include "mod_duktape.inl"
  11114. #endif /* USE_DUKTAPE */
  11115. #if defined(USE_WEBSOCKET)
  11116. #if !defined(NO_SSL_DL)
  11117. #if !defined(OPENSSL_API_3_0)
  11118. #define SHA_API static
  11119. #include "sha1.inl"
  11120. #endif
  11121. #endif
  11122. static int
  11123. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11124. {
  11125. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11126. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11127. size_t dst_len = sizeof(b64_sha);
  11128. #if !defined(OPENSSL_API_3_0)
  11129. SHA_CTX sha_ctx;
  11130. #endif
  11131. int truncated;
  11132. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11133. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11134. if (truncated) {
  11135. conn->must_close = 1;
  11136. return 0;
  11137. }
  11138. DEBUG_TRACE("%s", "Send websocket handshake");
  11139. #if defined(OPENSSL_API_3_0)
  11140. EVP_Digest((unsigned char *)buf,
  11141. (uint32_t)strlen(buf),
  11142. (unsigned char *)sha,
  11143. NULL,
  11144. EVP_get_digestbyname("sha1"),
  11145. NULL);
  11146. #else
  11147. SHA1_Init(&sha_ctx);
  11148. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11149. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11150. #endif
  11151. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11152. mg_printf(conn,
  11153. "HTTP/1.1 101 Switching Protocols\r\n"
  11154. "Upgrade: websocket\r\n"
  11155. "Connection: Upgrade\r\n"
  11156. "Sec-WebSocket-Accept: %s\r\n",
  11157. b64_sha);
  11158. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11159. // Send negotiated compression extension parameters
  11160. websocket_deflate_response(conn);
  11161. #endif
  11162. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11163. mg_printf(conn,
  11164. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11165. conn->request_info.acceptedWebSocketSubprotocol);
  11166. } else {
  11167. mg_printf(conn, "%s", "\r\n");
  11168. }
  11169. return 1;
  11170. }
  11171. #if !defined(MG_MAX_UNANSWERED_PING)
  11172. /* Configuration of the maximum number of websocket PINGs that might
  11173. * stay unanswered before the connection is considered broken.
  11174. * Note: The name of this define may still change (until it is
  11175. * defined as a compile parameter in a documentation).
  11176. */
  11177. #define MG_MAX_UNANSWERED_PING (5)
  11178. #endif
  11179. static void
  11180. read_websocket(struct mg_connection *conn,
  11181. mg_websocket_data_handler ws_data_handler,
  11182. void *callback_data)
  11183. {
  11184. /* Pointer to the beginning of the portion of the incoming websocket
  11185. * message queue.
  11186. * The original websocket upgrade request is never removed, so the queue
  11187. * begins after it. */
  11188. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11189. int n, error, exit_by_callback;
  11190. int ret;
  11191. /* body_len is the length of the entire queue in bytes
  11192. * len is the length of the current message
  11193. * data_len is the length of the current message's data payload
  11194. * header_len is the length of the current message's header */
  11195. size_t i, len, mask_len = 0, header_len, body_len;
  11196. uint64_t data_len = 0;
  11197. /* "The masking key is a 32-bit value chosen at random by the client."
  11198. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11199. */
  11200. unsigned char mask[4];
  11201. /* data points to the place where the message is stored when passed to
  11202. * the websocket_data callback. This is either mem on the stack, or a
  11203. * dynamically allocated buffer if it is too large. */
  11204. unsigned char mem[4096];
  11205. unsigned char mop; /* mask flag and opcode */
  11206. /* Variables used for connection monitoring */
  11207. double timeout = -1.0;
  11208. int enable_ping_pong = 0;
  11209. int ping_count = 0;
  11210. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11211. enable_ping_pong =
  11212. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11213. "yes");
  11214. }
  11215. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11216. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11217. }
  11218. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11219. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11220. }
  11221. if (timeout <= 0.0) {
  11222. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11223. }
  11224. /* Enter data processing loop */
  11225. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11226. conn->request_info.remote_addr,
  11227. conn->request_info.remote_port);
  11228. conn->in_websocket_handling = 1;
  11229. mg_set_thread_name("wsock");
  11230. /* Loop continuously, reading messages from the socket, invoking the
  11231. * callback, and waiting repeatedly until an error occurs. */
  11232. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11233. && (!conn->must_close)) {
  11234. header_len = 0;
  11235. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11236. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11237. len = buf[1] & 127;
  11238. mask_len = (buf[1] & 128) ? 4 : 0;
  11239. if ((len < 126) && (body_len >= mask_len)) {
  11240. /* inline 7-bit length field */
  11241. data_len = len;
  11242. header_len = 2 + mask_len;
  11243. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11244. /* 16-bit length field */
  11245. header_len = 4 + mask_len;
  11246. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11247. } else if (body_len >= (10 + mask_len)) {
  11248. /* 64-bit length field */
  11249. uint32_t l1, l2;
  11250. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11251. memcpy(&l2, &buf[6], 4);
  11252. header_len = 10 + mask_len;
  11253. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11254. if (data_len > (uint64_t)0x7FFF0000ul) {
  11255. /* no can do */
  11256. mg_cry_internal(
  11257. conn,
  11258. "%s",
  11259. "websocket out of memory; closing connection");
  11260. break;
  11261. }
  11262. }
  11263. }
  11264. if ((header_len > 0) && (body_len >= header_len)) {
  11265. /* Allocate space to hold websocket payload */
  11266. unsigned char *data = mem;
  11267. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11268. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11269. conn->phys_ctx);
  11270. if (data == NULL) {
  11271. /* Allocation failed, exit the loop and then close the
  11272. * connection */
  11273. mg_cry_internal(
  11274. conn,
  11275. "%s",
  11276. "websocket out of memory; closing connection");
  11277. break;
  11278. }
  11279. }
  11280. /* Copy the mask before we shift the queue and destroy it */
  11281. if (mask_len > 0) {
  11282. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11283. } else {
  11284. memset(mask, 0, sizeof(mask));
  11285. }
  11286. /* Read frame payload from the first message in the queue into
  11287. * data and advance the queue by moving the memory in place. */
  11288. DEBUG_ASSERT(body_len >= header_len);
  11289. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11290. mop = buf[0]; /* current mask and opcode */
  11291. /* Overflow case */
  11292. len = body_len - header_len;
  11293. memcpy(data, buf + header_len, len);
  11294. error = 0;
  11295. while ((uint64_t)len < data_len) {
  11296. n = pull_inner(NULL,
  11297. conn,
  11298. (char *)(data + len),
  11299. (int)(data_len - len),
  11300. timeout);
  11301. if (n <= -2) {
  11302. error = 1;
  11303. break;
  11304. } else if (n > 0) {
  11305. len += (size_t)n;
  11306. } else {
  11307. /* Timeout: should retry */
  11308. /* TODO: retry condition */
  11309. }
  11310. }
  11311. if (error) {
  11312. mg_cry_internal(
  11313. conn,
  11314. "%s",
  11315. "Websocket pull failed; closing connection");
  11316. if (data != mem) {
  11317. mg_free(data);
  11318. }
  11319. break;
  11320. }
  11321. conn->data_len = conn->request_len;
  11322. } else {
  11323. mop = buf[0]; /* current mask and opcode, overwritten by
  11324. * memmove() */
  11325. /* Length of the message being read at the front of the
  11326. * queue. Cast to 31 bit is OK, since we limited
  11327. * data_len before. */
  11328. len = (size_t)data_len + header_len;
  11329. /* Copy the data payload into the data pointer for the
  11330. * callback. Cast to 31 bit is OK, since we
  11331. * limited data_len */
  11332. memcpy(data, buf + header_len, (size_t)data_len);
  11333. /* Move the queue forward len bytes */
  11334. memmove(buf, buf + len, body_len - len);
  11335. /* Mark the queue as advanced */
  11336. conn->data_len -= (int)len;
  11337. }
  11338. /* Apply mask if necessary */
  11339. if (mask_len > 0) {
  11340. for (i = 0; i < (size_t)data_len; i++) {
  11341. data[i] ^= mask[i & 3];
  11342. }
  11343. }
  11344. exit_by_callback = 0;
  11345. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11346. /* filter PONG messages */
  11347. DEBUG_TRACE("PONG from %s:%u",
  11348. conn->request_info.remote_addr,
  11349. conn->request_info.remote_port);
  11350. /* No unanwered PINGs left */
  11351. ping_count = 0;
  11352. } else if (enable_ping_pong
  11353. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11354. /* reply PING messages */
  11355. DEBUG_TRACE("Reply PING from %s:%u",
  11356. conn->request_info.remote_addr,
  11357. conn->request_info.remote_port);
  11358. ret = mg_websocket_write(conn,
  11359. MG_WEBSOCKET_OPCODE_PONG,
  11360. (char *)data,
  11361. (size_t)data_len);
  11362. if (ret <= 0) {
  11363. /* Error: send failed */
  11364. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11365. break;
  11366. }
  11367. } else {
  11368. /* Exit the loop if callback signals to exit (server side),
  11369. * or "connection close" opcode received (client side). */
  11370. if (ws_data_handler != NULL) {
  11371. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11372. if (mop & 0x40) {
  11373. /* Inflate the data received if bit RSV1 is set. */
  11374. if (!conn->websocket_deflate_initialized) {
  11375. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11376. exit_by_callback = 1;
  11377. }
  11378. if (!exit_by_callback) {
  11379. size_t inflate_buf_size_old = 0;
  11380. size_t inflate_buf_size =
  11381. data_len
  11382. * 4; // Initial guess of the inflated message
  11383. // size. We double the memory when needed.
  11384. Bytef *inflated = NULL;
  11385. Bytef *new_mem = NULL;
  11386. conn->websocket_inflate_state.avail_in =
  11387. (uInt)(data_len + 4);
  11388. conn->websocket_inflate_state.next_in = data;
  11389. // Add trailing 0x00 0x00 0xff 0xff bytes
  11390. data[data_len] = '\x00';
  11391. data[data_len + 1] = '\x00';
  11392. data[data_len + 2] = '\xff';
  11393. data[data_len + 3] = '\xff';
  11394. do {
  11395. if (inflate_buf_size_old == 0) {
  11396. new_mem =
  11397. (Bytef *)mg_calloc(inflate_buf_size,
  11398. sizeof(Bytef));
  11399. } else {
  11400. inflate_buf_size *= 2;
  11401. new_mem =
  11402. (Bytef *)mg_realloc(inflated,
  11403. inflate_buf_size);
  11404. }
  11405. if (new_mem == NULL) {
  11406. mg_cry_internal(
  11407. conn,
  11408. "Out of memory: Cannot allocate "
  11409. "inflate buffer of %lu bytes",
  11410. (unsigned long)inflate_buf_size);
  11411. exit_by_callback = 1;
  11412. break;
  11413. }
  11414. inflated = new_mem;
  11415. conn->websocket_inflate_state.avail_out =
  11416. (uInt)(inflate_buf_size
  11417. - inflate_buf_size_old);
  11418. conn->websocket_inflate_state.next_out =
  11419. inflated + inflate_buf_size_old;
  11420. ret = inflate(&conn->websocket_inflate_state,
  11421. Z_SYNC_FLUSH);
  11422. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11423. || ret == Z_MEM_ERROR) {
  11424. mg_cry_internal(
  11425. conn,
  11426. "ZLIB inflate error: %i %s",
  11427. ret,
  11428. (conn->websocket_inflate_state.msg
  11429. ? conn->websocket_inflate_state.msg
  11430. : "<no error message>"));
  11431. exit_by_callback = 1;
  11432. break;
  11433. }
  11434. inflate_buf_size_old = inflate_buf_size;
  11435. } while (conn->websocket_inflate_state.avail_out
  11436. == 0);
  11437. inflate_buf_size -=
  11438. conn->websocket_inflate_state.avail_out;
  11439. if (!ws_data_handler(conn,
  11440. mop,
  11441. (char *)inflated,
  11442. inflate_buf_size,
  11443. callback_data)) {
  11444. exit_by_callback = 1;
  11445. }
  11446. mg_free(inflated);
  11447. }
  11448. } else
  11449. #endif
  11450. if (!ws_data_handler(conn,
  11451. mop,
  11452. (char *)data,
  11453. (size_t)data_len,
  11454. callback_data)) {
  11455. exit_by_callback = 1;
  11456. }
  11457. }
  11458. }
  11459. /* It a buffer has been allocated, free it again */
  11460. if (data != mem) {
  11461. mg_free(data);
  11462. }
  11463. if (exit_by_callback) {
  11464. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11465. conn->request_info.remote_addr,
  11466. conn->request_info.remote_port);
  11467. break;
  11468. }
  11469. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11470. /* Opcode == 8, connection close */
  11471. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11472. conn->request_info.remote_addr,
  11473. conn->request_info.remote_port);
  11474. break;
  11475. }
  11476. /* Not breaking the loop, process next websocket frame. */
  11477. } else {
  11478. /* Read from the socket into the next available location in the
  11479. * message queue. */
  11480. n = pull_inner(NULL,
  11481. conn,
  11482. conn->buf + conn->data_len,
  11483. conn->buf_size - conn->data_len,
  11484. timeout);
  11485. if (n <= -2) {
  11486. /* Error, no bytes read */
  11487. DEBUG_TRACE("PULL from %s:%u failed",
  11488. conn->request_info.remote_addr,
  11489. conn->request_info.remote_port);
  11490. break;
  11491. }
  11492. if (n > 0) {
  11493. conn->data_len += n;
  11494. /* Reset open PING count */
  11495. ping_count = 0;
  11496. } else {
  11497. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11498. && (!conn->must_close)) {
  11499. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11500. /* Stop sending PING */
  11501. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11502. "- closing connection",
  11503. ping_count,
  11504. conn->request_info.remote_addr,
  11505. conn->request_info.remote_port);
  11506. break;
  11507. }
  11508. if (enable_ping_pong) {
  11509. /* Send Websocket PING message */
  11510. DEBUG_TRACE("PING to %s:%u",
  11511. conn->request_info.remote_addr,
  11512. conn->request_info.remote_port);
  11513. ret = mg_websocket_write(conn,
  11514. MG_WEBSOCKET_OPCODE_PING,
  11515. NULL,
  11516. 0);
  11517. if (ret <= 0) {
  11518. /* Error: send failed */
  11519. DEBUG_TRACE("Send PING failed (%i)", ret);
  11520. break;
  11521. }
  11522. ping_count++;
  11523. }
  11524. }
  11525. /* Timeout: should retry */
  11526. /* TODO: get timeout def */
  11527. }
  11528. }
  11529. }
  11530. /* Leave data processing loop */
  11531. mg_set_thread_name("worker");
  11532. conn->in_websocket_handling = 0;
  11533. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11534. conn->request_info.remote_addr,
  11535. conn->request_info.remote_port);
  11536. }
  11537. static int
  11538. mg_websocket_write_exec(struct mg_connection *conn,
  11539. int opcode,
  11540. const char *data,
  11541. size_t dataLen,
  11542. uint32_t masking_key)
  11543. {
  11544. unsigned char header[14];
  11545. size_t headerLen;
  11546. int retval;
  11547. #if defined(GCC_DIAGNOSTIC)
  11548. /* Disable spurious conversion warning for GCC */
  11549. #pragma GCC diagnostic push
  11550. #pragma GCC diagnostic ignored "-Wconversion"
  11551. #endif
  11552. /* Note that POSIX/Winsock's send() is threadsafe
  11553. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11554. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11555. * push(), although that is only a problem if the packet is large or
  11556. * outgoing buffer is full). */
  11557. /* TODO: Check if this lock should be moved to user land.
  11558. * Currently the server sets this lock for websockets, but
  11559. * not for any other connection. It must be set for every
  11560. * conn read/written by more than one thread, no matter if
  11561. * it is a websocket or regular connection. */
  11562. (void)mg_lock_connection(conn);
  11563. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11564. size_t deflated_size = 0;
  11565. Bytef *deflated = 0;
  11566. // Deflate websocket messages over 100kb
  11567. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11568. if (use_deflate) {
  11569. if (!conn->websocket_deflate_initialized) {
  11570. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11571. return 0;
  11572. }
  11573. // Deflating the message
  11574. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11575. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11576. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11577. deflated_size = (size_t)compressBound((uLong)dataLen);
  11578. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11579. if (deflated == NULL) {
  11580. mg_cry_internal(
  11581. conn,
  11582. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11583. (unsigned long)deflated_size);
  11584. mg_unlock_connection(conn);
  11585. return -1;
  11586. }
  11587. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11588. conn->websocket_deflate_state.next_out = deflated;
  11589. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11590. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11591. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11592. } else
  11593. #endif
  11594. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11595. #if defined(GCC_DIAGNOSTIC)
  11596. #pragma GCC diagnostic pop
  11597. #endif
  11598. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11599. if (dataLen < 126) {
  11600. /* inline 7-bit length field */
  11601. header[1] = (unsigned char)dataLen;
  11602. headerLen = 2;
  11603. } else if (dataLen <= 0xFFFF) {
  11604. /* 16-bit length field */
  11605. uint16_t len = htons((uint16_t)dataLen);
  11606. header[1] = 126;
  11607. memcpy(header + 2, &len, 2);
  11608. headerLen = 4;
  11609. } else {
  11610. /* 64-bit length field */
  11611. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11612. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11613. header[1] = 127;
  11614. memcpy(header + 2, &len1, 4);
  11615. memcpy(header + 6, &len2, 4);
  11616. headerLen = 10;
  11617. }
  11618. if (masking_key) {
  11619. /* add mask */
  11620. header[1] |= 0x80;
  11621. memcpy(header + headerLen, &masking_key, 4);
  11622. headerLen += 4;
  11623. }
  11624. retval = mg_write(conn, header, headerLen);
  11625. if (retval != (int)headerLen) {
  11626. /* Did not send complete header */
  11627. retval = -1;
  11628. } else {
  11629. if (dataLen > 0) {
  11630. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11631. if (use_deflate) {
  11632. retval = mg_write(conn, deflated, dataLen);
  11633. mg_free(deflated);
  11634. } else
  11635. #endif
  11636. retval = mg_write(conn, data, dataLen);
  11637. }
  11638. /* if dataLen == 0, the header length (2) is returned */
  11639. }
  11640. /* TODO: Remove this unlock as well, when lock is removed. */
  11641. mg_unlock_connection(conn);
  11642. return retval;
  11643. }
  11644. CIVETWEB_API int
  11645. mg_websocket_write(struct mg_connection *conn,
  11646. int opcode,
  11647. const char *data,
  11648. size_t dataLen)
  11649. {
  11650. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11651. }
  11652. static void
  11653. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11654. {
  11655. size_t i = 0;
  11656. i = 0;
  11657. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11658. /* Convert in 32 bit words, if data is 4 byte aligned */
  11659. while (i < (in_len - 3)) {
  11660. *(uint32_t *)(void *)(out + i) =
  11661. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11662. i += 4;
  11663. }
  11664. }
  11665. if (i != in_len) {
  11666. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11667. while (i < in_len) {
  11668. *(uint8_t *)(void *)(out + i) =
  11669. *(uint8_t *)(void *)(in + i)
  11670. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11671. i++;
  11672. }
  11673. }
  11674. }
  11675. CIVETWEB_API int
  11676. mg_websocket_client_write(struct mg_connection *conn,
  11677. int opcode,
  11678. const char *data,
  11679. size_t dataLen)
  11680. {
  11681. int retval = -1;
  11682. char *masked_data =
  11683. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11684. uint32_t masking_key = 0;
  11685. if (masked_data == NULL) {
  11686. /* Return -1 in an error case */
  11687. mg_cry_internal(conn,
  11688. "%s",
  11689. "Cannot allocate buffer for masked websocket response: "
  11690. "Out of memory");
  11691. return -1;
  11692. }
  11693. do {
  11694. /* Get a masking key - but not 0 */
  11695. masking_key = (uint32_t)get_random();
  11696. } while (masking_key == 0);
  11697. mask_data(data, dataLen, masking_key, masked_data);
  11698. retval = mg_websocket_write_exec(
  11699. conn, opcode, masked_data, dataLen, masking_key);
  11700. mg_free(masked_data);
  11701. return retval;
  11702. }
  11703. static void
  11704. handle_websocket_request(struct mg_connection *conn,
  11705. const char *path,
  11706. int is_callback_resource,
  11707. struct mg_websocket_subprotocols *subprotocols,
  11708. mg_websocket_connect_handler ws_connect_handler,
  11709. mg_websocket_ready_handler ws_ready_handler,
  11710. mg_websocket_data_handler ws_data_handler,
  11711. mg_websocket_close_handler ws_close_handler,
  11712. void *cbData)
  11713. {
  11714. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11715. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11716. ptrdiff_t lua_websock = 0;
  11717. #if !defined(USE_LUA)
  11718. (void)path;
  11719. #endif
  11720. /* Step 1: Check websocket protocol version. */
  11721. /* Step 1.1: Check Sec-WebSocket-Key. */
  11722. if (!websock_key) {
  11723. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11724. * requires a Sec-WebSocket-Key header.
  11725. */
  11726. /* It could be the hixie draft version
  11727. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11728. */
  11729. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11730. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11731. char key3[8];
  11732. if ((key1 != NULL) && (key2 != NULL)) {
  11733. /* This version uses 8 byte body data in a GET request */
  11734. conn->content_len = 8;
  11735. if (8 == mg_read(conn, key3, 8)) {
  11736. /* This is the hixie version */
  11737. mg_send_http_error(conn,
  11738. 426,
  11739. "%s",
  11740. "Protocol upgrade to RFC 6455 required");
  11741. return;
  11742. }
  11743. }
  11744. /* This is an unknown version */
  11745. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11746. return;
  11747. }
  11748. /* Step 1.2: Check websocket protocol version. */
  11749. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11750. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11751. /* Reject wrong versions */
  11752. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11753. return;
  11754. }
  11755. /* Step 1.3: Could check for "Host", but we do not really nead this
  11756. * value for anything, so just ignore it. */
  11757. /* Step 2: If a callback is responsible, call it. */
  11758. if (is_callback_resource) {
  11759. /* Step 2.1 check and select subprotocol */
  11760. const char *protocols[64]; // max 64 headers
  11761. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11762. "Sec-WebSocket-Protocol",
  11763. protocols,
  11764. 64);
  11765. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11766. int headerNo, idx;
  11767. size_t len;
  11768. const char *sep, *curSubProtocol,
  11769. *acceptedWebSocketSubprotocol = NULL;
  11770. /* look for matching subprotocol */
  11771. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11772. /* There might be multiple headers ... */
  11773. const char *protocol = protocols[headerNo];
  11774. curSubProtocol = protocol;
  11775. /* ... and in every header there might be a , separated list */
  11776. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11777. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11778. curSubProtocol++;
  11779. sep = strchr(curSubProtocol, ',');
  11780. if (sep) {
  11781. len = (size_t)(sep - curSubProtocol);
  11782. } else {
  11783. len = strlen(curSubProtocol);
  11784. }
  11785. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11786. // COMPARE: curSubProtocol ==
  11787. // subprotocols->subprotocols[idx]
  11788. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11789. && (strncmp(curSubProtocol,
  11790. subprotocols->subprotocols[idx],
  11791. len)
  11792. == 0)) {
  11793. acceptedWebSocketSubprotocol =
  11794. subprotocols->subprotocols[idx];
  11795. break;
  11796. }
  11797. }
  11798. curSubProtocol += len;
  11799. }
  11800. }
  11801. conn->request_info.acceptedWebSocketSubprotocol =
  11802. acceptedWebSocketSubprotocol;
  11803. }
  11804. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11805. websocket_deflate_negotiate(conn);
  11806. #endif
  11807. if ((ws_connect_handler != NULL)
  11808. && (ws_connect_handler(conn, cbData) != 0)) {
  11809. /* C callback has returned non-zero, do not proceed with
  11810. * handshake.
  11811. */
  11812. /* Note that C callbacks are no longer called when Lua is
  11813. * responsible, so C can no longer filter callbacks for Lua. */
  11814. return;
  11815. }
  11816. }
  11817. #if defined(USE_LUA)
  11818. /* Step 3: No callback. Check if Lua is responsible. */
  11819. else {
  11820. /* Step 3.1: Check if Lua is responsible. */
  11821. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11822. lua_websock = match_prefix_strlen(
  11823. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11824. }
  11825. if (lua_websock > 0) {
  11826. /* Step 3.2: Lua is responsible: call it. */
  11827. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11828. if (!conn->lua_websocket_state) {
  11829. /* Lua rejected the new client */
  11830. return;
  11831. }
  11832. }
  11833. }
  11834. #endif
  11835. /* Step 4: Check if there is a responsible websocket handler. */
  11836. if (!is_callback_resource && !lua_websock) {
  11837. /* There is no callback, and Lua is not responsible either. */
  11838. /* Reply with a 404 Not Found. We are still at a standard
  11839. * HTTP request here, before the websocket handshake, so
  11840. * we can still send standard HTTP error replies. */
  11841. mg_send_http_error(conn, 404, "%s", "Not found");
  11842. return;
  11843. }
  11844. /* Step 5: The websocket connection has been accepted */
  11845. if (!send_websocket_handshake(conn, websock_key)) {
  11846. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11847. return;
  11848. }
  11849. /* Step 6: Call the ready handler */
  11850. if (is_callback_resource) {
  11851. if (ws_ready_handler != NULL) {
  11852. ws_ready_handler(conn, cbData);
  11853. }
  11854. #if defined(USE_LUA)
  11855. } else if (lua_websock) {
  11856. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11857. /* the ready handler returned false */
  11858. return;
  11859. }
  11860. #endif
  11861. }
  11862. /* Step 7: Enter the read loop */
  11863. if (is_callback_resource) {
  11864. read_websocket(conn, ws_data_handler, cbData);
  11865. #if defined(USE_LUA)
  11866. } else if (lua_websock) {
  11867. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11868. #endif
  11869. }
  11870. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11871. /* Step 8: Close the deflate & inflate buffers */
  11872. if (conn->websocket_deflate_initialized) {
  11873. deflateEnd(&conn->websocket_deflate_state);
  11874. inflateEnd(&conn->websocket_inflate_state);
  11875. }
  11876. #endif
  11877. /* Step 9: Call the close handler */
  11878. if (ws_close_handler) {
  11879. ws_close_handler(conn, cbData);
  11880. }
  11881. }
  11882. #endif /* !USE_WEBSOCKET */
  11883. /* Is upgrade request:
  11884. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11885. * 1 = upgrade to websocket
  11886. * 2 = upgrade to HTTP/2
  11887. * -1 = upgrade to unknown protocol
  11888. */
  11889. static int
  11890. should_switch_to_protocol(const struct mg_connection *conn)
  11891. {
  11892. const char *connection_headers[8];
  11893. const char *upgrade_to;
  11894. int connection_header_count, i, should_upgrade;
  11895. /* A websocket protocoll has the following HTTP headers:
  11896. *
  11897. * Connection: Upgrade
  11898. * Upgrade: Websocket
  11899. *
  11900. * It seems some clients use multiple headers:
  11901. * see https://github.com/civetweb/civetweb/issues/1083
  11902. */
  11903. connection_header_count = get_req_headers(&conn->request_info,
  11904. "Connection",
  11905. connection_headers,
  11906. 8);
  11907. should_upgrade = 0;
  11908. for (i = 0; i < connection_header_count; i++) {
  11909. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  11910. should_upgrade = 1;
  11911. }
  11912. }
  11913. if (!should_upgrade) {
  11914. return PROTOCOL_TYPE_HTTP1;
  11915. }
  11916. upgrade_to = mg_get_header(conn, "Upgrade");
  11917. if (upgrade_to == NULL) {
  11918. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11919. return -1;
  11920. }
  11921. /* Upgrade to ... */
  11922. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  11923. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11924. * "Sec-WebSocket-Version" are also required.
  11925. * Don't check them here, since even an unsupported websocket protocol
  11926. * request still IS a websocket request (in contrast to a standard HTTP
  11927. * request). It will fail later in handle_websocket_request.
  11928. */
  11929. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11930. }
  11931. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  11932. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11933. }
  11934. /* Upgrade to another protocol */
  11935. return -1;
  11936. }
  11937. static int
  11938. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11939. {
  11940. int n;
  11941. unsigned int a, b, c, d, slash;
  11942. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  11943. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  11944. // integer value, but function will not report conversion
  11945. // errors; consider using 'strtol' instead
  11946. slash = 32;
  11947. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  11948. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  11949. // an integer value, but function will not report conversion
  11950. // errors; consider using 'strtol' instead
  11951. n = 0;
  11952. }
  11953. }
  11954. if ((n > 0) && ((size_t)n == vec->len)) {
  11955. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11956. /* IPv4 format */
  11957. if (sa->sa.sa_family == AF_INET) {
  11958. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  11959. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11960. | ((uint32_t)c << 8) | (uint32_t)d;
  11961. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11962. return (ip & mask) == net;
  11963. }
  11964. return 0;
  11965. }
  11966. }
  11967. #if defined(USE_IPV6)
  11968. else {
  11969. char ad[50];
  11970. const char *p;
  11971. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11972. slash = 128;
  11973. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11974. n = 0;
  11975. }
  11976. }
  11977. if ((n <= 0) && no_strict) {
  11978. /* no square brackets? */
  11979. p = strchr(vec->ptr, '/');
  11980. if (p && (p < (vec->ptr + vec->len))) {
  11981. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11982. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11983. n += (int)(p - vec->ptr);
  11984. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11985. } else {
  11986. n = 0;
  11987. }
  11988. } else if (vec->len < sizeof(ad)) {
  11989. n = (int)vec->len;
  11990. slash = 128;
  11991. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11992. }
  11993. }
  11994. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11995. p = ad;
  11996. c = 0;
  11997. /* zone indexes are unsupported, at least two colons are needed */
  11998. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11999. if (*(p++) == ':') {
  12000. c++;
  12001. }
  12002. }
  12003. if ((*p == '\0') && (c >= 2)) {
  12004. struct sockaddr_in6 sin6;
  12005. unsigned int i;
  12006. /* for strict validation, an actual IPv6 argument is needed */
  12007. if (sa->sa.sa_family != AF_INET6) {
  12008. return 0;
  12009. }
  12010. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12011. /* IPv6 format */
  12012. for (i = 0; i < 16; i++) {
  12013. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12014. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12015. uint8_t mask = 0;
  12016. if (8 * i + 8 < slash) {
  12017. mask = 0xFFu;
  12018. } else if (8 * i < slash) {
  12019. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12020. }
  12021. if ((ip & mask) != net) {
  12022. return 0;
  12023. }
  12024. }
  12025. return 1;
  12026. }
  12027. }
  12028. }
  12029. }
  12030. #else
  12031. (void)no_strict;
  12032. #endif
  12033. /* malformed */
  12034. return -1;
  12035. }
  12036. static int
  12037. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12038. {
  12039. int throttle = 0;
  12040. struct vec vec, val;
  12041. char mult;
  12042. double v;
  12043. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12044. mult = ',';
  12045. if ((val.ptr == NULL)
  12046. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12047. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12048. // to an integer value, but function will not report
  12049. // conversion errors; consider using 'strtol' instead
  12050. || (v < 0)
  12051. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12052. && (mult != ','))) {
  12053. continue;
  12054. }
  12055. v *= (lowercase(&mult) == 'k')
  12056. ? 1024
  12057. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12058. if (vec.len == 1 && vec.ptr[0] == '*') {
  12059. throttle = (int)v;
  12060. } else {
  12061. int matched = parse_match_net(&vec, rsa, 0);
  12062. if (matched >= 0) {
  12063. /* a valid IP subnet */
  12064. if (matched) {
  12065. throttle = (int)v;
  12066. }
  12067. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12068. throttle = (int)v;
  12069. }
  12070. }
  12071. }
  12072. return throttle;
  12073. }
  12074. /* The mg_upload function is superseeded by mg_handle_form_request. */
  12075. #include "handle_form.inl"
  12076. static int
  12077. get_first_ssl_listener_index(const struct mg_context *ctx)
  12078. {
  12079. unsigned int i;
  12080. int idx = -1;
  12081. if (ctx) {
  12082. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12083. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12084. }
  12085. }
  12086. return idx;
  12087. }
  12088. /* Return host (without port) */
  12089. static void
  12090. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12091. {
  12092. const char *host_header =
  12093. get_header(ri->http_headers, ri->num_headers, "Host");
  12094. host->ptr = NULL;
  12095. host->len = 0;
  12096. if (host_header != NULL) {
  12097. const char *pos;
  12098. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12099. * is found. */
  12100. if (*host_header == '[') {
  12101. pos = strchr(host_header, ']');
  12102. if (!pos) {
  12103. /* Malformed hostname starts with '[', but no ']' found */
  12104. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12105. return;
  12106. }
  12107. /* terminate after ']' */
  12108. host->ptr = host_header;
  12109. host->len = (size_t)(pos + 1 - host_header);
  12110. } else {
  12111. /* Otherwise, a ':' separates hostname and port number */
  12112. pos = strchr(host_header, ':');
  12113. if (pos != NULL) {
  12114. host->len = (size_t)(pos - host_header);
  12115. } else {
  12116. host->len = strlen(host_header);
  12117. }
  12118. host->ptr = host_header;
  12119. }
  12120. }
  12121. }
  12122. static int
  12123. switch_domain_context(struct mg_connection *conn)
  12124. {
  12125. struct vec host;
  12126. get_host_from_request_info(&host, &conn->request_info);
  12127. if (host.ptr) {
  12128. if (conn->ssl) {
  12129. /* This is a HTTPS connection, maybe we have a hostname
  12130. * from SNI (set in ssl_servername_callback). */
  12131. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12132. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12133. /* We are not using the default domain */
  12134. if ((strlen(sslhost) != host.len)
  12135. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12136. /* Mismatch between SNI domain and HTTP domain */
  12137. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12138. sslhost,
  12139. (int)host.len,
  12140. host.ptr);
  12141. return 0;
  12142. }
  12143. }
  12144. } else {
  12145. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12146. while (dom) {
  12147. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12148. size_t domNameLen = strlen(domName);
  12149. if ((domNameLen == host.len)
  12150. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12151. /* Found matching domain */
  12152. DEBUG_TRACE("HTTP domain %s found",
  12153. dom->config[AUTHENTICATION_DOMAIN]);
  12154. /* TODO: Check if this is a HTTP or HTTPS domain */
  12155. conn->dom_ctx = dom;
  12156. break;
  12157. }
  12158. mg_lock_context(conn->phys_ctx);
  12159. dom = dom->next;
  12160. mg_unlock_context(conn->phys_ctx);
  12161. }
  12162. }
  12163. DEBUG_TRACE("HTTP%s Host: %.*s",
  12164. conn->ssl ? "S" : "",
  12165. (int)host.len,
  12166. host.ptr);
  12167. } else {
  12168. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12169. return 1;
  12170. }
  12171. return 1;
  12172. }
  12173. static void
  12174. redirect_to_https_port(struct mg_connection *conn, int port)
  12175. {
  12176. char target_url[MG_BUF_LEN];
  12177. int truncated = 0;
  12178. const char *expect_proto =
  12179. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12180. /* Use "308 Permanent Redirect" */
  12181. int redirect_code = 308;
  12182. /* In any case, close the current connection */
  12183. conn->must_close = 1;
  12184. /* Send host, port, uri and (if it exists) ?query_string */
  12185. if (mg_construct_local_link(
  12186. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12187. < 0) {
  12188. truncated = 1;
  12189. } else if (conn->request_info.query_string != NULL) {
  12190. size_t slen1 = strlen(target_url);
  12191. size_t slen2 = strlen(conn->request_info.query_string);
  12192. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12193. target_url[slen1] = '?';
  12194. memcpy(target_url + slen1 + 1,
  12195. conn->request_info.query_string,
  12196. slen2);
  12197. target_url[slen1 + slen2 + 1] = 0;
  12198. } else {
  12199. truncated = 1;
  12200. }
  12201. }
  12202. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12203. * is used as buffer size) */
  12204. if (truncated) {
  12205. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12206. return;
  12207. }
  12208. /* Use redirect helper function */
  12209. mg_send_http_redirect(conn, target_url, redirect_code);
  12210. }
  12211. static void
  12212. mg_set_handler_type(struct mg_context *phys_ctx,
  12213. struct mg_domain_context *dom_ctx,
  12214. const char *uri,
  12215. int handler_type,
  12216. int is_delete_request,
  12217. mg_request_handler handler,
  12218. struct mg_websocket_subprotocols *subprotocols,
  12219. mg_websocket_connect_handler connect_handler,
  12220. mg_websocket_ready_handler ready_handler,
  12221. mg_websocket_data_handler data_handler,
  12222. mg_websocket_close_handler close_handler,
  12223. mg_authorization_handler auth_handler,
  12224. void *cbdata)
  12225. {
  12226. struct mg_handler_info *tmp_rh, **lastref;
  12227. size_t urilen = strlen(uri);
  12228. if (handler_type == WEBSOCKET_HANDLER) {
  12229. DEBUG_ASSERT(handler == NULL);
  12230. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12231. || ready_handler != NULL || data_handler != NULL
  12232. || close_handler != NULL);
  12233. DEBUG_ASSERT(auth_handler == NULL);
  12234. if (handler != NULL) {
  12235. return;
  12236. }
  12237. if (!is_delete_request && (connect_handler == NULL)
  12238. && (ready_handler == NULL) && (data_handler == NULL)
  12239. && (close_handler == NULL)) {
  12240. return;
  12241. }
  12242. if (auth_handler != NULL) {
  12243. return;
  12244. }
  12245. } else if (handler_type == REQUEST_HANDLER) {
  12246. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12247. && data_handler == NULL && close_handler == NULL);
  12248. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12249. DEBUG_ASSERT(auth_handler == NULL);
  12250. if ((connect_handler != NULL) || (ready_handler != NULL)
  12251. || (data_handler != NULL) || (close_handler != NULL)) {
  12252. return;
  12253. }
  12254. if (!is_delete_request && (handler == NULL)) {
  12255. return;
  12256. }
  12257. if (auth_handler != NULL) {
  12258. return;
  12259. }
  12260. } else if (handler_type == AUTH_HANDLER) {
  12261. DEBUG_ASSERT(handler == NULL);
  12262. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12263. && data_handler == NULL && close_handler == NULL);
  12264. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12265. if (handler != NULL) {
  12266. return;
  12267. }
  12268. if ((connect_handler != NULL) || (ready_handler != NULL)
  12269. || (data_handler != NULL) || (close_handler != NULL)) {
  12270. return;
  12271. }
  12272. if (!is_delete_request && (auth_handler == NULL)) {
  12273. return;
  12274. }
  12275. } else {
  12276. /* Unknown handler type. */
  12277. return;
  12278. }
  12279. if (!phys_ctx || !dom_ctx) {
  12280. /* no context available */
  12281. return;
  12282. }
  12283. mg_lock_context(phys_ctx);
  12284. /* first try to find an existing handler */
  12285. do {
  12286. lastref = &(dom_ctx->handlers);
  12287. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12288. tmp_rh = tmp_rh->next) {
  12289. if (tmp_rh->handler_type == handler_type
  12290. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12291. if (!is_delete_request) {
  12292. /* update existing handler */
  12293. if (handler_type == REQUEST_HANDLER) {
  12294. /* Wait for end of use before updating */
  12295. if (tmp_rh->refcount) {
  12296. mg_unlock_context(phys_ctx);
  12297. mg_sleep(1);
  12298. mg_lock_context(phys_ctx);
  12299. /* tmp_rh might have been freed, search again. */
  12300. break;
  12301. }
  12302. /* Ok, the handler is no more use -> Update it */
  12303. tmp_rh->handler = handler;
  12304. } else if (handler_type == WEBSOCKET_HANDLER) {
  12305. tmp_rh->subprotocols = subprotocols;
  12306. tmp_rh->connect_handler = connect_handler;
  12307. tmp_rh->ready_handler = ready_handler;
  12308. tmp_rh->data_handler = data_handler;
  12309. tmp_rh->close_handler = close_handler;
  12310. } else { /* AUTH_HANDLER */
  12311. tmp_rh->auth_handler = auth_handler;
  12312. }
  12313. tmp_rh->cbdata = cbdata;
  12314. } else {
  12315. /* remove existing handler */
  12316. if (handler_type == REQUEST_HANDLER) {
  12317. /* Wait for end of use before removing */
  12318. if (tmp_rh->refcount) {
  12319. tmp_rh->removing = 1;
  12320. mg_unlock_context(phys_ctx);
  12321. mg_sleep(1);
  12322. mg_lock_context(phys_ctx);
  12323. /* tmp_rh might have been freed, search again. */
  12324. break;
  12325. }
  12326. /* Ok, the handler is no more used */
  12327. }
  12328. *lastref = tmp_rh->next;
  12329. mg_free(tmp_rh->uri);
  12330. mg_free(tmp_rh);
  12331. }
  12332. mg_unlock_context(phys_ctx);
  12333. return;
  12334. }
  12335. lastref = &(tmp_rh->next);
  12336. }
  12337. } while (tmp_rh != NULL);
  12338. if (is_delete_request) {
  12339. /* no handler to set, this was a remove request to a non-existing
  12340. * handler */
  12341. mg_unlock_context(phys_ctx);
  12342. return;
  12343. }
  12344. tmp_rh =
  12345. (struct mg_handler_info *)mg_calloc_ctx(1,
  12346. sizeof(struct mg_handler_info),
  12347. phys_ctx);
  12348. if (tmp_rh == NULL) {
  12349. mg_unlock_context(phys_ctx);
  12350. mg_cry_ctx_internal(phys_ctx,
  12351. "%s",
  12352. "Cannot create new request handler struct, OOM");
  12353. return;
  12354. }
  12355. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12356. if (!tmp_rh->uri) {
  12357. mg_unlock_context(phys_ctx);
  12358. mg_free(tmp_rh);
  12359. mg_cry_ctx_internal(phys_ctx,
  12360. "%s",
  12361. "Cannot create new request handler struct, OOM");
  12362. return;
  12363. }
  12364. tmp_rh->uri_len = urilen;
  12365. if (handler_type == REQUEST_HANDLER) {
  12366. tmp_rh->refcount = 0;
  12367. tmp_rh->removing = 0;
  12368. tmp_rh->handler = handler;
  12369. } else if (handler_type == WEBSOCKET_HANDLER) {
  12370. tmp_rh->subprotocols = subprotocols;
  12371. tmp_rh->connect_handler = connect_handler;
  12372. tmp_rh->ready_handler = ready_handler;
  12373. tmp_rh->data_handler = data_handler;
  12374. tmp_rh->close_handler = close_handler;
  12375. } else { /* AUTH_HANDLER */
  12376. tmp_rh->auth_handler = auth_handler;
  12377. }
  12378. tmp_rh->cbdata = cbdata;
  12379. tmp_rh->handler_type = handler_type;
  12380. tmp_rh->next = NULL;
  12381. *lastref = tmp_rh;
  12382. mg_unlock_context(phys_ctx);
  12383. }
  12384. CIVETWEB_API void
  12385. mg_set_request_handler(struct mg_context *ctx,
  12386. const char *uri,
  12387. mg_request_handler handler,
  12388. void *cbdata)
  12389. {
  12390. mg_set_handler_type(ctx,
  12391. &(ctx->dd),
  12392. uri,
  12393. REQUEST_HANDLER,
  12394. handler == NULL,
  12395. handler,
  12396. NULL,
  12397. NULL,
  12398. NULL,
  12399. NULL,
  12400. NULL,
  12401. NULL,
  12402. cbdata);
  12403. }
  12404. CIVETWEB_API void
  12405. mg_set_websocket_handler(struct mg_context *ctx,
  12406. const char *uri,
  12407. mg_websocket_connect_handler connect_handler,
  12408. mg_websocket_ready_handler ready_handler,
  12409. mg_websocket_data_handler data_handler,
  12410. mg_websocket_close_handler close_handler,
  12411. void *cbdata)
  12412. {
  12413. mg_set_websocket_handler_with_subprotocols(ctx,
  12414. uri,
  12415. NULL,
  12416. connect_handler,
  12417. ready_handler,
  12418. data_handler,
  12419. close_handler,
  12420. cbdata);
  12421. }
  12422. CIVETWEB_API void
  12423. mg_set_websocket_handler_with_subprotocols(
  12424. struct mg_context *ctx,
  12425. const char *uri,
  12426. struct mg_websocket_subprotocols *subprotocols,
  12427. mg_websocket_connect_handler connect_handler,
  12428. mg_websocket_ready_handler ready_handler,
  12429. mg_websocket_data_handler data_handler,
  12430. mg_websocket_close_handler close_handler,
  12431. void *cbdata)
  12432. {
  12433. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12434. && (data_handler == NULL)
  12435. && (close_handler == NULL);
  12436. mg_set_handler_type(ctx,
  12437. &(ctx->dd),
  12438. uri,
  12439. WEBSOCKET_HANDLER,
  12440. is_delete_request,
  12441. NULL,
  12442. subprotocols,
  12443. connect_handler,
  12444. ready_handler,
  12445. data_handler,
  12446. close_handler,
  12447. NULL,
  12448. cbdata);
  12449. }
  12450. CIVETWEB_API void
  12451. mg_set_auth_handler(struct mg_context *ctx,
  12452. const char *uri,
  12453. mg_authorization_handler handler,
  12454. void *cbdata)
  12455. {
  12456. mg_set_handler_type(ctx,
  12457. &(ctx->dd),
  12458. uri,
  12459. AUTH_HANDLER,
  12460. handler == NULL,
  12461. NULL,
  12462. NULL,
  12463. NULL,
  12464. NULL,
  12465. NULL,
  12466. NULL,
  12467. handler,
  12468. cbdata);
  12469. }
  12470. static int
  12471. get_request_handler(struct mg_connection *conn,
  12472. int handler_type,
  12473. mg_request_handler *handler,
  12474. struct mg_websocket_subprotocols **subprotocols,
  12475. mg_websocket_connect_handler *connect_handler,
  12476. mg_websocket_ready_handler *ready_handler,
  12477. mg_websocket_data_handler *data_handler,
  12478. mg_websocket_close_handler *close_handler,
  12479. mg_authorization_handler *auth_handler,
  12480. void **cbdata,
  12481. struct mg_handler_info **handler_info)
  12482. {
  12483. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12484. if (request_info) {
  12485. const char *uri = request_info->local_uri;
  12486. size_t urilen = strlen(uri);
  12487. struct mg_handler_info *tmp_rh;
  12488. int step, matched;
  12489. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12490. return 0;
  12491. }
  12492. mg_lock_context(conn->phys_ctx);
  12493. for (step = 0; step < 3; step++) {
  12494. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12495. tmp_rh = tmp_rh->next) {
  12496. if (tmp_rh->handler_type != handler_type) {
  12497. continue;
  12498. }
  12499. if (step == 0) {
  12500. /* first try for an exact match */
  12501. matched = (tmp_rh->uri_len == urilen)
  12502. && (strcmp(tmp_rh->uri, uri) == 0);
  12503. } else if (step == 1) {
  12504. /* next try for a partial match, we will accept
  12505. uri/something */
  12506. matched =
  12507. (tmp_rh->uri_len < urilen)
  12508. && (uri[tmp_rh->uri_len] == '/')
  12509. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12510. } else {
  12511. /* finally try for pattern match */
  12512. matched =
  12513. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12514. }
  12515. if (matched) {
  12516. if (handler_type == WEBSOCKET_HANDLER) {
  12517. *subprotocols = tmp_rh->subprotocols;
  12518. *connect_handler = tmp_rh->connect_handler;
  12519. *ready_handler = tmp_rh->ready_handler;
  12520. *data_handler = tmp_rh->data_handler;
  12521. *close_handler = tmp_rh->close_handler;
  12522. } else if (handler_type == REQUEST_HANDLER) {
  12523. if (tmp_rh->removing) {
  12524. /* Treat as none found */
  12525. step = 2;
  12526. break;
  12527. }
  12528. *handler = tmp_rh->handler;
  12529. /* Acquire handler and give it back */
  12530. tmp_rh->refcount++;
  12531. *handler_info = tmp_rh;
  12532. } else { /* AUTH_HANDLER */
  12533. *auth_handler = tmp_rh->auth_handler;
  12534. }
  12535. *cbdata = tmp_rh->cbdata;
  12536. mg_unlock_context(conn->phys_ctx);
  12537. return 1;
  12538. }
  12539. }
  12540. }
  12541. mg_unlock_context(conn->phys_ctx);
  12542. }
  12543. return 0; /* none found */
  12544. }
  12545. /* Check if the script file is in a path, allowed for script files.
  12546. * This can be used if uploading files is possible not only for the server
  12547. * admin, and the upload mechanism does not check the file extension.
  12548. */
  12549. static int
  12550. is_in_script_path(const struct mg_connection *conn, const char *path)
  12551. {
  12552. /* TODO (Feature): Add config value for allowed script path.
  12553. * Default: All allowed. */
  12554. (void)conn;
  12555. (void)path;
  12556. return 1;
  12557. }
  12558. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12559. static int
  12560. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12561. int bits,
  12562. char *data,
  12563. size_t len,
  12564. void *cbdata)
  12565. {
  12566. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12567. if (pcallbacks->websocket_data) {
  12568. return pcallbacks->websocket_data(conn, bits, data, len);
  12569. }
  12570. /* No handler set - assume "OK" */
  12571. return 1;
  12572. }
  12573. static void
  12574. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12575. void *cbdata)
  12576. {
  12577. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12578. if (pcallbacks->connection_close) {
  12579. pcallbacks->connection_close(conn);
  12580. }
  12581. }
  12582. #endif
  12583. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12584. */
  12585. static void
  12586. release_handler_ref(struct mg_connection *conn,
  12587. struct mg_handler_info *handler_info)
  12588. {
  12589. if (handler_info != NULL) {
  12590. /* Use context lock for ref counter */
  12591. mg_lock_context(conn->phys_ctx);
  12592. handler_info->refcount--;
  12593. mg_unlock_context(conn->phys_ctx);
  12594. }
  12595. }
  12596. /* This is the heart of the Civetweb's logic.
  12597. * This function is called when the request is read, parsed and validated,
  12598. * and Civetweb must decide what action to take: serve a file, or
  12599. * a directory, or call embedded function, etcetera. */
  12600. static void
  12601. handle_request(struct mg_connection *conn)
  12602. {
  12603. struct mg_request_info *ri = &conn->request_info;
  12604. char path[UTF8_PATH_MAX];
  12605. int uri_len, ssl_index;
  12606. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12607. is_put_or_delete_request = 0, is_callback_resource = 0,
  12608. is_template_text_file = 0, is_webdav_request = 0;
  12609. int i;
  12610. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12611. mg_request_handler callback_handler = NULL;
  12612. struct mg_handler_info *handler_info = NULL;
  12613. struct mg_websocket_subprotocols *subprotocols;
  12614. mg_websocket_connect_handler ws_connect_handler = NULL;
  12615. mg_websocket_ready_handler ws_ready_handler = NULL;
  12616. mg_websocket_data_handler ws_data_handler = NULL;
  12617. mg_websocket_close_handler ws_close_handler = NULL;
  12618. void *callback_data = NULL;
  12619. mg_authorization_handler auth_handler = NULL;
  12620. void *auth_callback_data = NULL;
  12621. int handler_type;
  12622. time_t curtime = time(NULL);
  12623. char date[64];
  12624. char *tmp;
  12625. path[0] = 0;
  12626. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12627. conn->request_state = 0;
  12628. /* 1. get the request url */
  12629. /* 1.1. split into url and query string */
  12630. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12631. != NULL) {
  12632. *((char *)conn->request_info.query_string++) = '\0';
  12633. }
  12634. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12635. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12636. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12637. if (ssl_index >= 0) {
  12638. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12639. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12640. redirect_to_https_port(conn, port);
  12641. } else {
  12642. /* A http to https forward port has been specified,
  12643. * but no https port to forward to. */
  12644. mg_send_http_error(conn,
  12645. 503,
  12646. "%s",
  12647. "Error: SSL forward not configured properly");
  12648. mg_cry_internal(conn,
  12649. "%s",
  12650. "Can not redirect to SSL, no SSL port available");
  12651. }
  12652. return;
  12653. }
  12654. uri_len = (int)strlen(ri->local_uri);
  12655. /* 1.3. decode url (if config says so) */
  12656. if (should_decode_url(conn)) {
  12657. url_decode_in_place((char *)ri->local_uri);
  12658. }
  12659. /* URL decode the query-string only if explicity set in the configuration */
  12660. if (conn->request_info.query_string) {
  12661. if (should_decode_query_string(conn)) {
  12662. url_decode_in_place((char *)conn->request_info.query_string);
  12663. }
  12664. }
  12665. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12666. * possible. The fact that we cleaned the URI is stored in that the
  12667. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12668. * ri->local_uri_raw still points to memory allocated in
  12669. * worker_thread_run(). ri->local_uri is private to the request so we
  12670. * don't have to use preallocated memory here. */
  12671. tmp = mg_strdup(ri->local_uri_raw);
  12672. if (!tmp) {
  12673. /* Out of memory. We cannot do anything reasonable here. */
  12674. return;
  12675. }
  12676. remove_dot_segments(tmp);
  12677. ri->local_uri = tmp;
  12678. /* step 1. completed, the url is known now */
  12679. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12680. /* 2. if this ip has limited speed, set it for this connection */
  12681. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12682. &conn->client.rsa,
  12683. ri->local_uri);
  12684. /* 3. call a "handle everything" callback, if registered */
  12685. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12686. /* Note that since V1.7 the "begin_request" function is called
  12687. * before an authorization check. If an authorization check is
  12688. * required, use a request_handler instead. */
  12689. i = conn->phys_ctx->callbacks.begin_request(conn);
  12690. if (i > 0) {
  12691. /* callback already processed the request. Store the
  12692. return value as a status code for the access log. */
  12693. conn->status_code = i;
  12694. if (!conn->must_close) {
  12695. discard_unread_request_data(conn);
  12696. }
  12697. DEBUG_TRACE("%s", "begin_request handled request");
  12698. return;
  12699. } else if (i == 0) {
  12700. /* civetweb should process the request */
  12701. } else {
  12702. /* unspecified - may change with the next version */
  12703. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12704. return;
  12705. }
  12706. }
  12707. /* request not yet handled by a handler or redirect, so the request
  12708. * is processed here */
  12709. /* 4. Check for CORS preflight requests and handle them (if configured).
  12710. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12711. */
  12712. if (!strcmp(ri->request_method, "OPTIONS")) {
  12713. /* Send a response to CORS preflights only if
  12714. * access_control_allow_methods is not NULL and not an empty string.
  12715. * In this case, scripts can still handle CORS. */
  12716. const char *cors_meth_cfg =
  12717. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12718. const char *cors_orig_cfg =
  12719. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12720. const char *cors_origin =
  12721. get_header(ri->http_headers, ri->num_headers, "Origin");
  12722. const char *cors_acrm = get_header(ri->http_headers,
  12723. ri->num_headers,
  12724. "Access-Control-Request-Method");
  12725. /* Todo: check if cors_origin is in cors_orig_cfg.
  12726. * Or, let the client check this. */
  12727. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12728. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12729. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12730. /* This is a valid CORS preflight, and the server is configured
  12731. * to handle it automatically. */
  12732. const char *cors_acrh =
  12733. get_header(ri->http_headers,
  12734. ri->num_headers,
  12735. "Access-Control-Request-Headers");
  12736. gmt_time_string(date, sizeof(date), &curtime);
  12737. mg_printf(conn,
  12738. "HTTP/1.1 200 OK\r\n"
  12739. "Date: %s\r\n"
  12740. "Access-Control-Allow-Origin: %s\r\n"
  12741. "Access-Control-Allow-Methods: %s\r\n"
  12742. "Content-Length: 0\r\n"
  12743. "Connection: %s\r\n",
  12744. date,
  12745. cors_orig_cfg,
  12746. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12747. suggest_connection_header(conn));
  12748. if (cors_acrh != NULL) {
  12749. /* CORS request is asking for additional headers */
  12750. const char *cors_hdr_cfg =
  12751. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12752. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12753. /* Allow only if access_control_allow_headers is
  12754. * not NULL and not an empty string. If this
  12755. * configuration is set to *, allow everything.
  12756. * Otherwise this configuration must be a list
  12757. * of allowed HTTP header names. */
  12758. mg_printf(conn,
  12759. "Access-Control-Allow-Headers: %s\r\n",
  12760. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12761. : cors_hdr_cfg));
  12762. }
  12763. }
  12764. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12765. mg_printf(conn, "\r\n");
  12766. DEBUG_TRACE("%s", "OPTIONS done");
  12767. return;
  12768. }
  12769. }
  12770. /* 5. interpret the url to find out how the request must be handled
  12771. */
  12772. /* 5.1. first test, if the request targets the regular http(s)://
  12773. * protocol namespace or the websocket ws(s):// protocol namespace.
  12774. */
  12775. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12776. #if defined(USE_WEBSOCKET)
  12777. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12778. #else
  12779. handler_type = REQUEST_HANDLER;
  12780. #endif /* defined(USE_WEBSOCKET) */
  12781. if (is_websocket_request) {
  12782. HTTP1_only;
  12783. }
  12784. /* 5.2. check if the request will be handled by a callback */
  12785. if (get_request_handler(conn,
  12786. handler_type,
  12787. &callback_handler,
  12788. &subprotocols,
  12789. &ws_connect_handler,
  12790. &ws_ready_handler,
  12791. &ws_data_handler,
  12792. &ws_close_handler,
  12793. NULL,
  12794. &callback_data,
  12795. &handler_info)) {
  12796. /* 5.2.1. A callback will handle this request. All requests
  12797. * handled by a callback have to be considered as requests
  12798. * to a script resource. */
  12799. is_callback_resource = 1;
  12800. is_script_resource = 1;
  12801. is_put_or_delete_request = is_put_or_delete_method(conn);
  12802. /* Never handle a C callback according to File WebDav rules,
  12803. * even if it is a webdav method */
  12804. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12805. } else {
  12806. no_callback_resource:
  12807. /* 5.2.2. No callback is responsible for this request. The URI
  12808. * addresses a file based resource (static content or Lua/cgi
  12809. * scripts in the file system). */
  12810. is_callback_resource = 0;
  12811. interpret_uri(conn,
  12812. path,
  12813. sizeof(path),
  12814. &file.stat,
  12815. &is_found,
  12816. &is_script_resource,
  12817. &is_websocket_request,
  12818. &is_put_or_delete_request,
  12819. &is_webdav_request,
  12820. &is_template_text_file);
  12821. }
  12822. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12823. if (is_webdav_request) {
  12824. /* TODO: Do we need a config option? */
  12825. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  12826. if (webdav_enable[0] != 'y') {
  12827. mg_send_http_error(conn,
  12828. 405,
  12829. "%s method not allowed",
  12830. conn->request_info.request_method);
  12831. DEBUG_TRACE("%s", "webdav rejected");
  12832. return;
  12833. }
  12834. }
  12835. /* 6. authorization check */
  12836. /* 6.1. a custom authorization handler is installed */
  12837. if (get_request_handler(conn,
  12838. AUTH_HANDLER,
  12839. NULL,
  12840. NULL,
  12841. NULL,
  12842. NULL,
  12843. NULL,
  12844. NULL,
  12845. &auth_handler,
  12846. &auth_callback_data,
  12847. NULL)) {
  12848. if (!auth_handler(conn, auth_callback_data)) {
  12849. /* Callback handler will not be used anymore. Release it */
  12850. release_handler_ref(conn, handler_info);
  12851. DEBUG_TRACE("%s", "auth handler rejected request");
  12852. return;
  12853. }
  12854. } else if (is_put_or_delete_request && !is_script_resource
  12855. && !is_callback_resource) {
  12856. HTTP1_only;
  12857. /* 6.2. this request is a PUT/DELETE to a real file */
  12858. /* 6.2.1. thus, the server must have real files */
  12859. #if defined(NO_FILES)
  12860. if (1) {
  12861. #else
  12862. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12863. #endif
  12864. /* This code path will not be called for request handlers */
  12865. DEBUG_ASSERT(handler_info == NULL);
  12866. /* This server does not have any real files, thus the
  12867. * PUT/DELETE methods are not valid. */
  12868. mg_send_http_error(conn,
  12869. 405,
  12870. "%s method not allowed",
  12871. conn->request_info.request_method);
  12872. DEBUG_TRACE("%s", "all file based requests rejected");
  12873. return;
  12874. }
  12875. #if !defined(NO_FILES)
  12876. /* 6.2.2. Check if put authorization for static files is
  12877. * available.
  12878. */
  12879. if (!is_authorized_for_put(conn)) {
  12880. send_authorization_request(conn, NULL);
  12881. DEBUG_TRACE("%s", "file write needs authorization");
  12882. return;
  12883. }
  12884. #endif
  12885. } else {
  12886. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12887. * or it is a PUT or DELETE request to a resource that does not
  12888. * correspond to a file. Check authorization. */
  12889. if (!check_authorization(conn, path)) {
  12890. send_authorization_request(conn, NULL);
  12891. /* Callback handler will not be used anymore. Release it */
  12892. release_handler_ref(conn, handler_info);
  12893. DEBUG_TRACE("%s", "access authorization required");
  12894. return;
  12895. }
  12896. }
  12897. /* request is authorized or does not need authorization */
  12898. /* 7. check if there are request handlers for this uri */
  12899. if (is_callback_resource) {
  12900. HTTP1_only;
  12901. if (!is_websocket_request) {
  12902. i = callback_handler(conn, callback_data);
  12903. /* Callback handler will not be used anymore. Release it */
  12904. release_handler_ref(conn, handler_info);
  12905. if (i > 0) {
  12906. /* Do nothing, callback has served the request. Store
  12907. * then return value as status code for the log and discard
  12908. * all data from the client not used by the callback. */
  12909. conn->status_code = i;
  12910. if (!conn->must_close) {
  12911. discard_unread_request_data(conn);
  12912. }
  12913. } else {
  12914. /* The handler did NOT handle the request. */
  12915. /* Some proper reactions would be:
  12916. * a) close the connections without sending anything
  12917. * b) send a 404 not found
  12918. * c) try if there is a file matching the URI
  12919. * It would be possible to do a, b or c in the callback
  12920. * implementation, and return 1 - we cannot do anything
  12921. * here, that is not possible in the callback.
  12922. *
  12923. * TODO: What would be the best reaction here?
  12924. * (Note: The reaction may change, if there is a better
  12925. * idea.)
  12926. */
  12927. /* For the moment, use option c: We look for a proper file,
  12928. * but since a file request is not always a script resource,
  12929. * the authorization check might be different. */
  12930. callback_handler = NULL;
  12931. /* Here we are at a dead end:
  12932. * According to URI matching, a callback should be
  12933. * responsible for handling the request,
  12934. * we called it, but the callback declared itself
  12935. * not responsible.
  12936. * We use a goto here, to get out of this dead end,
  12937. * and continue with the default handling.
  12938. * A goto here is simpler and better to understand
  12939. * than some curious loop. */
  12940. goto no_callback_resource;
  12941. }
  12942. } else {
  12943. #if defined(USE_WEBSOCKET)
  12944. handle_websocket_request(conn,
  12945. path,
  12946. is_callback_resource,
  12947. subprotocols,
  12948. ws_connect_handler,
  12949. ws_ready_handler,
  12950. ws_data_handler,
  12951. ws_close_handler,
  12952. callback_data);
  12953. #endif
  12954. }
  12955. DEBUG_TRACE("%s", "websocket handling done");
  12956. return;
  12957. }
  12958. /* 8. handle websocket requests */
  12959. #if defined(USE_WEBSOCKET)
  12960. if (is_websocket_request) {
  12961. HTTP1_only;
  12962. if (is_script_resource) {
  12963. if (is_in_script_path(conn, path)) {
  12964. /* Websocket Lua script */
  12965. handle_websocket_request(conn,
  12966. path,
  12967. 0 /* Lua Script */,
  12968. NULL,
  12969. NULL,
  12970. NULL,
  12971. NULL,
  12972. NULL,
  12973. conn->phys_ctx->user_data);
  12974. } else {
  12975. /* Script was in an illegal path */
  12976. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12977. }
  12978. } else {
  12979. mg_send_http_error(conn, 404, "%s", "Not found");
  12980. }
  12981. DEBUG_TRACE("%s", "websocket script done");
  12982. return;
  12983. } else
  12984. #endif
  12985. #if defined(NO_FILES)
  12986. /* 9a. In case the server uses only callbacks, this uri is
  12987. * unknown.
  12988. * Then, all request handling ends here. */
  12989. mg_send_http_error(conn, 404, "%s", "Not Found");
  12990. #else
  12991. /* 9b. This request is either for a static file or resource handled
  12992. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12993. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12994. mg_send_http_error(conn, 404, "%s", "Not Found");
  12995. DEBUG_TRACE("%s", "no document root available");
  12996. return;
  12997. }
  12998. /* 10. Request is handled by a script */
  12999. if (is_script_resource) {
  13000. HTTP1_only;
  13001. handle_file_based_request(conn, path, &file);
  13002. DEBUG_TRACE("%s", "script handling done");
  13003. return;
  13004. }
  13005. /* Request was not handled by a callback or script. It will be
  13006. * handled by a server internal method. */
  13007. /* 11. Handle put/delete/mkcol requests */
  13008. if (is_put_or_delete_request) {
  13009. HTTP1_only;
  13010. /* 11.1. PUT method */
  13011. if (!strcmp(ri->request_method, "PUT")) {
  13012. put_file(conn, path);
  13013. DEBUG_TRACE("handling %s request to %s done",
  13014. ri->request_method,
  13015. path);
  13016. return;
  13017. }
  13018. /* 11.2. DELETE method */
  13019. if (!strcmp(ri->request_method, "DELETE")) {
  13020. delete_file(conn, path);
  13021. DEBUG_TRACE("handling %s request to %s done",
  13022. ri->request_method,
  13023. path);
  13024. return;
  13025. }
  13026. /* 11.3. MKCOL method */
  13027. if (!strcmp(ri->request_method, "MKCOL")) {
  13028. dav_mkcol(conn, path);
  13029. DEBUG_TRACE("handling %s request to %s done",
  13030. ri->request_method,
  13031. path);
  13032. return;
  13033. }
  13034. /* 11.4. MOVE method */
  13035. if (!strcmp(ri->request_method, "MOVE")) {
  13036. dav_move_file(conn, path, 0);
  13037. DEBUG_TRACE("handling %s request to %s done",
  13038. ri->request_method,
  13039. path);
  13040. return;
  13041. }
  13042. if (!strcmp(ri->request_method, "COPY")) {
  13043. dav_move_file(conn, path, 1);
  13044. DEBUG_TRACE("handling %s request to %s done",
  13045. ri->request_method,
  13046. path);
  13047. return;
  13048. }
  13049. /* 11.5. LOCK method */
  13050. if (!strcmp(ri->request_method, "LOCK")) {
  13051. dav_lock_file(conn, path);
  13052. DEBUG_TRACE("handling %s request to %s done",
  13053. ri->request_method,
  13054. path);
  13055. return;
  13056. }
  13057. /* 11.6. UNLOCK method */
  13058. if (!strcmp(ri->request_method, "UNLOCK")) {
  13059. dav_unlock_file(conn, path);
  13060. DEBUG_TRACE("handling %s request to %s done",
  13061. ri->request_method,
  13062. path);
  13063. return;
  13064. }
  13065. /* 11.7. PROPPATCH method */
  13066. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13067. dav_proppatch(conn, path);
  13068. DEBUG_TRACE("handling %s request to %s done",
  13069. ri->request_method,
  13070. path);
  13071. return;
  13072. }
  13073. /* 11.8. Other methods, e.g.: PATCH
  13074. * This method is not supported for static resources,
  13075. * only for scripts (Lua, CGI) and callbacks. */
  13076. mg_send_http_error(conn,
  13077. 405,
  13078. "%s method not allowed",
  13079. conn->request_info.request_method);
  13080. DEBUG_TRACE("method %s on %s is not supported",
  13081. ri->request_method,
  13082. path);
  13083. return;
  13084. }
  13085. /* 11. File does not exist, or it was configured that it should be
  13086. * hidden */
  13087. if (!is_found || (must_hide_file(conn, path))) {
  13088. mg_send_http_error(conn, 404, "%s", "Not found");
  13089. DEBUG_TRACE("handling %s request to %s: file not found",
  13090. ri->request_method,
  13091. path);
  13092. return;
  13093. }
  13094. /* 12. Directory uris should end with a slash */
  13095. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13096. && (ri->local_uri[uri_len - 1] != '/')) {
  13097. /* Path + server root */
  13098. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13099. char *new_path;
  13100. if (ri->query_string) {
  13101. buflen += strlen(ri->query_string);
  13102. }
  13103. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13104. if (!new_path) {
  13105. mg_send_http_error(conn, 500, "out or memory");
  13106. } else {
  13107. mg_get_request_link(conn, new_path, buflen - 1);
  13108. strcat(new_path, "/");
  13109. if (ri->query_string) {
  13110. /* Append ? and query string */
  13111. strcat(new_path, "?");
  13112. strcat(new_path, ri->query_string);
  13113. }
  13114. mg_send_http_redirect(conn, new_path, 301);
  13115. mg_free(new_path);
  13116. }
  13117. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13118. ri->request_method,
  13119. path);
  13120. return;
  13121. }
  13122. /* 13. Handle other methods than GET/HEAD */
  13123. /* 13.1. Handle PROPFIND */
  13124. if (!strcmp(ri->request_method, "PROPFIND")) {
  13125. handle_propfind(conn, path, &file.stat);
  13126. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13127. return;
  13128. }
  13129. /* 13.2. Handle OPTIONS for files */
  13130. if (!strcmp(ri->request_method, "OPTIONS")) {
  13131. /* This standard handler is only used for real files.
  13132. * Scripts should support the OPTIONS method themselves, to allow a
  13133. * maximum flexibility.
  13134. * Lua and CGI scripts may fully support CORS this way (including
  13135. * preflights). */
  13136. send_options(conn);
  13137. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13138. return;
  13139. }
  13140. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13141. if ((0 != strcmp(ri->request_method, "GET"))
  13142. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13143. mg_send_http_error(conn,
  13144. 405,
  13145. "%s method not allowed",
  13146. conn->request_info.request_method);
  13147. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13148. return;
  13149. }
  13150. /* 14. directories */
  13151. if (file.stat.is_directory) {
  13152. /* Substitute files have already been handled above. */
  13153. /* Here we can either generate and send a directory listing,
  13154. * or send an "access denied" error. */
  13155. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13156. "yes")) {
  13157. handle_directory_request(conn, path);
  13158. } else {
  13159. mg_send_http_error(conn,
  13160. 403,
  13161. "%s",
  13162. "Error: Directory listing denied");
  13163. }
  13164. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13165. return;
  13166. }
  13167. /* 15. Files with search/replace patterns: LSP and SSI */
  13168. if (is_template_text_file) {
  13169. HTTP1_only;
  13170. handle_file_based_request(conn, path, &file);
  13171. DEBUG_TRACE("handling %s request to %s done (template)",
  13172. ri->request_method,
  13173. path);
  13174. return;
  13175. }
  13176. /* 16. Static file - maybe cached */
  13177. #if !defined(NO_CACHING)
  13178. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13179. /* Send 304 "Not Modified" - this must not send any body data */
  13180. handle_not_modified_static_file_request(conn, &file);
  13181. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13182. ri->request_method,
  13183. path);
  13184. return;
  13185. }
  13186. #endif /* !NO_CACHING */
  13187. /* 17. Static file - not cached */
  13188. handle_static_file_request(conn, path, &file, NULL, NULL);
  13189. DEBUG_TRACE("handling %s request to %s done (static)",
  13190. ri->request_method,
  13191. path);
  13192. #endif /* !defined(NO_FILES) */
  13193. }
  13194. #if !defined(NO_FILESYSTEMS)
  13195. static void
  13196. handle_file_based_request(struct mg_connection *conn,
  13197. const char *path,
  13198. struct mg_file *file)
  13199. {
  13200. #if !defined(NO_CGI)
  13201. unsigned char cgi_config_idx, inc, max;
  13202. #endif
  13203. if (!conn || !conn->dom_ctx) {
  13204. return;
  13205. }
  13206. #if defined(USE_LUA)
  13207. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13208. path)
  13209. > 0) {
  13210. if (is_in_script_path(conn, path)) {
  13211. /* Lua server page: an SSI like page containing mostly plain
  13212. * html code plus some tags with server generated contents. */
  13213. handle_lsp_request(conn, path, file, NULL);
  13214. } else {
  13215. /* Script was in an illegal path */
  13216. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13217. }
  13218. return;
  13219. }
  13220. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13221. > 0) {
  13222. if (is_in_script_path(conn, path)) {
  13223. /* Lua in-server module script: a CGI like script used to
  13224. * generate the entire reply. */
  13225. mg_exec_lua_script(conn, path, NULL);
  13226. } else {
  13227. /* Script was in an illegal path */
  13228. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13229. }
  13230. return;
  13231. }
  13232. #endif
  13233. #if defined(USE_DUKTAPE)
  13234. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13235. path)
  13236. > 0) {
  13237. if (is_in_script_path(conn, path)) {
  13238. /* Call duktape to generate the page */
  13239. mg_exec_duktape_script(conn, path);
  13240. } else {
  13241. /* Script was in an illegal path */
  13242. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13243. }
  13244. return;
  13245. }
  13246. #endif
  13247. #if !defined(NO_CGI)
  13248. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13249. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13250. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13251. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13252. if (match_prefix_strlen(
  13253. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13254. path)
  13255. > 0) {
  13256. if (is_in_script_path(conn, path)) {
  13257. /* CGI scripts may support all HTTP methods */
  13258. handle_cgi_request(conn, path, cgi_config_idx);
  13259. } else {
  13260. /* Script was in an illegal path */
  13261. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13262. }
  13263. return;
  13264. }
  13265. }
  13266. }
  13267. #endif /* !NO_CGI */
  13268. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13269. if (is_in_script_path(conn, path)) {
  13270. handle_ssi_file_request(conn, path, file);
  13271. } else {
  13272. /* Script was in an illegal path */
  13273. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13274. }
  13275. return;
  13276. }
  13277. #if !defined(NO_CACHING)
  13278. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13279. /* Send 304 "Not Modified" - this must not send any body data */
  13280. handle_not_modified_static_file_request(conn, file);
  13281. return;
  13282. }
  13283. #endif /* !NO_CACHING */
  13284. handle_static_file_request(conn, path, file, NULL, NULL);
  13285. }
  13286. #endif /* NO_FILESYSTEMS */
  13287. static void
  13288. close_all_listening_sockets(struct mg_context *ctx)
  13289. {
  13290. unsigned int i;
  13291. if (!ctx) {
  13292. return;
  13293. }
  13294. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13295. closesocket(ctx->listening_sockets[i].sock);
  13296. #if defined(USE_X_DOM_SOCKET)
  13297. /* For unix domain sockets, the socket name represents a file that has
  13298. * to be deleted. */
  13299. /* See
  13300. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13301. */
  13302. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13303. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13304. IGNORE_UNUSED_RESULT(
  13305. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13306. }
  13307. #endif
  13308. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13309. }
  13310. mg_free(ctx->listening_sockets);
  13311. ctx->listening_sockets = NULL;
  13312. mg_free(ctx->listening_socket_fds);
  13313. ctx->listening_socket_fds = NULL;
  13314. }
  13315. /* Valid listening port specification is: [ip_address:]port[s]
  13316. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13317. * Examples for IPv6: [::]:80, [::1]:80,
  13318. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13319. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13320. * In order to bind to both, IPv4 and IPv6, you can either add
  13321. * both ports using 8080,[::]:8080, or the short form +8080.
  13322. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13323. * one only accepting IPv4 the other only IPv6. +8080 creates
  13324. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13325. * environment, they might work differently, or might not work
  13326. * at all - it must be tested what options work best in the
  13327. * relevant network environment.
  13328. */
  13329. static int
  13330. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13331. {
  13332. unsigned int a, b, c, d;
  13333. unsigned port;
  13334. unsigned long portUL;
  13335. int ch, len;
  13336. const char *cb;
  13337. char *endptr;
  13338. #if defined(USE_IPV6)
  13339. char buf[100] = {0};
  13340. #endif
  13341. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13342. * Also, all-zeroes in the socket address means binding to all addresses
  13343. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13344. memset(so, 0, sizeof(*so));
  13345. so->lsa.sin.sin_family = AF_INET;
  13346. *ip_version = 0;
  13347. /* Initialize len as invalid. */
  13348. port = 0;
  13349. len = 0;
  13350. /* Test for different ways to format this string */
  13351. if (sscanf(vec->ptr,
  13352. "%u.%u.%u.%u:%u%n",
  13353. &a,
  13354. &b,
  13355. &c,
  13356. &d,
  13357. &port,
  13358. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13359. // to an integer value, but function will not report
  13360. // conversion errors; consider using 'strtol' instead
  13361. == 5) {
  13362. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13363. so->lsa.sin.sin_addr.s_addr =
  13364. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13365. so->lsa.sin.sin_port = htons((uint16_t)port);
  13366. *ip_version = 4;
  13367. #if defined(USE_IPV6)
  13368. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13369. && ((size_t)len <= vec->len)
  13370. && mg_inet_pton(
  13371. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13372. /* IPv6 address, examples: see above */
  13373. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13374. */
  13375. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13376. *ip_version = 6;
  13377. #endif
  13378. } else if ((vec->ptr[0] == '+')
  13379. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13380. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13381. // string to an integer value, but function will not
  13382. // report conversion errors; consider using 'strtol'
  13383. // instead
  13384. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13385. /* Add 1 to len for the + character we skipped before */
  13386. len++;
  13387. #if defined(USE_IPV6)
  13388. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13389. so->lsa.sin6.sin6_family = AF_INET6;
  13390. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13391. *ip_version = 4 + 6;
  13392. #else
  13393. /* Bind to IPv4 only, since IPv6 is not built in. */
  13394. so->lsa.sin.sin_port = htons((uint16_t)port);
  13395. *ip_version = 4;
  13396. #endif
  13397. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13398. && (vec->ptr != endptr)) {
  13399. len = (int)(endptr - vec->ptr);
  13400. port = (uint16_t)portUL;
  13401. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13402. so->lsa.sin.sin_port = htons((uint16_t)port);
  13403. *ip_version = 4;
  13404. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13405. /* String could be a hostname. This check algotithm
  13406. * will only work for RFC 952 compliant hostnames,
  13407. * starting with a letter, containing only letters,
  13408. * digits and hyphen ('-'). Newer specs may allow
  13409. * more, but this is not guaranteed here, since it
  13410. * may interfere with rules for port option lists. */
  13411. /* According to RFC 1035, hostnames are restricted to 255 characters
  13412. * in total (63 between two dots). */
  13413. char hostname[256];
  13414. size_t hostnlen = (size_t)(cb - vec->ptr);
  13415. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13416. /* This would be invalid in any case */
  13417. *ip_version = 0;
  13418. return 0;
  13419. }
  13420. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13421. if (mg_inet_pton(
  13422. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13423. if (sscanf(cb + 1, "%u%n", &port, &len)
  13424. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13425. // string to an integer value, but function will not
  13426. // report conversion errors; consider using 'strtol'
  13427. // instead
  13428. *ip_version = 4;
  13429. so->lsa.sin.sin_port = htons((uint16_t)port);
  13430. len += (int)(hostnlen + 1);
  13431. } else {
  13432. len = 0;
  13433. }
  13434. #if defined(USE_IPV6)
  13435. } else if (mg_inet_pton(AF_INET6,
  13436. hostname,
  13437. &so->lsa.sin6,
  13438. sizeof(so->lsa.sin6),
  13439. 1)) {
  13440. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13441. *ip_version = 6;
  13442. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13443. len += (int)(hostnlen + 1);
  13444. } else {
  13445. len = 0;
  13446. }
  13447. #endif
  13448. } else {
  13449. len = 0;
  13450. }
  13451. #if defined(USE_X_DOM_SOCKET)
  13452. } else if (vec->ptr[0] == 'x') {
  13453. /* unix (linux) domain socket */
  13454. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13455. len = vec->len;
  13456. so->lsa.sun.sun_family = AF_UNIX;
  13457. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13458. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13459. port = 0;
  13460. *ip_version = 99;
  13461. } else {
  13462. /* String too long */
  13463. len = 0;
  13464. }
  13465. #endif
  13466. } else {
  13467. /* Parsing failure. */
  13468. len = 0;
  13469. }
  13470. /* sscanf and the option splitting code ensure the following condition
  13471. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13472. if ((len > 0) && is_valid_port(port)
  13473. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13474. /* Next character after the port number */
  13475. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13476. so->is_ssl = (ch == 's');
  13477. so->ssl_redir = (ch == 'r');
  13478. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13479. return 1;
  13480. }
  13481. }
  13482. /* Reset ip_version to 0 if there is an error */
  13483. *ip_version = 0;
  13484. return 0;
  13485. }
  13486. /* Is there any SSL port in use? */
  13487. static int
  13488. is_ssl_port_used(const char *ports)
  13489. {
  13490. if (ports) {
  13491. /* There are several different allowed syntax variants:
  13492. * - "80" for a single port using every network interface
  13493. * - "localhost:80" for a single port using only localhost
  13494. * - "80,localhost:8080" for two ports, one bound to localhost
  13495. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13496. * to IPv4 localhost, one to IPv6 localhost
  13497. * - "+80" use port 80 for IPv4 and IPv6
  13498. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13499. * for both: IPv4 and IPv4
  13500. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13501. * additionally port 8080 bound to localhost connections
  13502. *
  13503. * If we just look for 's' anywhere in the string, "localhost:80"
  13504. * will be detected as SSL (false positive).
  13505. * Looking for 's' after a digit may cause false positives in
  13506. * "my24service:8080".
  13507. * Looking from 's' backward if there are only ':' and numbers
  13508. * before will not work for "24service:8080" (non SSL, port 8080)
  13509. * or "24s" (SSL, port 24).
  13510. *
  13511. * Remark: Initially hostnames were not allowed to start with a
  13512. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13513. * Section 2.1).
  13514. *
  13515. * To get this correct, the entire string must be parsed as a whole,
  13516. * reading it as a list element for element and parsing with an
  13517. * algorithm equivalent to parse_port_string.
  13518. *
  13519. * In fact, we use local interface names here, not arbitrary
  13520. * hostnames, so in most cases the only name will be "localhost".
  13521. *
  13522. * So, for now, we use this simple algorithm, that may still return
  13523. * a false positive in bizarre cases.
  13524. */
  13525. int i;
  13526. int portslen = (int)strlen(ports);
  13527. char prevIsNumber = 0;
  13528. for (i = 0; i < portslen; i++) {
  13529. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13530. return 1;
  13531. }
  13532. if (ports[i] >= '0' && ports[i] <= '9') {
  13533. prevIsNumber = 1;
  13534. } else {
  13535. prevIsNumber = 0;
  13536. }
  13537. }
  13538. }
  13539. return 0;
  13540. }
  13541. static int
  13542. set_ports_option(struct mg_context *phys_ctx)
  13543. {
  13544. const char *list;
  13545. int on = 1;
  13546. #if defined(USE_IPV6)
  13547. int off = 0;
  13548. #endif
  13549. struct vec vec;
  13550. struct socket so, *ptr;
  13551. struct mg_pollfd *pfd;
  13552. union usa usa;
  13553. socklen_t len;
  13554. int ip_version;
  13555. int portsTotal = 0;
  13556. int portsOk = 0;
  13557. const char *opt_txt;
  13558. long opt_listen_backlog;
  13559. if (!phys_ctx) {
  13560. return 0;
  13561. }
  13562. memset(&so, 0, sizeof(so));
  13563. memset(&usa, 0, sizeof(usa));
  13564. len = sizeof(usa);
  13565. list = phys_ctx->dd.config[LISTENING_PORTS];
  13566. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13567. portsTotal++;
  13568. if (!parse_port_string(&vec, &so, &ip_version)) {
  13569. mg_cry_ctx_internal(
  13570. phys_ctx,
  13571. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13572. (int)vec.len,
  13573. vec.ptr,
  13574. portsTotal,
  13575. "[IP_ADDRESS:]PORT[s|r]");
  13576. continue;
  13577. }
  13578. #if !defined(NO_SSL)
  13579. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13580. mg_cry_ctx_internal(phys_ctx,
  13581. "Cannot add SSL socket (entry %i)",
  13582. portsTotal);
  13583. continue;
  13584. }
  13585. #endif
  13586. /* Create socket. */
  13587. /* For a list of protocol numbers (e.g., TCP==6) see:
  13588. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13589. */
  13590. if ((so.sock =
  13591. socket(so.lsa.sa.sa_family,
  13592. SOCK_STREAM,
  13593. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13594. == INVALID_SOCKET) {
  13595. mg_cry_ctx_internal(phys_ctx,
  13596. "cannot create socket (entry %i)",
  13597. portsTotal);
  13598. continue;
  13599. }
  13600. #if defined(_WIN32)
  13601. /* Windows SO_REUSEADDR lets many procs binds to a
  13602. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13603. * if someone already has the socket -- DTL */
  13604. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13605. * Windows might need a few seconds before
  13606. * the same port can be used again in the
  13607. * same process, so a short Sleep may be
  13608. * required between mg_stop and mg_start.
  13609. */
  13610. if (setsockopt(so.sock,
  13611. SOL_SOCKET,
  13612. SO_EXCLUSIVEADDRUSE,
  13613. (SOCK_OPT_TYPE)&on,
  13614. sizeof(on))
  13615. != 0) {
  13616. /* Set reuse option, but don't abort on errors. */
  13617. mg_cry_ctx_internal(
  13618. phys_ctx,
  13619. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13620. portsTotal);
  13621. }
  13622. #else
  13623. if (setsockopt(so.sock,
  13624. SOL_SOCKET,
  13625. SO_REUSEADDR,
  13626. (SOCK_OPT_TYPE)&on,
  13627. sizeof(on))
  13628. != 0) {
  13629. /* Set reuse option, but don't abort on errors. */
  13630. mg_cry_ctx_internal(
  13631. phys_ctx,
  13632. "cannot set socket option SO_REUSEADDR (entry %i)",
  13633. portsTotal);
  13634. }
  13635. #endif
  13636. #if defined(USE_X_DOM_SOCKET)
  13637. if (ip_version == 99) {
  13638. /* Unix domain socket */
  13639. } else
  13640. #endif
  13641. if (ip_version > 4) {
  13642. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13643. #if defined(USE_IPV6)
  13644. if (ip_version > 6) {
  13645. if (so.lsa.sa.sa_family == AF_INET6
  13646. && setsockopt(so.sock,
  13647. IPPROTO_IPV6,
  13648. IPV6_V6ONLY,
  13649. (void *)&off,
  13650. sizeof(off))
  13651. != 0) {
  13652. /* Set IPv6 only option, but don't abort on errors. */
  13653. mg_cry_ctx_internal(phys_ctx,
  13654. "cannot set socket option "
  13655. "IPV6_V6ONLY=off (entry %i)",
  13656. portsTotal);
  13657. }
  13658. } else {
  13659. if (so.lsa.sa.sa_family == AF_INET6
  13660. && setsockopt(so.sock,
  13661. IPPROTO_IPV6,
  13662. IPV6_V6ONLY,
  13663. (void *)&on,
  13664. sizeof(on))
  13665. != 0) {
  13666. /* Set IPv6 only option, but don't abort on errors. */
  13667. mg_cry_ctx_internal(phys_ctx,
  13668. "cannot set socket option "
  13669. "IPV6_V6ONLY=on (entry %i)",
  13670. portsTotal);
  13671. }
  13672. }
  13673. #else
  13674. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13675. closesocket(so.sock);
  13676. so.sock = INVALID_SOCKET;
  13677. continue;
  13678. #endif
  13679. }
  13680. if (so.lsa.sa.sa_family == AF_INET) {
  13681. len = sizeof(so.lsa.sin);
  13682. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13683. mg_cry_ctx_internal(phys_ctx,
  13684. "cannot bind to %.*s: %d (%s)",
  13685. (int)vec.len,
  13686. vec.ptr,
  13687. (int)ERRNO,
  13688. strerror(errno));
  13689. closesocket(so.sock);
  13690. so.sock = INVALID_SOCKET;
  13691. continue;
  13692. }
  13693. }
  13694. #if defined(USE_IPV6)
  13695. else if (so.lsa.sa.sa_family == AF_INET6) {
  13696. len = sizeof(so.lsa.sin6);
  13697. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13698. mg_cry_ctx_internal(phys_ctx,
  13699. "cannot bind to IPv6 %.*s: %d (%s)",
  13700. (int)vec.len,
  13701. vec.ptr,
  13702. (int)ERRNO,
  13703. strerror(errno));
  13704. closesocket(so.sock);
  13705. so.sock = INVALID_SOCKET;
  13706. continue;
  13707. }
  13708. }
  13709. #endif
  13710. #if defined(USE_X_DOM_SOCKET)
  13711. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13712. len = sizeof(so.lsa.sun);
  13713. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13714. mg_cry_ctx_internal(phys_ctx,
  13715. "cannot bind to unix socket %s: %d (%s)",
  13716. so.lsa.sun.sun_path,
  13717. (int)ERRNO,
  13718. strerror(errno));
  13719. closesocket(so.sock);
  13720. so.sock = INVALID_SOCKET;
  13721. continue;
  13722. }
  13723. }
  13724. #endif
  13725. else {
  13726. mg_cry_ctx_internal(
  13727. phys_ctx,
  13728. "cannot bind: address family not supported (entry %i)",
  13729. portsTotal);
  13730. closesocket(so.sock);
  13731. so.sock = INVALID_SOCKET;
  13732. continue;
  13733. }
  13734. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13735. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13736. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13737. mg_cry_ctx_internal(phys_ctx,
  13738. "%s value \"%s\" is invalid",
  13739. config_options[LISTEN_BACKLOG_SIZE].name,
  13740. opt_txt);
  13741. closesocket(so.sock);
  13742. so.sock = INVALID_SOCKET;
  13743. continue;
  13744. }
  13745. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13746. mg_cry_ctx_internal(phys_ctx,
  13747. "cannot listen to %.*s: %d (%s)",
  13748. (int)vec.len,
  13749. vec.ptr,
  13750. (int)ERRNO,
  13751. strerror(errno));
  13752. closesocket(so.sock);
  13753. so.sock = INVALID_SOCKET;
  13754. continue;
  13755. }
  13756. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13757. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13758. int err = (int)ERRNO;
  13759. mg_cry_ctx_internal(phys_ctx,
  13760. "call to getsockname failed %.*s: %d (%s)",
  13761. (int)vec.len,
  13762. vec.ptr,
  13763. err,
  13764. strerror(errno));
  13765. closesocket(so.sock);
  13766. so.sock = INVALID_SOCKET;
  13767. continue;
  13768. }
  13769. /* Update lsa port in case of random free ports */
  13770. #if defined(USE_IPV6)
  13771. if (so.lsa.sa.sa_family == AF_INET6) {
  13772. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13773. } else
  13774. #endif
  13775. {
  13776. so.lsa.sin.sin_port = usa.sin.sin_port;
  13777. }
  13778. if ((ptr = (struct socket *)
  13779. mg_realloc_ctx(phys_ctx->listening_sockets,
  13780. (phys_ctx->num_listening_sockets + 1)
  13781. * sizeof(phys_ctx->listening_sockets[0]),
  13782. phys_ctx))
  13783. == NULL) {
  13784. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13785. closesocket(so.sock);
  13786. so.sock = INVALID_SOCKET;
  13787. continue;
  13788. }
  13789. if ((pfd = (struct mg_pollfd *)
  13790. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13791. (phys_ctx->num_listening_sockets + 1)
  13792. * sizeof(phys_ctx->listening_socket_fds[0]),
  13793. phys_ctx))
  13794. == NULL) {
  13795. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13796. closesocket(so.sock);
  13797. so.sock = INVALID_SOCKET;
  13798. mg_free(ptr);
  13799. continue;
  13800. }
  13801. set_close_on_exec(so.sock, NULL, phys_ctx);
  13802. phys_ctx->listening_sockets = ptr;
  13803. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13804. phys_ctx->listening_socket_fds = pfd;
  13805. phys_ctx->num_listening_sockets++;
  13806. portsOk++;
  13807. }
  13808. if (portsOk != portsTotal) {
  13809. close_all_listening_sockets(phys_ctx);
  13810. portsOk = 0;
  13811. }
  13812. return portsOk;
  13813. }
  13814. static const char *
  13815. header_val(const struct mg_connection *conn, const char *header)
  13816. {
  13817. const char *header_value;
  13818. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13819. return "-";
  13820. } else {
  13821. return header_value;
  13822. }
  13823. }
  13824. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13825. #include "external_log_access.inl"
  13826. #elif !defined(NO_FILESYSTEMS)
  13827. static void
  13828. log_access(const struct mg_connection *conn)
  13829. {
  13830. const struct mg_request_info *ri;
  13831. struct mg_file fi;
  13832. char date[64], src_addr[IP_ADDR_STR_LEN];
  13833. #if defined(REENTRANT_TIME)
  13834. struct tm _tm;
  13835. struct tm *tm = &_tm;
  13836. #else
  13837. struct tm *tm;
  13838. #endif
  13839. const char *referer;
  13840. const char *user_agent;
  13841. char log_buf[4096];
  13842. if (!conn || !conn->dom_ctx) {
  13843. return;
  13844. }
  13845. /* Set log message to "empty" */
  13846. log_buf[0] = 0;
  13847. #if defined(USE_LUA)
  13848. if (conn->phys_ctx->lua_bg_log_available) {
  13849. int ret;
  13850. struct mg_context *ctx = conn->phys_ctx;
  13851. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13852. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13853. /* call "log()" in Lua */
  13854. lua_getglobal(lstate, "log");
  13855. prepare_lua_request_info_inner(conn, lstate);
  13856. push_lua_response_log_data(conn, lstate);
  13857. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13858. if (ret == 0) {
  13859. int t = lua_type(lstate, -1);
  13860. if (t == LUA_TBOOLEAN) {
  13861. if (lua_toboolean(lstate, -1) == 0) {
  13862. /* log() returned false: do not log */
  13863. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13864. return;
  13865. }
  13866. /* log returned true: continue logging */
  13867. } else if (t == LUA_TSTRING) {
  13868. size_t len;
  13869. const char *txt = lua_tolstring(lstate, -1, &len);
  13870. if ((len == 0) || (*txt == 0)) {
  13871. /* log() returned empty string: do not log */
  13872. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13873. return;
  13874. }
  13875. /* Copy test from Lua into log_buf */
  13876. if (len >= sizeof(log_buf)) {
  13877. len = sizeof(log_buf) - 1;
  13878. }
  13879. memcpy(log_buf, txt, len);
  13880. log_buf[len] = 0;
  13881. }
  13882. } else {
  13883. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13884. }
  13885. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13886. }
  13887. #endif
  13888. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13889. if (mg_fopen(conn,
  13890. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13891. MG_FOPEN_MODE_APPEND,
  13892. &fi)
  13893. == 0) {
  13894. fi.access.fp = NULL;
  13895. }
  13896. } else {
  13897. fi.access.fp = NULL;
  13898. }
  13899. /* Log is written to a file and/or a callback. If both are not set,
  13900. * executing the rest of the function is pointless. */
  13901. if ((fi.access.fp == NULL)
  13902. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13903. return;
  13904. }
  13905. /* If we did not get a log message from Lua, create it here. */
  13906. if (!log_buf[0]) {
  13907. #if defined(REENTRANT_TIME)
  13908. localtime_r(&conn->conn_birth_time, tm);
  13909. #else
  13910. tm = localtime(&conn->conn_birth_time);
  13911. #endif
  13912. if (tm != NULL) {
  13913. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13914. } else {
  13915. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13916. date[sizeof(date) - 1] = '\0';
  13917. }
  13918. ri = &conn->request_info;
  13919. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13920. referer = header_val(conn, "Referer");
  13921. user_agent = header_val(conn, "User-Agent");
  13922. mg_snprintf(conn,
  13923. NULL, /* Ignore truncation in access log */
  13924. log_buf,
  13925. sizeof(log_buf),
  13926. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13927. " %s %s",
  13928. src_addr,
  13929. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13930. date,
  13931. ri->request_method ? ri->request_method : "-",
  13932. ri->request_uri ? ri->request_uri : "-",
  13933. ri->query_string ? "?" : "",
  13934. ri->query_string ? ri->query_string : "",
  13935. ri->http_version,
  13936. conn->status_code,
  13937. conn->num_bytes_sent,
  13938. referer,
  13939. user_agent);
  13940. }
  13941. /* Here we have a log message in log_buf. Call the callback */
  13942. if (conn->phys_ctx->callbacks.log_access) {
  13943. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13944. /* do not log if callack returns non-zero */
  13945. if (fi.access.fp) {
  13946. mg_fclose(&fi.access);
  13947. }
  13948. return;
  13949. }
  13950. }
  13951. /* Store in file */
  13952. if (fi.access.fp) {
  13953. int ok = 1;
  13954. flockfile(fi.access.fp);
  13955. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13956. ok = 0;
  13957. }
  13958. if (fflush(fi.access.fp) != 0) {
  13959. ok = 0;
  13960. }
  13961. funlockfile(fi.access.fp);
  13962. if (mg_fclose(&fi.access) != 0) {
  13963. ok = 0;
  13964. }
  13965. if (!ok) {
  13966. mg_cry_internal(conn,
  13967. "Error writing log file %s",
  13968. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13969. }
  13970. }
  13971. }
  13972. #else
  13973. #error "Either enable filesystems or provide a custom log_access implementation"
  13974. #endif /* Externally provided function */
  13975. /* Verify given socket address against the ACL.
  13976. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13977. */
  13978. static int
  13979. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13980. {
  13981. int allowed, flag, matched;
  13982. struct vec vec;
  13983. if (phys_ctx) {
  13984. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13985. /* If any ACL is set, deny by default */
  13986. allowed = (list == NULL) ? '+' : '-';
  13987. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13988. flag = vec.ptr[0];
  13989. matched = -1;
  13990. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13991. vec.ptr++;
  13992. vec.len--;
  13993. matched = parse_match_net(&vec, sa, 1);
  13994. }
  13995. if (matched < 0) {
  13996. mg_cry_ctx_internal(phys_ctx,
  13997. "%s: subnet must be [+|-]IP-addr[/x]",
  13998. __func__);
  13999. return -1;
  14000. }
  14001. if (matched) {
  14002. allowed = flag;
  14003. }
  14004. }
  14005. return allowed == '+';
  14006. }
  14007. return -1;
  14008. }
  14009. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14010. static int
  14011. set_uid_option(struct mg_context *phys_ctx)
  14012. {
  14013. int success = 0;
  14014. if (phys_ctx) {
  14015. /* We are currently running as curr_uid. */
  14016. const uid_t curr_uid = getuid();
  14017. /* If set, we want to run as run_as_user. */
  14018. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14019. const struct passwd *to_pw = NULL;
  14020. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14021. /* run_as_user does not exist on the system. We can't proceed
  14022. * further. */
  14023. mg_cry_ctx_internal(phys_ctx,
  14024. "%s: unknown user [%s]",
  14025. __func__,
  14026. run_as_user);
  14027. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14028. /* There was either no request to change user, or we're already
  14029. * running as run_as_user. Nothing else to do.
  14030. */
  14031. success = 1;
  14032. } else {
  14033. /* Valid change request. */
  14034. if (setgid(to_pw->pw_gid) == -1) {
  14035. mg_cry_ctx_internal(phys_ctx,
  14036. "%s: setgid(%s): %s",
  14037. __func__,
  14038. run_as_user,
  14039. strerror(errno));
  14040. } else if (setgroups(0, NULL) == -1) {
  14041. mg_cry_ctx_internal(phys_ctx,
  14042. "%s: setgroups(): %s",
  14043. __func__,
  14044. strerror(errno));
  14045. } else if (setuid(to_pw->pw_uid) == -1) {
  14046. mg_cry_ctx_internal(phys_ctx,
  14047. "%s: setuid(%s): %s",
  14048. __func__,
  14049. run_as_user,
  14050. strerror(errno));
  14051. } else {
  14052. success = 1;
  14053. }
  14054. }
  14055. }
  14056. return success;
  14057. }
  14058. #endif /* !_WIN32 */
  14059. static void
  14060. tls_dtor(void *key)
  14061. {
  14062. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14063. /* key == pthread_getspecific(sTlsKey); */
  14064. if (tls) {
  14065. if (tls->is_master == 2) {
  14066. tls->is_master = -3; /* Mark memory as dead */
  14067. mg_free(tls);
  14068. }
  14069. }
  14070. pthread_setspecific(sTlsKey, NULL);
  14071. }
  14072. #if defined(USE_MBEDTLS)
  14073. /* Check if SSL is required.
  14074. * If so, set up ctx->ssl_ctx pointer. */
  14075. static int
  14076. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14077. {
  14078. if (!phys_ctx) {
  14079. return 0;
  14080. }
  14081. if (!dom_ctx) {
  14082. dom_ctx = &(phys_ctx->dd);
  14083. }
  14084. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14085. /* No SSL port is set. No need to setup SSL. */
  14086. return 1;
  14087. }
  14088. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14089. if (dom_ctx->ssl_ctx == NULL) {
  14090. fprintf(stderr, "ssl_ctx malloc failed\n");
  14091. return 0;
  14092. }
  14093. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14094. == 0
  14095. ? 1
  14096. : 0;
  14097. }
  14098. #elif !defined(NO_SSL)
  14099. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14100. struct mg_domain_context *dom_ctx,
  14101. const char *pem,
  14102. const char *chain);
  14103. static const char *ssl_error(void);
  14104. static int
  14105. refresh_trust(struct mg_connection *conn)
  14106. {
  14107. struct stat cert_buf;
  14108. int64_t t = 0;
  14109. const char *pem;
  14110. const char *chain;
  14111. int should_verify_peer;
  14112. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14113. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14114. * refresh_trust still can not work. */
  14115. return 0;
  14116. }
  14117. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14118. if (chain == NULL) {
  14119. /* pem is not NULL here */
  14120. chain = pem;
  14121. }
  14122. if (*chain == 0) {
  14123. chain = NULL;
  14124. }
  14125. if (stat(pem, &cert_buf) != -1) {
  14126. t = (int64_t)cert_buf.st_mtime;
  14127. }
  14128. mg_lock_context(conn->phys_ctx);
  14129. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14130. conn->dom_ctx->ssl_cert_last_mtime = t;
  14131. should_verify_peer = 0;
  14132. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14133. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14134. == 0) {
  14135. should_verify_peer = 1;
  14136. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14137. "optional")
  14138. == 0) {
  14139. should_verify_peer = 1;
  14140. }
  14141. }
  14142. if (should_verify_peer) {
  14143. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14144. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14145. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14146. ca_file,
  14147. ca_path)
  14148. != 1) {
  14149. mg_unlock_context(conn->phys_ctx);
  14150. mg_cry_ctx_internal(
  14151. conn->phys_ctx,
  14152. "SSL_CTX_load_verify_locations error: %s "
  14153. "ssl_verify_peer requires setting "
  14154. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14155. "present in "
  14156. "the .conf file?",
  14157. ssl_error());
  14158. return 0;
  14159. }
  14160. }
  14161. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14162. mg_unlock_context(conn->phys_ctx);
  14163. return 0;
  14164. }
  14165. }
  14166. mg_unlock_context(conn->phys_ctx);
  14167. return 1;
  14168. }
  14169. #if defined(OPENSSL_API_1_1)
  14170. #else
  14171. static pthread_mutex_t *ssl_mutexes;
  14172. #endif /* OPENSSL_API_1_1 */
  14173. static int
  14174. sslize(struct mg_connection *conn,
  14175. int (*func)(SSL *),
  14176. const struct mg_client_options *client_options)
  14177. {
  14178. int ret, err;
  14179. int short_trust;
  14180. unsigned timeout = 1024;
  14181. unsigned i;
  14182. if (!conn) {
  14183. return 0;
  14184. }
  14185. short_trust =
  14186. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14187. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14188. if (short_trust) {
  14189. int trust_ret = refresh_trust(conn);
  14190. if (!trust_ret) {
  14191. return trust_ret;
  14192. }
  14193. }
  14194. mg_lock_context(conn->phys_ctx);
  14195. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14196. mg_unlock_context(conn->phys_ctx);
  14197. if (conn->ssl == NULL) {
  14198. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14199. OPENSSL_REMOVE_THREAD_STATE();
  14200. return 0;
  14201. }
  14202. SSL_set_app_data(conn->ssl, (char *)conn);
  14203. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14204. if (ret != 1) {
  14205. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14206. SSL_free(conn->ssl);
  14207. conn->ssl = NULL;
  14208. OPENSSL_REMOVE_THREAD_STATE();
  14209. return 0;
  14210. }
  14211. if (client_options) {
  14212. if (client_options->host_name) {
  14213. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14214. }
  14215. }
  14216. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14217. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14218. /* NOTE: The loop below acts as a back-off, so we can end
  14219. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14220. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14221. if (to >= 0) {
  14222. timeout = (unsigned)to;
  14223. }
  14224. }
  14225. /* SSL functions may fail and require to be called again:
  14226. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14227. * Here "func" could be SSL_connect or SSL_accept. */
  14228. for (i = 0; i <= timeout; i += 50) {
  14229. ERR_clear_error();
  14230. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14231. ret = func(conn->ssl);
  14232. if (ret != 1) {
  14233. err = SSL_get_error(conn->ssl, ret);
  14234. if ((err == SSL_ERROR_WANT_CONNECT)
  14235. || (err == SSL_ERROR_WANT_ACCEPT)
  14236. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14237. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14238. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14239. /* Don't wait if the server is going to be stopped. */
  14240. break;
  14241. }
  14242. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14243. /* Simply retry the function call. */
  14244. mg_sleep(50);
  14245. } else {
  14246. /* Need to retry the function call "later".
  14247. * See https://linux.die.net/man/3/ssl_get_error
  14248. * This is typical for non-blocking sockets. */
  14249. struct mg_pollfd pfd;
  14250. int pollres;
  14251. pfd.fd = conn->client.sock;
  14252. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14253. || (err == SSL_ERROR_WANT_WRITE))
  14254. ? POLLOUT
  14255. : POLLIN;
  14256. pollres =
  14257. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14258. if (pollres < 0) {
  14259. /* Break if error occured (-1)
  14260. * or server shutdown (-2) */
  14261. break;
  14262. }
  14263. }
  14264. } else if (err == SSL_ERROR_SYSCALL) {
  14265. /* This is an IO error. Look at errno. */
  14266. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14267. break;
  14268. } else {
  14269. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14270. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14271. break;
  14272. }
  14273. } else {
  14274. /* success */
  14275. break;
  14276. }
  14277. }
  14278. ERR_clear_error();
  14279. if (ret != 1) {
  14280. SSL_free(conn->ssl);
  14281. conn->ssl = NULL;
  14282. OPENSSL_REMOVE_THREAD_STATE();
  14283. return 0;
  14284. }
  14285. return 1;
  14286. }
  14287. /* Return OpenSSL error message (from CRYPTO lib) */
  14288. static const char *
  14289. ssl_error(void)
  14290. {
  14291. unsigned long err;
  14292. err = ERR_get_error();
  14293. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14294. }
  14295. static int
  14296. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14297. {
  14298. int i;
  14299. const char hexdigit[] = "0123456789abcdef";
  14300. if ((memlen <= 0) || (buflen <= 0)) {
  14301. return 0;
  14302. }
  14303. if (buflen < (3 * memlen)) {
  14304. return 0;
  14305. }
  14306. for (i = 0; i < memlen; i++) {
  14307. if (i > 0) {
  14308. buf[3 * i - 1] = ' ';
  14309. }
  14310. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14311. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14312. }
  14313. buf[3 * memlen - 1] = 0;
  14314. return 1;
  14315. }
  14316. static int
  14317. ssl_get_client_cert_info(const struct mg_connection *conn,
  14318. struct mg_client_cert *client_cert)
  14319. {
  14320. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14321. if (cert) {
  14322. char str_buf[1024];
  14323. unsigned char buf[256];
  14324. char *str_serial = NULL;
  14325. unsigned int ulen;
  14326. int ilen;
  14327. unsigned char *tmp_buf;
  14328. unsigned char *tmp_p;
  14329. /* Handle to algorithm used for fingerprint */
  14330. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14331. /* Get Subject and issuer */
  14332. X509_NAME *subj = X509_get_subject_name(cert);
  14333. X509_NAME *iss = X509_get_issuer_name(cert);
  14334. /* Get serial number */
  14335. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14336. /* Translate serial number to a hex string */
  14337. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14338. if (serial_bn) {
  14339. str_serial = BN_bn2hex(serial_bn);
  14340. BN_free(serial_bn);
  14341. }
  14342. client_cert->serial =
  14343. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14344. /* Translate subject and issuer to a string */
  14345. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14346. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14347. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14348. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14349. /* Calculate SHA1 fingerprint and store as a hex string */
  14350. ulen = 0;
  14351. /* ASN1_digest is deprecated. Do the calculation manually,
  14352. * using EVP_Digest. */
  14353. ilen = i2d_X509(cert, NULL);
  14354. tmp_buf = (ilen > 0)
  14355. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14356. conn->phys_ctx)
  14357. : NULL;
  14358. if (tmp_buf) {
  14359. tmp_p = tmp_buf;
  14360. (void)i2d_X509(cert, &tmp_p);
  14361. if (!EVP_Digest(
  14362. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14363. ulen = 0;
  14364. }
  14365. mg_free(tmp_buf);
  14366. }
  14367. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14368. *str_buf = 0;
  14369. }
  14370. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14371. client_cert->peer_cert = (void *)cert;
  14372. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14373. * see https://linux.die.net/man/3/bn_bn2hex */
  14374. OPENSSL_free(str_serial);
  14375. return 1;
  14376. }
  14377. return 0;
  14378. }
  14379. #if defined(OPENSSL_API_1_1)
  14380. #else
  14381. static void
  14382. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14383. {
  14384. (void)line;
  14385. (void)file;
  14386. if (mode & 1) {
  14387. /* 1 is CRYPTO_LOCK */
  14388. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14389. } else {
  14390. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14391. }
  14392. }
  14393. #endif /* OPENSSL_API_1_1 */
  14394. #if !defined(NO_SSL_DL)
  14395. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14396. static void *
  14397. load_tls_dll(char *ebuf,
  14398. size_t ebuf_len,
  14399. const char *dll_name,
  14400. struct ssl_func *sw,
  14401. int *feature_missing)
  14402. {
  14403. union {
  14404. void *p;
  14405. void (*fp)(void);
  14406. } u;
  14407. void *dll_handle;
  14408. struct ssl_func *fp;
  14409. int ok;
  14410. int truncated = 0;
  14411. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14412. mg_snprintf(NULL,
  14413. NULL, /* No truncation check for ebuf */
  14414. ebuf,
  14415. ebuf_len,
  14416. "%s: cannot load %s",
  14417. __func__,
  14418. dll_name);
  14419. return NULL;
  14420. }
  14421. ok = 1;
  14422. for (fp = sw; fp->name != NULL; fp++) {
  14423. #if defined(_WIN32)
  14424. /* GetProcAddress() returns pointer to function */
  14425. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14426. #else
  14427. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14428. * pointers to function pointers. We need to use a union to make a
  14429. * cast. */
  14430. u.p = dlsym(dll_handle, fp->name);
  14431. #endif /* _WIN32 */
  14432. /* Set pointer (might be NULL) */
  14433. fp->ptr = u.fp;
  14434. if (u.fp == NULL) {
  14435. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14436. if (feature_missing) {
  14437. feature_missing[fp->required]++;
  14438. }
  14439. if (fp->required == TLS_Mandatory) {
  14440. /* Mandatory function is missing */
  14441. if (ok) {
  14442. /* This is the first missing function.
  14443. * Create a new error message. */
  14444. mg_snprintf(NULL,
  14445. &truncated,
  14446. ebuf,
  14447. ebuf_len,
  14448. "%s: %s: cannot find %s",
  14449. __func__,
  14450. dll_name,
  14451. fp->name);
  14452. ok = 0;
  14453. } else {
  14454. /* This is yet anothermissing function.
  14455. * Append existing error message. */
  14456. size_t cur_len = strlen(ebuf);
  14457. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14458. mg_snprintf(NULL,
  14459. &truncated,
  14460. ebuf + cur_len,
  14461. ebuf_len - cur_len - 3,
  14462. ", %s",
  14463. fp->name);
  14464. if (truncated) {
  14465. /* If truncated, add "..." */
  14466. strcat(ebuf, "...");
  14467. }
  14468. }
  14469. }
  14470. }
  14471. }
  14472. }
  14473. if (!ok) {
  14474. (void)dlclose(dll_handle);
  14475. return NULL;
  14476. }
  14477. return dll_handle;
  14478. }
  14479. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14480. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14481. #endif /* NO_SSL_DL */
  14482. #if defined(SSL_ALREADY_INITIALIZED)
  14483. static volatile ptrdiff_t cryptolib_users =
  14484. 1; /* Reference counter for crypto library. */
  14485. #else
  14486. static volatile ptrdiff_t cryptolib_users =
  14487. 0; /* Reference counter for crypto library. */
  14488. #endif
  14489. static int
  14490. initialize_openssl(char *ebuf, size_t ebuf_len)
  14491. {
  14492. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14493. int i, num_locks;
  14494. size_t size;
  14495. #endif
  14496. if (ebuf_len > 0) {
  14497. ebuf[0] = 0;
  14498. }
  14499. #if !defined(NO_SSL_DL)
  14500. if (!cryptolib_dll_handle) {
  14501. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14502. cryptolib_dll_handle = load_tls_dll(
  14503. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14504. if (!cryptolib_dll_handle) {
  14505. mg_snprintf(NULL,
  14506. NULL, /* No truncation check for ebuf */
  14507. ebuf,
  14508. ebuf_len,
  14509. "%s: error loading library %s",
  14510. __func__,
  14511. CRYPTO_LIB);
  14512. DEBUG_TRACE("%s", ebuf);
  14513. return 0;
  14514. }
  14515. }
  14516. #endif /* NO_SSL_DL */
  14517. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14518. return 1;
  14519. }
  14520. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14521. /* Initialize locking callbacks, needed for thread safety.
  14522. * http://www.openssl.org/support/faq.html#PROG1
  14523. */
  14524. num_locks = CRYPTO_num_locks();
  14525. if (num_locks < 0) {
  14526. num_locks = 0;
  14527. }
  14528. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14529. /* allocate mutex array, if required */
  14530. if (num_locks == 0) {
  14531. /* No mutex array required */
  14532. ssl_mutexes = NULL;
  14533. } else {
  14534. /* Mutex array required - allocate it */
  14535. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14536. /* Check OOM */
  14537. if (ssl_mutexes == NULL) {
  14538. mg_snprintf(NULL,
  14539. NULL, /* No truncation check for ebuf */
  14540. ebuf,
  14541. ebuf_len,
  14542. "%s: cannot allocate mutexes: %s",
  14543. __func__,
  14544. ssl_error());
  14545. DEBUG_TRACE("%s", ebuf);
  14546. return 0;
  14547. }
  14548. /* initialize mutex array */
  14549. for (i = 0; i < num_locks; i++) {
  14550. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14551. mg_snprintf(NULL,
  14552. NULL, /* No truncation check for ebuf */
  14553. ebuf,
  14554. ebuf_len,
  14555. "%s: error initializing mutex %i of %i",
  14556. __func__,
  14557. i,
  14558. num_locks);
  14559. DEBUG_TRACE("%s", ebuf);
  14560. mg_free(ssl_mutexes);
  14561. return 0;
  14562. }
  14563. }
  14564. }
  14565. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14566. CRYPTO_set_id_callback(&mg_current_thread_id);
  14567. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14568. #if !defined(NO_SSL_DL)
  14569. if (!ssllib_dll_handle) {
  14570. ssllib_dll_handle =
  14571. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14572. if (!ssllib_dll_handle) {
  14573. #if !defined(OPENSSL_API_1_1)
  14574. mg_free(ssl_mutexes);
  14575. #endif
  14576. DEBUG_TRACE("%s", ebuf);
  14577. return 0;
  14578. }
  14579. }
  14580. #endif /* NO_SSL_DL */
  14581. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14582. && !defined(NO_SSL_DL)
  14583. /* Initialize SSL library */
  14584. OPENSSL_init_ssl(0, NULL);
  14585. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14586. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14587. NULL);
  14588. #else
  14589. /* Initialize SSL library */
  14590. SSL_library_init();
  14591. SSL_load_error_strings();
  14592. #endif
  14593. return 1;
  14594. }
  14595. static int
  14596. ssl_use_pem_file(struct mg_context *phys_ctx,
  14597. struct mg_domain_context *dom_ctx,
  14598. const char *pem,
  14599. const char *chain)
  14600. {
  14601. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14602. mg_cry_ctx_internal(phys_ctx,
  14603. "%s: cannot open certificate file %s: %s",
  14604. __func__,
  14605. pem,
  14606. ssl_error());
  14607. return 0;
  14608. }
  14609. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14610. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14611. mg_cry_ctx_internal(phys_ctx,
  14612. "%s: cannot open private key file %s: %s",
  14613. __func__,
  14614. pem,
  14615. ssl_error());
  14616. return 0;
  14617. }
  14618. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14619. mg_cry_ctx_internal(phys_ctx,
  14620. "%s: certificate and private key do not match: %s",
  14621. __func__,
  14622. pem);
  14623. return 0;
  14624. }
  14625. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14626. * chain files that contain private keys and certificates in
  14627. * SSL_CTX_use_certificate_chain_file.
  14628. * The CivetWeb-Server used pem-Files that contained both information.
  14629. * In order to make wolfSSL work, it is split in two files.
  14630. * One file that contains key and certificate used by the server and
  14631. * an optional chain file for the ssl stack.
  14632. */
  14633. if (chain) {
  14634. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14635. mg_cry_ctx_internal(phys_ctx,
  14636. "%s: cannot use certificate chain file %s: %s",
  14637. __func__,
  14638. chain,
  14639. ssl_error());
  14640. return 0;
  14641. }
  14642. }
  14643. return 1;
  14644. }
  14645. #if defined(OPENSSL_API_1_1)
  14646. static unsigned long
  14647. ssl_get_protocol(int version_id)
  14648. {
  14649. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14650. if (version_id > 0)
  14651. ret |= SSL_OP_NO_SSLv2;
  14652. if (version_id > 1)
  14653. ret |= SSL_OP_NO_SSLv3;
  14654. if (version_id > 2)
  14655. ret |= SSL_OP_NO_TLSv1;
  14656. if (version_id > 3)
  14657. ret |= SSL_OP_NO_TLSv1_1;
  14658. if (version_id > 4)
  14659. ret |= SSL_OP_NO_TLSv1_2;
  14660. #if defined(SSL_OP_NO_TLSv1_3)
  14661. if (version_id > 5)
  14662. ret |= SSL_OP_NO_TLSv1_3;
  14663. #endif
  14664. return ret;
  14665. }
  14666. #else
  14667. static long
  14668. ssl_get_protocol(int version_id)
  14669. {
  14670. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14671. if (version_id > 0)
  14672. ret |= SSL_OP_NO_SSLv2;
  14673. if (version_id > 1)
  14674. ret |= SSL_OP_NO_SSLv3;
  14675. if (version_id > 2)
  14676. ret |= SSL_OP_NO_TLSv1;
  14677. if (version_id > 3)
  14678. ret |= SSL_OP_NO_TLSv1_1;
  14679. if (version_id > 4)
  14680. ret |= SSL_OP_NO_TLSv1_2;
  14681. #if defined(SSL_OP_NO_TLSv1_3)
  14682. if (version_id > 5)
  14683. ret |= SSL_OP_NO_TLSv1_3;
  14684. #endif
  14685. return (long)ret;
  14686. }
  14687. #endif /* OPENSSL_API_1_1 */
  14688. /* SSL callback documentation:
  14689. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14690. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14691. * https://linux.die.net/man/3/ssl_set_info_callback */
  14692. /* Note: There is no "const" for the first argument in the documentation
  14693. * examples, however some (maybe most, but not all) headers of OpenSSL
  14694. * versions / OpenSSL compatibility layers have it. Having a different
  14695. * definition will cause a warning in C and an error in C++. Use "const SSL
  14696. * *", while automatical conversion from "SSL *" works for all compilers,
  14697. * but not other way around */
  14698. static void
  14699. ssl_info_callback(const SSL *ssl, int what, int ret)
  14700. {
  14701. (void)ret;
  14702. if (what & SSL_CB_HANDSHAKE_START) {
  14703. SSL_get_app_data(ssl);
  14704. }
  14705. if (what & SSL_CB_HANDSHAKE_DONE) {
  14706. /* TODO: check for openSSL 1.1 */
  14707. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14708. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14709. }
  14710. }
  14711. static int
  14712. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14713. {
  14714. #if defined(GCC_DIAGNOSTIC)
  14715. #pragma GCC diagnostic push
  14716. #pragma GCC diagnostic ignored "-Wcast-align"
  14717. #endif /* defined(GCC_DIAGNOSTIC) */
  14718. /* We used an aligned pointer in SSL_set_app_data */
  14719. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14720. #if defined(GCC_DIAGNOSTIC)
  14721. #pragma GCC diagnostic pop
  14722. #endif /* defined(GCC_DIAGNOSTIC) */
  14723. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14724. (void)ad;
  14725. (void)arg;
  14726. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14727. DEBUG_ASSERT(0);
  14728. return SSL_TLSEXT_ERR_NOACK;
  14729. }
  14730. conn->dom_ctx = &(conn->phys_ctx->dd);
  14731. /* Old clients (Win XP) will not support SNI. Then, there
  14732. * is no server name available in the request - we can
  14733. * only work with the default certificate.
  14734. * Multiple HTTPS hosts on one IP+port are only possible
  14735. * with a certificate containing all alternative names.
  14736. */
  14737. if ((servername == NULL) || (*servername == 0)) {
  14738. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14739. mg_lock_context(conn->phys_ctx);
  14740. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14741. mg_unlock_context(conn->phys_ctx);
  14742. return SSL_TLSEXT_ERR_NOACK;
  14743. }
  14744. DEBUG_TRACE("TLS connection to host %s", servername);
  14745. while (conn->dom_ctx) {
  14746. if (!mg_strcasecmp(servername,
  14747. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14748. /* Found matching domain */
  14749. DEBUG_TRACE("TLS domain %s found",
  14750. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14751. break;
  14752. }
  14753. mg_lock_context(conn->phys_ctx);
  14754. conn->dom_ctx = conn->dom_ctx->next;
  14755. mg_unlock_context(conn->phys_ctx);
  14756. }
  14757. if (conn->dom_ctx == NULL) {
  14758. /* Default domain */
  14759. DEBUG_TRACE("TLS default domain %s used",
  14760. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14761. conn->dom_ctx = &(conn->phys_ctx->dd);
  14762. }
  14763. mg_lock_context(conn->phys_ctx);
  14764. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14765. mg_unlock_context(conn->phys_ctx);
  14766. return SSL_TLSEXT_ERR_OK;
  14767. }
  14768. #if defined(USE_ALPN)
  14769. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14770. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14771. alpn_proto_list + 3 + 8,
  14772. NULL};
  14773. #if defined(USE_HTTP2)
  14774. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14775. alpn_proto_list + 3,
  14776. alpn_proto_list + 3 + 8,
  14777. NULL};
  14778. #endif
  14779. static int
  14780. alpn_select_cb(SSL *ssl,
  14781. const unsigned char **out,
  14782. unsigned char *outlen,
  14783. const unsigned char *in,
  14784. unsigned int inlen,
  14785. void *arg)
  14786. {
  14787. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14788. unsigned int i, j, enable_http2 = 0;
  14789. const char **alpn_proto_order = alpn_proto_order_http1;
  14790. struct mg_workerTLS *tls =
  14791. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14792. (void)ssl;
  14793. if (tls == NULL) {
  14794. /* Need to store protocol in Thread Local Storage */
  14795. /* If there is no Thread Local Storage, don't use ALPN */
  14796. return SSL_TLSEXT_ERR_NOACK;
  14797. }
  14798. #if defined(USE_HTTP2)
  14799. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14800. if (enable_http2) {
  14801. alpn_proto_order = alpn_proto_order_http2;
  14802. }
  14803. #endif
  14804. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14805. /* check all accepted protocols in this order */
  14806. const char *alpn_proto = alpn_proto_order[j];
  14807. /* search input for matching protocol */
  14808. for (i = 0; i < inlen; i++) {
  14809. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14810. *out = in + i + 1;
  14811. *outlen = in[i];
  14812. tls->alpn_proto = alpn_proto;
  14813. return SSL_TLSEXT_ERR_OK;
  14814. }
  14815. }
  14816. }
  14817. /* Nothing found */
  14818. return SSL_TLSEXT_ERR_NOACK;
  14819. }
  14820. static int
  14821. next_protos_advertised_cb(SSL *ssl,
  14822. const unsigned char **data,
  14823. unsigned int *len,
  14824. void *arg)
  14825. {
  14826. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14827. *data = (const unsigned char *)alpn_proto_list;
  14828. *len = (unsigned int)strlen((const char *)data);
  14829. (void)ssl;
  14830. (void)dom_ctx;
  14831. return SSL_TLSEXT_ERR_OK;
  14832. }
  14833. static int
  14834. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14835. {
  14836. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14837. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14838. (const unsigned char *)alpn_proto_list,
  14839. alpn_len);
  14840. if (ret != 0) {
  14841. mg_cry_ctx_internal(phys_ctx,
  14842. "SSL_CTX_set_alpn_protos error: %s",
  14843. ssl_error());
  14844. }
  14845. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14846. alpn_select_cb,
  14847. (void *)dom_ctx);
  14848. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14849. next_protos_advertised_cb,
  14850. (void *)dom_ctx);
  14851. return ret;
  14852. }
  14853. #endif
  14854. /* Setup SSL CTX as required by CivetWeb */
  14855. static int
  14856. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14857. struct mg_domain_context *dom_ctx,
  14858. const char *pem,
  14859. const char *chain)
  14860. {
  14861. int callback_ret;
  14862. int should_verify_peer;
  14863. int peer_certificate_optional;
  14864. const char *ca_path;
  14865. const char *ca_file;
  14866. int use_default_verify_paths;
  14867. int verify_depth;
  14868. struct timespec now_mt;
  14869. md5_byte_t ssl_context_id[16];
  14870. md5_state_t md5state;
  14871. int protocol_ver;
  14872. int ssl_cache_timeout;
  14873. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14874. && !defined(NO_SSL_DL)
  14875. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14876. mg_cry_ctx_internal(phys_ctx,
  14877. "SSL_CTX_new (server) error: %s",
  14878. ssl_error());
  14879. return 0;
  14880. }
  14881. #else
  14882. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14883. mg_cry_ctx_internal(phys_ctx,
  14884. "SSL_CTX_new (server) error: %s",
  14885. ssl_error());
  14886. return 0;
  14887. }
  14888. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14889. #if defined(SSL_OP_NO_TLSv1_3)
  14890. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14891. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14892. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14893. | SSL_OP_NO_TLSv1_3);
  14894. #else
  14895. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14896. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14897. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14898. #endif
  14899. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14900. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14901. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14902. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14903. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14904. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14905. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14906. #if defined(SSL_OP_NO_RENEGOTIATION)
  14907. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14908. #endif
  14909. #if !defined(NO_SSL_DL)
  14910. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14911. #endif /* NO_SSL_DL */
  14912. /* In SSL documentation examples callback defined without const
  14913. * specifier 'void (*)(SSL *, int, int)' See:
  14914. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14915. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14916. * But in the source code const SSL is used:
  14917. * 'void (*)(const SSL *, int, int)' See:
  14918. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14919. * Problem about wrong documentation described, but not resolved:
  14920. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14921. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14922. * But when compiled with modern C++ compiler, correct const should be
  14923. * provided
  14924. */
  14925. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14926. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14927. ssl_servername_callback);
  14928. /* If a callback has been specified, call it. */
  14929. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14930. ? 0
  14931. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14932. phys_ctx->user_data));
  14933. /* If callback returns 0, civetweb sets up the SSL certificate.
  14934. * If it returns 1, civetweb assumes the calback already did this.
  14935. * If it returns -1, initializing ssl fails. */
  14936. if (callback_ret < 0) {
  14937. mg_cry_ctx_internal(phys_ctx,
  14938. "SSL callback returned error: %i",
  14939. callback_ret);
  14940. return 0;
  14941. }
  14942. if (callback_ret > 0) {
  14943. /* Callback did everything. */
  14944. return 1;
  14945. }
  14946. /* If a domain callback has been specified, call it. */
  14947. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14948. ? 0
  14949. : (phys_ctx->callbacks.init_ssl_domain(
  14950. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14951. dom_ctx->ssl_ctx,
  14952. phys_ctx->user_data));
  14953. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14954. * If it returns 1, civetweb assumes the calback already did this.
  14955. * If it returns -1, initializing ssl fails. */
  14956. if (callback_ret < 0) {
  14957. mg_cry_ctx_internal(phys_ctx,
  14958. "Domain SSL callback returned error: %i",
  14959. callback_ret);
  14960. return 0;
  14961. }
  14962. if (callback_ret > 0) {
  14963. /* Domain callback did everything. */
  14964. return 1;
  14965. }
  14966. /* Use some combination of start time, domain and port as a SSL
  14967. * context ID. This should be unique on the current machine. */
  14968. md5_init(&md5state);
  14969. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14970. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14971. md5_append(&md5state,
  14972. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14973. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14974. md5_append(&md5state,
  14975. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14976. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14977. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14978. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14979. md5_finish(&md5state, ssl_context_id);
  14980. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14981. (unsigned char *)ssl_context_id,
  14982. sizeof(ssl_context_id));
  14983. if (pem != NULL) {
  14984. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14985. return 0;
  14986. }
  14987. }
  14988. /* Should we support client certificates? */
  14989. /* Default is "no". */
  14990. should_verify_peer = 0;
  14991. peer_certificate_optional = 0;
  14992. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14993. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14994. /* Yes, they are mandatory */
  14995. should_verify_peer = 1;
  14996. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14997. "optional")
  14998. == 0) {
  14999. /* Yes, they are optional */
  15000. should_verify_peer = 1;
  15001. peer_certificate_optional = 1;
  15002. }
  15003. }
  15004. use_default_verify_paths =
  15005. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15006. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15007. == 0);
  15008. if (should_verify_peer) {
  15009. ca_path = dom_ctx->config[SSL_CA_PATH];
  15010. ca_file = dom_ctx->config[SSL_CA_FILE];
  15011. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15012. != 1) {
  15013. mg_cry_ctx_internal(phys_ctx,
  15014. "SSL_CTX_load_verify_locations error: %s "
  15015. "ssl_verify_peer requires setting "
  15016. "either ssl_ca_path or ssl_ca_file. "
  15017. "Is any of them present in the "
  15018. ".conf file?",
  15019. ssl_error());
  15020. return 0;
  15021. }
  15022. if (peer_certificate_optional) {
  15023. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15024. } else {
  15025. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15026. SSL_VERIFY_PEER
  15027. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15028. NULL);
  15029. }
  15030. if (use_default_verify_paths
  15031. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15032. mg_cry_ctx_internal(phys_ctx,
  15033. "SSL_CTX_set_default_verify_paths error: %s",
  15034. ssl_error());
  15035. return 0;
  15036. }
  15037. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15038. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15039. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15040. }
  15041. }
  15042. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15043. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15044. dom_ctx->config[SSL_CIPHER_LIST])
  15045. != 1) {
  15046. mg_cry_ctx_internal(phys_ctx,
  15047. "SSL_CTX_set_cipher_list error: %s",
  15048. ssl_error());
  15049. }
  15050. }
  15051. /* SSL session caching */
  15052. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15053. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15054. : 0);
  15055. if (ssl_cache_timeout > 0) {
  15056. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15057. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15058. * default */
  15059. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15060. }
  15061. #if defined(USE_ALPN)
  15062. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15063. #if !defined(NO_SSL_DL)
  15064. if (!tls_feature_missing[TLS_ALPN])
  15065. #endif
  15066. {
  15067. init_alpn(phys_ctx, dom_ctx);
  15068. }
  15069. #endif
  15070. return 1;
  15071. }
  15072. /* Check if SSL is required.
  15073. * If so, dynamically load SSL library
  15074. * and set up ctx->ssl_ctx pointer. */
  15075. static int
  15076. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15077. {
  15078. void *ssl_ctx = 0;
  15079. int callback_ret;
  15080. const char *pem;
  15081. const char *chain;
  15082. char ebuf[128];
  15083. if (!phys_ctx) {
  15084. return 0;
  15085. }
  15086. if (!dom_ctx) {
  15087. dom_ctx = &(phys_ctx->dd);
  15088. }
  15089. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15090. /* No SSL port is set. No need to setup SSL. */
  15091. return 1;
  15092. }
  15093. /* Check for external SSL_CTX */
  15094. callback_ret =
  15095. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15096. ? 0
  15097. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15098. phys_ctx->user_data));
  15099. if (callback_ret < 0) {
  15100. /* Callback exists and returns <0: Initializing failed. */
  15101. mg_cry_ctx_internal(phys_ctx,
  15102. "external_ssl_ctx callback returned error: %i",
  15103. callback_ret);
  15104. return 0;
  15105. } else if (callback_ret > 0) {
  15106. /* Callback exists and returns >0: Initializing complete,
  15107. * civetweb should not modify the SSL context. */
  15108. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15109. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15110. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15111. return 0;
  15112. }
  15113. return 1;
  15114. }
  15115. /* If the callback does not exist or return 0, civetweb must initialize
  15116. * the SSL context. Handle "domain" callback next. */
  15117. /* Check for external domain SSL_CTX callback. */
  15118. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15119. ? 0
  15120. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15121. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15122. &ssl_ctx,
  15123. phys_ctx->user_data));
  15124. if (callback_ret < 0) {
  15125. /* Callback < 0: Error. Abort init. */
  15126. mg_cry_ctx_internal(
  15127. phys_ctx,
  15128. "external_ssl_ctx_domain callback returned error: %i",
  15129. callback_ret);
  15130. return 0;
  15131. } else if (callback_ret > 0) {
  15132. /* Callback > 0: Consider init done. */
  15133. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15134. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15135. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15136. return 0;
  15137. }
  15138. return 1;
  15139. }
  15140. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15141. * 0, CivetWeb should continue initializing SSL */
  15142. /* If PEM file is not specified and the init_ssl callbacks
  15143. * are not specified, setup will fail. */
  15144. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15145. && (phys_ctx->callbacks.init_ssl == NULL)
  15146. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15147. /* No certificate and no init_ssl callbacks:
  15148. * Essential data to set up TLS is missing.
  15149. */
  15150. mg_cry_ctx_internal(phys_ctx,
  15151. "Initializing SSL failed: -%s is not set",
  15152. config_options[SSL_CERTIFICATE].name);
  15153. return 0;
  15154. }
  15155. /* If a certificate chain is configured, use it. */
  15156. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15157. if (chain == NULL) {
  15158. /* Default: certificate chain in PEM file */
  15159. chain = pem;
  15160. }
  15161. if ((chain != NULL) && (*chain == 0)) {
  15162. /* If the chain is an empty string, don't use it. */
  15163. chain = NULL;
  15164. }
  15165. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15166. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15167. return 0;
  15168. }
  15169. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15170. }
  15171. static void
  15172. uninitialize_openssl(void)
  15173. {
  15174. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15175. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15176. /* Shutdown according to
  15177. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15178. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15179. */
  15180. CONF_modules_unload(1);
  15181. #else
  15182. int i;
  15183. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15184. /* Shutdown according to
  15185. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15186. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15187. */
  15188. CRYPTO_set_locking_callback(NULL);
  15189. CRYPTO_set_id_callback(NULL);
  15190. ENGINE_cleanup();
  15191. CONF_modules_unload(1);
  15192. ERR_free_strings();
  15193. EVP_cleanup();
  15194. CRYPTO_cleanup_all_ex_data();
  15195. OPENSSL_REMOVE_THREAD_STATE();
  15196. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15197. pthread_mutex_destroy(&ssl_mutexes[i]);
  15198. }
  15199. mg_free(ssl_mutexes);
  15200. ssl_mutexes = NULL;
  15201. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15202. }
  15203. }
  15204. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15205. #if !defined(NO_FILESYSTEMS)
  15206. static int
  15207. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15208. {
  15209. if (phys_ctx) {
  15210. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15211. const char *path;
  15212. struct mg_connection fc;
  15213. if (!dom_ctx) {
  15214. dom_ctx = &(phys_ctx->dd);
  15215. }
  15216. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15217. if ((path != NULL)
  15218. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15219. mg_cry_ctx_internal(phys_ctx,
  15220. "Cannot open %s: %s",
  15221. path,
  15222. strerror(ERRNO));
  15223. return 0;
  15224. }
  15225. return 1;
  15226. }
  15227. return 0;
  15228. }
  15229. #endif /* NO_FILESYSTEMS */
  15230. static int
  15231. set_acl_option(struct mg_context *phys_ctx)
  15232. {
  15233. union usa sa;
  15234. memset(&sa, 0, sizeof(sa));
  15235. #if defined(USE_IPV6)
  15236. sa.sin6.sin6_family = AF_INET6;
  15237. #else
  15238. sa.sin.sin_family = AF_INET;
  15239. #endif
  15240. return check_acl(phys_ctx, &sa) != -1;
  15241. }
  15242. static void
  15243. reset_per_request_attributes(struct mg_connection *conn)
  15244. {
  15245. if (!conn) {
  15246. return;
  15247. }
  15248. conn->num_bytes_sent = conn->consumed_content = 0;
  15249. conn->path_info = NULL;
  15250. conn->status_code = -1;
  15251. conn->content_len = -1;
  15252. conn->is_chunked = 0;
  15253. conn->must_close = 0;
  15254. conn->request_len = 0;
  15255. conn->request_state = 0;
  15256. conn->throttle = 0;
  15257. conn->accept_gzip = 0;
  15258. conn->response_info.content_length = conn->request_info.content_length = -1;
  15259. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15260. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15261. conn->response_info.status_text = NULL;
  15262. conn->response_info.status_code = 0;
  15263. conn->request_info.remote_user = NULL;
  15264. conn->request_info.request_method = NULL;
  15265. conn->request_info.request_uri = NULL;
  15266. /* Free cleaned local URI (if any) */
  15267. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15268. mg_free((void *)conn->request_info.local_uri);
  15269. conn->request_info.local_uri = NULL;
  15270. }
  15271. conn->request_info.local_uri = NULL;
  15272. #if defined(USE_SERVER_STATS)
  15273. conn->processing_time = 0;
  15274. #endif
  15275. }
  15276. static int
  15277. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15278. {
  15279. if ((so->lsa.sa.sa_family == AF_INET)
  15280. || (so->lsa.sa.sa_family == AF_INET6)) {
  15281. /* Only for TCP sockets */
  15282. if (setsockopt(so->sock,
  15283. IPPROTO_TCP,
  15284. TCP_NODELAY,
  15285. (SOCK_OPT_TYPE)&nodelay_on,
  15286. sizeof(nodelay_on))
  15287. != 0) {
  15288. /* Error */
  15289. return 1;
  15290. }
  15291. }
  15292. /* OK */
  15293. return 0;
  15294. }
  15295. #if !defined(__ZEPHYR__)
  15296. static void
  15297. close_socket_gracefully(struct mg_connection *conn)
  15298. {
  15299. #if defined(_WIN32)
  15300. char buf[MG_BUF_LEN];
  15301. int n;
  15302. #endif
  15303. struct linger linger;
  15304. int error_code = 0;
  15305. int linger_timeout = -2;
  15306. socklen_t opt_len = sizeof(error_code);
  15307. if (!conn) {
  15308. return;
  15309. }
  15310. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15311. * "Note that enabling a nonzero timeout on a nonblocking socket
  15312. * is not recommended.", so set it to blocking now */
  15313. set_blocking_mode(conn->client.sock);
  15314. /* Send FIN to the client */
  15315. shutdown(conn->client.sock, SHUTDOWN_WR);
  15316. #if defined(_WIN32)
  15317. /* Read and discard pending incoming data. If we do not do that and
  15318. * close
  15319. * the socket, the data in the send buffer may be discarded. This
  15320. * behaviour is seen on Windows, when client keeps sending data
  15321. * when server decides to close the connection; then when client
  15322. * does recv() it gets no data back. */
  15323. do {
  15324. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15325. } while (n > 0);
  15326. #endif
  15327. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15328. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15329. }
  15330. /* Set linger option according to configuration */
  15331. if (linger_timeout >= 0) {
  15332. /* Set linger option to avoid socket hanging out after close. This
  15333. * prevent ephemeral port exhaust problem under high QPS. */
  15334. linger.l_onoff = 1;
  15335. #if defined(_MSC_VER)
  15336. #pragma warning(push)
  15337. #pragma warning(disable : 4244)
  15338. #endif
  15339. #if defined(GCC_DIAGNOSTIC)
  15340. #pragma GCC diagnostic push
  15341. #pragma GCC diagnostic ignored "-Wconversion"
  15342. #endif
  15343. /* Data type of linger structure elements may differ,
  15344. * so we don't know what cast we need here.
  15345. * Disable type conversion warnings. */
  15346. linger.l_linger = (linger_timeout + 999) / 1000;
  15347. #if defined(GCC_DIAGNOSTIC)
  15348. #pragma GCC diagnostic pop
  15349. #endif
  15350. #if defined(_MSC_VER)
  15351. #pragma warning(pop)
  15352. #endif
  15353. } else {
  15354. linger.l_onoff = 0;
  15355. linger.l_linger = 0;
  15356. }
  15357. if (linger_timeout < -1) {
  15358. /* Default: don't configure any linger */
  15359. } else if (getsockopt(conn->client.sock,
  15360. SOL_SOCKET,
  15361. SO_ERROR,
  15362. #if defined(_WIN32) /* WinSock uses different data type here */
  15363. (char *)&error_code,
  15364. #else
  15365. &error_code,
  15366. #endif
  15367. &opt_len)
  15368. != 0) {
  15369. /* Cannot determine if socket is already closed. This should
  15370. * not occur and never did in a test. Log an error message
  15371. * and continue. */
  15372. mg_cry_internal(conn,
  15373. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15374. __func__,
  15375. strerror(ERRNO));
  15376. #if defined(_WIN32)
  15377. } else if (error_code == WSAECONNRESET) {
  15378. #else
  15379. } else if (error_code == ECONNRESET) {
  15380. #endif
  15381. /* Socket already closed by client/peer, close socket without linger
  15382. */
  15383. } else {
  15384. /* Set linger timeout */
  15385. if (setsockopt(conn->client.sock,
  15386. SOL_SOCKET,
  15387. SO_LINGER,
  15388. (char *)&linger,
  15389. sizeof(linger))
  15390. != 0) {
  15391. mg_cry_internal(
  15392. conn,
  15393. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15394. __func__,
  15395. linger.l_onoff,
  15396. linger.l_linger,
  15397. strerror(ERRNO));
  15398. }
  15399. }
  15400. /* Now we know that our FIN is ACK-ed, safe to close */
  15401. closesocket(conn->client.sock);
  15402. conn->client.sock = INVALID_SOCKET;
  15403. }
  15404. #endif
  15405. static void
  15406. close_connection(struct mg_connection *conn)
  15407. {
  15408. #if defined(USE_SERVER_STATS)
  15409. conn->conn_state = 6; /* to close */
  15410. #endif
  15411. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15412. if (conn->lua_websocket_state) {
  15413. lua_websocket_close(conn, conn->lua_websocket_state);
  15414. conn->lua_websocket_state = NULL;
  15415. }
  15416. #endif
  15417. mg_lock_connection(conn);
  15418. /* Set close flag, so keep-alive loops will stop */
  15419. conn->must_close = 1;
  15420. /* call the connection_close callback if assigned */
  15421. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15422. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15423. conn->phys_ctx->callbacks.connection_close(conn);
  15424. }
  15425. }
  15426. /* Reset user data, after close callback is called.
  15427. * Do not reuse it. If the user needs a destructor,
  15428. * it must be done in the connection_close callback. */
  15429. mg_set_user_connection_data(conn, NULL);
  15430. #if defined(USE_SERVER_STATS)
  15431. conn->conn_state = 7; /* closing */
  15432. #endif
  15433. #if defined(USE_MBEDTLS)
  15434. if (conn->ssl != NULL) {
  15435. mbed_ssl_close(conn->ssl);
  15436. conn->ssl = NULL;
  15437. }
  15438. #elif !defined(NO_SSL)
  15439. if (conn->ssl != NULL) {
  15440. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15441. */
  15442. SSL_shutdown(conn->ssl);
  15443. SSL_free(conn->ssl);
  15444. OPENSSL_REMOVE_THREAD_STATE();
  15445. conn->ssl = NULL;
  15446. }
  15447. #endif
  15448. if (conn->client.sock != INVALID_SOCKET) {
  15449. #if defined(__ZEPHYR__)
  15450. closesocket(conn->client.sock);
  15451. #else
  15452. close_socket_gracefully(conn);
  15453. #endif
  15454. conn->client.sock = INVALID_SOCKET;
  15455. }
  15456. /* call the connection_closed callback if assigned */
  15457. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15458. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15459. conn->phys_ctx->callbacks.connection_closed(conn);
  15460. }
  15461. }
  15462. mg_unlock_connection(conn);
  15463. #if defined(USE_SERVER_STATS)
  15464. conn->conn_state = 8; /* closed */
  15465. #endif
  15466. }
  15467. CIVETWEB_API void
  15468. mg_close_connection(struct mg_connection *conn)
  15469. {
  15470. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15471. return;
  15472. }
  15473. #if defined(USE_WEBSOCKET)
  15474. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15475. if (conn->in_websocket_handling) {
  15476. /* Set close flag, so the server thread can exit. */
  15477. conn->must_close = 1;
  15478. return;
  15479. }
  15480. }
  15481. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15482. unsigned int i;
  15483. /* client context: loops must end */
  15484. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15485. conn->must_close = 1;
  15486. /* We need to get the client thread out of the select/recv call
  15487. * here. */
  15488. /* Since we use a sleep quantum of some seconds to check for recv
  15489. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15490. /* join worker thread */
  15491. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15492. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15493. }
  15494. }
  15495. #endif /* defined(USE_WEBSOCKET) */
  15496. close_connection(conn);
  15497. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15498. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15499. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15500. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15501. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15502. }
  15503. #endif
  15504. #if defined(USE_WEBSOCKET)
  15505. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15506. mg_free(conn->phys_ctx->worker_threadids);
  15507. (void)pthread_mutex_destroy(&conn->mutex);
  15508. mg_free(conn);
  15509. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15510. (void)pthread_mutex_destroy(&conn->mutex);
  15511. mg_free(conn);
  15512. }
  15513. #else
  15514. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15515. (void)pthread_mutex_destroy(&conn->mutex);
  15516. mg_free(conn);
  15517. }
  15518. #endif /* defined(USE_WEBSOCKET) */
  15519. }
  15520. static struct mg_connection *
  15521. mg_connect_client_impl(const struct mg_client_options *client_options,
  15522. int use_ssl,
  15523. struct mg_init_data *init,
  15524. struct mg_error_data *error)
  15525. {
  15526. struct mg_connection *conn = NULL;
  15527. SOCKET sock;
  15528. union usa sa;
  15529. struct sockaddr *psa;
  15530. socklen_t len;
  15531. unsigned max_req_size =
  15532. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15533. /* Size of structures, aligned to 8 bytes */
  15534. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15535. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15536. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15537. (void)init; /* TODO: Implement required options */
  15538. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15539. if (error != NULL) {
  15540. error->code = MG_ERROR_DATA_CODE_OK;
  15541. error->code_sub = 0;
  15542. if (error->text_buffer_size > 0) {
  15543. error->text[0] = 0;
  15544. }
  15545. }
  15546. if (conn == NULL) {
  15547. if (error != NULL) {
  15548. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15549. error->code_sub = (unsigned)alloc_size;
  15550. mg_snprintf(NULL,
  15551. NULL, /* No truncation check for ebuf */
  15552. error->text,
  15553. error->text_buffer_size,
  15554. "calloc(): %s",
  15555. strerror(ERRNO));
  15556. }
  15557. return NULL;
  15558. }
  15559. #if defined(GCC_DIAGNOSTIC)
  15560. #pragma GCC diagnostic push
  15561. #pragma GCC diagnostic ignored "-Wcast-align"
  15562. #endif /* defined(GCC_DIAGNOSTIC) */
  15563. /* conn_size is aligned to 8 bytes */
  15564. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15565. #if defined(GCC_DIAGNOSTIC)
  15566. #pragma GCC diagnostic pop
  15567. #endif /* defined(GCC_DIAGNOSTIC) */
  15568. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15569. conn->buf_size = (int)max_req_size;
  15570. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15571. conn->dom_ctx = &(conn->phys_ctx->dd);
  15572. if (!connect_socket(conn->phys_ctx,
  15573. client_options->host,
  15574. client_options->port,
  15575. use_ssl,
  15576. error,
  15577. &sock,
  15578. &sa)) {
  15579. /* "error" will be set by connect_socket. */
  15580. /* free all memory and return NULL; */
  15581. mg_free(conn);
  15582. return NULL;
  15583. }
  15584. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15585. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15586. && !defined(NO_SSL_DL)
  15587. if (use_ssl
  15588. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15589. == NULL) {
  15590. if (error != NULL) {
  15591. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15592. mg_snprintf(NULL,
  15593. NULL, /* No truncation check for ebuf */
  15594. error->text,
  15595. error->text_buffer_size,
  15596. "SSL_CTX_new error: %s",
  15597. ssl_error());
  15598. }
  15599. closesocket(sock);
  15600. mg_free(conn);
  15601. return NULL;
  15602. }
  15603. #else
  15604. if (use_ssl
  15605. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15606. == NULL) {
  15607. if (error != NULL) {
  15608. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15609. mg_snprintf(NULL,
  15610. NULL, /* No truncation check for ebuf */
  15611. error->text,
  15612. error->text_buffer_size,
  15613. "SSL_CTX_new error: %s",
  15614. ssl_error());
  15615. }
  15616. closesocket(sock);
  15617. mg_free(conn);
  15618. return NULL;
  15619. }
  15620. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15621. #endif /* NO_SSL */
  15622. #if defined(USE_IPV6)
  15623. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15624. : sizeof(conn->client.rsa.sin6);
  15625. psa = (sa.sa.sa_family == AF_INET)
  15626. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15627. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15628. #else
  15629. len = sizeof(conn->client.rsa.sin);
  15630. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15631. #endif
  15632. conn->client.sock = sock;
  15633. conn->client.lsa = sa;
  15634. if (getsockname(sock, psa, &len) != 0) {
  15635. mg_cry_internal(conn,
  15636. "%s: getsockname() failed: %s",
  15637. __func__,
  15638. strerror(ERRNO));
  15639. }
  15640. conn->client.is_ssl = use_ssl ? 1 : 0;
  15641. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15642. if (error != NULL) {
  15643. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15644. error->code_sub = (unsigned)ERRNO;
  15645. mg_snprintf(NULL,
  15646. NULL, /* No truncation check for ebuf */
  15647. error->text,
  15648. error->text_buffer_size,
  15649. "Can not create mutex");
  15650. }
  15651. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15652. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15653. #endif
  15654. closesocket(sock);
  15655. mg_free(conn);
  15656. return NULL;
  15657. }
  15658. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15659. if (use_ssl) {
  15660. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15661. * SSL_CTX_set_verify call is needed to switch off server
  15662. * certificate checking, which is off by default in OpenSSL and
  15663. * on in yaSSL. */
  15664. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15665. * SSL_VERIFY_PEER, verify_ssl_server); */
  15666. if (client_options->client_cert) {
  15667. if (!ssl_use_pem_file(conn->phys_ctx,
  15668. conn->dom_ctx,
  15669. client_options->client_cert,
  15670. NULL)) {
  15671. if (error != NULL) {
  15672. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15673. mg_snprintf(NULL,
  15674. NULL, /* No truncation check for ebuf */
  15675. error->text,
  15676. error->text_buffer_size,
  15677. "Can not use SSL client certificate");
  15678. }
  15679. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15680. closesocket(sock);
  15681. mg_free(conn);
  15682. return NULL;
  15683. }
  15684. }
  15685. if (client_options->server_cert) {
  15686. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15687. client_options->server_cert,
  15688. NULL)
  15689. != 1) {
  15690. if (error != NULL) {
  15691. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15692. mg_snprintf(NULL,
  15693. NULL, /* No truncation check for ebuf */
  15694. error->text,
  15695. error->text_buffer_size,
  15696. "SSL_CTX_load_verify_locations error: %s",
  15697. ssl_error());
  15698. }
  15699. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15700. closesocket(sock);
  15701. mg_free(conn);
  15702. return NULL;
  15703. }
  15704. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15705. } else {
  15706. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15707. }
  15708. if (!sslize(conn, SSL_connect, client_options)) {
  15709. if (error != NULL) {
  15710. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15711. mg_snprintf(NULL,
  15712. NULL, /* No truncation check for ebuf */
  15713. error->text,
  15714. error->text_buffer_size,
  15715. "SSL connection error");
  15716. }
  15717. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15718. closesocket(sock);
  15719. mg_free(conn);
  15720. return NULL;
  15721. }
  15722. }
  15723. #endif
  15724. return conn;
  15725. }
  15726. CIVETWEB_API struct mg_connection *
  15727. mg_connect_client_secure(const struct mg_client_options *client_options,
  15728. char *error_buffer,
  15729. size_t error_buffer_size)
  15730. {
  15731. struct mg_init_data init;
  15732. struct mg_error_data error;
  15733. memset(&init, 0, sizeof(init));
  15734. memset(&error, 0, sizeof(error));
  15735. error.text_buffer_size = error_buffer_size;
  15736. error.text = error_buffer;
  15737. return mg_connect_client_impl(client_options, 1, &init, &error);
  15738. }
  15739. CIVETWEB_API struct mg_connection *
  15740. mg_connect_client(const char *host,
  15741. int port,
  15742. int use_ssl,
  15743. char *error_buffer,
  15744. size_t error_buffer_size)
  15745. {
  15746. struct mg_client_options opts;
  15747. struct mg_init_data init;
  15748. struct mg_error_data error;
  15749. memset(&init, 0, sizeof(init));
  15750. memset(&error, 0, sizeof(error));
  15751. error.text_buffer_size = error_buffer_size;
  15752. error.text = error_buffer;
  15753. memset(&opts, 0, sizeof(opts));
  15754. opts.host = host;
  15755. opts.port = port;
  15756. if (use_ssl) {
  15757. opts.host_name = host;
  15758. }
  15759. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  15760. }
  15761. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15762. CIVETWEB_API struct mg_connection *
  15763. mg_connect_client2(const char *host,
  15764. const char *protocol,
  15765. int port,
  15766. const char *path,
  15767. struct mg_init_data *init,
  15768. struct mg_error_data *error)
  15769. {
  15770. (void)path;
  15771. int is_ssl, is_ws;
  15772. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15773. if (error != NULL) {
  15774. error->code = MG_ERROR_DATA_CODE_OK;
  15775. error->code_sub = 0;
  15776. if (error->text_buffer_size > 0) {
  15777. *error->text = 0;
  15778. }
  15779. }
  15780. if ((host == NULL) || (protocol == NULL)) {
  15781. if (error != NULL) {
  15782. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15783. mg_snprintf(NULL,
  15784. NULL, /* No truncation check for error buffers */
  15785. error->text,
  15786. error->text_buffer_size,
  15787. "%s",
  15788. "Invalid parameters");
  15789. }
  15790. return NULL;
  15791. }
  15792. /* check all known protocolls */
  15793. if (!mg_strcasecmp(protocol, "http")) {
  15794. is_ssl = 0;
  15795. is_ws = 0;
  15796. } else if (!mg_strcasecmp(protocol, "https")) {
  15797. is_ssl = 1;
  15798. is_ws = 0;
  15799. #if defined(USE_WEBSOCKET)
  15800. } else if (!mg_strcasecmp(protocol, "ws")) {
  15801. is_ssl = 0;
  15802. is_ws = 1;
  15803. } else if (!mg_strcasecmp(protocol, "wss")) {
  15804. is_ssl = 1;
  15805. is_ws = 1;
  15806. #endif
  15807. } else {
  15808. if (error != NULL) {
  15809. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15810. mg_snprintf(NULL,
  15811. NULL, /* No truncation check for error buffers */
  15812. error->text,
  15813. error->text_buffer_size,
  15814. "Protocol %s not supported",
  15815. protocol);
  15816. }
  15817. return NULL;
  15818. }
  15819. /* TODO: The current implementation here just calls the old
  15820. * implementations, without using any new options. This is just a first
  15821. * step to test the new interfaces. */
  15822. #if defined(USE_WEBSOCKET)
  15823. if (is_ws) {
  15824. /* TODO: implement all options */
  15825. return mg_connect_websocket_client(
  15826. host,
  15827. port,
  15828. is_ssl,
  15829. ((error != NULL) ? error->text : NULL),
  15830. ((error != NULL) ? error->text_buffer_size : 0),
  15831. (path ? path : ""),
  15832. NULL /* TODO: origin */,
  15833. experimental_websocket_client_data_wrapper,
  15834. experimental_websocket_client_close_wrapper,
  15835. (void *)init->callbacks);
  15836. }
  15837. #else
  15838. (void)is_ws;
  15839. #endif
  15840. /* TODO: all additional options */
  15841. struct mg_client_options opts;
  15842. memset(&opts, 0, sizeof(opts));
  15843. opts.host = host;
  15844. opts.port = port;
  15845. return mg_connect_client_impl(&opts, is_ssl, init, error);
  15846. }
  15847. #endif
  15848. static const struct {
  15849. const char *proto;
  15850. size_t proto_len;
  15851. unsigned default_port;
  15852. } abs_uri_protocols[] = {{"http://", 7, 80},
  15853. {"https://", 8, 443},
  15854. {"ws://", 5, 80},
  15855. {"wss://", 6, 443},
  15856. {NULL, 0, 0}};
  15857. /* Check if the uri is valid.
  15858. * return 0 for invalid uri,
  15859. * return 1 for *,
  15860. * return 2 for relative uri,
  15861. * return 3 for absolute uri without port,
  15862. * return 4 for absolute uri with port */
  15863. static int
  15864. get_uri_type(const char *uri)
  15865. {
  15866. int i;
  15867. const char *hostend, *portbegin;
  15868. char *portend;
  15869. unsigned long port;
  15870. /* According to the HTTP standard
  15871. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15872. * URI can be an asterisk (*) or should start with slash (relative uri),
  15873. * or it should start with the protocol (absolute uri). */
  15874. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15875. /* asterisk */
  15876. return 1;
  15877. }
  15878. /* Valid URIs according to RFC 3986
  15879. * (https://www.ietf.org/rfc/rfc3986.txt)
  15880. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15881. * and unreserved characters A-Z a-z 0-9 and -._~
  15882. * and % encoded symbols.
  15883. */
  15884. for (i = 0; uri[i] != 0; i++) {
  15885. if (uri[i] < 33) {
  15886. /* control characters and spaces are invalid */
  15887. return 0;
  15888. }
  15889. /* Allow everything else here (See #894) */
  15890. }
  15891. /* A relative uri starts with a / character */
  15892. if (uri[0] == '/') {
  15893. /* relative uri */
  15894. return 2;
  15895. }
  15896. /* It could be an absolute uri: */
  15897. /* This function only checks if the uri is valid, not if it is
  15898. * addressing the current server. So civetweb can also be used
  15899. * as a proxy server. */
  15900. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15901. if (mg_strncasecmp(uri,
  15902. abs_uri_protocols[i].proto,
  15903. abs_uri_protocols[i].proto_len)
  15904. == 0) {
  15905. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15906. if (!hostend) {
  15907. return 0;
  15908. }
  15909. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15910. if (!portbegin) {
  15911. return 3;
  15912. }
  15913. port = strtoul(portbegin + 1, &portend, 10);
  15914. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15915. return 0;
  15916. }
  15917. return 4;
  15918. }
  15919. }
  15920. return 0;
  15921. }
  15922. /* Return NULL or the relative uri at the current server */
  15923. static const char *
  15924. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15925. {
  15926. const char *server_domain;
  15927. size_t server_domain_len;
  15928. size_t request_domain_len = 0;
  15929. unsigned long port = 0;
  15930. int i, auth_domain_check_enabled;
  15931. const char *hostbegin = NULL;
  15932. const char *hostend = NULL;
  15933. const char *portbegin;
  15934. char *portend;
  15935. auth_domain_check_enabled =
  15936. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15937. /* DNS is case insensitive, so use case insensitive string compare here
  15938. */
  15939. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15940. if (mg_strncasecmp(uri,
  15941. abs_uri_protocols[i].proto,
  15942. abs_uri_protocols[i].proto_len)
  15943. == 0) {
  15944. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15945. hostend = strchr(hostbegin, '/');
  15946. if (!hostend) {
  15947. return 0;
  15948. }
  15949. portbegin = strchr(hostbegin, ':');
  15950. if ((!portbegin) || (portbegin > hostend)) {
  15951. port = abs_uri_protocols[i].default_port;
  15952. request_domain_len = (size_t)(hostend - hostbegin);
  15953. } else {
  15954. port = strtoul(portbegin + 1, &portend, 10);
  15955. if ((portend != hostend) || (port <= 0)
  15956. || !is_valid_port(port)) {
  15957. return 0;
  15958. }
  15959. request_domain_len = (size_t)(portbegin - hostbegin);
  15960. }
  15961. /* protocol found, port set */
  15962. break;
  15963. }
  15964. }
  15965. if (!port) {
  15966. /* port remains 0 if the protocol is not found */
  15967. return 0;
  15968. }
  15969. /* Check if the request is directed to a different server. */
  15970. /* First check if the port is the same. */
  15971. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15972. /* Request is directed to a different port */
  15973. return 0;
  15974. }
  15975. /* Finally check if the server corresponds to the authentication
  15976. * domain of the server (the server domain).
  15977. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15978. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15979. * but do not allow substrings (like
  15980. * http://notmydomain.com/path/file.ext
  15981. * or http://mydomain.com.fake/path/file.ext).
  15982. */
  15983. if (auth_domain_check_enabled) {
  15984. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15985. server_domain_len = strlen(server_domain);
  15986. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15987. return 0;
  15988. }
  15989. if ((request_domain_len == server_domain_len)
  15990. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15991. /* Request is directed to this server - full name match. */
  15992. } else {
  15993. if (request_domain_len < (server_domain_len + 2)) {
  15994. /* Request is directed to another server: The server name
  15995. * is longer than the request name.
  15996. * Drop this case here to avoid overflows in the
  15997. * following checks. */
  15998. return 0;
  15999. }
  16000. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16001. /* Request is directed to another server: It could be a
  16002. * substring
  16003. * like notmyserver.com */
  16004. return 0;
  16005. }
  16006. if (0
  16007. != memcmp(server_domain,
  16008. hostbegin + request_domain_len - server_domain_len,
  16009. server_domain_len)) {
  16010. /* Request is directed to another server:
  16011. * The server name is different. */
  16012. return 0;
  16013. }
  16014. }
  16015. }
  16016. return hostend;
  16017. }
  16018. static int
  16019. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16020. {
  16021. if (ebuf_len > 0) {
  16022. ebuf[0] = '\0';
  16023. }
  16024. *err = 0;
  16025. reset_per_request_attributes(conn);
  16026. if (!conn) {
  16027. mg_snprintf(conn,
  16028. NULL, /* No truncation check for ebuf */
  16029. ebuf,
  16030. ebuf_len,
  16031. "%s",
  16032. "Internal error");
  16033. *err = 500;
  16034. return 0;
  16035. }
  16036. /* Set the time the request was received. This value should be used for
  16037. * timeouts. */
  16038. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16039. conn->request_len =
  16040. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16041. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16042. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16043. mg_snprintf(conn,
  16044. NULL, /* No truncation check for ebuf */
  16045. ebuf,
  16046. ebuf_len,
  16047. "%s",
  16048. "Invalid message size");
  16049. *err = 500;
  16050. return 0;
  16051. }
  16052. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16053. mg_snprintf(conn,
  16054. NULL, /* No truncation check for ebuf */
  16055. ebuf,
  16056. ebuf_len,
  16057. "%s",
  16058. "Message too large");
  16059. *err = 413;
  16060. return 0;
  16061. }
  16062. if (conn->request_len <= 0) {
  16063. if (conn->data_len > 0) {
  16064. mg_snprintf(conn,
  16065. NULL, /* No truncation check for ebuf */
  16066. ebuf,
  16067. ebuf_len,
  16068. "%s",
  16069. "Malformed message");
  16070. *err = 400;
  16071. } else {
  16072. /* Server did not recv anything -> just close the connection */
  16073. conn->must_close = 1;
  16074. mg_snprintf(conn,
  16075. NULL, /* No truncation check for ebuf */
  16076. ebuf,
  16077. ebuf_len,
  16078. "%s",
  16079. "No data received");
  16080. *err = 0;
  16081. }
  16082. return 0;
  16083. }
  16084. return 1;
  16085. }
  16086. static int
  16087. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16088. {
  16089. const char *cl;
  16090. conn->connection_type =
  16091. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16092. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16093. return 0;
  16094. }
  16095. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16096. <= 0) {
  16097. mg_snprintf(conn,
  16098. NULL, /* No truncation check for ebuf */
  16099. ebuf,
  16100. ebuf_len,
  16101. "%s",
  16102. "Bad request");
  16103. *err = 400;
  16104. return 0;
  16105. }
  16106. /* Message is a valid request */
  16107. if (!switch_domain_context(conn)) {
  16108. mg_snprintf(conn,
  16109. NULL, /* No truncation check for ebuf */
  16110. ebuf,
  16111. ebuf_len,
  16112. "%s",
  16113. "Bad request: Host mismatch");
  16114. *err = 400;
  16115. return 0;
  16116. }
  16117. #if USE_ZLIB
  16118. if (((cl = get_header(conn->request_info.http_headers,
  16119. conn->request_info.num_headers,
  16120. "Accept-Encoding"))
  16121. != NULL)
  16122. && strstr(cl, "gzip")) {
  16123. conn->accept_gzip = 1;
  16124. }
  16125. #endif
  16126. if (((cl = get_header(conn->request_info.http_headers,
  16127. conn->request_info.num_headers,
  16128. "Transfer-Encoding"))
  16129. != NULL)
  16130. && mg_strcasecmp(cl, "identity")) {
  16131. if (mg_strcasecmp(cl, "chunked")) {
  16132. mg_snprintf(conn,
  16133. NULL, /* No truncation check for ebuf */
  16134. ebuf,
  16135. ebuf_len,
  16136. "%s",
  16137. "Bad request");
  16138. *err = 400;
  16139. return 0;
  16140. }
  16141. conn->is_chunked = 1;
  16142. conn->content_len = 0; /* not yet read */
  16143. } else if ((cl = get_header(conn->request_info.http_headers,
  16144. conn->request_info.num_headers,
  16145. "Content-Length"))
  16146. != NULL) {
  16147. /* Request has content length set */
  16148. char *endptr = NULL;
  16149. conn->content_len = strtoll(cl, &endptr, 10);
  16150. if ((endptr == cl) || (conn->content_len < 0)) {
  16151. mg_snprintf(conn,
  16152. NULL, /* No truncation check for ebuf */
  16153. ebuf,
  16154. ebuf_len,
  16155. "%s",
  16156. "Bad request");
  16157. *err = 411;
  16158. return 0;
  16159. }
  16160. /* Publish the content length back to the request info. */
  16161. conn->request_info.content_length = conn->content_len;
  16162. } else {
  16163. /* There is no exception, see RFC7230. */
  16164. conn->content_len = 0;
  16165. }
  16166. return 1;
  16167. }
  16168. /* conn is assumed to be valid in this internal function */
  16169. static int
  16170. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16171. {
  16172. const char *cl;
  16173. conn->connection_type =
  16174. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16175. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16176. return 0;
  16177. }
  16178. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16179. <= 0) {
  16180. mg_snprintf(conn,
  16181. NULL, /* No truncation check for ebuf */
  16182. ebuf,
  16183. ebuf_len,
  16184. "%s",
  16185. "Bad response");
  16186. *err = 400;
  16187. return 0;
  16188. }
  16189. /* Message is a valid response */
  16190. if (((cl = get_header(conn->response_info.http_headers,
  16191. conn->response_info.num_headers,
  16192. "Transfer-Encoding"))
  16193. != NULL)
  16194. && mg_strcasecmp(cl, "identity")) {
  16195. if (mg_strcasecmp(cl, "chunked")) {
  16196. mg_snprintf(conn,
  16197. NULL, /* No truncation check for ebuf */
  16198. ebuf,
  16199. ebuf_len,
  16200. "%s",
  16201. "Bad request");
  16202. *err = 400;
  16203. return 0;
  16204. }
  16205. conn->is_chunked = 1;
  16206. conn->content_len = 0; /* not yet read */
  16207. } else if ((cl = get_header(conn->response_info.http_headers,
  16208. conn->response_info.num_headers,
  16209. "Content-Length"))
  16210. != NULL) {
  16211. char *endptr = NULL;
  16212. conn->content_len = strtoll(cl, &endptr, 10);
  16213. if ((endptr == cl) || (conn->content_len < 0)) {
  16214. mg_snprintf(conn,
  16215. NULL, /* No truncation check for ebuf */
  16216. ebuf,
  16217. ebuf_len,
  16218. "%s",
  16219. "Bad request");
  16220. *err = 411;
  16221. return 0;
  16222. }
  16223. /* Publish the content length back to the response info. */
  16224. conn->response_info.content_length = conn->content_len;
  16225. /* TODO: check if it is still used in response_info */
  16226. conn->request_info.content_length = conn->content_len;
  16227. /* TODO: we should also consider HEAD method */
  16228. if (conn->response_info.status_code == 304) {
  16229. conn->content_len = 0;
  16230. }
  16231. } else {
  16232. /* TODO: we should also consider HEAD method */
  16233. if (((conn->response_info.status_code >= 100)
  16234. && (conn->response_info.status_code <= 199))
  16235. || (conn->response_info.status_code == 204)
  16236. || (conn->response_info.status_code == 304)) {
  16237. conn->content_len = 0;
  16238. } else {
  16239. conn->content_len = -1; /* unknown content length */
  16240. }
  16241. }
  16242. return 1;
  16243. }
  16244. CIVETWEB_API int
  16245. mg_get_response(struct mg_connection *conn,
  16246. char *ebuf,
  16247. size_t ebuf_len,
  16248. int timeout)
  16249. {
  16250. int err, ret;
  16251. char txt[32]; /* will not overflow */
  16252. char *save_timeout;
  16253. char *new_timeout;
  16254. if (ebuf_len > 0) {
  16255. ebuf[0] = '\0';
  16256. }
  16257. if (!conn) {
  16258. mg_snprintf(conn,
  16259. NULL, /* No truncation check for ebuf */
  16260. ebuf,
  16261. ebuf_len,
  16262. "%s",
  16263. "Parameter error");
  16264. return -1;
  16265. }
  16266. /* Reset the previous responses */
  16267. conn->data_len = 0;
  16268. /* Implementation of API function for HTTP clients */
  16269. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16270. if (timeout >= 0) {
  16271. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16272. new_timeout = txt;
  16273. } else {
  16274. new_timeout = NULL;
  16275. }
  16276. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16277. ret = get_response(conn, ebuf, ebuf_len, &err);
  16278. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16279. /* TODO: here, the URI is the http response code */
  16280. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16281. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16282. /* TODO (mid): Define proper return values - maybe return length?
  16283. * For the first test use <0 for error and >0 for OK */
  16284. return (ret == 0) ? -1 : +1;
  16285. }
  16286. CIVETWEB_API struct mg_connection *
  16287. mg_download(const char *host,
  16288. int port,
  16289. int use_ssl,
  16290. char *ebuf,
  16291. size_t ebuf_len,
  16292. const char *fmt,
  16293. ...)
  16294. {
  16295. struct mg_connection *conn;
  16296. va_list ap;
  16297. int i;
  16298. int reqerr;
  16299. if (ebuf_len > 0) {
  16300. ebuf[0] = '\0';
  16301. }
  16302. va_start(ap, fmt);
  16303. /* open a connection */
  16304. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16305. if (conn != NULL) {
  16306. i = mg_vprintf(conn, fmt, ap);
  16307. if (i <= 0) {
  16308. mg_snprintf(conn,
  16309. NULL, /* No truncation check for ebuf */
  16310. ebuf,
  16311. ebuf_len,
  16312. "%s",
  16313. "Error sending request");
  16314. } else {
  16315. /* make sure the buffer is clear */
  16316. conn->data_len = 0;
  16317. get_response(conn, ebuf, ebuf_len, &reqerr);
  16318. /* TODO: here, the URI is the http response code */
  16319. conn->request_info.local_uri = conn->request_info.request_uri;
  16320. }
  16321. }
  16322. /* if an error occurred, close the connection */
  16323. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16324. mg_close_connection(conn);
  16325. conn = NULL;
  16326. }
  16327. va_end(ap);
  16328. return conn;
  16329. }
  16330. struct websocket_client_thread_data {
  16331. struct mg_connection *conn;
  16332. mg_websocket_data_handler data_handler;
  16333. mg_websocket_close_handler close_handler;
  16334. void *callback_data;
  16335. };
  16336. #if defined(USE_WEBSOCKET)
  16337. #if defined(_WIN32)
  16338. static unsigned __stdcall websocket_client_thread(void *data)
  16339. #else
  16340. static void *
  16341. websocket_client_thread(void *data)
  16342. #endif
  16343. {
  16344. struct websocket_client_thread_data *cdata =
  16345. (struct websocket_client_thread_data *)data;
  16346. void *user_thread_ptr = NULL;
  16347. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16348. struct sigaction sa;
  16349. /* Ignore SIGPIPE */
  16350. memset(&sa, 0, sizeof(sa));
  16351. sa.sa_handler = SIG_IGN;
  16352. sigaction(SIGPIPE, &sa, NULL);
  16353. #endif
  16354. mg_set_thread_name("ws-clnt");
  16355. if (cdata->conn->phys_ctx) {
  16356. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16357. /* 3 indicates a websocket client thread */
  16358. /* TODO: check if conn->phys_ctx can be set */
  16359. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16360. cdata->conn->phys_ctx, 3);
  16361. }
  16362. }
  16363. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16364. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16365. if (cdata->close_handler != NULL) {
  16366. cdata->close_handler(cdata->conn, cdata->callback_data);
  16367. }
  16368. /* The websocket_client context has only this thread. If it runs out,
  16369. set the stop_flag to 2 (= "stopped"). */
  16370. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16371. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16372. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16373. 3,
  16374. user_thread_ptr);
  16375. }
  16376. mg_free((void *)cdata);
  16377. #if defined(_WIN32)
  16378. return 0;
  16379. #else
  16380. return NULL;
  16381. #endif
  16382. }
  16383. #endif
  16384. static struct mg_connection *
  16385. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16386. int use_ssl,
  16387. char *error_buffer,
  16388. size_t error_buffer_size,
  16389. const char *path,
  16390. const char *origin,
  16391. const char *extensions,
  16392. mg_websocket_data_handler data_func,
  16393. mg_websocket_close_handler close_func,
  16394. void *user_data)
  16395. {
  16396. struct mg_connection *conn = NULL;
  16397. #if defined(USE_WEBSOCKET)
  16398. struct websocket_client_thread_data *thread_data;
  16399. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16400. const char *host = client_options->host;
  16401. int i;
  16402. struct mg_init_data init;
  16403. struct mg_error_data error;
  16404. memset(&init, 0, sizeof(init));
  16405. memset(&error, 0, sizeof(error));
  16406. error.text_buffer_size = error_buffer_size;
  16407. error.text = error_buffer;
  16408. #if defined(__clang__)
  16409. #pragma clang diagnostic push
  16410. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16411. #endif
  16412. /* Establish the client connection and request upgrade */
  16413. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16414. /* Connection object will be null if something goes wrong */
  16415. if (conn == NULL) {
  16416. /* error_buffer should be already filled ... */
  16417. if (!error_buffer[0]) {
  16418. /* ... if not add an error message */
  16419. mg_snprintf(conn,
  16420. NULL, /* No truncation check for ebuf */
  16421. error_buffer,
  16422. error_buffer_size,
  16423. "Unexpected error");
  16424. }
  16425. return NULL;
  16426. }
  16427. if (origin != NULL) {
  16428. if (extensions != NULL) {
  16429. i = mg_printf(conn,
  16430. "GET %s HTTP/1.1\r\n"
  16431. "Host: %s\r\n"
  16432. "Upgrade: websocket\r\n"
  16433. "Connection: Upgrade\r\n"
  16434. "Sec-WebSocket-Key: %s\r\n"
  16435. "Sec-WebSocket-Version: 13\r\n"
  16436. "Sec-WebSocket-Extensions: %s\r\n"
  16437. "Origin: %s\r\n"
  16438. "\r\n",
  16439. path,
  16440. host,
  16441. magic,
  16442. extensions,
  16443. origin);
  16444. } else {
  16445. i = mg_printf(conn,
  16446. "GET %s HTTP/1.1\r\n"
  16447. "Host: %s\r\n"
  16448. "Upgrade: websocket\r\n"
  16449. "Connection: Upgrade\r\n"
  16450. "Sec-WebSocket-Key: %s\r\n"
  16451. "Sec-WebSocket-Version: 13\r\n"
  16452. "Origin: %s\r\n"
  16453. "\r\n",
  16454. path,
  16455. host,
  16456. magic,
  16457. origin);
  16458. }
  16459. } else {
  16460. if (extensions != NULL) {
  16461. i = mg_printf(conn,
  16462. "GET %s HTTP/1.1\r\n"
  16463. "Host: %s\r\n"
  16464. "Upgrade: websocket\r\n"
  16465. "Connection: Upgrade\r\n"
  16466. "Sec-WebSocket-Key: %s\r\n"
  16467. "Sec-WebSocket-Version: 13\r\n"
  16468. "Sec-WebSocket-Extensions: %s\r\n"
  16469. "\r\n",
  16470. path,
  16471. host,
  16472. magic,
  16473. extensions);
  16474. } else {
  16475. i = mg_printf(conn,
  16476. "GET %s HTTP/1.1\r\n"
  16477. "Host: %s\r\n"
  16478. "Upgrade: websocket\r\n"
  16479. "Connection: Upgrade\r\n"
  16480. "Sec-WebSocket-Key: %s\r\n"
  16481. "Sec-WebSocket-Version: 13\r\n"
  16482. "\r\n",
  16483. path,
  16484. host,
  16485. magic);
  16486. }
  16487. }
  16488. if (i <= 0) {
  16489. mg_snprintf(conn,
  16490. NULL, /* No truncation check for ebuf */
  16491. error_buffer,
  16492. error_buffer_size,
  16493. "%s",
  16494. "Error sending request");
  16495. mg_close_connection(conn);
  16496. return NULL;
  16497. }
  16498. conn->data_len = 0;
  16499. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16500. mg_close_connection(conn);
  16501. return NULL;
  16502. }
  16503. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16504. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16505. #if defined(__clang__)
  16506. #pragma clang diagnostic pop
  16507. #endif
  16508. if (conn->response_info.status_code != 101) {
  16509. /* We sent an "upgrade" request. For a correct websocket
  16510. * protocol handshake, we expect a "101 Continue" response.
  16511. * Otherwise it is a protocol violation. Maybe the HTTP
  16512. * Server does not know websockets. */
  16513. if (!*error_buffer) {
  16514. /* set an error, if not yet set */
  16515. mg_snprintf(conn,
  16516. NULL, /* No truncation check for ebuf */
  16517. error_buffer,
  16518. error_buffer_size,
  16519. "Unexpected server reply");
  16520. }
  16521. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16522. mg_close_connection(conn);
  16523. return NULL;
  16524. }
  16525. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16526. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16527. if (!thread_data) {
  16528. DEBUG_TRACE("%s\r\n", "Out of memory");
  16529. mg_close_connection(conn);
  16530. return NULL;
  16531. }
  16532. thread_data->conn = conn;
  16533. thread_data->data_handler = data_func;
  16534. thread_data->close_handler = close_func;
  16535. thread_data->callback_data = user_data;
  16536. conn->phys_ctx->worker_threadids =
  16537. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16538. if (!conn->phys_ctx->worker_threadids) {
  16539. DEBUG_TRACE("%s\r\n", "Out of memory");
  16540. mg_free(thread_data);
  16541. mg_close_connection(conn);
  16542. return NULL;
  16543. }
  16544. /* Now upgrade to ws/wss client context */
  16545. conn->phys_ctx->user_data = user_data;
  16546. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16547. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16548. /* Start a thread to read the websocket client connection
  16549. * This thread will automatically stop when mg_disconnect is
  16550. * called on the client connection */
  16551. if (mg_start_thread_with_id(websocket_client_thread,
  16552. thread_data,
  16553. conn->phys_ctx->worker_threadids)
  16554. != 0) {
  16555. conn->phys_ctx->cfg_worker_threads = 0;
  16556. mg_free(thread_data);
  16557. mg_close_connection(conn);
  16558. conn = NULL;
  16559. DEBUG_TRACE("%s",
  16560. "Websocket client connect thread could not be started\r\n");
  16561. }
  16562. #else
  16563. /* Appease "unused parameter" warnings */
  16564. (void)client_options;
  16565. (void)use_ssl;
  16566. (void)error_buffer;
  16567. (void)error_buffer_size;
  16568. (void)path;
  16569. (void)origin;
  16570. (void)extensions;
  16571. (void)user_data;
  16572. (void)data_func;
  16573. (void)close_func;
  16574. #endif
  16575. return conn;
  16576. }
  16577. CIVETWEB_API struct mg_connection *
  16578. mg_connect_websocket_client(const char *host,
  16579. int port,
  16580. int use_ssl,
  16581. char *error_buffer,
  16582. size_t error_buffer_size,
  16583. const char *path,
  16584. const char *origin,
  16585. mg_websocket_data_handler data_func,
  16586. mg_websocket_close_handler close_func,
  16587. void *user_data)
  16588. {
  16589. struct mg_client_options client_options;
  16590. memset(&client_options, 0, sizeof(client_options));
  16591. client_options.host = host;
  16592. client_options.port = port;
  16593. return mg_connect_websocket_client_impl(&client_options,
  16594. use_ssl,
  16595. error_buffer,
  16596. error_buffer_size,
  16597. path,
  16598. origin,
  16599. NULL,
  16600. data_func,
  16601. close_func,
  16602. user_data);
  16603. }
  16604. CIVETWEB_API struct mg_connection *
  16605. mg_connect_websocket_client_secure(
  16606. const struct mg_client_options *client_options,
  16607. char *error_buffer,
  16608. size_t error_buffer_size,
  16609. const char *path,
  16610. const char *origin,
  16611. mg_websocket_data_handler data_func,
  16612. mg_websocket_close_handler close_func,
  16613. void *user_data)
  16614. {
  16615. if (!client_options) {
  16616. return NULL;
  16617. }
  16618. return mg_connect_websocket_client_impl(client_options,
  16619. 1,
  16620. error_buffer,
  16621. error_buffer_size,
  16622. path,
  16623. origin,
  16624. NULL,
  16625. data_func,
  16626. close_func,
  16627. user_data);
  16628. }
  16629. CIVETWEB_API struct mg_connection *
  16630. mg_connect_websocket_client_extensions(const char *host,
  16631. int port,
  16632. int use_ssl,
  16633. char *error_buffer,
  16634. size_t error_buffer_size,
  16635. const char *path,
  16636. const char *origin,
  16637. const char *extensions,
  16638. mg_websocket_data_handler data_func,
  16639. mg_websocket_close_handler close_func,
  16640. void *user_data)
  16641. {
  16642. struct mg_client_options client_options;
  16643. memset(&client_options, 0, sizeof(client_options));
  16644. client_options.host = host;
  16645. client_options.port = port;
  16646. return mg_connect_websocket_client_impl(&client_options,
  16647. use_ssl,
  16648. error_buffer,
  16649. error_buffer_size,
  16650. path,
  16651. origin,
  16652. extensions,
  16653. data_func,
  16654. close_func,
  16655. user_data);
  16656. }
  16657. CIVETWEB_API struct mg_connection *
  16658. mg_connect_websocket_client_secure_extensions(
  16659. const struct mg_client_options *client_options,
  16660. char *error_buffer,
  16661. size_t error_buffer_size,
  16662. const char *path,
  16663. const char *origin,
  16664. const char *extensions,
  16665. mg_websocket_data_handler data_func,
  16666. mg_websocket_close_handler close_func,
  16667. void *user_data)
  16668. {
  16669. if (!client_options) {
  16670. return NULL;
  16671. }
  16672. return mg_connect_websocket_client_impl(client_options,
  16673. 1,
  16674. error_buffer,
  16675. error_buffer_size,
  16676. path,
  16677. origin,
  16678. extensions,
  16679. data_func,
  16680. close_func,
  16681. user_data);
  16682. }
  16683. /* Prepare connection data structure */
  16684. static void
  16685. init_connection(struct mg_connection *conn)
  16686. {
  16687. /* Is keep alive allowed by the server */
  16688. int keep_alive_enabled =
  16689. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16690. if (!keep_alive_enabled) {
  16691. conn->must_close = 1;
  16692. }
  16693. /* Important: on new connection, reset the receiving buffer. Credit
  16694. * goes to crule42. */
  16695. conn->data_len = 0;
  16696. conn->handled_requests = 0;
  16697. conn->connection_type = CONNECTION_TYPE_INVALID;
  16698. mg_set_user_connection_data(conn, NULL);
  16699. #if defined(USE_SERVER_STATS)
  16700. conn->conn_state = 2; /* init */
  16701. #endif
  16702. /* call the init_connection callback if assigned */
  16703. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16704. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16705. void *conn_data = NULL;
  16706. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16707. mg_set_user_connection_data(conn, conn_data);
  16708. }
  16709. }
  16710. }
  16711. /* Process a connection - may handle multiple requests
  16712. * using the same connection.
  16713. * Must be called with a valid connection (conn and
  16714. * conn->phys_ctx must be valid).
  16715. */
  16716. static void
  16717. process_new_connection(struct mg_connection *conn)
  16718. {
  16719. struct mg_request_info *ri = &conn->request_info;
  16720. int keep_alive, discard_len;
  16721. char ebuf[100];
  16722. const char *hostend;
  16723. int reqerr, uri_type;
  16724. #if defined(USE_SERVER_STATS)
  16725. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16726. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16727. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16728. #endif
  16729. DEBUG_TRACE("Start processing connection from %s",
  16730. conn->request_info.remote_addr);
  16731. /* Loop over multiple requests sent using the same connection
  16732. * (while "keep alive"). */
  16733. do {
  16734. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16735. conn->handled_requests + 1);
  16736. #if defined(USE_SERVER_STATS)
  16737. conn->conn_state = 3; /* ready */
  16738. #endif
  16739. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16740. /* The request sent by the client could not be understood by
  16741. * the server, or it was incomplete or a timeout. Send an
  16742. * error message and close the connection. */
  16743. if (reqerr > 0) {
  16744. DEBUG_ASSERT(ebuf[0] != '\0');
  16745. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16746. }
  16747. } else if (strcmp(ri->http_version, "1.0")
  16748. && strcmp(ri->http_version, "1.1")) {
  16749. /* HTTP/2 is not allowed here */
  16750. mg_snprintf(conn,
  16751. NULL, /* No truncation check for ebuf */
  16752. ebuf,
  16753. sizeof(ebuf),
  16754. "Bad HTTP version: [%s]",
  16755. ri->http_version);
  16756. mg_send_http_error(conn, 505, "%s", ebuf);
  16757. }
  16758. if (ebuf[0] == '\0') {
  16759. uri_type = get_uri_type(conn->request_info.request_uri);
  16760. switch (uri_type) {
  16761. case 1:
  16762. /* Asterisk */
  16763. conn->request_info.local_uri_raw = 0;
  16764. /* TODO: Deal with '*'. */
  16765. break;
  16766. case 2:
  16767. /* relative uri */
  16768. conn->request_info.local_uri_raw =
  16769. conn->request_info.request_uri;
  16770. break;
  16771. case 3:
  16772. case 4:
  16773. /* absolute uri (with/without port) */
  16774. hostend = get_rel_url_at_current_server(
  16775. conn->request_info.request_uri, conn);
  16776. if (hostend) {
  16777. conn->request_info.local_uri_raw = hostend;
  16778. } else {
  16779. conn->request_info.local_uri_raw = NULL;
  16780. }
  16781. break;
  16782. default:
  16783. mg_snprintf(conn,
  16784. NULL, /* No truncation check for ebuf */
  16785. ebuf,
  16786. sizeof(ebuf),
  16787. "Invalid URI");
  16788. mg_send_http_error(conn, 400, "%s", ebuf);
  16789. conn->request_info.local_uri_raw = NULL;
  16790. break;
  16791. }
  16792. conn->request_info.local_uri =
  16793. (char *)conn->request_info.local_uri_raw;
  16794. }
  16795. if (ebuf[0] != '\0') {
  16796. conn->protocol_type = -1;
  16797. } else {
  16798. /* HTTP/1 allows protocol upgrade */
  16799. conn->protocol_type = should_switch_to_protocol(conn);
  16800. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16801. /* This will occur, if a HTTP/1.1 request should be upgraded
  16802. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16803. * Since most (all?) major browsers only support HTTP/2 using
  16804. * ALPN, this is hard to test and very low priority.
  16805. * Deactivate it (at least for now).
  16806. */
  16807. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16808. }
  16809. }
  16810. DEBUG_TRACE("http: %s, error: %s",
  16811. (ri->http_version ? ri->http_version : "none"),
  16812. (ebuf[0] ? ebuf : "none"));
  16813. if (ebuf[0] == '\0') {
  16814. if (conn->request_info.local_uri) {
  16815. /* handle request to local server */
  16816. handle_request_stat_log(conn);
  16817. } else {
  16818. /* TODO: handle non-local request (PROXY) */
  16819. conn->must_close = 1;
  16820. }
  16821. } else {
  16822. conn->must_close = 1;
  16823. }
  16824. /* Response complete. Free header buffer */
  16825. free_buffered_response_header_list(conn);
  16826. if (ri->remote_user != NULL) {
  16827. mg_free((void *)ri->remote_user);
  16828. /* Important! When having connections with and without auth
  16829. * would cause double free and then crash */
  16830. ri->remote_user = NULL;
  16831. }
  16832. /* NOTE(lsm): order is important here. should_keep_alive() call
  16833. * is using parsed request, which will be invalid after
  16834. * memmove's below.
  16835. * Therefore, memorize should_keep_alive() result now for later
  16836. * use in loop exit condition. */
  16837. /* Enable it only if this request is completely discardable. */
  16838. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16839. && should_keep_alive(conn) && (conn->content_len >= 0)
  16840. && (conn->request_len > 0)
  16841. && ((conn->is_chunked == 4)
  16842. || (!conn->is_chunked
  16843. && ((conn->consumed_content == conn->content_len)
  16844. || ((conn->request_len + conn->content_len)
  16845. <= conn->data_len))))
  16846. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16847. if (keep_alive) {
  16848. /* Discard all buffered data for this request */
  16849. discard_len =
  16850. ((conn->request_len + conn->content_len) < conn->data_len)
  16851. ? (int)(conn->request_len + conn->content_len)
  16852. : conn->data_len;
  16853. conn->data_len -= discard_len;
  16854. if (conn->data_len > 0) {
  16855. DEBUG_TRACE("discard_len = %d", discard_len);
  16856. memmove(conn->buf,
  16857. conn->buf + discard_len,
  16858. (size_t)conn->data_len);
  16859. }
  16860. }
  16861. DEBUG_ASSERT(conn->data_len >= 0);
  16862. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16863. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16864. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16865. (long int)conn->data_len,
  16866. (long int)conn->buf_size);
  16867. break;
  16868. }
  16869. conn->handled_requests++;
  16870. } while (keep_alive);
  16871. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16872. conn->request_info.remote_addr,
  16873. difftime(time(NULL), conn->conn_birth_time));
  16874. close_connection(conn);
  16875. #if defined(USE_SERVER_STATS)
  16876. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16877. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16878. #endif
  16879. }
  16880. #if defined(ALTERNATIVE_QUEUE)
  16881. static void
  16882. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16883. {
  16884. unsigned int i;
  16885. while (!ctx->stop_flag) {
  16886. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16887. /* find a free worker slot and signal it */
  16888. if (ctx->client_socks[i].in_use == 2) {
  16889. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16890. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16891. ctx->client_socks[i] = *sp;
  16892. ctx->client_socks[i].in_use = 1;
  16893. /* socket has been moved to the consumer */
  16894. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16895. (void)event_signal(ctx->client_wait_events[i]);
  16896. return;
  16897. }
  16898. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16899. }
  16900. }
  16901. /* queue is full */
  16902. mg_sleep(1);
  16903. }
  16904. /* must consume */
  16905. set_blocking_mode(sp->sock);
  16906. closesocket(sp->sock);
  16907. }
  16908. static int
  16909. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16910. {
  16911. DEBUG_TRACE("%s", "going idle");
  16912. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16913. ctx->client_socks[thread_index].in_use = 2;
  16914. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16915. event_wait(ctx->client_wait_events[thread_index]);
  16916. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16917. *sp = ctx->client_socks[thread_index];
  16918. if (ctx->stop_flag) {
  16919. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16920. if (sp->in_use == 1) {
  16921. /* must consume */
  16922. set_blocking_mode(sp->sock);
  16923. closesocket(sp->sock);
  16924. }
  16925. return 0;
  16926. }
  16927. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16928. if (sp->in_use == 1) {
  16929. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16930. return 1;
  16931. }
  16932. /* must not reach here */
  16933. DEBUG_ASSERT(0);
  16934. return 0;
  16935. }
  16936. #else /* ALTERNATIVE_QUEUE */
  16937. /* Worker threads take accepted socket from the queue */
  16938. static int
  16939. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16940. {
  16941. (void)thread_index;
  16942. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16943. DEBUG_TRACE("%s", "going idle");
  16944. /* If the queue is empty, wait. We're idle at this point. */
  16945. while ((ctx->sq_head == ctx->sq_tail)
  16946. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16947. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16948. }
  16949. /* If we're stopping, sq_head may be equal to sq_tail. */
  16950. if (ctx->sq_head > ctx->sq_tail) {
  16951. /* Copy socket from the queue and increment tail */
  16952. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16953. ctx->sq_tail++;
  16954. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16955. /* Wrap pointers if needed */
  16956. while (ctx->sq_tail > ctx->sq_size) {
  16957. ctx->sq_tail -= ctx->sq_size;
  16958. ctx->sq_head -= ctx->sq_size;
  16959. }
  16960. }
  16961. (void)pthread_cond_signal(&ctx->sq_empty);
  16962. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16963. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16964. }
  16965. /* Master thread adds accepted socket to a queue */
  16966. static void
  16967. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16968. {
  16969. int queue_filled;
  16970. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16971. queue_filled = ctx->sq_head - ctx->sq_tail;
  16972. /* If the queue is full, wait */
  16973. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16974. && (queue_filled >= ctx->sq_size)) {
  16975. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16976. #if defined(USE_SERVER_STATS)
  16977. if (queue_filled > ctx->sq_max_fill) {
  16978. ctx->sq_max_fill = queue_filled;
  16979. }
  16980. #endif
  16981. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16982. ctx->sq_blocked = 0; /* Not blocked now */
  16983. queue_filled = ctx->sq_head - ctx->sq_tail;
  16984. }
  16985. if (queue_filled < ctx->sq_size) {
  16986. /* Copy socket to the queue and increment head */
  16987. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16988. ctx->sq_head++;
  16989. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16990. }
  16991. queue_filled = ctx->sq_head - ctx->sq_tail;
  16992. #if defined(USE_SERVER_STATS)
  16993. if (queue_filled > ctx->sq_max_fill) {
  16994. ctx->sq_max_fill = queue_filled;
  16995. }
  16996. #endif
  16997. (void)pthread_cond_signal(&ctx->sq_full);
  16998. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16999. }
  17000. #endif /* ALTERNATIVE_QUEUE */
  17001. static void
  17002. worker_thread_run(struct mg_connection *conn)
  17003. {
  17004. struct mg_context *ctx = conn->phys_ctx;
  17005. int thread_index;
  17006. struct mg_workerTLS tls;
  17007. mg_set_thread_name("worker");
  17008. tls.is_master = 0;
  17009. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17010. #if defined(_WIN32)
  17011. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17012. #endif
  17013. /* Initialize thread local storage before calling any callback */
  17014. pthread_setspecific(sTlsKey, &tls);
  17015. /* Check if there is a user callback */
  17016. if (ctx->callbacks.init_thread) {
  17017. /* call init_thread for a worker thread (type 1), and store the
  17018. * return value */
  17019. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17020. } else {
  17021. /* No callback: set user pointer to NULL */
  17022. tls.user_ptr = NULL;
  17023. }
  17024. /* Connection structure has been pre-allocated */
  17025. thread_index = (int)(conn - ctx->worker_connections);
  17026. if ((thread_index < 0)
  17027. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  17028. mg_cry_ctx_internal(ctx,
  17029. "Internal error: Invalid worker index %i",
  17030. thread_index);
  17031. return;
  17032. }
  17033. /* Request buffers are not pre-allocated. They are private to the
  17034. * request and do not contain any state information that might be
  17035. * of interest to anyone observing a server status. */
  17036. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17037. if (conn->buf == NULL) {
  17038. mg_cry_ctx_internal(
  17039. ctx,
  17040. "Out of memory: Cannot allocate buffer for worker %i",
  17041. thread_index);
  17042. return;
  17043. }
  17044. conn->buf_size = (int)ctx->max_request_size;
  17045. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17046. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17047. conn->request_info.user_data = ctx->user_data;
  17048. /* Allocate a mutex for this connection to allow communication both
  17049. * within the request handler and from elsewhere in the application
  17050. */
  17051. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17052. mg_free(conn->buf);
  17053. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17054. return;
  17055. }
  17056. #if defined(USE_SERVER_STATS)
  17057. conn->conn_state = 1; /* not consumed */
  17058. #endif
  17059. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17060. * signal sq_empty condvar to wake up the master waiting in
  17061. * produce_socket() */
  17062. while (consume_socket(ctx, &conn->client, thread_index)) {
  17063. /* New connections must start with new protocol negotiation */
  17064. tls.alpn_proto = NULL;
  17065. #if defined(USE_SERVER_STATS)
  17066. conn->conn_close_time = 0;
  17067. #endif
  17068. conn->conn_birth_time = time(NULL);
  17069. /* Fill in IP, port info early so even if SSL setup below fails,
  17070. * error handler would have the corresponding info.
  17071. * Thanks to Johannes Winkelmann for the patch.
  17072. */
  17073. conn->request_info.remote_port =
  17074. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17075. conn->request_info.server_port =
  17076. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17077. sockaddr_to_string(conn->request_info.remote_addr,
  17078. sizeof(conn->request_info.remote_addr),
  17079. &conn->client.rsa);
  17080. DEBUG_TRACE("Incomming %sconnection from %s",
  17081. (conn->client.is_ssl ? "SSL " : ""),
  17082. conn->request_info.remote_addr);
  17083. conn->request_info.is_ssl = conn->client.is_ssl;
  17084. if (conn->client.is_ssl) {
  17085. #if defined(USE_MBEDTLS)
  17086. /* HTTPS connection */
  17087. if (mbed_ssl_accept(&(conn->ssl),
  17088. conn->dom_ctx->ssl_ctx,
  17089. (int *)&(conn->client.sock),
  17090. conn->phys_ctx)
  17091. == 0) {
  17092. /* conn->dom_ctx is set in get_request */
  17093. /* process HTTPS connection */
  17094. init_connection(conn);
  17095. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17096. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17097. process_new_connection(conn);
  17098. } else {
  17099. /* make sure the connection is cleaned up on SSL failure */
  17100. close_connection(conn);
  17101. }
  17102. #elif !defined(NO_SSL)
  17103. /* HTTPS connection */
  17104. if (sslize(conn, SSL_accept, NULL)) {
  17105. /* conn->dom_ctx is set in get_request */
  17106. /* Get SSL client certificate information (if set) */
  17107. struct mg_client_cert client_cert;
  17108. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17109. conn->request_info.client_cert = &client_cert;
  17110. }
  17111. /* process HTTPS connection */
  17112. #if defined(USE_HTTP2)
  17113. if ((tls.alpn_proto != NULL)
  17114. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17115. /* process HTTPS/2 connection */
  17116. init_connection(conn);
  17117. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17118. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17119. conn->content_len =
  17120. -1; /* content length is not predefined */
  17121. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17122. process_new_http2_connection(conn);
  17123. } else
  17124. #endif
  17125. {
  17126. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17127. init_connection(conn);
  17128. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17129. /* Start with HTTP, WS will be an "upgrade" request later */
  17130. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17131. process_new_connection(conn);
  17132. }
  17133. /* Free client certificate info */
  17134. if (conn->request_info.client_cert) {
  17135. mg_free((void *)(conn->request_info.client_cert->subject));
  17136. mg_free((void *)(conn->request_info.client_cert->issuer));
  17137. mg_free((void *)(conn->request_info.client_cert->serial));
  17138. mg_free((void *)(conn->request_info.client_cert->finger));
  17139. /* Free certificate memory */
  17140. X509_free(
  17141. (X509 *)conn->request_info.client_cert->peer_cert);
  17142. conn->request_info.client_cert->peer_cert = 0;
  17143. conn->request_info.client_cert->subject = 0;
  17144. conn->request_info.client_cert->issuer = 0;
  17145. conn->request_info.client_cert->serial = 0;
  17146. conn->request_info.client_cert->finger = 0;
  17147. conn->request_info.client_cert = 0;
  17148. }
  17149. } else {
  17150. /* make sure the connection is cleaned up on SSL failure */
  17151. close_connection(conn);
  17152. }
  17153. #endif
  17154. } else {
  17155. /* process HTTP connection */
  17156. init_connection(conn);
  17157. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17158. /* Start with HTTP, WS will be an "upgrade" request later */
  17159. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17160. process_new_connection(conn);
  17161. }
  17162. DEBUG_TRACE("%s", "Connection closed");
  17163. #if defined(USE_SERVER_STATS)
  17164. conn->conn_close_time = time(NULL);
  17165. #endif
  17166. }
  17167. /* Call exit thread user callback */
  17168. if (ctx->callbacks.exit_thread) {
  17169. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17170. }
  17171. /* delete thread local storage objects */
  17172. pthread_setspecific(sTlsKey, NULL);
  17173. #if defined(_WIN32)
  17174. CloseHandle(tls.pthread_cond_helper_mutex);
  17175. #endif
  17176. pthread_mutex_destroy(&conn->mutex);
  17177. /* Free the request buffer. */
  17178. conn->buf_size = 0;
  17179. mg_free(conn->buf);
  17180. conn->buf = NULL;
  17181. /* Free cleaned URI (if any) */
  17182. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17183. mg_free((void *)conn->request_info.local_uri);
  17184. conn->request_info.local_uri = NULL;
  17185. }
  17186. #if defined(USE_SERVER_STATS)
  17187. conn->conn_state = 9; /* done */
  17188. #endif
  17189. DEBUG_TRACE("%s", "exiting");
  17190. }
  17191. /* Threads have different return types on Windows and Unix. */
  17192. #if defined(_WIN32)
  17193. static unsigned __stdcall worker_thread(void *thread_func_param)
  17194. {
  17195. worker_thread_run((struct mg_connection *)thread_func_param);
  17196. return 0;
  17197. }
  17198. #else
  17199. static void *
  17200. worker_thread(void *thread_func_param)
  17201. {
  17202. #if !defined(__ZEPHYR__)
  17203. struct sigaction sa;
  17204. /* Ignore SIGPIPE */
  17205. memset(&sa, 0, sizeof(sa));
  17206. sa.sa_handler = SIG_IGN;
  17207. sigaction(SIGPIPE, &sa, NULL);
  17208. #endif
  17209. worker_thread_run((struct mg_connection *)thread_func_param);
  17210. return NULL;
  17211. }
  17212. #endif /* _WIN32 */
  17213. /* This is an internal function, thus all arguments are expected to be
  17214. * valid - a NULL check is not required. */
  17215. static void
  17216. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17217. {
  17218. struct socket so;
  17219. char src_addr[IP_ADDR_STR_LEN];
  17220. socklen_t len = sizeof(so.rsa);
  17221. #if !defined(__ZEPHYR__)
  17222. int on = 1;
  17223. #endif
  17224. memset(&so, 0, sizeof(so));
  17225. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17226. == INVALID_SOCKET) {
  17227. } else if (check_acl(ctx, &so.rsa) != 1) {
  17228. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17229. mg_cry_ctx_internal(ctx,
  17230. "%s: %s is not allowed to connect",
  17231. __func__,
  17232. src_addr);
  17233. closesocket(so.sock);
  17234. } else {
  17235. /* Put so socket structure into the queue */
  17236. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17237. set_close_on_exec(so.sock, NULL, ctx);
  17238. so.is_ssl = listener->is_ssl;
  17239. so.ssl_redir = listener->ssl_redir;
  17240. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17241. mg_cry_ctx_internal(ctx,
  17242. "%s: getsockname() failed: %s",
  17243. __func__,
  17244. strerror(ERRNO));
  17245. }
  17246. #if !defined(__ZEPHYR__)
  17247. if ((so.lsa.sa.sa_family == AF_INET)
  17248. || (so.lsa.sa.sa_family == AF_INET6)) {
  17249. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17250. * This is needed because if HTTP-level keep-alive
  17251. * is enabled, and client resets the connection, server won't get
  17252. * TCP FIN or RST and will keep the connection open forever. With
  17253. * TCP keep-alive, next keep-alive handshake will figure out that
  17254. * the client is down and will close the server end.
  17255. * Thanks to Igor Klopov who suggested the patch. */
  17256. if (setsockopt(so.sock,
  17257. SOL_SOCKET,
  17258. SO_KEEPALIVE,
  17259. (SOCK_OPT_TYPE)&on,
  17260. sizeof(on))
  17261. != 0) {
  17262. mg_cry_ctx_internal(
  17263. ctx,
  17264. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17265. __func__,
  17266. strerror(ERRNO));
  17267. }
  17268. }
  17269. #endif
  17270. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17271. * to effectively fill up the underlying IP packet payload and
  17272. * reduce the overhead of sending lots of small buffers. However
  17273. * this hurts the server's throughput (ie. operations per second)
  17274. * when HTTP 1.1 persistent connections are used and the responses
  17275. * are relatively small (eg. less than 1400 bytes).
  17276. */
  17277. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17278. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17279. if (set_tcp_nodelay(&so, 1) != 0) {
  17280. mg_cry_ctx_internal(
  17281. ctx,
  17282. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17283. __func__,
  17284. strerror(ERRNO));
  17285. }
  17286. }
  17287. /* The "non blocking" property should already be
  17288. * inherited from the parent socket. Set it for
  17289. * non-compliant socket implementations. */
  17290. set_non_blocking_mode(so.sock);
  17291. so.in_use = 0;
  17292. produce_socket(ctx, &so);
  17293. }
  17294. }
  17295. static void
  17296. master_thread_run(struct mg_context *ctx)
  17297. {
  17298. struct mg_workerTLS tls;
  17299. struct mg_pollfd *pfd;
  17300. unsigned int i;
  17301. unsigned int workerthreadcount;
  17302. if (!ctx) {
  17303. return;
  17304. }
  17305. mg_set_thread_name("master");
  17306. /* Increase priority of the master thread */
  17307. #if defined(_WIN32)
  17308. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17309. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17310. int min_prio = sched_get_priority_min(SCHED_RR);
  17311. int max_prio = sched_get_priority_max(SCHED_RR);
  17312. if ((min_prio >= 0) && (max_prio >= 0)
  17313. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17314. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17315. struct sched_param sched_param = {0};
  17316. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17317. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17318. }
  17319. #endif
  17320. /* Initialize thread local storage */
  17321. #if defined(_WIN32)
  17322. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17323. #endif
  17324. tls.is_master = 1;
  17325. pthread_setspecific(sTlsKey, &tls);
  17326. if (ctx->callbacks.init_thread) {
  17327. /* Callback for the master thread (type 0) */
  17328. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17329. } else {
  17330. tls.user_ptr = NULL;
  17331. }
  17332. /* Lua background script "start" event */
  17333. #if defined(USE_LUA)
  17334. if (ctx->lua_background_state) {
  17335. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17336. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17337. /* call "start()" in Lua */
  17338. lua_getglobal(lstate, "start");
  17339. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17340. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17341. if (ret != 0) {
  17342. struct mg_connection fc;
  17343. lua_cry(fake_connection(&fc, ctx),
  17344. ret,
  17345. lstate,
  17346. "lua_background_script",
  17347. "start");
  17348. }
  17349. } else {
  17350. lua_pop(lstate, 1);
  17351. }
  17352. /* determine if there is a "log()" function in Lua background script */
  17353. lua_getglobal(lstate, "log");
  17354. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17355. ctx->lua_bg_log_available = 1;
  17356. }
  17357. lua_pop(lstate, 1);
  17358. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17359. }
  17360. #endif
  17361. /* Server starts *now* */
  17362. ctx->start_time = time(NULL);
  17363. /* Server accept loop */
  17364. pfd = ctx->listening_socket_fds;
  17365. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17366. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17367. pfd[i].fd = ctx->listening_sockets[i].sock;
  17368. pfd[i].events = POLLIN;
  17369. }
  17370. if (mg_poll(pfd,
  17371. ctx->num_listening_sockets,
  17372. SOCKET_TIMEOUT_QUANTUM,
  17373. &(ctx->stop_flag))
  17374. > 0) {
  17375. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17376. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17377. * successful poll, and POLLIN is defined as
  17378. * (POLLRDNORM | POLLRDBAND)
  17379. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17380. * pfd[i].revents == POLLIN. */
  17381. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17382. && (pfd[i].revents & POLLIN)) {
  17383. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17384. }
  17385. }
  17386. }
  17387. }
  17388. /* Here stop_flag is 1 - Initiate shutdown. */
  17389. DEBUG_TRACE("%s", "stopping workers");
  17390. /* Stop signal received: somebody called mg_stop. Quit. */
  17391. close_all_listening_sockets(ctx);
  17392. /* Wakeup workers that are waiting for connections to handle. */
  17393. #if defined(ALTERNATIVE_QUEUE)
  17394. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17395. event_signal(ctx->client_wait_events[i]);
  17396. }
  17397. #else
  17398. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17399. pthread_cond_broadcast(&ctx->sq_full);
  17400. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17401. #endif
  17402. /* Join all worker threads to avoid leaking threads. */
  17403. workerthreadcount = ctx->cfg_worker_threads;
  17404. for (i = 0; i < workerthreadcount; i++) {
  17405. if (ctx->worker_threadids[i] != 0) {
  17406. mg_join_thread(ctx->worker_threadids[i]);
  17407. }
  17408. }
  17409. #if defined(USE_LUA)
  17410. /* Free Lua state of lua background task */
  17411. if (ctx->lua_background_state) {
  17412. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17413. ctx->lua_bg_log_available = 0;
  17414. /* call "stop()" in Lua */
  17415. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17416. lua_getglobal(lstate, "stop");
  17417. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17418. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17419. if (ret != 0) {
  17420. struct mg_connection fc;
  17421. lua_cry(fake_connection(&fc, ctx),
  17422. ret,
  17423. lstate,
  17424. "lua_background_script",
  17425. "stop");
  17426. }
  17427. }
  17428. lua_close(lstate);
  17429. ctx->lua_background_state = 0;
  17430. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17431. }
  17432. #endif
  17433. DEBUG_TRACE("%s", "exiting");
  17434. /* call exit thread callback */
  17435. if (ctx->callbacks.exit_thread) {
  17436. /* Callback for the master thread (type 0) */
  17437. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17438. }
  17439. #if defined(_WIN32)
  17440. CloseHandle(tls.pthread_cond_helper_mutex);
  17441. #endif
  17442. pthread_setspecific(sTlsKey, NULL);
  17443. /* Signal mg_stop() that we're done.
  17444. * WARNING: This must be the very last thing this
  17445. * thread does, as ctx becomes invalid after this line. */
  17446. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17447. }
  17448. /* Threads have different return types on Windows and Unix. */
  17449. #if defined(_WIN32)
  17450. static unsigned __stdcall master_thread(void *thread_func_param)
  17451. {
  17452. master_thread_run((struct mg_context *)thread_func_param);
  17453. return 0;
  17454. }
  17455. #else
  17456. static void *
  17457. master_thread(void *thread_func_param)
  17458. {
  17459. #if !defined(__ZEPHYR__)
  17460. struct sigaction sa;
  17461. /* Ignore SIGPIPE */
  17462. memset(&sa, 0, sizeof(sa));
  17463. sa.sa_handler = SIG_IGN;
  17464. sigaction(SIGPIPE, &sa, NULL);
  17465. #endif
  17466. master_thread_run((struct mg_context *)thread_func_param);
  17467. return NULL;
  17468. }
  17469. #endif /* _WIN32 */
  17470. static void
  17471. free_context(struct mg_context *ctx)
  17472. {
  17473. int i;
  17474. struct mg_handler_info *tmp_rh;
  17475. if (ctx == NULL) {
  17476. return;
  17477. }
  17478. /* Call user callback */
  17479. if (ctx->callbacks.exit_context) {
  17480. ctx->callbacks.exit_context(ctx);
  17481. }
  17482. /* All threads exited, no sync is needed. Destroy thread mutex and
  17483. * condvars
  17484. */
  17485. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17486. #if defined(ALTERNATIVE_QUEUE)
  17487. mg_free(ctx->client_socks);
  17488. if (ctx->client_wait_events != NULL) {
  17489. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17490. event_destroy(ctx->client_wait_events[i]);
  17491. }
  17492. mg_free(ctx->client_wait_events);
  17493. }
  17494. #else
  17495. (void)pthread_cond_destroy(&ctx->sq_empty);
  17496. (void)pthread_cond_destroy(&ctx->sq_full);
  17497. mg_free(ctx->squeue);
  17498. #endif
  17499. /* Destroy other context global data structures mutex */
  17500. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17501. #if defined(USE_LUA)
  17502. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17503. #endif
  17504. /* Deallocate config parameters */
  17505. for (i = 0; i < NUM_OPTIONS; i++) {
  17506. if (ctx->dd.config[i] != NULL) {
  17507. #if defined(_MSC_VER)
  17508. #pragma warning(suppress : 6001)
  17509. #endif
  17510. mg_free(ctx->dd.config[i]);
  17511. }
  17512. }
  17513. /* Deallocate request handlers */
  17514. while (ctx->dd.handlers) {
  17515. tmp_rh = ctx->dd.handlers;
  17516. ctx->dd.handlers = tmp_rh->next;
  17517. mg_free(tmp_rh->uri);
  17518. mg_free(tmp_rh);
  17519. }
  17520. #if defined(USE_MBEDTLS)
  17521. if (ctx->dd.ssl_ctx != NULL) {
  17522. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17523. mg_free(ctx->dd.ssl_ctx);
  17524. ctx->dd.ssl_ctx = NULL;
  17525. }
  17526. #elif !defined(NO_SSL)
  17527. /* Deallocate SSL context */
  17528. if (ctx->dd.ssl_ctx != NULL) {
  17529. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17530. int callback_ret =
  17531. (ctx->callbacks.external_ssl_ctx == NULL)
  17532. ? 0
  17533. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17534. if (callback_ret == 0) {
  17535. SSL_CTX_free(ctx->dd.ssl_ctx);
  17536. }
  17537. /* else: ignore error and ommit SSL_CTX_free in case
  17538. * callback_ret is 1 */
  17539. }
  17540. #endif /* !NO_SSL */
  17541. /* Deallocate worker thread ID array */
  17542. mg_free(ctx->worker_threadids);
  17543. /* Deallocate worker thread ID array */
  17544. mg_free(ctx->worker_connections);
  17545. /* deallocate system name string */
  17546. mg_free(ctx->systemName);
  17547. /* Deallocate context itself */
  17548. mg_free(ctx);
  17549. }
  17550. CIVETWEB_API void
  17551. mg_stop(struct mg_context *ctx)
  17552. {
  17553. pthread_t mt;
  17554. if (!ctx) {
  17555. return;
  17556. }
  17557. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17558. * two threads is not allowed. */
  17559. mt = ctx->masterthreadid;
  17560. if (mt == 0) {
  17561. return;
  17562. }
  17563. ctx->masterthreadid = 0;
  17564. /* Set stop flag, so all threads know they have to exit. */
  17565. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17566. /* Join timer thread */
  17567. #if defined(USE_TIMERS)
  17568. timers_exit(ctx);
  17569. #endif
  17570. /* Wait until everything has stopped. */
  17571. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17572. (void)mg_sleep(10);
  17573. }
  17574. /* Wait to stop master thread */
  17575. mg_join_thread(mt);
  17576. /* Close remaining Lua states */
  17577. #if defined(USE_LUA)
  17578. lua_ctx_exit(ctx);
  17579. #endif
  17580. /* Free memory */
  17581. free_context(ctx);
  17582. }
  17583. static void
  17584. get_system_name(char **sysName)
  17585. {
  17586. #if defined(_WIN32)
  17587. char name[128];
  17588. DWORD dwVersion = 0;
  17589. DWORD dwMajorVersion = 0;
  17590. DWORD dwMinorVersion = 0;
  17591. DWORD dwBuild = 0;
  17592. BOOL wowRet, isWoW = FALSE;
  17593. #if defined(_MSC_VER)
  17594. #pragma warning(push)
  17595. /* GetVersion was declared deprecated */
  17596. #pragma warning(disable : 4996)
  17597. #endif
  17598. dwVersion = GetVersion();
  17599. #if defined(_MSC_VER)
  17600. #pragma warning(pop)
  17601. #endif
  17602. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17603. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17604. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17605. (void)dwBuild;
  17606. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17607. sprintf(name,
  17608. "Windows %u.%u%s",
  17609. (unsigned)dwMajorVersion,
  17610. (unsigned)dwMinorVersion,
  17611. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17612. *sysName = mg_strdup(name);
  17613. #elif defined(__ZEPHYR__)
  17614. *sysName = mg_strdup("Zephyr OS");
  17615. #else
  17616. struct utsname name;
  17617. memset(&name, 0, sizeof(name));
  17618. uname(&name);
  17619. *sysName = mg_strdup(name.sysname);
  17620. #endif
  17621. }
  17622. static void
  17623. legacy_init(const char **options)
  17624. {
  17625. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17626. if (options) {
  17627. const char **run_options = options;
  17628. const char *optname = config_options[LISTENING_PORTS].name;
  17629. /* Try to find the "listening_ports" option */
  17630. while (*run_options) {
  17631. if (!strcmp(*run_options, optname)) {
  17632. ports_option = run_options[1];
  17633. }
  17634. run_options += 2;
  17635. }
  17636. }
  17637. if (is_ssl_port_used(ports_option)) {
  17638. /* Initialize with SSL support */
  17639. mg_init_library(MG_FEATURES_TLS);
  17640. } else {
  17641. /* Initialize without SSL support */
  17642. mg_init_library(MG_FEATURES_DEFAULT);
  17643. }
  17644. }
  17645. CIVETWEB_API struct mg_context *
  17646. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17647. {
  17648. struct mg_context *ctx;
  17649. const char *name, *value, *default_value;
  17650. int idx, ok, workerthreadcount;
  17651. unsigned int i;
  17652. int itmp;
  17653. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17654. const char **options =
  17655. ((init != NULL) ? (init->configuration_options) : (NULL));
  17656. struct mg_workerTLS tls;
  17657. if (error != NULL) {
  17658. error->code = MG_ERROR_DATA_CODE_OK;
  17659. error->code_sub = 0;
  17660. if (error->text_buffer_size > 0) {
  17661. *error->text = 0;
  17662. }
  17663. }
  17664. if (mg_init_library_called == 0) {
  17665. /* Legacy INIT, if mg_start is called without mg_init_library.
  17666. * Note: This will cause a memory leak when unloading the library.
  17667. */
  17668. legacy_init(options);
  17669. }
  17670. if (mg_init_library_called == 0) {
  17671. if (error != NULL) {
  17672. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  17673. mg_snprintf(NULL,
  17674. NULL, /* No truncation check for error buffers */
  17675. error->text,
  17676. error->text_buffer_size,
  17677. "%s",
  17678. "Library uninitialized");
  17679. }
  17680. return NULL;
  17681. }
  17682. /* Allocate context and initialize reasonable general case defaults. */
  17683. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  17684. if (ctx == NULL) {
  17685. if (error != NULL) {
  17686. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17687. error->code_sub = (unsigned)sizeof(*ctx);
  17688. mg_snprintf(NULL,
  17689. NULL, /* No truncation check for error buffers */
  17690. error->text,
  17691. error->text_buffer_size,
  17692. "%s",
  17693. "Out of memory");
  17694. }
  17695. return NULL;
  17696. }
  17697. /* Random number generator will initialize at the first call */
  17698. ctx->dd.auth_nonce_mask =
  17699. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17700. /* Save started thread index to reuse in other external API calls
  17701. * For the sake of thread synchronization all non-civetweb threads
  17702. * can be considered as single external thread */
  17703. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17704. tls.is_master = -1; /* Thread calling mg_start */
  17705. tls.thread_idx = ctx->starter_thread_idx;
  17706. #if defined(_WIN32)
  17707. tls.pthread_cond_helper_mutex = NULL;
  17708. #endif
  17709. pthread_setspecific(sTlsKey, &tls);
  17710. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17711. #if !defined(ALTERNATIVE_QUEUE)
  17712. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17713. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17714. ctx->sq_blocked = 0;
  17715. #endif
  17716. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17717. #if defined(USE_LUA)
  17718. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17719. #endif
  17720. if (!ok) {
  17721. unsigned error_id = (unsigned)ERRNO;
  17722. const char *err_msg =
  17723. "Cannot initialize thread synchronization objects";
  17724. /* Fatal error - abort start. However, this situation should never
  17725. * occur in practice. */
  17726. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17727. if (error != NULL) {
  17728. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  17729. error->code_sub = error_id;
  17730. mg_snprintf(NULL,
  17731. NULL, /* No truncation check for error buffers */
  17732. error->text,
  17733. error->text_buffer_size,
  17734. "%s",
  17735. err_msg);
  17736. }
  17737. mg_free(ctx);
  17738. pthread_setspecific(sTlsKey, NULL);
  17739. return NULL;
  17740. }
  17741. if ((init != NULL) && (init->callbacks != NULL)) {
  17742. /* Set all callbacks except exit_context. */
  17743. ctx->callbacks = *init->callbacks;
  17744. exit_callback = init->callbacks->exit_context;
  17745. /* The exit callback is activated once the context is successfully
  17746. * created. It should not be called, if an incomplete context object
  17747. * is deleted during a failed initialization. */
  17748. ctx->callbacks.exit_context = 0;
  17749. }
  17750. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17751. ctx->dd.handlers = NULL;
  17752. ctx->dd.next = NULL;
  17753. #if defined(USE_LUA)
  17754. lua_ctx_init(ctx);
  17755. #endif
  17756. /* Store options */
  17757. while (options && (name = *options++) != NULL) {
  17758. idx = get_option_index(name);
  17759. if (idx == -1) {
  17760. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17761. if (error != NULL) {
  17762. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17763. error->code_sub = (unsigned)-1;
  17764. mg_snprintf(NULL,
  17765. NULL, /* No truncation check for error buffers */
  17766. error->text,
  17767. error->text_buffer_size,
  17768. "Invalid configuration option: %s",
  17769. name);
  17770. }
  17771. free_context(ctx);
  17772. pthread_setspecific(sTlsKey, NULL);
  17773. return NULL;
  17774. } else if ((value = *options++) == NULL) {
  17775. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17776. if (error != NULL) {
  17777. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17778. error->code_sub = (unsigned)idx;
  17779. mg_snprintf(NULL,
  17780. NULL, /* No truncation check for error buffers */
  17781. error->text,
  17782. error->text_buffer_size,
  17783. "Invalid configuration option value: %s",
  17784. name);
  17785. }
  17786. free_context(ctx);
  17787. pthread_setspecific(sTlsKey, NULL);
  17788. return NULL;
  17789. }
  17790. if (ctx->dd.config[idx] != NULL) {
  17791. /* A duplicate configuration option is not an error - the last
  17792. * option value will be used. */
  17793. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17794. mg_free(ctx->dd.config[idx]);
  17795. }
  17796. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17797. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17798. }
  17799. /* Set default value if needed */
  17800. for (i = 0; config_options[i].name != NULL; i++) {
  17801. default_value = config_options[i].default_value;
  17802. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17803. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17804. }
  17805. }
  17806. /* Request size option */
  17807. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17808. if (itmp < 1024) {
  17809. mg_cry_ctx_internal(ctx,
  17810. "%s too small",
  17811. config_options[MAX_REQUEST_SIZE].name);
  17812. if (error != NULL) {
  17813. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17814. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  17815. mg_snprintf(NULL,
  17816. NULL, /* No truncation check for error buffers */
  17817. error->text,
  17818. error->text_buffer_size,
  17819. "Invalid configuration option value: %s",
  17820. config_options[MAX_REQUEST_SIZE].name);
  17821. }
  17822. free_context(ctx);
  17823. pthread_setspecific(sTlsKey, NULL);
  17824. return NULL;
  17825. }
  17826. ctx->max_request_size = (unsigned)itmp;
  17827. /* Queue length */
  17828. #if !defined(ALTERNATIVE_QUEUE)
  17829. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17830. if (itmp < 1) {
  17831. mg_cry_ctx_internal(ctx,
  17832. "%s too small",
  17833. config_options[CONNECTION_QUEUE_SIZE].name);
  17834. if (error != NULL) {
  17835. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17836. error->code_sub = CONNECTION_QUEUE_SIZE;
  17837. mg_snprintf(NULL,
  17838. NULL, /* No truncation check for error buffers */
  17839. error->text,
  17840. error->text_buffer_size,
  17841. "Invalid configuration option value: %s",
  17842. config_options[CONNECTION_QUEUE_SIZE].name);
  17843. }
  17844. free_context(ctx);
  17845. pthread_setspecific(sTlsKey, NULL);
  17846. return NULL;
  17847. }
  17848. ctx->squeue =
  17849. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17850. if (ctx->squeue == NULL) {
  17851. mg_cry_ctx_internal(ctx,
  17852. "Out of memory: Cannot allocate %s",
  17853. config_options[CONNECTION_QUEUE_SIZE].name);
  17854. if (error != NULL) {
  17855. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17856. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  17857. mg_snprintf(NULL,
  17858. NULL, /* No truncation check for error buffers */
  17859. error->text,
  17860. error->text_buffer_size,
  17861. "Out of memory: Cannot allocate %s",
  17862. config_options[CONNECTION_QUEUE_SIZE].name);
  17863. }
  17864. free_context(ctx);
  17865. pthread_setspecific(sTlsKey, NULL);
  17866. return NULL;
  17867. }
  17868. ctx->sq_size = itmp;
  17869. #endif
  17870. /* Worker thread count option */
  17871. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17872. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17873. if (workerthreadcount <= 0) {
  17874. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17875. } else {
  17876. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17877. }
  17878. if (error != NULL) {
  17879. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17880. error->code_sub = NUM_THREADS;
  17881. mg_snprintf(NULL,
  17882. NULL, /* No truncation check for error buffers */
  17883. error->text,
  17884. error->text_buffer_size,
  17885. "Invalid configuration option value: %s",
  17886. config_options[NUM_THREADS].name);
  17887. }
  17888. free_context(ctx);
  17889. pthread_setspecific(sTlsKey, NULL);
  17890. return NULL;
  17891. }
  17892. /* Document root */
  17893. #if defined(NO_FILES)
  17894. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17895. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17896. if (error != NULL) {
  17897. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17898. error->code_sub = (unsigned)DOCUMENT_ROOT;
  17899. mg_snprintf(NULL,
  17900. NULL, /* No truncation check for error buffers */
  17901. error->text,
  17902. error->text_buffer_size,
  17903. "Invalid configuration option value: %s",
  17904. config_options[DOCUMENT_ROOT].name);
  17905. }
  17906. free_context(ctx);
  17907. pthread_setspecific(sTlsKey, NULL);
  17908. return NULL;
  17909. }
  17910. #endif
  17911. get_system_name(&ctx->systemName);
  17912. #if defined(USE_LUA)
  17913. /* If a Lua background script has been configured, start it. */
  17914. ctx->lua_bg_log_available = 0;
  17915. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17916. char ebuf[256];
  17917. struct vec opt_vec;
  17918. struct vec eq_vec;
  17919. const char *sparams;
  17920. memset(ebuf, 0, sizeof(ebuf));
  17921. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17922. /* Create a Lua state, load all standard libraries and the mg table */
  17923. lua_State *state = mg_lua_context_script_prepare(
  17924. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17925. if (!state) {
  17926. mg_cry_ctx_internal(ctx,
  17927. "lua_background_script load error: %s",
  17928. ebuf);
  17929. if (error != NULL) {
  17930. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  17931. mg_snprintf(NULL,
  17932. NULL, /* No truncation check for error buffers */
  17933. error->text,
  17934. error->text_buffer_size,
  17935. "Error in script %s: %s",
  17936. config_options[LUA_BACKGROUND_SCRIPT].name,
  17937. ebuf);
  17938. }
  17939. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17940. free_context(ctx);
  17941. pthread_setspecific(sTlsKey, NULL);
  17942. return NULL;
  17943. }
  17944. /* Add a table with parameters into mg.params */
  17945. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17946. if (sparams && sparams[0]) {
  17947. lua_getglobal(state, "mg");
  17948. lua_pushstring(state, "params");
  17949. lua_newtable(state);
  17950. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17951. != NULL) {
  17952. reg_llstring(
  17953. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17954. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17955. break;
  17956. }
  17957. lua_rawset(state, -3);
  17958. lua_pop(state, 1);
  17959. }
  17960. /* Call script */
  17961. state = mg_lua_context_script_run(state,
  17962. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17963. ctx,
  17964. ebuf,
  17965. sizeof(ebuf));
  17966. if (!state) {
  17967. mg_cry_ctx_internal(ctx,
  17968. "lua_background_script start error: %s",
  17969. ebuf);
  17970. if (error != NULL) {
  17971. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  17972. mg_snprintf(NULL,
  17973. NULL, /* No truncation check for error buffers */
  17974. error->text,
  17975. error->text_buffer_size,
  17976. "Error in script %s: %s",
  17977. config_options[DOCUMENT_ROOT].name,
  17978. ebuf);
  17979. }
  17980. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17981. free_context(ctx);
  17982. pthread_setspecific(sTlsKey, NULL);
  17983. return NULL;
  17984. }
  17985. /* state remains valid */
  17986. ctx->lua_background_state = (void *)state;
  17987. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17988. } else {
  17989. ctx->lua_background_state = 0;
  17990. }
  17991. #endif
  17992. /* Step by step initialization of ctx - depending on build options */
  17993. #if !defined(NO_FILESYSTEMS)
  17994. if (!set_gpass_option(ctx, NULL)) {
  17995. const char *err_msg = "Invalid global password file";
  17996. /* Fatal error - abort start. */
  17997. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17998. if (error != NULL) {
  17999. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18000. mg_snprintf(NULL,
  18001. NULL, /* No truncation check for error buffers */
  18002. error->text,
  18003. error->text_buffer_size,
  18004. "%s",
  18005. err_msg);
  18006. }
  18007. free_context(ctx);
  18008. pthread_setspecific(sTlsKey, NULL);
  18009. return NULL;
  18010. }
  18011. #endif
  18012. #if defined(USE_MBEDTLS)
  18013. if (!mg_sslctx_init(ctx, NULL)) {
  18014. const char *err_msg = "Error initializing SSL context";
  18015. /* Fatal error - abort start. */
  18016. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18017. if (error != NULL) {
  18018. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18019. mg_snprintf(NULL,
  18020. NULL, /* No truncation check for error buffers */
  18021. error->text,
  18022. error->text_buffer_size,
  18023. "%s",
  18024. err_msg);
  18025. }
  18026. free_context(ctx);
  18027. pthread_setspecific(sTlsKey, NULL);
  18028. return NULL;
  18029. }
  18030. #elif !defined(NO_SSL)
  18031. if (!init_ssl_ctx(ctx, NULL)) {
  18032. const char *err_msg = "Error initializing SSL context";
  18033. /* Fatal error - abort start. */
  18034. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18035. if (error != NULL) {
  18036. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18037. mg_snprintf(NULL,
  18038. NULL, /* No truncation check for error buffers */
  18039. error->text,
  18040. error->text_buffer_size,
  18041. "%s",
  18042. err_msg);
  18043. }
  18044. free_context(ctx);
  18045. pthread_setspecific(sTlsKey, NULL);
  18046. return NULL;
  18047. }
  18048. #endif
  18049. if (!set_ports_option(ctx)) {
  18050. const char *err_msg = "Failed to setup server ports";
  18051. /* Fatal error - abort start. */
  18052. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18053. if (error != NULL) {
  18054. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18055. mg_snprintf(NULL,
  18056. NULL, /* No truncation check for error buffers */
  18057. error->text,
  18058. error->text_buffer_size,
  18059. "%s",
  18060. err_msg);
  18061. }
  18062. free_context(ctx);
  18063. pthread_setspecific(sTlsKey, NULL);
  18064. return NULL;
  18065. }
  18066. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18067. if (!set_uid_option(ctx)) {
  18068. const char *err_msg = "Failed to run as configured user";
  18069. /* Fatal error - abort start. */
  18070. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18071. if (error != NULL) {
  18072. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18073. mg_snprintf(NULL,
  18074. NULL, /* No truncation check for error buffers */
  18075. error->text,
  18076. error->text_buffer_size,
  18077. "%s",
  18078. err_msg);
  18079. }
  18080. free_context(ctx);
  18081. pthread_setspecific(sTlsKey, NULL);
  18082. return NULL;
  18083. }
  18084. #endif
  18085. if (!set_acl_option(ctx)) {
  18086. const char *err_msg = "Failed to setup access control list";
  18087. /* Fatal error - abort start. */
  18088. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18089. if (error != NULL) {
  18090. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18091. mg_snprintf(NULL,
  18092. NULL, /* No truncation check for error buffers */
  18093. error->text,
  18094. error->text_buffer_size,
  18095. "%s",
  18096. err_msg);
  18097. }
  18098. free_context(ctx);
  18099. pthread_setspecific(sTlsKey, NULL);
  18100. return NULL;
  18101. }
  18102. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  18103. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18104. sizeof(pthread_t),
  18105. ctx);
  18106. if (ctx->worker_threadids == NULL) {
  18107. const char *err_msg = "Not enough memory for worker thread ID array";
  18108. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18109. if (error != NULL) {
  18110. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18111. error->code_sub =
  18112. (unsigned)ctx->cfg_worker_threads * (unsigned)sizeof(pthread_t);
  18113. mg_snprintf(NULL,
  18114. NULL, /* No truncation check for error buffers */
  18115. error->text,
  18116. error->text_buffer_size,
  18117. "%s",
  18118. err_msg);
  18119. }
  18120. free_context(ctx);
  18121. pthread_setspecific(sTlsKey, NULL);
  18122. return NULL;
  18123. }
  18124. ctx->worker_connections =
  18125. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18126. sizeof(struct mg_connection),
  18127. ctx);
  18128. if (ctx->worker_connections == NULL) {
  18129. const char *err_msg =
  18130. "Not enough memory for worker thread connection array";
  18131. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18132. if (error != NULL) {
  18133. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18134. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18135. * (unsigned)sizeof(struct mg_connection);
  18136. mg_snprintf(NULL,
  18137. NULL, /* No truncation check for error buffers */
  18138. error->text,
  18139. error->text_buffer_size,
  18140. "%s",
  18141. err_msg);
  18142. }
  18143. free_context(ctx);
  18144. pthread_setspecific(sTlsKey, NULL);
  18145. return NULL;
  18146. }
  18147. #if defined(ALTERNATIVE_QUEUE)
  18148. ctx->client_wait_events =
  18149. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  18150. sizeof(ctx->client_wait_events[0]),
  18151. ctx);
  18152. if (ctx->client_wait_events == NULL) {
  18153. const char *err_msg = "Not enough memory for worker event array";
  18154. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18155. mg_free(ctx->worker_threadids);
  18156. if (error != NULL) {
  18157. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18158. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18159. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18160. mg_snprintf(NULL,
  18161. NULL, /* No truncation check for error buffers */
  18162. error->text,
  18163. error->text_buffer_size,
  18164. "%s",
  18165. err_msg);
  18166. }
  18167. free_context(ctx);
  18168. pthread_setspecific(sTlsKey, NULL);
  18169. return NULL;
  18170. }
  18171. ctx->client_socks =
  18172. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18173. sizeof(ctx->client_socks[0]),
  18174. ctx);
  18175. if (ctx->client_socks == NULL) {
  18176. const char *err_msg = "Not enough memory for worker socket array";
  18177. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18178. mg_free(ctx->client_wait_events);
  18179. mg_free(ctx->worker_threadids);
  18180. if (error != NULL) {
  18181. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18182. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18183. * (unsigned)sizeof(ctx->client_socks[0]);
  18184. mg_snprintf(NULL,
  18185. NULL, /* No truncation check for error buffers */
  18186. error->text,
  18187. error->text_buffer_size,
  18188. "%s",
  18189. err_msg);
  18190. }
  18191. free_context(ctx);
  18192. pthread_setspecific(sTlsKey, NULL);
  18193. return NULL;
  18194. }
  18195. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  18196. ctx->client_wait_events[i] = event_create();
  18197. if (ctx->client_wait_events[i] == 0) {
  18198. const char *err_msg = "Error creating worker event %i";
  18199. mg_cry_ctx_internal(ctx, err_msg, i);
  18200. while (i > 0) {
  18201. i--;
  18202. event_destroy(ctx->client_wait_events[i]);
  18203. }
  18204. mg_free(ctx->client_socks);
  18205. mg_free(ctx->client_wait_events);
  18206. mg_free(ctx->worker_threadids);
  18207. if (error != NULL) {
  18208. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18209. error->code_sub = ERRNO;
  18210. mg_snprintf(NULL,
  18211. NULL, /* No truncation check for error buffers */
  18212. error->text,
  18213. error->text_buffer_size,
  18214. err_msg,
  18215. i);
  18216. }
  18217. free_context(ctx);
  18218. pthread_setspecific(sTlsKey, NULL);
  18219. return NULL;
  18220. }
  18221. }
  18222. #endif
  18223. #if defined(USE_TIMERS)
  18224. if (timers_init(ctx) != 0) {
  18225. const char *err_msg = "Error creating timers";
  18226. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18227. if (error != NULL) {
  18228. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18229. error->code_sub = ERRNO;
  18230. mg_snprintf(NULL,
  18231. NULL, /* No truncation check for error buffers */
  18232. error->text,
  18233. error->text_buffer_size,
  18234. "%s",
  18235. err_msg);
  18236. }
  18237. free_context(ctx);
  18238. pthread_setspecific(sTlsKey, NULL);
  18239. return NULL;
  18240. }
  18241. #endif
  18242. /* Context has been created - init user libraries */
  18243. if (ctx->callbacks.init_context) {
  18244. ctx->callbacks.init_context(ctx);
  18245. }
  18246. /* From now, the context is successfully created.
  18247. * When it is destroyed, the exit callback should be called. */
  18248. ctx->callbacks.exit_context = exit_callback;
  18249. ctx->context_type = CONTEXT_SERVER; /* server context */
  18250. /* Start worker threads */
  18251. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  18252. /* worker_thread sets up the other fields */
  18253. ctx->worker_connections[i].phys_ctx = ctx;
  18254. if (mg_start_thread_with_id(worker_thread,
  18255. &ctx->worker_connections[i],
  18256. &ctx->worker_threadids[i])
  18257. != 0) {
  18258. long error_no = (long)ERRNO;
  18259. /* thread was not created */
  18260. if (i > 0) {
  18261. /* If the second, third, ... thread cannot be created, set a
  18262. * warning, but keep running. */
  18263. mg_cry_ctx_internal(ctx,
  18264. "Cannot start worker thread %i: error %ld",
  18265. i + 1,
  18266. error_no);
  18267. /* If the server initialization should stop here, all
  18268. * threads that have already been created must be stopped
  18269. * first, before any free_context(ctx) call.
  18270. */
  18271. } else {
  18272. /* If the first worker thread cannot be created, stop
  18273. * initialization and free the entire server context. */
  18274. mg_cry_ctx_internal(ctx,
  18275. "Cannot create threads: error %ld",
  18276. error_no);
  18277. if (error != NULL) {
  18278. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18279. error->code_sub = (unsigned)error_no;
  18280. mg_snprintf(
  18281. NULL,
  18282. NULL, /* No truncation check for error buffers */
  18283. error->text,
  18284. error->text_buffer_size,
  18285. "Cannot create first worker thread: error %ld",
  18286. error_no);
  18287. }
  18288. free_context(ctx);
  18289. pthread_setspecific(sTlsKey, NULL);
  18290. return NULL;
  18291. }
  18292. break;
  18293. }
  18294. }
  18295. /* Start master (listening) thread */
  18296. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18297. pthread_setspecific(sTlsKey, NULL);
  18298. return ctx;
  18299. }
  18300. CIVETWEB_API struct mg_context *
  18301. mg_start(const struct mg_callbacks *callbacks,
  18302. void *user_data,
  18303. const char **options)
  18304. {
  18305. struct mg_init_data init = {0};
  18306. init.callbacks = callbacks;
  18307. init.user_data = user_data;
  18308. init.configuration_options = options;
  18309. return mg_start2(&init, NULL);
  18310. }
  18311. /* Add an additional domain to an already running web server. */
  18312. CIVETWEB_API int
  18313. mg_start_domain2(struct mg_context *ctx,
  18314. const char **options,
  18315. struct mg_error_data *error)
  18316. {
  18317. const char *name;
  18318. const char *value;
  18319. const char *default_value;
  18320. struct mg_domain_context *new_dom;
  18321. struct mg_domain_context *dom;
  18322. int idx, i;
  18323. if (error != NULL) {
  18324. error->code = MG_ERROR_DATA_CODE_OK;
  18325. error->code_sub = 0;
  18326. if (error->text_buffer_size > 0) {
  18327. *error->text = 0;
  18328. }
  18329. }
  18330. if ((ctx == NULL) || (options == NULL)) {
  18331. if (error != NULL) {
  18332. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18333. mg_snprintf(NULL,
  18334. NULL, /* No truncation check for error buffers */
  18335. error->text,
  18336. error->text_buffer_size,
  18337. "%s",
  18338. "Invalid parameters");
  18339. }
  18340. return -1;
  18341. }
  18342. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18343. if (error != NULL) {
  18344. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18345. mg_snprintf(NULL,
  18346. NULL, /* No truncation check for error buffers */
  18347. error->text,
  18348. error->text_buffer_size,
  18349. "%s",
  18350. "Server already stopped");
  18351. }
  18352. return -7;
  18353. }
  18354. new_dom = (struct mg_domain_context *)
  18355. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18356. if (!new_dom) {
  18357. /* Out of memory */
  18358. if (error != NULL) {
  18359. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18360. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18361. mg_snprintf(NULL,
  18362. NULL, /* No truncation check for error buffers */
  18363. error->text,
  18364. error->text_buffer_size,
  18365. "%s",
  18366. "Out or memory");
  18367. }
  18368. return -6;
  18369. }
  18370. /* Store options - TODO: unite duplicate code */
  18371. while (options && (name = *options++) != NULL) {
  18372. idx = get_option_index(name);
  18373. if (idx == -1) {
  18374. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18375. if (error != NULL) {
  18376. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18377. error->code_sub = (unsigned)-1;
  18378. mg_snprintf(NULL,
  18379. NULL, /* No truncation check for error buffers */
  18380. error->text,
  18381. error->text_buffer_size,
  18382. "Invalid option: %s",
  18383. name);
  18384. }
  18385. mg_free(new_dom);
  18386. return -2;
  18387. } else if ((value = *options++) == NULL) {
  18388. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18389. if (error != NULL) {
  18390. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18391. error->code_sub = idx;
  18392. mg_snprintf(NULL,
  18393. NULL, /* No truncation check for error buffers */
  18394. error->text,
  18395. error->text_buffer_size,
  18396. "Invalid option value: %s",
  18397. name);
  18398. }
  18399. mg_free(new_dom);
  18400. return -2;
  18401. }
  18402. if (new_dom->config[idx] != NULL) {
  18403. /* Duplicate option: Later values overwrite earlier ones. */
  18404. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18405. mg_free(new_dom->config[idx]);
  18406. }
  18407. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18408. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18409. }
  18410. /* Authentication domain is mandatory */
  18411. /* TODO: Maybe use a new option hostname? */
  18412. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18413. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18414. if (error != NULL) {
  18415. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18416. error->code_sub = AUTHENTICATION_DOMAIN;
  18417. mg_snprintf(NULL,
  18418. NULL, /* No truncation check for error buffers */
  18419. error->text,
  18420. error->text_buffer_size,
  18421. "Mandatory option %s missing",
  18422. config_options[AUTHENTICATION_DOMAIN].name);
  18423. }
  18424. mg_free(new_dom);
  18425. return -4;
  18426. }
  18427. /* Set default value if needed. Take the config value from
  18428. * ctx as a default value. */
  18429. for (i = 0; config_options[i].name != NULL; i++) {
  18430. default_value = ctx->dd.config[i];
  18431. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18432. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18433. }
  18434. }
  18435. new_dom->handlers = NULL;
  18436. new_dom->next = NULL;
  18437. new_dom->nonce_count = 0;
  18438. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18439. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18440. new_dom->shared_lua_websockets = NULL;
  18441. #endif
  18442. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18443. if (!init_ssl_ctx(ctx, new_dom)) {
  18444. /* Init SSL failed */
  18445. if (error != NULL) {
  18446. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18447. mg_snprintf(NULL,
  18448. NULL, /* No truncation check for error buffers */
  18449. error->text,
  18450. error->text_buffer_size,
  18451. "%s",
  18452. "Initializing SSL context failed");
  18453. }
  18454. mg_free(new_dom);
  18455. return -3;
  18456. }
  18457. #endif
  18458. /* Add element to linked list. */
  18459. mg_lock_context(ctx);
  18460. idx = 0;
  18461. dom = &(ctx->dd);
  18462. for (;;) {
  18463. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18464. dom->config[AUTHENTICATION_DOMAIN])) {
  18465. /* Domain collision */
  18466. mg_cry_ctx_internal(ctx,
  18467. "domain %s already in use",
  18468. new_dom->config[AUTHENTICATION_DOMAIN]);
  18469. if (error != NULL) {
  18470. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18471. mg_snprintf(NULL,
  18472. NULL, /* No truncation check for error buffers */
  18473. error->text,
  18474. error->text_buffer_size,
  18475. "Domain %s specified by %s is already in use",
  18476. new_dom->config[AUTHENTICATION_DOMAIN],
  18477. config_options[AUTHENTICATION_DOMAIN].name);
  18478. }
  18479. mg_free(new_dom);
  18480. mg_unlock_context(ctx);
  18481. return -5;
  18482. }
  18483. /* Count number of domains */
  18484. idx++;
  18485. if (dom->next == NULL) {
  18486. dom->next = new_dom;
  18487. break;
  18488. }
  18489. dom = dom->next;
  18490. }
  18491. mg_unlock_context(ctx);
  18492. /* Return domain number */
  18493. return idx;
  18494. }
  18495. CIVETWEB_API int
  18496. mg_start_domain(struct mg_context *ctx, const char **options)
  18497. {
  18498. return mg_start_domain2(ctx, options, NULL);
  18499. }
  18500. /* Feature check API function */
  18501. CIVETWEB_API unsigned
  18502. mg_check_feature(unsigned feature)
  18503. {
  18504. static const unsigned feature_set = 0
  18505. /* Set bits for available features according to API documentation.
  18506. * This bit mask is created at compile time, according to the active
  18507. * preprocessor defines. It is a single const value at runtime. */
  18508. #if !defined(NO_FILES)
  18509. | MG_FEATURES_FILES
  18510. #endif
  18511. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18512. | MG_FEATURES_SSL
  18513. #endif
  18514. #if !defined(NO_CGI)
  18515. | MG_FEATURES_CGI
  18516. #endif
  18517. #if defined(USE_IPV6)
  18518. | MG_FEATURES_IPV6
  18519. #endif
  18520. #if defined(USE_WEBSOCKET)
  18521. | MG_FEATURES_WEBSOCKET
  18522. #endif
  18523. #if defined(USE_LUA)
  18524. | MG_FEATURES_LUA
  18525. #endif
  18526. #if defined(USE_DUKTAPE)
  18527. | MG_FEATURES_SSJS
  18528. #endif
  18529. #if !defined(NO_CACHING)
  18530. | MG_FEATURES_CACHE
  18531. #endif
  18532. #if defined(USE_SERVER_STATS)
  18533. | MG_FEATURES_STATS
  18534. #endif
  18535. #if defined(USE_ZLIB)
  18536. | MG_FEATURES_COMPRESSION
  18537. #endif
  18538. #if defined(USE_HTTP2)
  18539. | MG_FEATURES_HTTP2
  18540. #endif
  18541. #if defined(USE_X_DOM_SOCKET)
  18542. | MG_FEATURES_X_DOMAIN_SOCKET
  18543. #endif
  18544. /* Set some extra bits not defined in the API documentation.
  18545. * These bits may change without further notice. */
  18546. #if defined(MG_LEGACY_INTERFACE)
  18547. | 0x80000000u
  18548. #endif
  18549. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18550. | 0x40000000u
  18551. #endif
  18552. #if !defined(NO_RESPONSE_BUFFERING)
  18553. | 0x20000000u
  18554. #endif
  18555. #if defined(MEMORY_DEBUGGING)
  18556. | 0x10000000u
  18557. #endif
  18558. ;
  18559. return (feature & feature_set);
  18560. }
  18561. static size_t
  18562. mg_str_append(char **dst, char *end, const char *src)
  18563. {
  18564. size_t len = strlen(src);
  18565. if (*dst != end) {
  18566. /* Append src if enough space, or close dst. */
  18567. if ((size_t)(end - *dst) > len) {
  18568. strcpy(*dst, src);
  18569. *dst += len;
  18570. } else {
  18571. *dst = end;
  18572. }
  18573. }
  18574. return len;
  18575. }
  18576. /* Get system information. It can be printed or stored by the caller.
  18577. * Return the size of available information. */
  18578. CIVETWEB_API int
  18579. mg_get_system_info(char *buffer, int buflen)
  18580. {
  18581. char *end, *append_eoobj = NULL, block[256];
  18582. size_t system_info_length = 0;
  18583. #if defined(_WIN32)
  18584. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18585. #else
  18586. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18587. #endif
  18588. if ((buffer == NULL) || (buflen < 1)) {
  18589. buflen = 0;
  18590. end = buffer;
  18591. } else {
  18592. *buffer = 0;
  18593. end = buffer + buflen;
  18594. }
  18595. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18596. /* has enough space to append eoobj */
  18597. append_eoobj = buffer;
  18598. if (end) {
  18599. end -= sizeof(eoobj) - 1;
  18600. }
  18601. }
  18602. system_info_length += mg_str_append(&buffer, end, "{");
  18603. /* Server version */
  18604. {
  18605. const char *version = mg_version();
  18606. mg_snprintf(NULL,
  18607. NULL,
  18608. block,
  18609. sizeof(block),
  18610. "%s\"version\" : \"%s\"",
  18611. eol,
  18612. version);
  18613. system_info_length += mg_str_append(&buffer, end, block);
  18614. }
  18615. /* System info */
  18616. {
  18617. #if defined(_WIN32)
  18618. DWORD dwVersion = 0;
  18619. DWORD dwMajorVersion = 0;
  18620. DWORD dwMinorVersion = 0;
  18621. SYSTEM_INFO si;
  18622. GetSystemInfo(&si);
  18623. #if defined(_MSC_VER)
  18624. #pragma warning(push)
  18625. /* GetVersion was declared deprecated */
  18626. #pragma warning(disable : 4996)
  18627. #endif
  18628. dwVersion = GetVersion();
  18629. #if defined(_MSC_VER)
  18630. #pragma warning(pop)
  18631. #endif
  18632. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18633. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18634. mg_snprintf(NULL,
  18635. NULL,
  18636. block,
  18637. sizeof(block),
  18638. ",%s\"os\" : \"Windows %u.%u\"",
  18639. eol,
  18640. (unsigned)dwMajorVersion,
  18641. (unsigned)dwMinorVersion);
  18642. system_info_length += mg_str_append(&buffer, end, block);
  18643. mg_snprintf(NULL,
  18644. NULL,
  18645. block,
  18646. sizeof(block),
  18647. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18648. eol,
  18649. (unsigned)si.wProcessorArchitecture,
  18650. (unsigned)si.dwNumberOfProcessors,
  18651. (unsigned)si.dwActiveProcessorMask);
  18652. system_info_length += mg_str_append(&buffer, end, block);
  18653. #elif defined(__ZEPHYR__)
  18654. mg_snprintf(NULL,
  18655. NULL,
  18656. block,
  18657. sizeof(block),
  18658. ",%s\"os\" : \"%s %s\"",
  18659. eol,
  18660. "Zephyr OS",
  18661. ZEPHYR_VERSION);
  18662. system_info_length += mg_str_append(&buffer, end, block);
  18663. #else
  18664. struct utsname name;
  18665. memset(&name, 0, sizeof(name));
  18666. uname(&name);
  18667. mg_snprintf(NULL,
  18668. NULL,
  18669. block,
  18670. sizeof(block),
  18671. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18672. eol,
  18673. name.sysname,
  18674. name.version,
  18675. name.release,
  18676. name.machine);
  18677. system_info_length += mg_str_append(&buffer, end, block);
  18678. #endif
  18679. }
  18680. /* Features */
  18681. {
  18682. mg_snprintf(NULL,
  18683. NULL,
  18684. block,
  18685. sizeof(block),
  18686. ",%s\"features\" : %lu"
  18687. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18688. eol,
  18689. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18690. eol,
  18691. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18692. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18693. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18694. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18695. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18696. : "",
  18697. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18698. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18699. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18700. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18701. system_info_length += mg_str_append(&buffer, end, block);
  18702. #if defined(USE_LUA)
  18703. mg_snprintf(NULL,
  18704. NULL,
  18705. block,
  18706. sizeof(block),
  18707. ",%s\"lua_version\" : \"%u (%s)\"",
  18708. eol,
  18709. (unsigned)LUA_VERSION_NUM,
  18710. LUA_RELEASE);
  18711. system_info_length += mg_str_append(&buffer, end, block);
  18712. #endif
  18713. #if defined(USE_DUKTAPE)
  18714. mg_snprintf(NULL,
  18715. NULL,
  18716. block,
  18717. sizeof(block),
  18718. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18719. eol,
  18720. (unsigned)DUK_VERSION / 10000,
  18721. ((unsigned)DUK_VERSION / 100) % 100,
  18722. (unsigned)DUK_VERSION % 100);
  18723. system_info_length += mg_str_append(&buffer, end, block);
  18724. #endif
  18725. }
  18726. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18727. {
  18728. #if defined(BUILD_DATE)
  18729. const char *bd = BUILD_DATE;
  18730. #else
  18731. #if defined(GCC_DIAGNOSTIC)
  18732. #if GCC_VERSION >= 40900
  18733. #pragma GCC diagnostic push
  18734. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18735. * does not work in some versions. If "BUILD_DATE" is defined to some
  18736. * string, it is used instead of __DATE__. */
  18737. #pragma GCC diagnostic ignored "-Wdate-time"
  18738. #endif
  18739. #endif
  18740. const char *bd = __DATE__;
  18741. #if defined(GCC_DIAGNOSTIC)
  18742. #if GCC_VERSION >= 40900
  18743. #pragma GCC diagnostic pop
  18744. #endif
  18745. #endif
  18746. #endif
  18747. mg_snprintf(
  18748. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18749. system_info_length += mg_str_append(&buffer, end, block);
  18750. }
  18751. /* Compiler information */
  18752. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18753. {
  18754. #if defined(_MSC_VER)
  18755. mg_snprintf(NULL,
  18756. NULL,
  18757. block,
  18758. sizeof(block),
  18759. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18760. eol,
  18761. (unsigned)_MSC_VER,
  18762. (unsigned)_MSC_FULL_VER);
  18763. system_info_length += mg_str_append(&buffer, end, block);
  18764. #elif defined(__MINGW64__)
  18765. mg_snprintf(NULL,
  18766. NULL,
  18767. block,
  18768. sizeof(block),
  18769. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18770. eol,
  18771. (unsigned)__MINGW64_VERSION_MAJOR,
  18772. (unsigned)__MINGW64_VERSION_MINOR);
  18773. system_info_length += mg_str_append(&buffer, end, block);
  18774. mg_snprintf(NULL,
  18775. NULL,
  18776. block,
  18777. sizeof(block),
  18778. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18779. eol,
  18780. (unsigned)__MINGW32_MAJOR_VERSION,
  18781. (unsigned)__MINGW32_MINOR_VERSION);
  18782. system_info_length += mg_str_append(&buffer, end, block);
  18783. #elif defined(__MINGW32__)
  18784. mg_snprintf(NULL,
  18785. NULL,
  18786. block,
  18787. sizeof(block),
  18788. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18789. eol,
  18790. (unsigned)__MINGW32_MAJOR_VERSION,
  18791. (unsigned)__MINGW32_MINOR_VERSION);
  18792. system_info_length += mg_str_append(&buffer, end, block);
  18793. #elif defined(__clang__)
  18794. mg_snprintf(NULL,
  18795. NULL,
  18796. block,
  18797. sizeof(block),
  18798. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18799. eol,
  18800. __clang_major__,
  18801. __clang_minor__,
  18802. __clang_patchlevel__,
  18803. __clang_version__);
  18804. system_info_length += mg_str_append(&buffer, end, block);
  18805. #elif defined(__GNUC__)
  18806. mg_snprintf(NULL,
  18807. NULL,
  18808. block,
  18809. sizeof(block),
  18810. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18811. eol,
  18812. (unsigned)__GNUC__,
  18813. (unsigned)__GNUC_MINOR__,
  18814. (unsigned)__GNUC_PATCHLEVEL__);
  18815. system_info_length += mg_str_append(&buffer, end, block);
  18816. #elif defined(__INTEL_COMPILER)
  18817. mg_snprintf(NULL,
  18818. NULL,
  18819. block,
  18820. sizeof(block),
  18821. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18822. eol,
  18823. (unsigned)__INTEL_COMPILER);
  18824. system_info_length += mg_str_append(&buffer, end, block);
  18825. #elif defined(__BORLANDC__)
  18826. mg_snprintf(NULL,
  18827. NULL,
  18828. block,
  18829. sizeof(block),
  18830. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18831. eol,
  18832. (unsigned)__BORLANDC__);
  18833. system_info_length += mg_str_append(&buffer, end, block);
  18834. #elif defined(__SUNPRO_C)
  18835. mg_snprintf(NULL,
  18836. NULL,
  18837. block,
  18838. sizeof(block),
  18839. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18840. eol,
  18841. (unsigned)__SUNPRO_C);
  18842. system_info_length += mg_str_append(&buffer, end, block);
  18843. #else
  18844. mg_snprintf(NULL,
  18845. NULL,
  18846. block,
  18847. sizeof(block),
  18848. ",%s\"compiler\" : \"other\"",
  18849. eol);
  18850. system_info_length += mg_str_append(&buffer, end, block);
  18851. #endif
  18852. }
  18853. /* Determine 32/64 bit data mode.
  18854. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18855. {
  18856. mg_snprintf(NULL,
  18857. NULL,
  18858. block,
  18859. sizeof(block),
  18860. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18861. "char:%u/%u, "
  18862. "ptr:%u, size:%u, time:%u\"",
  18863. eol,
  18864. (unsigned)sizeof(short),
  18865. (unsigned)sizeof(int),
  18866. (unsigned)sizeof(long),
  18867. (unsigned)sizeof(long long),
  18868. (unsigned)sizeof(float),
  18869. (unsigned)sizeof(double),
  18870. (unsigned)sizeof(long double),
  18871. (unsigned)sizeof(char),
  18872. (unsigned)sizeof(wchar_t),
  18873. (unsigned)sizeof(void *),
  18874. (unsigned)sizeof(size_t),
  18875. (unsigned)sizeof(time_t));
  18876. system_info_length += mg_str_append(&buffer, end, block);
  18877. }
  18878. /* Terminate string */
  18879. if (append_eoobj) {
  18880. strcat(append_eoobj, eoobj);
  18881. }
  18882. system_info_length += sizeof(eoobj) - 1;
  18883. return (int)system_info_length;
  18884. }
  18885. /* Get context information. It can be printed or stored by the caller.
  18886. * Return the size of available information. */
  18887. CIVETWEB_API int
  18888. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18889. {
  18890. #if defined(USE_SERVER_STATS)
  18891. char *end, *append_eoobj = NULL, block[256];
  18892. size_t context_info_length = 0;
  18893. #if defined(_WIN32)
  18894. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18895. #else
  18896. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18897. #endif
  18898. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18899. if ((buffer == NULL) || (buflen < 1)) {
  18900. buflen = 0;
  18901. end = buffer;
  18902. } else {
  18903. *buffer = 0;
  18904. end = buffer + buflen;
  18905. }
  18906. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18907. /* has enough space to append eoobj */
  18908. append_eoobj = buffer;
  18909. end -= sizeof(eoobj) - 1;
  18910. }
  18911. context_info_length += mg_str_append(&buffer, end, "{");
  18912. if (ms) { /* <-- should be always true */
  18913. /* Memory information */
  18914. int blockCount = (int)ms->blockCount;
  18915. int64_t totalMemUsed = ms->totalMemUsed;
  18916. int64_t maxMemUsed = ms->maxMemUsed;
  18917. if (totalMemUsed > maxMemUsed) {
  18918. maxMemUsed = totalMemUsed;
  18919. }
  18920. mg_snprintf(NULL,
  18921. NULL,
  18922. block,
  18923. sizeof(block),
  18924. "%s\"memory\" : {%s"
  18925. "\"blocks\" : %i,%s"
  18926. "\"used\" : %" INT64_FMT ",%s"
  18927. "\"maxUsed\" : %" INT64_FMT "%s"
  18928. "}",
  18929. eol,
  18930. eol,
  18931. blockCount,
  18932. eol,
  18933. totalMemUsed,
  18934. eol,
  18935. maxMemUsed,
  18936. eol);
  18937. context_info_length += mg_str_append(&buffer, end, block);
  18938. }
  18939. if (ctx) {
  18940. /* Declare all variables at begin of the block, to comply
  18941. * with old C standards. */
  18942. char start_time_str[64] = {0};
  18943. char now_str[64] = {0};
  18944. time_t start_time = ctx->start_time;
  18945. time_t now = time(NULL);
  18946. int64_t total_data_read, total_data_written;
  18947. int active_connections = (int)ctx->active_connections;
  18948. int max_active_connections = (int)ctx->max_active_connections;
  18949. int total_connections = (int)ctx->total_connections;
  18950. if (active_connections > max_active_connections) {
  18951. max_active_connections = active_connections;
  18952. }
  18953. if (active_connections > total_connections) {
  18954. total_connections = active_connections;
  18955. }
  18956. /* Connections information */
  18957. mg_snprintf(NULL,
  18958. NULL,
  18959. block,
  18960. sizeof(block),
  18961. ",%s\"connections\" : {%s"
  18962. "\"active\" : %i,%s"
  18963. "\"maxActive\" : %i,%s"
  18964. "\"total\" : %i%s"
  18965. "}",
  18966. eol,
  18967. eol,
  18968. active_connections,
  18969. eol,
  18970. max_active_connections,
  18971. eol,
  18972. total_connections,
  18973. eol);
  18974. context_info_length += mg_str_append(&buffer, end, block);
  18975. /* Queue information */
  18976. #if !defined(ALTERNATIVE_QUEUE)
  18977. mg_snprintf(NULL,
  18978. NULL,
  18979. block,
  18980. sizeof(block),
  18981. ",%s\"queue\" : {%s"
  18982. "\"length\" : %i,%s"
  18983. "\"filled\" : %i,%s"
  18984. "\"maxFilled\" : %i,%s"
  18985. "\"full\" : %s%s"
  18986. "}",
  18987. eol,
  18988. eol,
  18989. ctx->sq_size,
  18990. eol,
  18991. ctx->sq_head - ctx->sq_tail,
  18992. eol,
  18993. ctx->sq_max_fill,
  18994. eol,
  18995. (ctx->sq_blocked ? "true" : "false"),
  18996. eol);
  18997. context_info_length += mg_str_append(&buffer, end, block);
  18998. #endif
  18999. /* Requests information */
  19000. mg_snprintf(NULL,
  19001. NULL,
  19002. block,
  19003. sizeof(block),
  19004. ",%s\"requests\" : {%s"
  19005. "\"total\" : %lu%s"
  19006. "}",
  19007. eol,
  19008. eol,
  19009. (unsigned long)ctx->total_requests,
  19010. eol);
  19011. context_info_length += mg_str_append(&buffer, end, block);
  19012. /* Data information */
  19013. total_data_read =
  19014. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19015. total_data_written =
  19016. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19017. mg_snprintf(NULL,
  19018. NULL,
  19019. block,
  19020. sizeof(block),
  19021. ",%s\"data\" : {%s"
  19022. "\"read\" : %" INT64_FMT ",%s"
  19023. "\"written\" : %" INT64_FMT "%s"
  19024. "}",
  19025. eol,
  19026. eol,
  19027. total_data_read,
  19028. eol,
  19029. total_data_written,
  19030. eol);
  19031. context_info_length += mg_str_append(&buffer, end, block);
  19032. /* Execution time information */
  19033. gmt_time_string(start_time_str,
  19034. sizeof(start_time_str) - 1,
  19035. &start_time);
  19036. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19037. mg_snprintf(NULL,
  19038. NULL,
  19039. block,
  19040. sizeof(block),
  19041. ",%s\"time\" : {%s"
  19042. "\"uptime\" : %.0f,%s"
  19043. "\"start\" : \"%s\",%s"
  19044. "\"now\" : \"%s\"%s"
  19045. "}",
  19046. eol,
  19047. eol,
  19048. difftime(now, start_time),
  19049. eol,
  19050. start_time_str,
  19051. eol,
  19052. now_str,
  19053. eol);
  19054. context_info_length += mg_str_append(&buffer, end, block);
  19055. }
  19056. /* Terminate string */
  19057. if (append_eoobj) {
  19058. strcat(append_eoobj, eoobj);
  19059. }
  19060. context_info_length += sizeof(eoobj) - 1;
  19061. return (int)context_info_length;
  19062. #else
  19063. (void)ctx;
  19064. if ((buffer != NULL) && (buflen > 0)) {
  19065. *buffer = 0;
  19066. }
  19067. return 0;
  19068. #endif
  19069. }
  19070. CIVETWEB_API void
  19071. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19072. {
  19073. /* https://github.com/civetweb/civetweb/issues/727 */
  19074. if (conn != NULL) {
  19075. conn->must_close = 1;
  19076. }
  19077. }
  19078. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19079. /* Get connection information. It can be printed or stored by the caller.
  19080. * Return the size of available information. */
  19081. CIVETWEB_API int
  19082. mg_get_connection_info(const struct mg_context *ctx,
  19083. int idx,
  19084. char *buffer,
  19085. int buflen)
  19086. {
  19087. const struct mg_connection *conn;
  19088. const struct mg_request_info *ri;
  19089. char *end, *append_eoobj = NULL, block[256];
  19090. size_t connection_info_length = 0;
  19091. int state = 0;
  19092. const char *state_str = "unknown";
  19093. #if defined(_WIN32)
  19094. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19095. #else
  19096. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19097. #endif
  19098. if ((buffer == NULL) || (buflen < 1)) {
  19099. buflen = 0;
  19100. end = buffer;
  19101. } else {
  19102. *buffer = 0;
  19103. end = buffer + buflen;
  19104. }
  19105. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19106. /* has enough space to append eoobj */
  19107. append_eoobj = buffer;
  19108. end -= sizeof(eoobj) - 1;
  19109. }
  19110. if ((ctx == NULL) || (idx < 0)) {
  19111. /* Parameter error */
  19112. return 0;
  19113. }
  19114. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  19115. /* Out of range */
  19116. return 0;
  19117. }
  19118. /* Take connection [idx]. This connection is not locked in
  19119. * any way, so some other thread might use it. */
  19120. conn = (ctx->worker_connections) + idx;
  19121. /* Initialize output string */
  19122. connection_info_length += mg_str_append(&buffer, end, "{");
  19123. /* Init variables */
  19124. ri = &(conn->request_info);
  19125. #if defined(USE_SERVER_STATS)
  19126. state = conn->conn_state;
  19127. /* State as string */
  19128. switch (state) {
  19129. case 0:
  19130. state_str = "undefined";
  19131. break;
  19132. case 1:
  19133. state_str = "not used";
  19134. break;
  19135. case 2:
  19136. state_str = "init";
  19137. break;
  19138. case 3:
  19139. state_str = "ready";
  19140. break;
  19141. case 4:
  19142. state_str = "processing";
  19143. break;
  19144. case 5:
  19145. state_str = "processed";
  19146. break;
  19147. case 6:
  19148. state_str = "to close";
  19149. break;
  19150. case 7:
  19151. state_str = "closing";
  19152. break;
  19153. case 8:
  19154. state_str = "closed";
  19155. break;
  19156. case 9:
  19157. state_str = "done";
  19158. break;
  19159. }
  19160. #endif
  19161. /* Connection info */
  19162. if ((state >= 3) && (state < 9)) {
  19163. mg_snprintf(NULL,
  19164. NULL,
  19165. block,
  19166. sizeof(block),
  19167. "%s\"connection\" : {%s"
  19168. "\"remote\" : {%s"
  19169. "\"protocol\" : \"%s\",%s"
  19170. "\"addr\" : \"%s\",%s"
  19171. "\"port\" : %u%s"
  19172. "},%s"
  19173. "\"handled_requests\" : %u%s"
  19174. "}",
  19175. eol,
  19176. eol,
  19177. eol,
  19178. get_proto_name(conn),
  19179. eol,
  19180. ri->remote_addr,
  19181. eol,
  19182. ri->remote_port,
  19183. eol,
  19184. eol,
  19185. conn->handled_requests,
  19186. eol);
  19187. connection_info_length += mg_str_append(&buffer, end, block);
  19188. }
  19189. /* Request info */
  19190. if ((state >= 4) && (state < 6)) {
  19191. mg_snprintf(NULL,
  19192. NULL,
  19193. block,
  19194. sizeof(block),
  19195. "%s%s\"request_info\" : {%s"
  19196. "\"method\" : \"%s\",%s"
  19197. "\"uri\" : \"%s\",%s"
  19198. "\"query\" : %s%s%s%s"
  19199. "}",
  19200. (connection_info_length > 1 ? "," : ""),
  19201. eol,
  19202. eol,
  19203. ri->request_method,
  19204. eol,
  19205. ri->request_uri,
  19206. eol,
  19207. ri->query_string ? "\"" : "",
  19208. ri->query_string ? ri->query_string : "null",
  19209. ri->query_string ? "\"" : "",
  19210. eol);
  19211. connection_info_length += mg_str_append(&buffer, end, block);
  19212. }
  19213. /* Execution time information */
  19214. if ((state >= 2) && (state < 9)) {
  19215. char start_time_str[64] = {0};
  19216. char close_time_str[64] = {0};
  19217. time_t start_time = conn->conn_birth_time;
  19218. time_t close_time = 0;
  19219. double time_diff;
  19220. gmt_time_string(start_time_str,
  19221. sizeof(start_time_str) - 1,
  19222. &start_time);
  19223. #if defined(USE_SERVER_STATS)
  19224. close_time = conn->conn_close_time;
  19225. #endif
  19226. if (close_time != 0) {
  19227. time_diff = difftime(close_time, start_time);
  19228. gmt_time_string(close_time_str,
  19229. sizeof(close_time_str) - 1,
  19230. &close_time);
  19231. } else {
  19232. time_t now = time(NULL);
  19233. time_diff = difftime(now, start_time);
  19234. close_time_str[0] = 0; /* or use "now" ? */
  19235. }
  19236. mg_snprintf(NULL,
  19237. NULL,
  19238. block,
  19239. sizeof(block),
  19240. "%s%s\"time\" : {%s"
  19241. "\"uptime\" : %.0f,%s"
  19242. "\"start\" : \"%s\",%s"
  19243. "\"closed\" : \"%s\"%s"
  19244. "}",
  19245. (connection_info_length > 1 ? "," : ""),
  19246. eol,
  19247. eol,
  19248. time_diff,
  19249. eol,
  19250. start_time_str,
  19251. eol,
  19252. close_time_str,
  19253. eol);
  19254. connection_info_length += mg_str_append(&buffer, end, block);
  19255. }
  19256. /* Remote user name */
  19257. if ((ri->remote_user) && (state < 9)) {
  19258. mg_snprintf(NULL,
  19259. NULL,
  19260. block,
  19261. sizeof(block),
  19262. "%s%s\"user\" : {%s"
  19263. "\"name\" : \"%s\",%s"
  19264. "}",
  19265. (connection_info_length > 1 ? "," : ""),
  19266. eol,
  19267. eol,
  19268. ri->remote_user,
  19269. eol);
  19270. connection_info_length += mg_str_append(&buffer, end, block);
  19271. }
  19272. /* Data block */
  19273. if (state >= 3) {
  19274. mg_snprintf(NULL,
  19275. NULL,
  19276. block,
  19277. sizeof(block),
  19278. "%s%s\"data\" : {%s"
  19279. "\"read\" : %" INT64_FMT ",%s"
  19280. "\"written\" : %" INT64_FMT "%s"
  19281. "}",
  19282. (connection_info_length > 1 ? "," : ""),
  19283. eol,
  19284. eol,
  19285. conn->consumed_content,
  19286. eol,
  19287. conn->num_bytes_sent,
  19288. eol);
  19289. connection_info_length += mg_str_append(&buffer, end, block);
  19290. }
  19291. /* State */
  19292. mg_snprintf(NULL,
  19293. NULL,
  19294. block,
  19295. sizeof(block),
  19296. "%s%s\"state\" : \"%s\"",
  19297. (connection_info_length > 1 ? "," : ""),
  19298. eol,
  19299. state_str);
  19300. connection_info_length += mg_str_append(&buffer, end, block);
  19301. /* Terminate string */
  19302. if (append_eoobj) {
  19303. strcat(append_eoobj, eoobj);
  19304. }
  19305. connection_info_length += sizeof(eoobj) - 1;
  19306. return (int)connection_info_length;
  19307. }
  19308. #if 0
  19309. /* Get handler information. It can be printed or stored by the caller.
  19310. * Return the size of available information. */
  19311. CIVETWEB_API int
  19312. mg_get_handler_info(struct mg_context *ctx,
  19313. char *buffer,
  19314. int buflen)
  19315. {
  19316. int handler_info_len = 0;
  19317. struct mg_handler_info *tmp_rh;
  19318. mg_lock_context(ctx);
  19319. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19320. if (buflen > handler_info_len+ tmp_rh->uri_len) {
  19321. memcpy(buffer+handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19322. }
  19323. handler_info_len += tmp_rh->uri_len;
  19324. switch (tmp_rh->handler_type) {
  19325. case REQUEST_HANDLER:
  19326. (void)tmp_rh->handler;
  19327. break;
  19328. case WEBSOCKET_HANDLER:
  19329. (void)tmp_rh->connect_handler;
  19330. (void) tmp_rh->ready_handler;
  19331. (void) tmp_rh->data_handler;
  19332. (void) tmp_rh->close_handler;
  19333. break;
  19334. case AUTH_HANDLER:
  19335. (void) tmp_rh->auth_handler;
  19336. break;
  19337. }
  19338. (void)cbdata;
  19339. }
  19340. mg_unlock_context(ctx);
  19341. return handler_info_len;
  19342. }
  19343. #endif
  19344. #endif
  19345. /* Initialize this library. This function does not need to be thread safe.
  19346. */
  19347. CIVETWEB_API unsigned
  19348. mg_init_library(unsigned features)
  19349. {
  19350. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19351. unsigned features_inited = features_to_init;
  19352. if (mg_init_library_called <= 0) {
  19353. /* Not initialized yet */
  19354. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19355. return 0;
  19356. }
  19357. }
  19358. mg_global_lock();
  19359. if (mg_init_library_called <= 0) {
  19360. int i, len;
  19361. #if defined(_WIN32)
  19362. int file_mutex_init = 1;
  19363. int wsa = 1;
  19364. #else
  19365. int mutexattr_init = 1;
  19366. #endif
  19367. int failed = 1;
  19368. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19369. if (key_create == 0) {
  19370. #if defined(_WIN32)
  19371. file_mutex_init =
  19372. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19373. if (file_mutex_init == 0) {
  19374. /* Start WinSock */
  19375. WSADATA data;
  19376. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19377. }
  19378. #else
  19379. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19380. if (mutexattr_init == 0) {
  19381. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19382. PTHREAD_MUTEX_RECURSIVE);
  19383. }
  19384. #endif
  19385. }
  19386. if (failed) {
  19387. #if defined(_WIN32)
  19388. if (wsa == 0) {
  19389. (void)WSACleanup();
  19390. }
  19391. if (file_mutex_init == 0) {
  19392. (void)pthread_mutex_destroy(&global_log_file_lock);
  19393. }
  19394. #else
  19395. if (mutexattr_init == 0) {
  19396. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19397. }
  19398. #endif
  19399. if (key_create == 0) {
  19400. (void)pthread_key_delete(sTlsKey);
  19401. }
  19402. mg_global_unlock();
  19403. (void)pthread_mutex_destroy(&global_lock_mutex);
  19404. return 0;
  19405. }
  19406. #if defined(USE_LUA)
  19407. lua_init_optional_libraries();
  19408. #endif
  19409. len = 1;
  19410. for (i = 0; http_methods[i].name != NULL; i++) {
  19411. size_t sl = strlen(http_methods[i].name);
  19412. len += (int)sl;
  19413. if (i > 0) {
  19414. len += 2;
  19415. }
  19416. }
  19417. all_methods = mg_malloc(len);
  19418. if (!all_methods) {
  19419. /* Must never happen */
  19420. return 0;
  19421. }
  19422. all_methods[0] = 0;
  19423. for (i = 0; http_methods[i].name != NULL; i++) {
  19424. if (i > 0) {
  19425. strcat(all_methods, ", ");
  19426. strcat(all_methods, http_methods[i].name);
  19427. } else {
  19428. strcpy(all_methods, http_methods[i].name);
  19429. }
  19430. }
  19431. }
  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 */