civetweb.c 614 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991
  1. /* Copyright (c) 2013-2024 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #ifndef GCC_VERSION
  24. #define GCC_VERSION \
  25. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  26. #endif
  27. #if GCC_VERSION >= 40500
  28. /* gcc diagnostic pragmas available */
  29. #define GCC_DIAGNOSTIC
  30. #endif
  31. #endif
  32. #if defined(GCC_DIAGNOSTIC)
  33. /* Disable unused macros warnings - not all defines are required
  34. * for all systems and all compilers. */
  35. #pragma GCC diagnostic ignored "-Wunused-macros"
  36. /* A padding warning is just plain useless */
  37. #pragma GCC diagnostic ignored "-Wpadded"
  38. #endif
  39. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  40. /* We must set some flags for the headers we include. These flags
  41. * are reserved ids according to C99, so we need to disable a
  42. * warning for that. */
  43. #pragma GCC diagnostic push
  44. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  45. #endif
  46. #if defined(_WIN32)
  47. #if !defined(_CRT_SECURE_NO_WARNINGS)
  48. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  49. #endif
  50. #if !defined(_WIN32_WINNT) /* Minimum API version */
  51. #define _WIN32_WINNT 0x0601
  52. #endif
  53. #else
  54. #if !defined(_GNU_SOURCE)
  55. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  56. #endif
  57. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  58. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  59. #endif
  60. #if defined(__LSB_VERSION__) || defined(__sun)
  61. #define NEED_TIMEGM
  62. #define NO_THREAD_NAME
  63. #endif
  64. #if !defined(_LARGEFILE_SOURCE)
  65. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  66. #endif
  67. #if !defined(_FILE_OFFSET_BITS)
  68. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  69. #endif
  70. #if !defined(__STDC_FORMAT_MACROS)
  71. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  72. #endif
  73. #if !defined(__STDC_LIMIT_MACROS)
  74. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  75. #endif
  76. #if !defined(_DARWIN_UNLIMITED_SELECT)
  77. #define _DARWIN_UNLIMITED_SELECT
  78. #endif
  79. #if defined(__sun)
  80. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  81. #define __inline inline /* not recognized on older compiler versions */
  82. #endif
  83. #endif
  84. #if defined(__clang__)
  85. /* Enable reserved-id-macro warning again. */
  86. #pragma GCC diagnostic pop
  87. #endif
  88. #if defined(USE_LUA)
  89. #define USE_TIMERS
  90. #endif
  91. #if defined(_MSC_VER)
  92. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  93. #pragma warning(disable : 4306)
  94. /* conditional expression is constant: introduced by FD_SET(..) */
  95. #pragma warning(disable : 4127)
  96. /* non-constant aggregate initializer: issued due to missing C99 support */
  97. #pragma warning(disable : 4204)
  98. /* padding added after data member */
  99. #pragma warning(disable : 4820)
  100. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  101. #pragma warning(disable : 4668)
  102. /* no function prototype given: converting '()' to '(void)' */
  103. #pragma warning(disable : 4255)
  104. /* function has been selected for automatic inline expansion */
  105. #pragma warning(disable : 4711)
  106. #endif
  107. /* This code uses static_assert to check some conditions.
  108. * Unfortunately some compilers still do not support it, so we have a
  109. * replacement function here. */
  110. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  111. #define mg_static_assert _Static_assert
  112. #elif defined(__cplusplus) && __cplusplus >= 201103L
  113. #define mg_static_assert static_assert
  114. #else
  115. char static_assert_replacement[1];
  116. #define mg_static_assert(cond, txt) \
  117. extern char static_assert_replacement[(cond) ? 1 : -1]
  118. #endif
  119. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  120. "int data type size check");
  121. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  122. "pointer data type size check");
  123. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  124. /* Select queue implementation. Diagnosis features originally only implemented
  125. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  126. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  127. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  128. * implementation, since the queue length is independent from the number of
  129. * worker threads there, while the new queue is one element per worker thread.
  130. *
  131. */
  132. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  133. /* The queues are exclusive or - only one can be used. */
  134. #error \
  135. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  136. #endif
  137. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  138. /* Use a default implementation */
  139. #define NO_ALTERNATIVE_QUEUE
  140. #endif
  141. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  142. /* File system access:
  143. * NO_FILES = do not serve any files from the file system automatically.
  144. * However, with NO_FILES CivetWeb may still write log files, read access
  145. * control files, default error page files or use API functions like
  146. * mg_send_file in callbacks to send files from the server local
  147. * file system.
  148. * NO_FILES only disables the automatic mapping between URLs and local
  149. * file names.
  150. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  151. * devices without file system. Logging to files in not available
  152. * (use callbacks instead) and API functions like mg_send_file are not
  153. * available.
  154. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  155. */
  156. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  157. #endif
  158. /* DTL -- including winsock2.h works better if lean and mean */
  159. #if !defined(WIN32_LEAN_AND_MEAN)
  160. #define WIN32_LEAN_AND_MEAN
  161. #endif
  162. #if defined(__SYMBIAN32__)
  163. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  164. * Symbian is no longer maintained since 2014-01-01.
  165. * Support for Symbian has been removed from CivetWeb
  166. */
  167. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  168. #endif /* __SYMBIAN32__ */
  169. #if defined(__ZEPHYR__)
  170. #include <ctype.h>
  171. #include <fcntl.h>
  172. #include <netdb.h>
  173. #include <poll.h>
  174. #include <pthread.h>
  175. #include <stdio.h>
  176. #include <stdlib.h>
  177. #include <string.h>
  178. #include <sys/socket.h>
  179. #include <time.h>
  180. #include <zephyr/kernel.h>
  181. /* Max worker threads is the max of pthreads minus the main application thread
  182. * and minus the main civetweb thread, thus -2
  183. */
  184. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  185. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  186. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  187. #else
  188. #define ZEPHYR_STACK_SIZE (1024 * 16)
  189. #endif
  190. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  191. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  192. MAX_WORKER_THREADS,
  193. ZEPHYR_STACK_SIZE);
  194. static int zephyr_worker_stack_index;
  195. #endif
  196. #if !defined(CIVETWEB_HEADER_INCLUDED)
  197. /* Include the header file here, so the CivetWeb interface is defined for the
  198. * entire implementation, including the following forward definitions. */
  199. #include "civetweb.h"
  200. #endif
  201. #if !defined(DEBUG_TRACE)
  202. #if defined(DEBUG)
  203. static void DEBUG_TRACE_FUNC(const char *func,
  204. unsigned line,
  205. PRINTF_FORMAT_STRING(const char *fmt),
  206. ...) PRINTF_ARGS(3, 4);
  207. #define DEBUG_TRACE(fmt, ...) \
  208. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  209. #define NEED_DEBUG_TRACE_FUNC
  210. #if !defined(DEBUG_TRACE_STREAM)
  211. #define DEBUG_TRACE_STREAM stdout
  212. #endif
  213. #else
  214. #define DEBUG_TRACE(fmt, ...) \
  215. do { \
  216. } while (0)
  217. #endif /* DEBUG */
  218. #endif /* DEBUG_TRACE */
  219. #if !defined(DEBUG_ASSERT)
  220. #if defined(DEBUG)
  221. #include <stdlib.h>
  222. #define DEBUG_ASSERT(cond) \
  223. do { \
  224. if (!(cond)) { \
  225. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  226. exit(2); /* Exit with error */ \
  227. } \
  228. } while (0)
  229. #else
  230. #define DEBUG_ASSERT(cond)
  231. #endif /* DEBUG */
  232. #endif
  233. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  234. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  235. __attribute__((no_instrument_function));
  236. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  237. __attribute__((no_instrument_function));
  238. void
  239. __cyg_profile_func_enter(void *this_fn, void *call_site)
  240. {
  241. if ((void *)this_fn != (void *)printf) {
  242. printf("E %p %p\n", this_fn, call_site);
  243. }
  244. }
  245. void
  246. __cyg_profile_func_exit(void *this_fn, void *call_site)
  247. {
  248. if ((void *)this_fn != (void *)printf) {
  249. printf("X %p %p\n", this_fn, call_site);
  250. }
  251. }
  252. #endif
  253. #if !defined(IGNORE_UNUSED_RESULT)
  254. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  255. #endif
  256. #if defined(__GNUC__) || defined(__MINGW32__)
  257. /* GCC unused function attribute seems fundamentally broken.
  258. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  259. * OR UNUSED" for individual functions failed.
  260. * Either the compiler creates an "unused-function" warning if a
  261. * function is not marked with __attribute__((unused)).
  262. * On the other hand, if the function is marked with this attribute,
  263. * but is used, the compiler raises a completely idiotic
  264. * "used-but-marked-unused" warning - and
  265. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  266. * raises error: unknown option after "#pragma GCC diagnostic".
  267. * Disable this warning completely, until the GCC guys sober up
  268. * again.
  269. */
  270. #pragma GCC diagnostic ignored "-Wunused-function"
  271. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  272. #else
  273. #define FUNCTION_MAY_BE_UNUSED
  274. #endif
  275. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  276. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  277. #include <errno.h>
  278. #include <fcntl.h>
  279. #include <signal.h>
  280. #include <stdlib.h>
  281. #include <sys/stat.h>
  282. #include <sys/types.h>
  283. #endif /* !_WIN32_WCE */
  284. #if defined(__clang__)
  285. /* When using -Weverything, clang does not accept it's own headers
  286. * in a release build configuration. Disable what is too much in
  287. * -Weverything. */
  288. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  289. #endif
  290. #if defined(__GNUC__) || defined(__MINGW32__)
  291. /* Who on earth came to the conclusion, using __DATE__ should rise
  292. * an "expansion of date or time macro is not reproducible"
  293. * warning. That's exactly what was intended by using this macro.
  294. * Just disable this nonsense warning. */
  295. /* And disabling them does not work either:
  296. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  297. * #pragma clang diagnostic ignored "-Wdate-time"
  298. * So we just have to disable ALL warnings for some lines
  299. * of code.
  300. * This seems to be a known GCC bug, not resolved since 2012:
  301. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  302. */
  303. #endif
  304. #if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
  305. #if defined(__clang__)
  306. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  307. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  308. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  309. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  310. #endif
  311. #endif
  312. #ifndef CLOCK_MONOTONIC
  313. #define CLOCK_MONOTONIC (1)
  314. #endif
  315. #ifndef CLOCK_REALTIME
  316. #define CLOCK_REALTIME (2)
  317. #endif
  318. #include <mach/clock.h>
  319. #include <mach/mach.h>
  320. #include <mach/mach_time.h>
  321. #include <sys/errno.h>
  322. #include <sys/time.h>
  323. /* clock_gettime is not implemented on OSX prior to 10.12 */
  324. static int
  325. _civet_clock_gettime(int clk_id, struct timespec *t)
  326. {
  327. memset(t, 0, sizeof(*t));
  328. if (clk_id == CLOCK_REALTIME) {
  329. struct timeval now;
  330. int rv = gettimeofday(&now, NULL);
  331. if (rv) {
  332. return rv;
  333. }
  334. t->tv_sec = now.tv_sec;
  335. t->tv_nsec = now.tv_usec * 1000;
  336. return 0;
  337. } else if (clk_id == CLOCK_MONOTONIC) {
  338. static uint64_t clock_start_time = 0;
  339. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  340. uint64_t now = mach_absolute_time();
  341. if (clock_start_time == 0) {
  342. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  343. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  344. /* appease "unused variable" warning for release builds */
  345. (void)mach_status;
  346. clock_start_time = now;
  347. }
  348. now = (uint64_t)((double)(now - clock_start_time)
  349. * (double)timebase_ifo.numer
  350. / (double)timebase_ifo.denom);
  351. t->tv_sec = now / 1000000000;
  352. t->tv_nsec = now % 1000000000;
  353. return 0;
  354. }
  355. return -1; /* EINVAL - Clock ID is unknown */
  356. }
  357. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  358. #if defined(__CLOCK_AVAILABILITY)
  359. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  360. * declared but it may be NULL at runtime. So we need to check before using
  361. * it. */
  362. static int
  363. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  364. {
  365. if (clock_gettime) {
  366. return clock_gettime(clk_id, t);
  367. }
  368. return _civet_clock_gettime(clk_id, t);
  369. }
  370. #define clock_gettime _civet_safe_clock_gettime
  371. #else
  372. #define clock_gettime _civet_clock_gettime
  373. #endif
  374. #endif
  375. #if defined(_WIN32)
  376. #define ERROR_TRY_AGAIN(err) ((err) == WSAEWOULDBLOCK)
  377. #else
  378. /* Unix might return different error codes indicating to try again.
  379. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  380. * decades ago, but better check both and let the compiler optimize it. */
  381. #define ERROR_TRY_AGAIN(err) \
  382. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  383. #endif
  384. #if defined(USE_ZLIB)
  385. #include "zconf.h"
  386. #include "zlib.h"
  387. #endif
  388. /********************************************************************/
  389. /* CivetWeb configuration defines */
  390. /********************************************************************/
  391. /* Maximum number of threads that can be configured.
  392. * The number of threads actually created depends on the "num_threads"
  393. * configuration parameter, but this is the upper limit. */
  394. #if !defined(MAX_WORKER_THREADS)
  395. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  396. #endif
  397. /* Timeout interval for select/poll calls.
  398. * The timeouts depend on "*_timeout_ms" configuration values, but long
  399. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  400. * This reduces the time required to stop the server. */
  401. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  402. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  403. #endif
  404. /* Do not try to compress files smaller than this limit. */
  405. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  406. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  407. #endif
  408. #if !defined(PASSWORDS_FILE_NAME)
  409. #define PASSWORDS_FILE_NAME ".htpasswd"
  410. #endif
  411. /* Initial buffer size for all CGI environment variables. In case there is
  412. * not enough space, another block is allocated. */
  413. #if !defined(CGI_ENVIRONMENT_SIZE)
  414. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  415. #endif
  416. /* Maximum number of environment variables. */
  417. #if !defined(MAX_CGI_ENVIR_VARS)
  418. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  419. #endif
  420. /* General purpose buffer size. */
  421. #if !defined(MG_BUF_LEN) /* in bytes */
  422. #define MG_BUF_LEN (1024 * 8)
  423. #endif
  424. /********************************************************************/
  425. /* Helper macros */
  426. #if !defined(ARRAY_SIZE)
  427. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  428. #endif
  429. #include <stdint.h>
  430. /* Standard defines */
  431. #if !defined(INT64_MAX)
  432. #define INT64_MAX (9223372036854775807)
  433. #endif
  434. #define SHUTDOWN_RD (0)
  435. #define SHUTDOWN_WR (1)
  436. #define SHUTDOWN_BOTH (2)
  437. mg_static_assert(MAX_WORKER_THREADS >= 1,
  438. "worker threads must be a positive number");
  439. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  440. "size_t data type size check");
  441. #if defined(_WIN32) /* WINDOWS include block */
  442. #include <malloc.h> /* *alloc( */
  443. #include <stdlib.h> /* *alloc( */
  444. #include <time.h> /* struct timespec */
  445. #include <windows.h>
  446. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  447. #include <ws2tcpip.h>
  448. typedef const char *SOCK_OPT_TYPE;
  449. /* For a detailed description of these *_PATH_MAX defines, see
  450. * https://github.com/civetweb/civetweb/issues/937. */
  451. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  452. * null termination, rounded up to the next 4 bytes boundary */
  453. #define UTF8_PATH_MAX (3 * 260)
  454. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  455. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  456. #define UTF16_PATH_MAX (260)
  457. #if !defined(_IN_PORT_T)
  458. #if !defined(in_port_t)
  459. #define in_port_t u_short
  460. #endif
  461. #endif
  462. #if defined(_WIN32_WCE)
  463. #error "WinCE support has ended"
  464. #endif
  465. #include <direct.h>
  466. #include <io.h>
  467. #include <process.h>
  468. #define MAKEUQUAD(lo, hi) \
  469. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  470. #define RATE_DIFF (10000000) /* 100 nsecs */
  471. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  472. #define SYS2UNIX_TIME(lo, hi) \
  473. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  474. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  475. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  476. * Also use _strtoui64 on modern M$ compilers */
  477. #if defined(_MSC_VER)
  478. #if (_MSC_VER < 1300)
  479. #define STRX(x) #x
  480. #define STR(x) STRX(x)
  481. #define __func__ __FILE__ ":" STR(__LINE__)
  482. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  483. #define strtoll(x, y, z) (_atoi64(x))
  484. #else
  485. #define __func__ __FUNCTION__
  486. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  487. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  488. #endif
  489. #endif /* _MSC_VER */
  490. #define ERRNO ((int)(GetLastError()))
  491. #define NO_SOCKLEN_T
  492. #if defined(_WIN64) || defined(__MINGW64__)
  493. #if !defined(SSL_LIB)
  494. #if defined(OPENSSL_API_3_0)
  495. #define SSL_LIB "libssl-3-x64.dll"
  496. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  497. #endif
  498. #if defined(OPENSSL_API_1_1)
  499. #define SSL_LIB "libssl-1_1-x64.dll"
  500. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  501. #endif /* OPENSSL_API_1_1 */
  502. #if defined(OPENSSL_API_1_0)
  503. #define SSL_LIB "ssleay64.dll"
  504. #define CRYPTO_LIB "libeay64.dll"
  505. #endif /* OPENSSL_API_1_0 */
  506. #endif
  507. #else /* defined(_WIN64) || defined(__MINGW64__) */
  508. #if !defined(SSL_LIB)
  509. #if defined(OPENSSL_API_3_0)
  510. #define SSL_LIB "libssl-3.dll"
  511. #define CRYPTO_LIB "libcrypto-3.dll"
  512. #endif
  513. #if defined(OPENSSL_API_1_1)
  514. #define SSL_LIB "libssl-1_1.dll"
  515. #define CRYPTO_LIB "libcrypto-1_1.dll"
  516. #endif /* OPENSSL_API_1_1 */
  517. #if defined(OPENSSL_API_1_0)
  518. #define SSL_LIB "ssleay32.dll"
  519. #define CRYPTO_LIB "libeay32.dll"
  520. #endif /* OPENSSL_API_1_0 */
  521. #endif /* SSL_LIB */
  522. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  523. #define O_NONBLOCK (0)
  524. #if !defined(W_OK)
  525. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  526. #endif
  527. #define _POSIX_
  528. #define INT64_FMT "I64d"
  529. #define UINT64_FMT "I64u"
  530. #define WINCDECL __cdecl
  531. #define vsnprintf_impl _vsnprintf
  532. #define access _access
  533. #define mg_sleep(x) (Sleep(x))
  534. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  535. #if !defined(popen)
  536. #define popen(x, y) (_popen(x, y))
  537. #endif
  538. #if !defined(pclose)
  539. #define pclose(x) (_pclose(x))
  540. #endif
  541. #define close(x) (_close(x))
  542. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  543. #define RTLD_LAZY (0)
  544. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  545. #define fdopen(x, y) (_fdopen((x), (y)))
  546. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  547. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  548. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  549. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  550. #define sleep(x) (Sleep((x)*1000))
  551. #define rmdir(x) (_rmdir(x))
  552. #if defined(_WIN64) || !defined(__MINGW32__)
  553. /* Only MinGW 32 bit is missing this function */
  554. #define timegm(x) (_mkgmtime(x))
  555. #else
  556. time_t timegm(struct tm *tm);
  557. #define NEED_TIMEGM
  558. #endif
  559. #if !defined(fileno)
  560. #define fileno(x) (_fileno(x))
  561. #endif /* !fileno MINGW #defines fileno */
  562. typedef struct {
  563. CRITICAL_SECTION sec; /* Immovable */
  564. } pthread_mutex_t;
  565. typedef DWORD pthread_key_t;
  566. typedef HANDLE pthread_t;
  567. typedef struct {
  568. pthread_mutex_t threadIdSec;
  569. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  570. } pthread_cond_t;
  571. #if !defined(__clockid_t_defined)
  572. typedef DWORD clockid_t;
  573. #endif
  574. #if !defined(CLOCK_MONOTONIC)
  575. #define CLOCK_MONOTONIC (1)
  576. #endif
  577. #if !defined(CLOCK_REALTIME)
  578. #define CLOCK_REALTIME (2)
  579. #endif
  580. #if !defined(CLOCK_THREAD)
  581. #define CLOCK_THREAD (3)
  582. #endif
  583. #if !defined(CLOCK_PROCESS)
  584. #define CLOCK_PROCESS (4)
  585. #endif
  586. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  587. #define _TIMESPEC_DEFINED
  588. #endif
  589. #if !defined(_TIMESPEC_DEFINED)
  590. struct timespec {
  591. time_t tv_sec; /* seconds */
  592. long tv_nsec; /* nanoseconds */
  593. };
  594. #endif
  595. #if !defined(WIN_PTHREADS_TIME_H)
  596. #define MUST_IMPLEMENT_CLOCK_GETTIME
  597. #endif
  598. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  599. #define clock_gettime mg_clock_gettime
  600. static int
  601. clock_gettime(clockid_t clk_id, struct timespec *tp)
  602. {
  603. FILETIME ft;
  604. ULARGE_INTEGER li, li2;
  605. BOOL ok = FALSE;
  606. double d;
  607. static double perfcnt_per_sec = 0.0;
  608. static BOOL initialized = FALSE;
  609. if (!initialized) {
  610. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  611. perfcnt_per_sec = 1.0 / li.QuadPart;
  612. initialized = TRUE;
  613. }
  614. if (tp) {
  615. memset(tp, 0, sizeof(*tp));
  616. if (clk_id == CLOCK_REALTIME) {
  617. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  618. GetSystemTimeAsFileTime(&ft);
  619. li.LowPart = ft.dwLowDateTime;
  620. li.HighPart = ft.dwHighDateTime;
  621. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  622. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  623. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  624. ok = TRUE;
  625. /* END: CLOCK_REALTIME */
  626. } else if (clk_id == CLOCK_MONOTONIC) {
  627. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  628. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  629. d = li.QuadPart * perfcnt_per_sec;
  630. tp->tv_sec = (time_t)d;
  631. d -= (double)tp->tv_sec;
  632. tp->tv_nsec = (long)(d * 1.0E9);
  633. ok = TRUE;
  634. /* END: CLOCK_MONOTONIC */
  635. } else if (clk_id == CLOCK_THREAD) {
  636. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  637. FILETIME t_create, t_exit, t_kernel, t_user;
  638. if (GetThreadTimes(GetCurrentThread(),
  639. &t_create,
  640. &t_exit,
  641. &t_kernel,
  642. &t_user)) {
  643. li.LowPart = t_user.dwLowDateTime;
  644. li.HighPart = t_user.dwHighDateTime;
  645. li2.LowPart = t_kernel.dwLowDateTime;
  646. li2.HighPart = t_kernel.dwHighDateTime;
  647. li.QuadPart += li2.QuadPart;
  648. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  649. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  650. ok = TRUE;
  651. }
  652. /* END: CLOCK_THREAD */
  653. } else if (clk_id == CLOCK_PROCESS) {
  654. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  655. FILETIME t_create, t_exit, t_kernel, t_user;
  656. if (GetProcessTimes(GetCurrentProcess(),
  657. &t_create,
  658. &t_exit,
  659. &t_kernel,
  660. &t_user)) {
  661. li.LowPart = t_user.dwLowDateTime;
  662. li.HighPart = t_user.dwHighDateTime;
  663. li2.LowPart = t_kernel.dwLowDateTime;
  664. li2.HighPart = t_kernel.dwHighDateTime;
  665. li.QuadPart += li2.QuadPart;
  666. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  667. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  668. ok = TRUE;
  669. }
  670. /* END: CLOCK_PROCESS */
  671. } else {
  672. /* BEGIN: unknown clock */
  673. /* ok = FALSE; already set by init */
  674. /* END: unknown clock */
  675. }
  676. }
  677. return ok ? 0 : -1;
  678. }
  679. #endif
  680. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  681. static int pthread_mutex_lock(pthread_mutex_t *);
  682. static int pthread_mutex_unlock(pthread_mutex_t *);
  683. static void path_to_unicode(const struct mg_connection *conn,
  684. const char *path,
  685. wchar_t *wbuf,
  686. size_t wbuf_len);
  687. /* All file operations need to be rewritten to solve #246. */
  688. struct mg_file;
  689. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  690. /* POSIX dirent interface */
  691. struct dirent {
  692. char d_name[UTF8_PATH_MAX];
  693. };
  694. typedef struct DIR {
  695. HANDLE handle;
  696. WIN32_FIND_DATAW info;
  697. struct dirent result;
  698. } DIR;
  699. #if defined(HAVE_POLL)
  700. #define mg_pollfd pollfd
  701. #else
  702. struct mg_pollfd {
  703. SOCKET fd;
  704. short events;
  705. short revents;
  706. };
  707. #endif
  708. /* Mark required libraries */
  709. #if defined(_MSC_VER)
  710. #pragma comment(lib, "Ws2_32.lib")
  711. #endif
  712. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  713. #include <inttypes.h>
  714. /* Linux & co. internally use UTF8 */
  715. #define UTF8_PATH_MAX (PATH_MAX)
  716. typedef const void *SOCK_OPT_TYPE;
  717. #if defined(ANDROID)
  718. typedef unsigned short int in_port_t;
  719. #endif
  720. #if !defined(__ZEPHYR__)
  721. #include <arpa/inet.h>
  722. #include <ctype.h>
  723. #include <dirent.h>
  724. #include <grp.h>
  725. #include <limits.h>
  726. #include <netdb.h>
  727. #include <netinet/in.h>
  728. #include <netinet/tcp.h>
  729. #include <poll.h>
  730. #include <pthread.h>
  731. #include <pwd.h>
  732. #include <stdarg.h>
  733. #include <stddef.h>
  734. #include <stdio.h>
  735. #include <stdlib.h>
  736. #include <string.h>
  737. #include <sys/socket.h>
  738. #include <sys/time.h>
  739. #include <sys/utsname.h>
  740. #include <sys/wait.h>
  741. #include <time.h>
  742. #include <unistd.h>
  743. #if defined(USE_X_DOM_SOCKET)
  744. #include <sys/un.h>
  745. #endif
  746. #endif
  747. #define vsnprintf_impl vsnprintf
  748. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  749. #include <dlfcn.h>
  750. #endif
  751. #if defined(__MACH__) && defined(__APPLE__)
  752. #define SSL_LIB "libssl.dylib"
  753. #define CRYPTO_LIB "libcrypto.dylib"
  754. #else
  755. #if !defined(SSL_LIB)
  756. #define SSL_LIB "libssl.so"
  757. #endif
  758. #if !defined(CRYPTO_LIB)
  759. #define CRYPTO_LIB "libcrypto.so"
  760. #endif
  761. #endif
  762. #if !defined(O_BINARY)
  763. #define O_BINARY (0)
  764. #endif /* O_BINARY */
  765. #define closesocket(a) (close(a))
  766. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  767. #define mg_remove(conn, x) (remove(x))
  768. #define mg_sleep(x) (usleep((x)*1000))
  769. #define mg_opendir(conn, x) (opendir(x))
  770. #define mg_closedir(x) (closedir(x))
  771. #define mg_readdir(x) (readdir(x))
  772. #define ERRNO (errno)
  773. #define INVALID_SOCKET (-1)
  774. #define INT64_FMT PRId64
  775. #define UINT64_FMT PRIu64
  776. typedef int SOCKET;
  777. #define WINCDECL
  778. #if defined(__hpux)
  779. /* HPUX 11 does not have monotonic, fall back to realtime */
  780. #if !defined(CLOCK_MONOTONIC)
  781. #define CLOCK_MONOTONIC CLOCK_REALTIME
  782. #endif
  783. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  784. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  785. * the prototypes use int* rather than socklen_t* which matches the
  786. * actual library expectation. When called with the wrong size arg
  787. * accept() returns a zero client inet addr and check_acl() always
  788. * fails. Since socklen_t is widely used below, just force replace
  789. * their typedef with int. - DTL
  790. */
  791. #define socklen_t int
  792. #endif /* hpux */
  793. #define mg_pollfd pollfd
  794. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  795. /* In case our C library is missing "timegm", provide an implementation */
  796. #if defined(NEED_TIMEGM)
  797. static inline int
  798. is_leap(int y)
  799. {
  800. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  801. }
  802. static inline int
  803. count_leap(int y)
  804. {
  805. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  806. }
  807. time_t
  808. timegm(struct tm *tm)
  809. {
  810. static const unsigned short ydays[] = {
  811. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  812. int year = tm->tm_year + 1900;
  813. int mon = tm->tm_mon;
  814. int mday = tm->tm_mday - 1;
  815. int hour = tm->tm_hour;
  816. int min = tm->tm_min;
  817. int sec = tm->tm_sec;
  818. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  819. || (mday >= ydays[mon + 1] - ydays[mon]
  820. + (mon == 1 && is_leap(year) ? 1 : 0))
  821. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  822. return -1;
  823. time_t res = year - 1970;
  824. res *= 365;
  825. res += mday;
  826. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  827. res += count_leap(year);
  828. res *= 24;
  829. res += hour;
  830. res *= 60;
  831. res += min;
  832. res *= 60;
  833. res += sec;
  834. return res;
  835. }
  836. #endif /* NEED_TIMEGM */
  837. /* va_copy should always be a macro, C99 and C++11 - DTL */
  838. #if !defined(va_copy)
  839. #define va_copy(x, y) ((x) = (y))
  840. #endif
  841. #if defined(_WIN32)
  842. /* Create substitutes for POSIX functions in Win32. */
  843. #if defined(GCC_DIAGNOSTIC)
  844. /* Show no warning in case system functions are not used. */
  845. #pragma GCC diagnostic push
  846. #pragma GCC diagnostic ignored "-Wunused-function"
  847. #endif
  848. static pthread_mutex_t global_log_file_lock;
  849. FUNCTION_MAY_BE_UNUSED
  850. static DWORD
  851. pthread_self(void)
  852. {
  853. return GetCurrentThreadId();
  854. }
  855. FUNCTION_MAY_BE_UNUSED
  856. static int
  857. pthread_key_create(
  858. pthread_key_t *key,
  859. void (*_ignored)(void *) /* destructor not supported for Windows */
  860. )
  861. {
  862. (void)_ignored;
  863. if ((key != 0)) {
  864. *key = TlsAlloc();
  865. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  866. }
  867. return -2;
  868. }
  869. FUNCTION_MAY_BE_UNUSED
  870. static int
  871. pthread_key_delete(pthread_key_t key)
  872. {
  873. return TlsFree(key) ? 0 : 1;
  874. }
  875. FUNCTION_MAY_BE_UNUSED
  876. static int
  877. pthread_setspecific(pthread_key_t key, void *value)
  878. {
  879. return TlsSetValue(key, value) ? 0 : 1;
  880. }
  881. FUNCTION_MAY_BE_UNUSED
  882. static void *
  883. pthread_getspecific(pthread_key_t key)
  884. {
  885. return TlsGetValue(key);
  886. }
  887. #if defined(GCC_DIAGNOSTIC)
  888. /* Enable unused function warning again */
  889. #pragma GCC diagnostic pop
  890. #endif
  891. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  892. #else
  893. static pthread_mutexattr_t pthread_mutex_attr;
  894. #endif /* _WIN32 */
  895. #if defined(GCC_DIAGNOSTIC)
  896. /* Show no warning in case system functions are not used. */
  897. #pragma GCC diagnostic push
  898. #pragma GCC diagnostic ignored "-Wunused-function"
  899. #endif /* defined(GCC_DIAGNOSTIC) */
  900. #if defined(__clang__)
  901. /* Show no warning in case system functions are not used. */
  902. #pragma clang diagnostic push
  903. #pragma clang diagnostic ignored "-Wunused-function"
  904. #endif
  905. static pthread_mutex_t global_lock_mutex;
  906. FUNCTION_MAY_BE_UNUSED
  907. static void
  908. mg_global_lock(void)
  909. {
  910. (void)pthread_mutex_lock(&global_lock_mutex);
  911. }
  912. FUNCTION_MAY_BE_UNUSED
  913. static void
  914. mg_global_unlock(void)
  915. {
  916. (void)pthread_mutex_unlock(&global_lock_mutex);
  917. }
  918. #if defined(_WIN64)
  919. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  920. #elif defined(_WIN32)
  921. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  922. #endif
  923. /* Atomic functions working on ptrdiff_t ("signed size_t").
  924. * Operations: Increment, Decrement, Add, Maximum.
  925. * Up to size_t, they do not an atomic "load" operation.
  926. */
  927. FUNCTION_MAY_BE_UNUSED
  928. static ptrdiff_t
  929. mg_atomic_inc(volatile ptrdiff_t *addr)
  930. {
  931. ptrdiff_t ret;
  932. #if defined(_WIN64) && !defined(NO_ATOMICS)
  933. ret = InterlockedIncrement64(addr);
  934. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  935. #ifdef __cplusplus
  936. /* For C++ the Microsoft Visual Studio compiler can not decide what
  937. * overloaded function prototpye in the SDC corresponds to "ptrdiff_t". */
  938. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  939. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  940. ret = InterlockedIncrement((LONG *)addr);
  941. #else
  942. ret = InterlockedIncrement(addr);
  943. #endif
  944. #elif defined(__GNUC__) \
  945. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  946. && !defined(NO_ATOMICS)
  947. ret = __sync_add_and_fetch(addr, 1);
  948. #else
  949. mg_global_lock();
  950. ret = (++(*addr));
  951. mg_global_unlock();
  952. #endif
  953. return ret;
  954. }
  955. FUNCTION_MAY_BE_UNUSED
  956. static ptrdiff_t
  957. mg_atomic_dec(volatile ptrdiff_t *addr)
  958. {
  959. ptrdiff_t ret;
  960. #if defined(_WIN64) && !defined(NO_ATOMICS)
  961. ret = InterlockedDecrement64(addr);
  962. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  963. #ifdef __cplusplus
  964. /* see mg_atomic_inc */
  965. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  966. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  967. ret = InterlockedDecrement((LONG *)addr);
  968. #else
  969. ret = InterlockedDecrement(addr);
  970. #endif
  971. #elif defined(__GNUC__) \
  972. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  973. && !defined(NO_ATOMICS)
  974. ret = __sync_sub_and_fetch(addr, 1);
  975. #else
  976. mg_global_lock();
  977. ret = (--(*addr));
  978. mg_global_unlock();
  979. #endif
  980. return ret;
  981. }
  982. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  983. static ptrdiff_t
  984. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  985. {
  986. ptrdiff_t ret;
  987. #if defined(_WIN64) && !defined(NO_ATOMICS)
  988. ret = InterlockedAdd64(addr, value);
  989. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  990. ret = InterlockedExchangeAdd(addr, value) + value;
  991. #elif defined(__GNUC__) \
  992. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  993. && !defined(NO_ATOMICS)
  994. ret = __sync_add_and_fetch(addr, value);
  995. #else
  996. mg_global_lock();
  997. *addr += value;
  998. ret = (*addr);
  999. mg_global_unlock();
  1000. #endif
  1001. return ret;
  1002. }
  1003. FUNCTION_MAY_BE_UNUSED
  1004. static ptrdiff_t
  1005. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1006. ptrdiff_t oldval,
  1007. ptrdiff_t newval)
  1008. {
  1009. ptrdiff_t ret;
  1010. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1011. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1012. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1013. ret = InterlockedCompareExchange(addr, newval, oldval);
  1014. #elif defined(__GNUC__) \
  1015. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1016. && !defined(NO_ATOMICS)
  1017. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1018. #else
  1019. mg_global_lock();
  1020. ret = *addr;
  1021. if ((ret != newval) && (ret == oldval)) {
  1022. *addr = newval;
  1023. }
  1024. mg_global_unlock();
  1025. #endif
  1026. return ret;
  1027. }
  1028. static void
  1029. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1030. {
  1031. register ptrdiff_t tmp = *addr;
  1032. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1033. while (tmp < value) {
  1034. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1035. }
  1036. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1037. while (tmp < value) {
  1038. tmp = InterlockedCompareExchange(addr, value, tmp);
  1039. }
  1040. #elif defined(__GNUC__) \
  1041. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1042. && !defined(NO_ATOMICS)
  1043. while (tmp < value) {
  1044. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1045. }
  1046. #else
  1047. mg_global_lock();
  1048. if (*addr < value) {
  1049. *addr = value;
  1050. }
  1051. mg_global_unlock();
  1052. #endif
  1053. }
  1054. static int64_t
  1055. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1056. {
  1057. int64_t ret;
  1058. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1059. ret = InterlockedAdd64(addr, value);
  1060. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1061. ret = InterlockedExchangeAdd64(addr, value) + value;
  1062. #elif defined(__GNUC__) \
  1063. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1064. && !defined(NO_ATOMICS)
  1065. ret = __sync_add_and_fetch(addr, value);
  1066. #else
  1067. mg_global_lock();
  1068. *addr += value;
  1069. ret = (*addr);
  1070. mg_global_unlock();
  1071. #endif
  1072. return ret;
  1073. }
  1074. #endif
  1075. #if defined(GCC_DIAGNOSTIC)
  1076. /* Show no warning in case system functions are not used. */
  1077. #pragma GCC diagnostic pop
  1078. #endif /* defined(GCC_DIAGNOSTIC) */
  1079. #if defined(__clang__)
  1080. /* Show no warning in case system functions are not used. */
  1081. #pragma clang diagnostic pop
  1082. #endif
  1083. #if defined(USE_SERVER_STATS)
  1084. struct mg_memory_stat {
  1085. volatile ptrdiff_t totalMemUsed;
  1086. volatile ptrdiff_t maxMemUsed;
  1087. volatile ptrdiff_t blockCount;
  1088. };
  1089. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1090. static void *
  1091. mg_malloc_ex(size_t size,
  1092. struct mg_context *ctx,
  1093. const char *file,
  1094. unsigned line)
  1095. {
  1096. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1097. void *memory = 0;
  1098. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1099. #if defined(MEMORY_DEBUGGING)
  1100. char mallocStr[256];
  1101. #else
  1102. (void)file;
  1103. (void)line;
  1104. #endif
  1105. if (data) {
  1106. uintptr_t *tmp = (uintptr_t *)data;
  1107. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1108. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1109. mg_atomic_inc(&mstat->blockCount);
  1110. tmp[0] = size;
  1111. tmp[1] = (uintptr_t)mstat;
  1112. memory = (void *)&tmp[2];
  1113. }
  1114. #if defined(MEMORY_DEBUGGING)
  1115. sprintf(mallocStr,
  1116. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1117. memory,
  1118. (unsigned long)size,
  1119. (unsigned long)mstat->totalMemUsed,
  1120. (unsigned long)mstat->blockCount,
  1121. file,
  1122. line);
  1123. DEBUG_TRACE("%s", mallocStr);
  1124. #endif
  1125. return memory;
  1126. }
  1127. static void *
  1128. mg_calloc_ex(size_t count,
  1129. size_t size,
  1130. struct mg_context *ctx,
  1131. const char *file,
  1132. unsigned line)
  1133. {
  1134. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1135. if (data) {
  1136. memset(data, 0, size * count);
  1137. }
  1138. return data;
  1139. }
  1140. static void
  1141. mg_free_ex(void *memory, const char *file, unsigned line)
  1142. {
  1143. #if defined(MEMORY_DEBUGGING)
  1144. char mallocStr[256];
  1145. #else
  1146. (void)file;
  1147. (void)line;
  1148. #endif
  1149. if (memory) {
  1150. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1151. uintptr_t size = ((uintptr_t *)data)[0];
  1152. struct mg_memory_stat *mstat =
  1153. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1154. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1155. mg_atomic_dec(&mstat->blockCount);
  1156. #if defined(MEMORY_DEBUGGING)
  1157. sprintf(mallocStr,
  1158. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1159. memory,
  1160. (unsigned long)size,
  1161. (unsigned long)mstat->totalMemUsed,
  1162. (unsigned long)mstat->blockCount,
  1163. file,
  1164. line);
  1165. DEBUG_TRACE("%s", mallocStr);
  1166. #endif
  1167. free(data);
  1168. }
  1169. }
  1170. static void *
  1171. mg_realloc_ex(void *memory,
  1172. size_t newsize,
  1173. struct mg_context *ctx,
  1174. const char *file,
  1175. unsigned line)
  1176. {
  1177. void *data;
  1178. void *_realloc;
  1179. uintptr_t oldsize;
  1180. #if defined(MEMORY_DEBUGGING)
  1181. char mallocStr[256];
  1182. #else
  1183. (void)file;
  1184. (void)line;
  1185. #endif
  1186. if (newsize) {
  1187. if (memory) {
  1188. /* Reallocate existing block */
  1189. struct mg_memory_stat *mstat;
  1190. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1191. oldsize = ((uintptr_t *)data)[0];
  1192. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1193. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1194. if (_realloc) {
  1195. data = _realloc;
  1196. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1197. #if defined(MEMORY_DEBUGGING)
  1198. sprintf(mallocStr,
  1199. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1200. memory,
  1201. (unsigned long)oldsize,
  1202. (unsigned long)mstat->totalMemUsed,
  1203. (unsigned long)mstat->blockCount,
  1204. file,
  1205. line);
  1206. DEBUG_TRACE("%s", mallocStr);
  1207. #endif
  1208. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1209. #if defined(MEMORY_DEBUGGING)
  1210. sprintf(mallocStr,
  1211. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1212. memory,
  1213. (unsigned long)newsize,
  1214. (unsigned long)mstat->totalMemUsed,
  1215. (unsigned long)mstat->blockCount,
  1216. file,
  1217. line);
  1218. DEBUG_TRACE("%s", mallocStr);
  1219. #endif
  1220. *(uintptr_t *)data = newsize;
  1221. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1222. } else {
  1223. #if defined(MEMORY_DEBUGGING)
  1224. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1225. #endif
  1226. return _realloc;
  1227. }
  1228. } else {
  1229. /* Allocate new block */
  1230. data = mg_malloc_ex(newsize, ctx, file, line);
  1231. }
  1232. } else {
  1233. /* Free existing block */
  1234. data = 0;
  1235. mg_free_ex(memory, file, line);
  1236. }
  1237. return data;
  1238. }
  1239. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1240. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1241. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1242. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1243. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1244. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1245. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1246. #else /* USE_SERVER_STATS */
  1247. static __inline void *
  1248. mg_malloc(size_t a)
  1249. {
  1250. return malloc(a);
  1251. }
  1252. static __inline void *
  1253. mg_calloc(size_t a, size_t b)
  1254. {
  1255. return calloc(a, b);
  1256. }
  1257. static __inline void *
  1258. mg_realloc(void *a, size_t b)
  1259. {
  1260. return realloc(a, b);
  1261. }
  1262. static __inline void
  1263. mg_free(void *a)
  1264. {
  1265. free(a);
  1266. }
  1267. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1268. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1269. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1270. #define mg_free_ctx(a, c) mg_free(a)
  1271. #endif /* USE_SERVER_STATS */
  1272. static void mg_vsnprintf(const struct mg_connection *conn,
  1273. int *truncated,
  1274. char *buf,
  1275. size_t buflen,
  1276. const char *fmt,
  1277. va_list ap);
  1278. static void mg_snprintf(const struct mg_connection *conn,
  1279. int *truncated,
  1280. char *buf,
  1281. size_t buflen,
  1282. PRINTF_FORMAT_STRING(const char *fmt),
  1283. ...) PRINTF_ARGS(5, 6);
  1284. /* This following lines are just meant as a reminder to use the mg-functions
  1285. * for memory management */
  1286. #if defined(malloc)
  1287. #undef malloc
  1288. #endif
  1289. #if defined(calloc)
  1290. #undef calloc
  1291. #endif
  1292. #if defined(realloc)
  1293. #undef realloc
  1294. #endif
  1295. #if defined(free)
  1296. #undef free
  1297. #endif
  1298. #if defined(snprintf)
  1299. #undef snprintf
  1300. #endif
  1301. #if defined(vsnprintf)
  1302. #undef vsnprintf
  1303. #endif
  1304. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1305. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1306. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1307. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1308. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1309. #if defined(_WIN32)
  1310. /* vsnprintf must not be used in any system,
  1311. * but this define only works well for Windows. */
  1312. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1313. #endif
  1314. /* mg_init_library counter */
  1315. static int mg_init_library_called = 0;
  1316. #if !defined(NO_SSL)
  1317. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1318. || defined(OPENSSL_API_3_0)
  1319. static int mg_openssl_initialized = 0;
  1320. #endif
  1321. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1322. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1323. #error "Please define OPENSSL_API_#_# or USE_MBEDTLS"
  1324. #endif
  1325. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1326. #error "Multiple OPENSSL_API versions defined"
  1327. #endif
  1328. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1329. #error "Multiple OPENSSL_API versions defined"
  1330. #endif
  1331. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1332. #error "Multiple OPENSSL_API versions defined"
  1333. #endif
  1334. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1335. || defined(OPENSSL_API_3_0)) \
  1336. && defined(USE_MBEDTLS)
  1337. #error "Multiple SSL libraries defined"
  1338. #endif
  1339. #endif
  1340. static pthread_key_t sTlsKey; /* Thread local storage index */
  1341. static volatile ptrdiff_t thread_idx_max = 0;
  1342. #if defined(MG_LEGACY_INTERFACE)
  1343. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1344. #endif
  1345. struct mg_workerTLS {
  1346. int is_master;
  1347. unsigned long thread_idx;
  1348. void *user_ptr;
  1349. #if defined(_WIN32)
  1350. HANDLE pthread_cond_helper_mutex;
  1351. struct mg_workerTLS *next_waiting_thread;
  1352. #endif
  1353. const char *alpn_proto;
  1354. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1355. char txtbuf[4];
  1356. #endif
  1357. };
  1358. #if defined(GCC_DIAGNOSTIC)
  1359. /* Show no warning in case system functions are not used. */
  1360. #pragma GCC diagnostic push
  1361. #pragma GCC diagnostic ignored "-Wunused-function"
  1362. #endif /* defined(GCC_DIAGNOSTIC) */
  1363. #if defined(__clang__)
  1364. /* Show no warning in case system functions are not used. */
  1365. #pragma clang diagnostic push
  1366. #pragma clang diagnostic ignored "-Wunused-function"
  1367. #endif
  1368. /* Get a unique thread ID as unsigned long, independent from the data type
  1369. * of thread IDs defined by the operating system API.
  1370. * If two calls to mg_current_thread_id return the same value, they calls
  1371. * are done from the same thread. If they return different values, they are
  1372. * done from different threads. (Provided this function is used in the same
  1373. * process context and threads are not repeatedly created and deleted, but
  1374. * CivetWeb does not do that).
  1375. * This function must match the signature required for SSL id callbacks:
  1376. * CRYPTO_set_id_callback
  1377. */
  1378. FUNCTION_MAY_BE_UNUSED
  1379. static unsigned long
  1380. mg_current_thread_id(void)
  1381. {
  1382. #if defined(_WIN32)
  1383. return GetCurrentThreadId();
  1384. #else
  1385. #if defined(__clang__)
  1386. #pragma clang diagnostic push
  1387. #pragma clang diagnostic ignored "-Wunreachable-code"
  1388. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1389. * or not, so one of the two conditions will be unreachable by construction.
  1390. * Unfortunately the C standard does not define a way to check this at
  1391. * compile time, since the #if preprocessor conditions can not use the
  1392. * sizeof operator as an argument. */
  1393. #endif
  1394. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1395. /* This is the problematic case for CRYPTO_set_id_callback:
  1396. * The OS pthread_t can not be cast to unsigned long. */
  1397. struct mg_workerTLS *tls =
  1398. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1399. if (tls == NULL) {
  1400. /* SSL called from an unknown thread: Create some thread index.
  1401. */
  1402. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1403. tls->is_master = -2; /* -2 means "3rd party thread" */
  1404. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1405. pthread_setspecific(sTlsKey, tls);
  1406. }
  1407. return tls->thread_idx;
  1408. } else {
  1409. /* pthread_t may be any data type, so a simple cast to unsigned long
  1410. * can rise a warning/error, depending on the platform.
  1411. * Here memcpy is used as an anything-to-anything cast. */
  1412. unsigned long ret = 0;
  1413. pthread_t t = pthread_self();
  1414. memcpy(&ret, &t, sizeof(pthread_t));
  1415. return ret;
  1416. }
  1417. #if defined(__clang__)
  1418. #pragma clang diagnostic pop
  1419. #endif
  1420. #endif
  1421. }
  1422. FUNCTION_MAY_BE_UNUSED
  1423. static uint64_t
  1424. mg_get_current_time_ns(void)
  1425. {
  1426. struct timespec tsnow;
  1427. clock_gettime(CLOCK_REALTIME, &tsnow);
  1428. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1429. }
  1430. #if defined(GCC_DIAGNOSTIC)
  1431. /* Show no warning in case system functions are not used. */
  1432. #pragma GCC diagnostic pop
  1433. #endif /* defined(GCC_DIAGNOSTIC) */
  1434. #if defined(__clang__)
  1435. /* Show no warning in case system functions are not used. */
  1436. #pragma clang diagnostic pop
  1437. #endif
  1438. #if defined(NEED_DEBUG_TRACE_FUNC)
  1439. static void
  1440. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1441. {
  1442. va_list args;
  1443. struct timespec tsnow;
  1444. /* Get some operating system independent thread id */
  1445. unsigned long thread_id = mg_current_thread_id();
  1446. clock_gettime(CLOCK_REALTIME, &tsnow);
  1447. flockfile(DEBUG_TRACE_STREAM);
  1448. fprintf(DEBUG_TRACE_STREAM,
  1449. "*** %lu.%09lu %lu %s:%u: ",
  1450. (unsigned long)tsnow.tv_sec,
  1451. (unsigned long)tsnow.tv_nsec,
  1452. thread_id,
  1453. func,
  1454. line);
  1455. va_start(args, fmt);
  1456. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1457. va_end(args);
  1458. putc('\n', DEBUG_TRACE_STREAM);
  1459. fflush(DEBUG_TRACE_STREAM);
  1460. funlockfile(DEBUG_TRACE_STREAM);
  1461. }
  1462. #endif /* NEED_DEBUG_TRACE_FUNC */
  1463. #define MD5_STATIC static
  1464. #include "md5.inl"
  1465. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1466. #if defined(NO_SOCKLEN_T)
  1467. typedef int socklen_t;
  1468. #endif /* NO_SOCKLEN_T */
  1469. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1470. #if !defined(MSG_NOSIGNAL)
  1471. #define MSG_NOSIGNAL (0)
  1472. #endif
  1473. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1474. #if defined(USE_MBEDTLS)
  1475. /* mbedTLS */
  1476. #include "mod_mbedtls.inl"
  1477. #elif defined(NO_SSL)
  1478. /* no SSL */
  1479. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1480. typedef struct SSL_CTX SSL_CTX;
  1481. #elif defined(NO_SSL_DL)
  1482. /* OpenSSL without dynamic loading */
  1483. #include <openssl/bn.h>
  1484. #include <openssl/conf.h>
  1485. #include <openssl/crypto.h>
  1486. #include <openssl/dh.h>
  1487. #include <openssl/engine.h>
  1488. #include <openssl/err.h>
  1489. #include <openssl/opensslv.h>
  1490. #include <openssl/pem.h>
  1491. #include <openssl/ssl.h>
  1492. #include <openssl/tls1.h>
  1493. #include <openssl/x509.h>
  1494. #if defined(WOLFSSL_VERSION)
  1495. /* Additional defines for WolfSSL, see
  1496. * https://github.com/civetweb/civetweb/issues/583 */
  1497. #include "wolfssl_extras.inl"
  1498. #endif
  1499. #if defined(OPENSSL_IS_BORINGSSL)
  1500. /* From boringssl/src/include/openssl/mem.h:
  1501. *
  1502. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1503. * However, that was written in a time before Valgrind and ASAN. Since we now
  1504. * have those tools, the OpenSSL allocation functions are simply macros around
  1505. * the standard memory functions.
  1506. *
  1507. * #define OPENSSL_free free */
  1508. #define free free
  1509. // disable for boringssl
  1510. #define CONF_modules_unload(a) ((void)0)
  1511. #define ENGINE_cleanup() ((void)0)
  1512. #endif
  1513. /* If OpenSSL headers are included, automatically select the API version */
  1514. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1515. #if !defined(OPENSSL_API_3_0)
  1516. #define OPENSSL_API_3_0
  1517. #endif
  1518. #define OPENSSL_REMOVE_THREAD_STATE()
  1519. #else
  1520. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1521. #if !defined(OPENSSL_API_1_1)
  1522. #define OPENSSL_API_1_1
  1523. #endif
  1524. #define OPENSSL_REMOVE_THREAD_STATE()
  1525. #else
  1526. #if !defined(OPENSSL_API_1_0)
  1527. #define OPENSSL_API_1_0
  1528. #endif
  1529. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1530. #endif
  1531. #endif
  1532. #else
  1533. /* SSL loaded dynamically from DLL / shared object */
  1534. /* Add all prototypes here, to be independent from OpenSSL source
  1535. * installation. */
  1536. #include "openssl_dl.inl"
  1537. #endif /* Various SSL bindings */
  1538. #if !defined(NO_CACHING)
  1539. static const char month_names[][4] = {"Jan",
  1540. "Feb",
  1541. "Mar",
  1542. "Apr",
  1543. "May",
  1544. "Jun",
  1545. "Jul",
  1546. "Aug",
  1547. "Sep",
  1548. "Oct",
  1549. "Nov",
  1550. "Dec"};
  1551. #endif /* !NO_CACHING */
  1552. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1553. * the union u. */
  1554. union usa {
  1555. struct sockaddr sa;
  1556. struct sockaddr_in sin;
  1557. #if defined(USE_IPV6)
  1558. struct sockaddr_in6 sin6;
  1559. #endif
  1560. #if defined(USE_X_DOM_SOCKET)
  1561. struct sockaddr_un sun;
  1562. #endif
  1563. };
  1564. #if defined(USE_X_DOM_SOCKET)
  1565. static unsigned short
  1566. USA_IN_PORT_UNSAFE(union usa *s)
  1567. {
  1568. if (s->sa.sa_family == AF_INET)
  1569. return s->sin.sin_port;
  1570. #if defined(USE_IPV6)
  1571. if (s->sa.sa_family == AF_INET6)
  1572. return s->sin6.sin6_port;
  1573. #endif
  1574. return 0;
  1575. }
  1576. #endif
  1577. #if defined(USE_IPV6)
  1578. #define USA_IN_PORT_UNSAFE(s) \
  1579. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1580. #else
  1581. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1582. #endif
  1583. /* Describes a string (chunk of memory). */
  1584. struct vec {
  1585. const char *ptr;
  1586. size_t len;
  1587. };
  1588. struct mg_file_stat {
  1589. /* File properties filled by mg_stat: */
  1590. uint64_t size;
  1591. time_t last_modified;
  1592. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1593. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1594. * case we need a "Content-Eencoding: gzip" header */
  1595. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1596. };
  1597. struct mg_file_access {
  1598. /* File properties filled by mg_fopen: */
  1599. FILE *fp;
  1600. };
  1601. struct mg_file {
  1602. struct mg_file_stat stat;
  1603. struct mg_file_access access;
  1604. };
  1605. #define STRUCT_FILE_INITIALIZER \
  1606. { \
  1607. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1608. { \
  1609. (FILE *)NULL \
  1610. } \
  1611. }
  1612. /* Describes listening socket, or socket which was accept()-ed by the master
  1613. * thread and queued for future handling by the worker thread. */
  1614. struct socket {
  1615. SOCKET sock; /* Listening socket */
  1616. union usa lsa; /* Local socket address */
  1617. union usa rsa; /* Remote socket address */
  1618. unsigned char is_ssl; /* Is port SSL-ed */
  1619. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1620. * port */
  1621. unsigned char
  1622. is_optional; /* Shouldn't cause us to exit if we can't bind to it */
  1623. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1624. };
  1625. /* Enum const for all options must be in sync with
  1626. * static struct mg_option config_options[]
  1627. * This is tested in the unit test (test/private.c)
  1628. * "Private Config Options"
  1629. */
  1630. enum {
  1631. /* Once for each server */
  1632. LISTENING_PORTS,
  1633. NUM_THREADS,
  1634. PRESPAWN_THREADS,
  1635. RUN_AS_USER,
  1636. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1637. * socket option typedef TCP_NODELAY. */
  1638. MAX_REQUEST_SIZE,
  1639. LINGER_TIMEOUT,
  1640. CONNECTION_QUEUE_SIZE,
  1641. LISTEN_BACKLOG_SIZE,
  1642. #if defined(__linux__)
  1643. ALLOW_SENDFILE_CALL,
  1644. #endif
  1645. #if defined(_WIN32)
  1646. CASE_SENSITIVE_FILES,
  1647. #endif
  1648. THROTTLE,
  1649. ENABLE_KEEP_ALIVE,
  1650. REQUEST_TIMEOUT,
  1651. KEEP_ALIVE_TIMEOUT,
  1652. #if defined(USE_WEBSOCKET)
  1653. WEBSOCKET_TIMEOUT,
  1654. ENABLE_WEBSOCKET_PING_PONG,
  1655. #endif
  1656. DECODE_URL,
  1657. DECODE_QUERY_STRING,
  1658. #if defined(USE_LUA)
  1659. LUA_BACKGROUND_SCRIPT,
  1660. LUA_BACKGROUND_SCRIPT_PARAMS,
  1661. #endif
  1662. #if defined(USE_HTTP2)
  1663. ENABLE_HTTP2,
  1664. #endif
  1665. /* Once for each domain */
  1666. DOCUMENT_ROOT,
  1667. FALLBACK_DOCUMENT_ROOT,
  1668. ACCESS_LOG_FILE,
  1669. ERROR_LOG_FILE,
  1670. CGI_EXTENSIONS,
  1671. CGI_ENVIRONMENT,
  1672. CGI_INTERPRETER,
  1673. CGI_INTERPRETER_ARGS,
  1674. #if defined(USE_TIMERS)
  1675. CGI_TIMEOUT,
  1676. #endif
  1677. CGI_BUFFERING,
  1678. CGI2_EXTENSIONS,
  1679. CGI2_ENVIRONMENT,
  1680. CGI2_INTERPRETER,
  1681. CGI2_INTERPRETER_ARGS,
  1682. #if defined(USE_TIMERS)
  1683. CGI2_TIMEOUT,
  1684. #endif
  1685. CGI2_BUFFERING,
  1686. #if defined(USE_4_CGI)
  1687. CGI3_EXTENSIONS,
  1688. CGI3_ENVIRONMENT,
  1689. CGI3_INTERPRETER,
  1690. CGI3_INTERPRETER_ARGS,
  1691. #if defined(USE_TIMERS)
  1692. CGI3_TIMEOUT,
  1693. #endif
  1694. CGI3_BUFFERING,
  1695. CGI4_EXTENSIONS,
  1696. CGI4_ENVIRONMENT,
  1697. CGI4_INTERPRETER,
  1698. CGI4_INTERPRETER_ARGS,
  1699. #if defined(USE_TIMERS)
  1700. CGI4_TIMEOUT,
  1701. #endif
  1702. CGI4_BUFFERING,
  1703. #endif
  1704. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1705. PROTECT_URI,
  1706. AUTHENTICATION_DOMAIN,
  1707. ENABLE_AUTH_DOMAIN_CHECK,
  1708. SSI_EXTENSIONS,
  1709. ENABLE_DIRECTORY_LISTING,
  1710. ENABLE_WEBDAV,
  1711. GLOBAL_PASSWORDS_FILE,
  1712. INDEX_FILES,
  1713. ACCESS_CONTROL_LIST,
  1714. EXTRA_MIME_TYPES,
  1715. SSL_CERTIFICATE,
  1716. SSL_CERTIFICATE_CHAIN,
  1717. URL_REWRITE_PATTERN,
  1718. HIDE_FILES,
  1719. SSL_DO_VERIFY_PEER,
  1720. SSL_CACHE_TIMEOUT,
  1721. SSL_CA_PATH,
  1722. SSL_CA_FILE,
  1723. SSL_VERIFY_DEPTH,
  1724. SSL_DEFAULT_VERIFY_PATHS,
  1725. SSL_CIPHER_LIST,
  1726. SSL_PROTOCOL_VERSION,
  1727. SSL_SHORT_TRUST,
  1728. #if defined(USE_LUA)
  1729. LUA_PRELOAD_FILE,
  1730. LUA_SCRIPT_EXTENSIONS,
  1731. LUA_SERVER_PAGE_EXTENSIONS,
  1732. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1733. LUA_DEBUG_PARAMS,
  1734. #endif
  1735. #endif
  1736. #if defined(USE_DUKTAPE)
  1737. DUKTAPE_SCRIPT_EXTENSIONS,
  1738. #endif
  1739. #if defined(USE_WEBSOCKET)
  1740. WEBSOCKET_ROOT,
  1741. FALLBACK_WEBSOCKET_ROOT,
  1742. #endif
  1743. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1744. LUA_WEBSOCKET_EXTENSIONS,
  1745. #endif
  1746. ACCESS_CONTROL_ALLOW_ORIGIN,
  1747. ACCESS_CONTROL_ALLOW_METHODS,
  1748. ACCESS_CONTROL_ALLOW_HEADERS,
  1749. ACCESS_CONTROL_EXPOSE_HEADERS,
  1750. ACCESS_CONTROL_ALLOW_CREDENTIALS,
  1751. ERROR_PAGES,
  1752. #if !defined(NO_CACHING)
  1753. STATIC_FILE_MAX_AGE,
  1754. STATIC_FILE_CACHE_CONTROL,
  1755. #endif
  1756. #if !defined(NO_SSL)
  1757. STRICT_HTTPS_MAX_AGE,
  1758. #endif
  1759. ADDITIONAL_HEADER,
  1760. ALLOW_INDEX_SCRIPT_SUB_RES,
  1761. NUM_OPTIONS
  1762. };
  1763. /* Config option name, config types, default value.
  1764. * Must be in the same order as the enum const above.
  1765. */
  1766. static const struct mg_option config_options[] = {
  1767. /* Once for each server */
  1768. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1769. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1770. {"prespawn_threads", MG_CONFIG_TYPE_NUMBER, "0"},
  1771. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1772. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1773. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1774. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1775. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1776. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1777. #if defined(__linux__)
  1778. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1779. #endif
  1780. #if defined(_WIN32)
  1781. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1782. #endif
  1783. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1784. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1785. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1786. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1787. #if defined(USE_WEBSOCKET)
  1788. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1789. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1790. #endif
  1791. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1792. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1793. #if defined(USE_LUA)
  1794. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1795. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1796. #endif
  1797. #if defined(USE_HTTP2)
  1798. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1799. #endif
  1800. /* Once for each domain */
  1801. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1802. {"fallback_document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1803. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1804. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1805. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1806. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1807. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1808. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1809. #if defined(USE_TIMERS)
  1810. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1811. #endif
  1812. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1813. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1814. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1815. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1816. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1817. #if defined(USE_TIMERS)
  1818. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1819. #endif
  1820. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1821. #if defined(USE_4_CGI)
  1822. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1823. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1824. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1825. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1826. #if defined(USE_TIMERS)
  1827. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1828. #endif
  1829. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1830. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1831. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1832. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1833. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1834. #if defined(USE_TIMERS)
  1835. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1836. #endif
  1837. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1838. #endif
  1839. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1840. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1841. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1842. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1843. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1844. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1845. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1846. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1847. {"index_files",
  1848. MG_CONFIG_TYPE_STRING_LIST,
  1849. #if defined(USE_LUA)
  1850. "index.xhtml,index.html,index.htm,"
  1851. "index.lp,index.lsp,index.lua,index.cgi,"
  1852. "index.shtml,index.php"},
  1853. #else
  1854. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1855. #endif
  1856. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1857. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1858. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1859. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1860. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1861. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1862. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1863. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1864. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1865. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1866. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1867. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1868. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1869. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1870. * as a minimum in 2020 */
  1871. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1872. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1873. #if defined(USE_LUA)
  1874. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1875. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1876. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1877. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1878. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1879. #endif
  1880. #endif
  1881. #if defined(USE_DUKTAPE)
  1882. /* The support for duktape is still in alpha version state.
  1883. * The name of this config option might change. */
  1884. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1885. #endif
  1886. #if defined(USE_WEBSOCKET)
  1887. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1888. {"fallback_websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1889. #endif
  1890. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1891. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1892. #endif
  1893. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1894. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1895. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1896. {"access_control_expose_headers", MG_CONFIG_TYPE_STRING, ""},
  1897. {"access_control_allow_credentials", MG_CONFIG_TYPE_STRING, ""},
  1898. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1899. #if !defined(NO_CACHING)
  1900. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1901. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1902. #endif
  1903. #if !defined(NO_SSL)
  1904. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1905. #endif
  1906. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1907. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1908. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1909. /* Check if the config_options and the corresponding enum have compatible
  1910. * sizes. */
  1911. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1912. == (NUM_OPTIONS + 1),
  1913. "config_options and enum not sync");
  1914. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1915. struct mg_handler_info {
  1916. /* Name/Pattern of the URI. */
  1917. char *uri;
  1918. size_t uri_len;
  1919. /* handler type */
  1920. int handler_type;
  1921. /* Handler for http/https or requests. */
  1922. mg_request_handler handler;
  1923. unsigned int refcount;
  1924. int removing;
  1925. /* Handler for ws/wss (websocket) requests. */
  1926. mg_websocket_connect_handler connect_handler;
  1927. mg_websocket_ready_handler ready_handler;
  1928. mg_websocket_data_handler data_handler;
  1929. mg_websocket_close_handler close_handler;
  1930. /* accepted subprotocols for ws/wss requests. */
  1931. struct mg_websocket_subprotocols *subprotocols;
  1932. /* Handler for authorization requests */
  1933. mg_authorization_handler auth_handler;
  1934. /* User supplied argument for the handler function. */
  1935. void *cbdata;
  1936. /* next handler in a linked list */
  1937. struct mg_handler_info *next;
  1938. };
  1939. enum {
  1940. CONTEXT_INVALID,
  1941. CONTEXT_SERVER,
  1942. CONTEXT_HTTP_CLIENT,
  1943. CONTEXT_WS_CLIENT
  1944. };
  1945. struct mg_domain_context {
  1946. SSL_CTX *ssl_ctx; /* SSL context */
  1947. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1948. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1949. int64_t ssl_cert_last_mtime;
  1950. /* Server nonce */
  1951. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1952. unsigned long nonce_count; /* Used nonces, used for authentication */
  1953. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1954. /* linked list of shared lua websockets */
  1955. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1956. #endif
  1957. /* Linked list of domains */
  1958. struct mg_domain_context *next;
  1959. };
  1960. /* Stop flag can be "volatile" or require a lock.
  1961. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1962. * states a read operation for int is always atomic. */
  1963. #if defined(STOP_FLAG_NEEDS_LOCK)
  1964. typedef ptrdiff_t volatile stop_flag_t;
  1965. static int
  1966. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1967. {
  1968. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1969. return (sf == 0);
  1970. }
  1971. static int
  1972. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1973. {
  1974. stop_flag_t sf = mg_atomic_add(f, 0);
  1975. return (sf == 2);
  1976. }
  1977. static void
  1978. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1979. {
  1980. stop_flag_t sf = 0;
  1981. do {
  1982. sf = mg_atomic_compare_and_swap(f, *f, v);
  1983. } while (sf != v);
  1984. }
  1985. #else /* STOP_FLAG_NEEDS_LOCK */
  1986. typedef int volatile stop_flag_t;
  1987. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1988. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1989. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1990. #endif /* STOP_FLAG_NEEDS_LOCK */
  1991. #if !defined(NUM_WEBDAV_LOCKS)
  1992. #define NUM_WEBDAV_LOCKS 10
  1993. #endif
  1994. #if !defined(LOCK_DURATION_S)
  1995. #define LOCK_DURATION_S 60
  1996. #endif
  1997. struct twebdav_lock {
  1998. uint64_t locktime;
  1999. char token[33];
  2000. char path[UTF8_PATH_MAX * 2];
  2001. char user[UTF8_PATH_MAX * 2];
  2002. };
  2003. struct mg_context {
  2004. /* Part 1 - Physical context:
  2005. * This holds threads, ports, timeouts, ...
  2006. * set for the entire server, independent from the
  2007. * addressed hostname.
  2008. */
  2009. /* Connection related */
  2010. int context_type; /* See CONTEXT_* above */
  2011. struct socket *listening_sockets;
  2012. struct mg_pollfd *listening_socket_fds;
  2013. unsigned int num_listening_sockets;
  2014. struct mg_connection *worker_connections; /* The connection struct, pre-
  2015. * allocated for each worker */
  2016. #if defined(USE_SERVER_STATS)
  2017. volatile ptrdiff_t active_connections;
  2018. volatile ptrdiff_t max_active_connections;
  2019. volatile ptrdiff_t total_connections;
  2020. volatile ptrdiff_t total_requests;
  2021. volatile int64_t total_data_read;
  2022. volatile int64_t total_data_written;
  2023. #endif
  2024. /* Thread related */
  2025. stop_flag_t stop_flag; /* Should we stop event loop */
  2026. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2027. pthread_t masterthreadid; /* The master thread ID */
  2028. unsigned int cfg_max_worker_threads; /* How many worker-threads we are
  2029. allowed to create, total */
  2030. unsigned int spawned_worker_threads; /* How many worker-threads currently
  2031. exist (modified by master thread) */
  2032. unsigned int
  2033. idle_worker_thread_count; /* How many worker-threads are currently
  2034. sitting around with nothing to do */
  2035. /* Access to this value MUST be synchronized by thread_mutex */
  2036. pthread_t *worker_threadids; /* The worker thread IDs */
  2037. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2038. /* Connection to thread dispatching */
  2039. #if defined(ALTERNATIVE_QUEUE)
  2040. struct socket *client_socks;
  2041. void **client_wait_events;
  2042. #else
  2043. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2044. worker thread */
  2045. volatile int sq_head; /* Head of the socket queue */
  2046. volatile int sq_tail; /* Tail of the socket queue */
  2047. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2048. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2049. volatile int sq_blocked; /* Status information: sq is full */
  2050. int sq_size; /* No of elements in socket queue */
  2051. #if defined(USE_SERVER_STATS)
  2052. int sq_max_fill;
  2053. #endif /* USE_SERVER_STATS */
  2054. #endif /* ALTERNATIVE_QUEUE */
  2055. /* Memory related */
  2056. unsigned int max_request_size; /* The max request size */
  2057. #if defined(USE_SERVER_STATS)
  2058. struct mg_memory_stat ctx_memory;
  2059. #endif
  2060. /* WebDAV lock structures */
  2061. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2062. /* Operating system related */
  2063. char *systemName; /* What operating system is running */
  2064. time_t start_time; /* Server start time, used for authentication
  2065. * and for diagnstics. */
  2066. #if defined(USE_TIMERS)
  2067. struct ttimers *timers;
  2068. #endif
  2069. /* Lua specific: Background operations and shared websockets */
  2070. #if defined(USE_LUA)
  2071. void *lua_background_state; /* lua_State (here as void *) */
  2072. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2073. int lua_bg_log_available; /* Use Lua background state for access log */
  2074. #endif
  2075. int user_shutdown_notification_socket; /* mg_stop() will close this
  2076. socket... */
  2077. int thread_shutdown_notification_socket; /* to cause poll() in all threads
  2078. to return immediately */
  2079. /* Server nonce */
  2080. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2081. * ssl_cert_last_mtime, nonce_count, and
  2082. * next (linked list) */
  2083. /* Server callbacks */
  2084. struct mg_callbacks callbacks; /* User-defined callback function */
  2085. void *user_data; /* User-defined data */
  2086. /* Part 2 - Logical domain:
  2087. * This holds hostname, TLS certificate, document root, ...
  2088. * set for a domain hosted at the server.
  2089. * There may be multiple domains hosted at one physical server.
  2090. * The default domain "dd" is the first element of a list of
  2091. * domains.
  2092. */
  2093. struct mg_domain_context dd; /* default domain */
  2094. };
  2095. #if defined(USE_SERVER_STATS)
  2096. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2097. static struct mg_memory_stat *
  2098. get_memory_stat(struct mg_context *ctx)
  2099. {
  2100. if (ctx) {
  2101. return &(ctx->ctx_memory);
  2102. }
  2103. return &mg_common_memory;
  2104. }
  2105. #endif
  2106. enum {
  2107. CONNECTION_TYPE_INVALID = 0,
  2108. CONNECTION_TYPE_REQUEST = 1,
  2109. CONNECTION_TYPE_RESPONSE = 2
  2110. };
  2111. enum {
  2112. PROTOCOL_TYPE_HTTP1 = 0,
  2113. PROTOCOL_TYPE_WEBSOCKET = 1,
  2114. PROTOCOL_TYPE_HTTP2 = 2
  2115. };
  2116. #if defined(USE_HTTP2)
  2117. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2118. #define HTTP2_DYN_TABLE_SIZE (256)
  2119. #endif
  2120. struct mg_http2_connection {
  2121. uint32_t stream_id;
  2122. uint32_t dyn_table_size;
  2123. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2124. };
  2125. #endif
  2126. struct mg_connection {
  2127. int connection_type; /* see CONNECTION_TYPE_* above */
  2128. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2129. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2130. fully sent */
  2131. #if defined(USE_HTTP2)
  2132. struct mg_http2_connection http2;
  2133. #endif
  2134. struct mg_request_info request_info;
  2135. struct mg_response_info response_info;
  2136. struct mg_context *phys_ctx;
  2137. struct mg_domain_context *dom_ctx;
  2138. #if defined(USE_SERVER_STATS)
  2139. int conn_state; /* 0 = undef, numerical value may change in different
  2140. * versions. For the current definition, see
  2141. * mg_get_connection_info_impl */
  2142. #endif
  2143. SSL *ssl; /* SSL descriptor */
  2144. struct socket client; /* Connected client */
  2145. time_t conn_birth_time; /* Time (wall clock) when connection was
  2146. * established */
  2147. #if defined(USE_SERVER_STATS)
  2148. time_t conn_close_time; /* Time (wall clock) when connection was
  2149. * closed (or 0 if still open) */
  2150. double processing_time; /* Processing time for one request. */
  2151. #endif
  2152. struct timespec req_time; /* Time (since system start) when the request
  2153. * was received */
  2154. int64_t num_bytes_sent; /* Total bytes sent to client */
  2155. int64_t content_len; /* How many bytes of content can be read
  2156. * !is_chunked: Content-Length header value
  2157. * or -1 (until connection closed,
  2158. * not allowed for a request)
  2159. * is_chunked: >= 0, appended gradually
  2160. */
  2161. int64_t consumed_content; /* How many bytes of content have been read */
  2162. int is_chunked; /* Transfer-Encoding is chunked:
  2163. * 0 = not chunked,
  2164. * 1 = chunked, not yet, or some data read,
  2165. * 2 = chunked, has error,
  2166. * 3 = chunked, all data read except trailer,
  2167. * 4 = chunked, all data read
  2168. */
  2169. char *buf; /* Buffer for received data */
  2170. char *path_info; /* PATH_INFO part of the URL */
  2171. int must_close; /* 1 if connection must be closed */
  2172. int accept_gzip; /* 1 if gzip encoding is accepted */
  2173. int in_error_handler; /* 1 if in handler for user defined error
  2174. * pages */
  2175. #if defined(USE_WEBSOCKET)
  2176. int in_websocket_handling; /* 1 if in read_websocket */
  2177. #endif
  2178. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2179. && defined(MG_EXPERIMENTAL_INTERFACES)
  2180. /* Parameters for websocket data compression according to rfc7692 */
  2181. int websocket_deflate_server_max_windows_bits;
  2182. int websocket_deflate_client_max_windows_bits;
  2183. int websocket_deflate_server_no_context_takeover;
  2184. int websocket_deflate_client_no_context_takeover;
  2185. int websocket_deflate_initialized;
  2186. int websocket_deflate_flush;
  2187. z_stream websocket_deflate_state;
  2188. z_stream websocket_inflate_state;
  2189. #endif
  2190. int handled_requests; /* Number of requests handled by this connection
  2191. */
  2192. int buf_size; /* Buffer size */
  2193. int request_len; /* Size of the request + headers in a buffer */
  2194. int data_len; /* Total size of data in a buffer */
  2195. int status_code; /* HTTP reply status code, e.g. 200 */
  2196. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2197. * throttle */
  2198. time_t last_throttle_time; /* Last time throttled data was sent */
  2199. int last_throttle_bytes; /* Bytes sent this second */
  2200. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2201. * atomic transmissions for websockets */
  2202. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2203. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2204. #endif
  2205. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2206. * for quick access */
  2207. };
  2208. /* Directory entry */
  2209. struct de {
  2210. char *file_name;
  2211. struct mg_file_stat file;
  2212. };
  2213. #define mg_cry_internal(conn, fmt, ...) \
  2214. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2215. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2216. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2217. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2218. struct mg_context *ctx,
  2219. const char *func,
  2220. unsigned line,
  2221. const char *fmt,
  2222. ...) PRINTF_ARGS(5, 6);
  2223. #if !defined(NO_THREAD_NAME)
  2224. #if defined(_WIN32) && defined(_MSC_VER)
  2225. /* Set the thread name for debugging purposes in Visual Studio
  2226. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2227. */
  2228. #pragma pack(push, 8)
  2229. typedef struct tagTHREADNAME_INFO {
  2230. DWORD dwType; /* Must be 0x1000. */
  2231. LPCSTR szName; /* Pointer to name (in user addr space). */
  2232. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2233. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2234. } THREADNAME_INFO;
  2235. #pragma pack(pop)
  2236. #elif defined(__linux__)
  2237. #include <sys/prctl.h>
  2238. #include <sys/sendfile.h>
  2239. #if defined(ALTERNATIVE_QUEUE)
  2240. #include <sys/eventfd.h>
  2241. #endif /* ALTERNATIVE_QUEUE */
  2242. #if defined(ALTERNATIVE_QUEUE)
  2243. static void *
  2244. event_create(void)
  2245. {
  2246. int evhdl = eventfd(0, EFD_CLOEXEC);
  2247. int *ret;
  2248. if (evhdl == -1) {
  2249. /* Linux uses -1 on error, Windows NULL. */
  2250. /* However, Linux does not return 0 on success either. */
  2251. return 0;
  2252. }
  2253. ret = (int *)mg_malloc(sizeof(int));
  2254. if (ret) {
  2255. *ret = evhdl;
  2256. } else {
  2257. (void)close(evhdl);
  2258. }
  2259. return (void *)ret;
  2260. }
  2261. static int
  2262. event_wait(void *eventhdl)
  2263. {
  2264. uint64_t u;
  2265. int evhdl, s;
  2266. if (!eventhdl) {
  2267. /* error */
  2268. return 0;
  2269. }
  2270. evhdl = *(int *)eventhdl;
  2271. s = (int)read(evhdl, &u, sizeof(u));
  2272. if (s != sizeof(u)) {
  2273. /* error */
  2274. return 0;
  2275. }
  2276. (void)u; /* the value is not required */
  2277. return 1;
  2278. }
  2279. static int
  2280. event_signal(void *eventhdl)
  2281. {
  2282. uint64_t u = 1;
  2283. int evhdl, s;
  2284. if (!eventhdl) {
  2285. /* error */
  2286. return 0;
  2287. }
  2288. evhdl = *(int *)eventhdl;
  2289. s = (int)write(evhdl, &u, sizeof(u));
  2290. if (s != sizeof(u)) {
  2291. /* error */
  2292. return 0;
  2293. }
  2294. return 1;
  2295. }
  2296. static void
  2297. event_destroy(void *eventhdl)
  2298. {
  2299. int evhdl;
  2300. if (!eventhdl) {
  2301. /* error */
  2302. return;
  2303. }
  2304. evhdl = *(int *)eventhdl;
  2305. close(evhdl);
  2306. mg_free(eventhdl);
  2307. }
  2308. #endif
  2309. #endif
  2310. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2311. struct posix_event {
  2312. pthread_mutex_t mutex;
  2313. pthread_cond_t cond;
  2314. int signaled;
  2315. };
  2316. static void *
  2317. event_create(void)
  2318. {
  2319. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2320. if (ret == 0) {
  2321. /* out of memory */
  2322. return 0;
  2323. }
  2324. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2325. /* pthread mutex not available */
  2326. mg_free(ret);
  2327. return 0;
  2328. }
  2329. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2330. /* pthread cond not available */
  2331. pthread_mutex_destroy(&(ret->mutex));
  2332. mg_free(ret);
  2333. return 0;
  2334. }
  2335. ret->signaled = 0;
  2336. return (void *)ret;
  2337. }
  2338. static int
  2339. event_wait(void *eventhdl)
  2340. {
  2341. struct posix_event *ev = (struct posix_event *)eventhdl;
  2342. pthread_mutex_lock(&(ev->mutex));
  2343. while (!ev->signaled) {
  2344. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2345. }
  2346. ev->signaled = 0;
  2347. pthread_mutex_unlock(&(ev->mutex));
  2348. return 1;
  2349. }
  2350. static int
  2351. event_signal(void *eventhdl)
  2352. {
  2353. struct posix_event *ev = (struct posix_event *)eventhdl;
  2354. pthread_mutex_lock(&(ev->mutex));
  2355. pthread_cond_signal(&(ev->cond));
  2356. ev->signaled = 1;
  2357. pthread_mutex_unlock(&(ev->mutex));
  2358. return 1;
  2359. }
  2360. static void
  2361. event_destroy(void *eventhdl)
  2362. {
  2363. struct posix_event *ev = (struct posix_event *)eventhdl;
  2364. pthread_cond_destroy(&(ev->cond));
  2365. pthread_mutex_destroy(&(ev->mutex));
  2366. mg_free(ev);
  2367. }
  2368. #endif
  2369. static void
  2370. mg_set_thread_name(const char *name)
  2371. {
  2372. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2373. mg_snprintf(
  2374. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2375. #if defined(_WIN32)
  2376. #if defined(_MSC_VER)
  2377. /* Windows and Visual Studio Compiler */
  2378. __try {
  2379. THREADNAME_INFO info;
  2380. info.dwType = 0x1000;
  2381. info.szName = threadName;
  2382. info.dwThreadID = ~0U;
  2383. info.dwFlags = 0;
  2384. RaiseException(0x406D1388,
  2385. 0,
  2386. sizeof(info) / sizeof(ULONG_PTR),
  2387. (ULONG_PTR *)&info);
  2388. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2389. }
  2390. #elif defined(__MINGW32__)
  2391. /* No option known to set thread name for MinGW known */
  2392. #endif
  2393. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2394. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2395. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2396. #if defined(__MACH__) && defined(__APPLE__)
  2397. /* OS X only current thread name can be changed */
  2398. (void)pthread_setname_np(threadName);
  2399. #else
  2400. (void)pthread_setname_np(pthread_self(), threadName);
  2401. #endif
  2402. #elif defined(__linux__)
  2403. /* On Linux we can use the prctl function.
  2404. * When building for Linux Standard Base (LSB) use
  2405. * NO_THREAD_NAME. However, thread names are a big
  2406. * help for debugging, so the stadard is to set them.
  2407. */
  2408. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2409. #endif
  2410. }
  2411. #else /* !defined(NO_THREAD_NAME) */
  2412. static void
  2413. mg_set_thread_name(const char *threadName)
  2414. {
  2415. }
  2416. #endif
  2417. CIVETWEB_API const struct mg_option *
  2418. mg_get_valid_options(void)
  2419. {
  2420. return config_options;
  2421. }
  2422. /* Do not open file (unused) */
  2423. #define MG_FOPEN_MODE_NONE (0)
  2424. /* Open file for read only access */
  2425. #define MG_FOPEN_MODE_READ (1)
  2426. /* Open file for writing, create and overwrite */
  2427. #define MG_FOPEN_MODE_WRITE (2)
  2428. /* Open file for writing, create and append */
  2429. #define MG_FOPEN_MODE_APPEND (4)
  2430. static int
  2431. is_file_opened(const struct mg_file_access *fileacc)
  2432. {
  2433. if (!fileacc) {
  2434. return 0;
  2435. }
  2436. return (fileacc->fp != NULL);
  2437. }
  2438. #if !defined(NO_FILESYSTEMS)
  2439. static int mg_stat(const struct mg_connection *conn,
  2440. const char *path,
  2441. struct mg_file_stat *filep);
  2442. /* Reject files with special characters (for Windows) */
  2443. static int
  2444. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2445. {
  2446. const uint8_t *c = (const uint8_t *)path;
  2447. (void)conn; /* not used */
  2448. if ((c == NULL) || (c[0] == 0)) {
  2449. /* Null pointer or empty path --> suspicious */
  2450. return 1;
  2451. }
  2452. #if defined(_WIN32)
  2453. while (*c) {
  2454. if (*c < 32) {
  2455. /* Control character */
  2456. return 1;
  2457. }
  2458. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2459. /* stdin/stdout redirection character */
  2460. return 1;
  2461. }
  2462. if ((*c == '*') || (*c == '?')) {
  2463. /* Wildcard character */
  2464. return 1;
  2465. }
  2466. if (*c == '"') {
  2467. /* Windows quotation */
  2468. return 1;
  2469. }
  2470. c++;
  2471. }
  2472. #endif
  2473. /* Nothing suspicious found */
  2474. return 0;
  2475. }
  2476. /* mg_fopen will open a file either in memory or on the disk.
  2477. * The input parameter path is a string in UTF-8 encoding.
  2478. * The input parameter mode is MG_FOPEN_MODE_*
  2479. * On success, fp will be set in the output struct mg_file.
  2480. * All status members will also be set.
  2481. * The function returns 1 on success, 0 on error. */
  2482. static int
  2483. mg_fopen(const struct mg_connection *conn,
  2484. const char *path,
  2485. int mode,
  2486. struct mg_file *filep)
  2487. {
  2488. int found;
  2489. if (!filep) {
  2490. return 0;
  2491. }
  2492. filep->access.fp = NULL;
  2493. if (mg_path_suspicious(conn, path)) {
  2494. return 0;
  2495. }
  2496. /* filep is initialized in mg_stat: all fields with memset to,
  2497. * some fields like size and modification date with values */
  2498. found = mg_stat(conn, path, &(filep->stat));
  2499. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2500. /* file does not exist and will not be created */
  2501. return 0;
  2502. }
  2503. #if defined(_WIN32)
  2504. {
  2505. wchar_t wbuf[UTF16_PATH_MAX];
  2506. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2507. switch (mode) {
  2508. case MG_FOPEN_MODE_READ:
  2509. filep->access.fp = _wfopen(wbuf, L"rb");
  2510. break;
  2511. case MG_FOPEN_MODE_WRITE:
  2512. filep->access.fp = _wfopen(wbuf, L"wb");
  2513. break;
  2514. case MG_FOPEN_MODE_APPEND:
  2515. filep->access.fp = _wfopen(wbuf, L"ab");
  2516. break;
  2517. }
  2518. }
  2519. #else
  2520. /* Linux et al already use unicode. No need to convert. */
  2521. switch (mode) {
  2522. case MG_FOPEN_MODE_READ:
  2523. filep->access.fp = fopen(path, "r");
  2524. break;
  2525. case MG_FOPEN_MODE_WRITE:
  2526. filep->access.fp = fopen(path, "w");
  2527. break;
  2528. case MG_FOPEN_MODE_APPEND:
  2529. filep->access.fp = fopen(path, "a");
  2530. break;
  2531. }
  2532. #endif
  2533. if (!found) {
  2534. /* File did not exist before fopen was called.
  2535. * Maybe it has been created now. Get stat info
  2536. * like creation time now. */
  2537. found = mg_stat(conn, path, &(filep->stat));
  2538. (void)found;
  2539. }
  2540. /* return OK if file is opened */
  2541. return (filep->access.fp != NULL);
  2542. }
  2543. /* return 0 on success, just like fclose */
  2544. static int
  2545. mg_fclose(struct mg_file_access *fileacc)
  2546. {
  2547. int ret = -1;
  2548. if (fileacc != NULL) {
  2549. if (fileacc->fp != NULL) {
  2550. ret = fclose(fileacc->fp);
  2551. }
  2552. /* reset all members of fileacc */
  2553. memset(fileacc, 0, sizeof(*fileacc));
  2554. }
  2555. return ret;
  2556. }
  2557. #endif /* NO_FILESYSTEMS */
  2558. static void
  2559. mg_strlcpy(char *dst, const char *src, size_t n)
  2560. {
  2561. for (; *src != '\0' && n > 1; n--) {
  2562. *dst++ = *src++;
  2563. }
  2564. *dst = '\0';
  2565. }
  2566. static int
  2567. lowercase(const char *s)
  2568. {
  2569. return tolower((unsigned char)*s);
  2570. }
  2571. CIVETWEB_API int
  2572. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2573. {
  2574. int diff = 0;
  2575. if (len > 0) {
  2576. do {
  2577. diff = lowercase(s1++) - lowercase(s2++);
  2578. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2579. }
  2580. return diff;
  2581. }
  2582. CIVETWEB_API int
  2583. mg_strcasecmp(const char *s1, const char *s2)
  2584. {
  2585. int diff;
  2586. do {
  2587. diff = lowercase(s1++) - lowercase(s2++);
  2588. } while (diff == 0 && s1[-1] != '\0');
  2589. return diff;
  2590. }
  2591. static char *
  2592. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2593. {
  2594. char *p;
  2595. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2596. * defined */
  2597. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2598. mg_strlcpy(p, ptr, len + 1);
  2599. }
  2600. return p;
  2601. }
  2602. static char *
  2603. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2604. {
  2605. return mg_strndup_ctx(str, strlen(str), ctx);
  2606. }
  2607. static char *
  2608. mg_strdup(const char *str)
  2609. {
  2610. return mg_strndup_ctx(str, strlen(str), NULL);
  2611. }
  2612. static const char *
  2613. mg_strcasestr(const char *big_str, const char *small_str)
  2614. {
  2615. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2616. if (big_len >= small_len) {
  2617. for (i = 0; i <= (big_len - small_len); i++) {
  2618. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2619. return big_str + i;
  2620. }
  2621. }
  2622. }
  2623. return NULL;
  2624. }
  2625. /* Return null terminated string of given maximum length.
  2626. * Report errors if length is exceeded. */
  2627. static void
  2628. mg_vsnprintf(const struct mg_connection *conn,
  2629. int *truncated,
  2630. char *buf,
  2631. size_t buflen,
  2632. const char *fmt,
  2633. va_list ap)
  2634. {
  2635. int n, ok;
  2636. if (buflen == 0) {
  2637. if (truncated) {
  2638. *truncated = 1;
  2639. }
  2640. return;
  2641. }
  2642. #if defined(__clang__)
  2643. #pragma clang diagnostic push
  2644. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2645. /* Using fmt as a non-literal is intended here, since it is mostly called
  2646. * indirectly by mg_snprintf */
  2647. #endif
  2648. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2649. ok = (n >= 0) && ((size_t)n < buflen);
  2650. #if defined(__clang__)
  2651. #pragma clang diagnostic pop
  2652. #endif
  2653. if (ok) {
  2654. if (truncated) {
  2655. *truncated = 0;
  2656. }
  2657. } else {
  2658. if (truncated) {
  2659. *truncated = 1;
  2660. }
  2661. mg_cry_internal(conn,
  2662. "truncating vsnprintf buffer: [%.*s]",
  2663. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2664. buf);
  2665. n = (int)buflen - 1;
  2666. }
  2667. buf[n] = '\0';
  2668. }
  2669. static void
  2670. mg_snprintf(const struct mg_connection *conn,
  2671. int *truncated,
  2672. char *buf,
  2673. size_t buflen,
  2674. const char *fmt,
  2675. ...)
  2676. {
  2677. va_list ap;
  2678. va_start(ap, fmt);
  2679. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2680. va_end(ap);
  2681. }
  2682. static int
  2683. get_option_index(const char *name)
  2684. {
  2685. int i;
  2686. for (i = 0; config_options[i].name != NULL; i++) {
  2687. if (strcmp(config_options[i].name, name) == 0) {
  2688. return i;
  2689. }
  2690. }
  2691. return -1;
  2692. }
  2693. CIVETWEB_API const char *
  2694. mg_get_option(const struct mg_context *ctx, const char *name)
  2695. {
  2696. int i;
  2697. if ((i = get_option_index(name)) == -1) {
  2698. return NULL;
  2699. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2700. return "";
  2701. } else {
  2702. return ctx->dd.config[i];
  2703. }
  2704. }
  2705. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2706. CIVETWEB_API struct mg_context *
  2707. mg_get_context(const struct mg_connection *conn)
  2708. {
  2709. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2710. }
  2711. CIVETWEB_API void *
  2712. mg_get_user_data(const struct mg_context *ctx)
  2713. {
  2714. return (ctx == NULL) ? NULL : ctx->user_data;
  2715. }
  2716. CIVETWEB_API void *
  2717. mg_get_user_context_data(const struct mg_connection *conn)
  2718. {
  2719. return mg_get_user_data(mg_get_context(conn));
  2720. }
  2721. CIVETWEB_API void *
  2722. mg_get_thread_pointer(const struct mg_connection *conn)
  2723. {
  2724. /* both methods should return the same pointer */
  2725. if (conn) {
  2726. /* quick access, in case conn is known */
  2727. return conn->tls_user_ptr;
  2728. } else {
  2729. /* otherwise get pointer from thread local storage (TLS) */
  2730. struct mg_workerTLS *tls =
  2731. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2732. return tls->user_ptr;
  2733. }
  2734. }
  2735. CIVETWEB_API void
  2736. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2737. {
  2738. if (const_conn != NULL) {
  2739. /* Const cast, since "const struct mg_connection *" does not mean
  2740. * the connection object is not modified. Here "const" is used,
  2741. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2742. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2743. conn->request_info.conn_data = data;
  2744. }
  2745. }
  2746. CIVETWEB_API void *
  2747. mg_get_user_connection_data(const struct mg_connection *conn)
  2748. {
  2749. if (conn != NULL) {
  2750. return conn->request_info.conn_data;
  2751. }
  2752. return NULL;
  2753. }
  2754. CIVETWEB_API int
  2755. mg_get_server_ports(const struct mg_context *ctx,
  2756. int size,
  2757. struct mg_server_port *ports)
  2758. {
  2759. int i, cnt = 0;
  2760. if (size <= 0) {
  2761. return -1;
  2762. }
  2763. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2764. if (!ctx) {
  2765. return -1;
  2766. }
  2767. if (!ctx->listening_sockets) {
  2768. return -1;
  2769. }
  2770. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2771. ports[cnt].port =
  2772. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2773. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2774. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2775. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2776. /* IPv4 */
  2777. ports[cnt].protocol = 1;
  2778. cnt++;
  2779. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2780. /* IPv6 */
  2781. ports[cnt].protocol = 3;
  2782. cnt++;
  2783. }
  2784. }
  2785. return cnt;
  2786. }
  2787. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2788. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2789. #endif
  2790. static void
  2791. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2792. {
  2793. buf[0] = '\0';
  2794. if (!usa) {
  2795. return;
  2796. }
  2797. if (usa->sa.sa_family == AF_INET) {
  2798. getnameinfo(&usa->sa,
  2799. sizeof(usa->sin),
  2800. buf,
  2801. (unsigned)len,
  2802. NULL,
  2803. 0,
  2804. NI_NUMERICHOST);
  2805. }
  2806. #if defined(USE_IPV6)
  2807. else if (usa->sa.sa_family == AF_INET6) {
  2808. getnameinfo(&usa->sa,
  2809. sizeof(usa->sin6),
  2810. buf,
  2811. (unsigned)len,
  2812. NULL,
  2813. 0,
  2814. NI_NUMERICHOST);
  2815. }
  2816. #endif
  2817. #if defined(USE_X_DOM_SOCKET)
  2818. else if (usa->sa.sa_family == AF_UNIX) {
  2819. /* TODO: Define a remote address for unix domain sockets.
  2820. * This code will always return "localhost", identical to http+tcp:
  2821. getnameinfo(&usa->sa,
  2822. sizeof(usa->sun),
  2823. buf,
  2824. (unsigned)len,
  2825. NULL,
  2826. 0,
  2827. NI_NUMERICHOST);
  2828. */
  2829. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2830. }
  2831. #endif
  2832. }
  2833. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2834. * included in all responses other than 100, 101, 5xx. */
  2835. static void
  2836. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2837. {
  2838. #if !defined(REENTRANT_TIME)
  2839. struct tm *tm;
  2840. tm = ((t != NULL) ? gmtime(t) : NULL);
  2841. if (tm != NULL) {
  2842. #else
  2843. struct tm _tm;
  2844. struct tm *tm = &_tm;
  2845. if (t != NULL) {
  2846. gmtime_r(t, tm);
  2847. #endif
  2848. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2849. } else {
  2850. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2851. }
  2852. }
  2853. /* difftime for struct timespec. Return value is in seconds. */
  2854. static double
  2855. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2856. {
  2857. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2858. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2859. }
  2860. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2861. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2862. const char *func,
  2863. unsigned line,
  2864. const char *fmt,
  2865. va_list ap);
  2866. #include "external_mg_cry_internal_impl.inl"
  2867. #elif !defined(NO_FILESYSTEMS)
  2868. /* Print error message to the opened error log stream. */
  2869. static void
  2870. mg_cry_internal_impl(const struct mg_connection *conn,
  2871. const char *func,
  2872. unsigned line,
  2873. const char *fmt,
  2874. va_list ap)
  2875. {
  2876. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2877. struct mg_file fi;
  2878. time_t timestamp;
  2879. /* Unused, in the RELEASE build */
  2880. (void)func;
  2881. (void)line;
  2882. #if defined(GCC_DIAGNOSTIC)
  2883. #pragma GCC diagnostic push
  2884. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2885. #endif
  2886. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2887. #if defined(GCC_DIAGNOSTIC)
  2888. #pragma GCC diagnostic pop
  2889. #endif
  2890. buf[sizeof(buf) - 1] = 0;
  2891. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2892. if (!conn) {
  2893. puts(buf);
  2894. return;
  2895. }
  2896. /* Do not lock when getting the callback value, here and below.
  2897. * I suppose this is fine, since function cannot disappear in the
  2898. * same way string option can. */
  2899. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2900. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2901. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2902. if (mg_fopen(conn,
  2903. conn->dom_ctx->config[ERROR_LOG_FILE],
  2904. MG_FOPEN_MODE_APPEND,
  2905. &fi)
  2906. == 0) {
  2907. fi.access.fp = NULL;
  2908. }
  2909. } else {
  2910. fi.access.fp = NULL;
  2911. }
  2912. if (fi.access.fp != NULL) {
  2913. flockfile(fi.access.fp);
  2914. timestamp = time(NULL);
  2915. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2916. fprintf(fi.access.fp,
  2917. "[%010lu] [error] [client %s] ",
  2918. (unsigned long)timestamp,
  2919. src_addr);
  2920. if (conn->request_info.request_method != NULL) {
  2921. fprintf(fi.access.fp,
  2922. "%s %s: ",
  2923. conn->request_info.request_method,
  2924. conn->request_info.request_uri
  2925. ? conn->request_info.request_uri
  2926. : "");
  2927. }
  2928. fprintf(fi.access.fp, "%s", buf);
  2929. fputc('\n', fi.access.fp);
  2930. fflush(fi.access.fp);
  2931. funlockfile(fi.access.fp);
  2932. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2933. * mg_cry here anyway ;-) */
  2934. }
  2935. }
  2936. }
  2937. #else
  2938. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2939. #endif /* Externally provided function */
  2940. /* Construct fake connection structure. Used for logging, if connection
  2941. * is not applicable at the moment of logging. */
  2942. static struct mg_connection *
  2943. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2944. {
  2945. static const struct mg_connection conn_zero = {0};
  2946. *fc = conn_zero;
  2947. fc->phys_ctx = ctx;
  2948. fc->dom_ctx = &(ctx->dd);
  2949. return fc;
  2950. }
  2951. static void
  2952. mg_cry_internal_wrap(const struct mg_connection *conn,
  2953. struct mg_context *ctx,
  2954. const char *func,
  2955. unsigned line,
  2956. const char *fmt,
  2957. ...)
  2958. {
  2959. va_list ap;
  2960. va_start(ap, fmt);
  2961. if (!conn && ctx) {
  2962. struct mg_connection fc;
  2963. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2964. } else {
  2965. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2966. }
  2967. va_end(ap);
  2968. }
  2969. CIVETWEB_API void
  2970. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2971. {
  2972. va_list ap;
  2973. va_start(ap, fmt);
  2974. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2975. va_end(ap);
  2976. }
  2977. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2978. CIVETWEB_API const char *
  2979. mg_version(void)
  2980. {
  2981. return CIVETWEB_VERSION;
  2982. }
  2983. CIVETWEB_API const struct mg_request_info *
  2984. mg_get_request_info(const struct mg_connection *conn)
  2985. {
  2986. if (!conn) {
  2987. return NULL;
  2988. }
  2989. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2990. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2991. char txt[16];
  2992. struct mg_workerTLS *tls =
  2993. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2994. sprintf(txt, "%03i", conn->response_info.status_code);
  2995. if (strlen(txt) == 3) {
  2996. memcpy(tls->txtbuf, txt, 4);
  2997. } else {
  2998. strcpy(tls->txtbuf, "ERR");
  2999. }
  3000. ((struct mg_connection *)conn)->request_info.local_uri =
  3001. tls->txtbuf; /* use thread safe buffer */
  3002. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3003. tls->txtbuf; /* use the same thread safe buffer */
  3004. ((struct mg_connection *)conn)->request_info.request_uri =
  3005. tls->txtbuf; /* use the same thread safe buffer */
  3006. ((struct mg_connection *)conn)->request_info.num_headers =
  3007. conn->response_info.num_headers;
  3008. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3009. conn->response_info.http_headers,
  3010. sizeof(conn->response_info.http_headers));
  3011. } else
  3012. #endif
  3013. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3014. return NULL;
  3015. }
  3016. return &conn->request_info;
  3017. }
  3018. CIVETWEB_API const struct mg_response_info *
  3019. mg_get_response_info(const struct mg_connection *conn)
  3020. {
  3021. if (!conn) {
  3022. return NULL;
  3023. }
  3024. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3025. return NULL;
  3026. }
  3027. return &conn->response_info;
  3028. }
  3029. static const char *
  3030. get_proto_name(const struct mg_connection *conn)
  3031. {
  3032. #if defined(__clang__)
  3033. #pragma clang diagnostic push
  3034. #pragma clang diagnostic ignored "-Wunreachable-code"
  3035. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3036. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3037. * unreachable, but splitting into four different #ifdef clauses here is
  3038. * more complicated.
  3039. */
  3040. #endif
  3041. const struct mg_request_info *ri = &conn->request_info;
  3042. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3043. ? (ri->is_ssl ? "wss" : "ws")
  3044. : (ri->is_ssl ? "https" : "http"));
  3045. return proto;
  3046. #if defined(__clang__)
  3047. #pragma clang diagnostic pop
  3048. #endif
  3049. }
  3050. static int
  3051. mg_construct_local_link(const struct mg_connection *conn,
  3052. char *buf,
  3053. size_t buflen,
  3054. const char *define_proto,
  3055. int define_port,
  3056. const char *define_uri)
  3057. {
  3058. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3059. return -1;
  3060. } else {
  3061. int i, j;
  3062. int truncated = 0;
  3063. const struct mg_request_info *ri = &conn->request_info;
  3064. const char *proto =
  3065. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3066. const char *uri =
  3067. (define_uri != NULL)
  3068. ? define_uri
  3069. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3070. int port = (define_port > 0) ? define_port : ri->server_port;
  3071. int default_port = 80;
  3072. char *uri_encoded;
  3073. size_t uri_encoded_len;
  3074. if (uri == NULL) {
  3075. return -1;
  3076. }
  3077. uri_encoded_len = strlen(uri) * 3 + 1;
  3078. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3079. if (uri_encoded == NULL) {
  3080. return -1;
  3081. }
  3082. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3083. /* Directory separator should be preserved. */
  3084. for (i = j = 0; uri_encoded[i]; j++) {
  3085. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3086. uri_encoded[j] = '/';
  3087. i += 3;
  3088. } else {
  3089. uri_encoded[j] = uri_encoded[i++];
  3090. }
  3091. }
  3092. uri_encoded[j] = '\0';
  3093. #if defined(USE_X_DOM_SOCKET)
  3094. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3095. /* TODO: Define and document a link for UNIX domain sockets. */
  3096. /* There seems to be no official standard for this.
  3097. * Common uses seem to be "httpunix://", "http.unix://" or
  3098. * "http+unix://" as a protocol definition string, followed by
  3099. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3100. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3101. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3102. * "" (completely skipping the server name part). In any case, the
  3103. * last part is the server local path. */
  3104. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3105. mg_snprintf(conn,
  3106. &truncated,
  3107. buf,
  3108. buflen,
  3109. "%s.unix://%s%s",
  3110. proto,
  3111. server_name,
  3112. ri->local_uri);
  3113. default_port = 0;
  3114. mg_free(uri_encoded);
  3115. return 0;
  3116. }
  3117. #endif
  3118. if (define_proto) {
  3119. /* If we got a protocol name, use the default port accordingly. */
  3120. if ((0 == strcmp(define_proto, "https"))
  3121. || (0 == strcmp(define_proto, "wss"))) {
  3122. default_port = 443;
  3123. }
  3124. } else if (ri->is_ssl) {
  3125. /* If we did not get a protocol name, use TLS as default if it is
  3126. * already used. */
  3127. default_port = 443;
  3128. }
  3129. {
  3130. #if defined(USE_IPV6)
  3131. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3132. #endif
  3133. int auth_domain_check_enabled =
  3134. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3135. && (!mg_strcasecmp(
  3136. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3137. const char *server_domain =
  3138. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3139. char portstr[16];
  3140. char server_ip[48];
  3141. if (port != default_port) {
  3142. sprintf(portstr, ":%u", (unsigned)port);
  3143. } else {
  3144. portstr[0] = 0;
  3145. }
  3146. if (!auth_domain_check_enabled || !server_domain) {
  3147. sockaddr_to_string(server_ip,
  3148. sizeof(server_ip),
  3149. &conn->client.lsa);
  3150. server_domain = server_ip;
  3151. }
  3152. mg_snprintf(conn,
  3153. &truncated,
  3154. buf,
  3155. buflen,
  3156. #if defined(USE_IPV6)
  3157. "%s://%s%s%s%s%s",
  3158. proto,
  3159. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3160. server_domain,
  3161. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3162. #else
  3163. "%s://%s%s%s",
  3164. proto,
  3165. server_domain,
  3166. #endif
  3167. portstr,
  3168. uri_encoded);
  3169. mg_free(uri_encoded);
  3170. if (truncated) {
  3171. return -1;
  3172. }
  3173. return 0;
  3174. }
  3175. }
  3176. }
  3177. CIVETWEB_API int
  3178. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3179. {
  3180. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3181. }
  3182. /* Skip the characters until one of the delimiters characters found.
  3183. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3184. * Advance pointer to buffer to the next word. Return found 0-terminated
  3185. * word.
  3186. * Delimiters can be quoted with quotechar. */
  3187. static char *
  3188. skip_quoted(char **buf,
  3189. const char *delimiters,
  3190. const char *whitespace,
  3191. char quotechar)
  3192. {
  3193. char *p, *begin_word, *end_word, *end_whitespace;
  3194. begin_word = *buf;
  3195. end_word = begin_word + strcspn(begin_word, delimiters);
  3196. /* Check for quotechar */
  3197. if (end_word > begin_word) {
  3198. p = end_word - 1;
  3199. while (*p == quotechar) {
  3200. /* While the delimiter is quoted, look for the next delimiter. */
  3201. /* This happens, e.g., in calls from parse_auth_header,
  3202. * if the user name contains a " character. */
  3203. /* If there is anything beyond end_word, copy it. */
  3204. if (*end_word != '\0') {
  3205. size_t end_off = strcspn(end_word + 1, delimiters);
  3206. memmove(p, end_word, end_off + 1);
  3207. p += end_off; /* p must correspond to end_word - 1 */
  3208. end_word += end_off + 1;
  3209. } else {
  3210. *p = '\0';
  3211. break;
  3212. }
  3213. }
  3214. for (p++; p < end_word; p++) {
  3215. *p = '\0';
  3216. }
  3217. }
  3218. if (*end_word == '\0') {
  3219. *buf = end_word;
  3220. } else {
  3221. #if defined(GCC_DIAGNOSTIC)
  3222. /* Disable spurious conversion warning for GCC */
  3223. #pragma GCC diagnostic push
  3224. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3225. #endif /* defined(GCC_DIAGNOSTIC) */
  3226. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3227. #if defined(GCC_DIAGNOSTIC)
  3228. #pragma GCC diagnostic pop
  3229. #endif /* defined(GCC_DIAGNOSTIC) */
  3230. for (p = end_word; p < end_whitespace; p++) {
  3231. *p = '\0';
  3232. }
  3233. *buf = end_whitespace;
  3234. }
  3235. return begin_word;
  3236. }
  3237. /* Return HTTP header value, or NULL if not found. */
  3238. static const char *
  3239. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3240. {
  3241. int i;
  3242. for (i = 0; i < num_hdr; i++) {
  3243. if (!mg_strcasecmp(name, hdr[i].name)) {
  3244. return hdr[i].value;
  3245. }
  3246. }
  3247. return NULL;
  3248. }
  3249. /* Retrieve requested HTTP header multiple values, and return the number of
  3250. * found occurrences */
  3251. static int
  3252. get_req_headers(const struct mg_request_info *ri,
  3253. const char *name,
  3254. const char **output,
  3255. int output_max_size)
  3256. {
  3257. int i;
  3258. int cnt = 0;
  3259. if (ri) {
  3260. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3261. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3262. output[cnt++] = ri->http_headers[i].value;
  3263. }
  3264. }
  3265. }
  3266. return cnt;
  3267. }
  3268. CIVETWEB_API const char *
  3269. mg_get_header(const struct mg_connection *conn, const char *name)
  3270. {
  3271. if (!conn) {
  3272. return NULL;
  3273. }
  3274. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3275. return get_header(conn->request_info.http_headers,
  3276. conn->request_info.num_headers,
  3277. name);
  3278. }
  3279. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3280. return get_header(conn->response_info.http_headers,
  3281. conn->response_info.num_headers,
  3282. name);
  3283. }
  3284. return NULL;
  3285. }
  3286. static const char *
  3287. get_http_version(const struct mg_connection *conn)
  3288. {
  3289. if (!conn) {
  3290. return NULL;
  3291. }
  3292. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3293. return conn->request_info.http_version;
  3294. }
  3295. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3296. return conn->response_info.http_version;
  3297. }
  3298. return NULL;
  3299. }
  3300. /* A helper function for traversing a comma separated list of values.
  3301. * It returns a list pointer shifted to the next value, or NULL if the end
  3302. * of the list found.
  3303. * Value is stored in val vector. If value has form "x=y", then eq_val
  3304. * vector is initialized to point to the "y" part, and val vector length
  3305. * is adjusted to point only to "x". */
  3306. static const char *
  3307. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3308. {
  3309. int end;
  3310. reparse:
  3311. if (val == NULL || list == NULL || *list == '\0') {
  3312. /* End of the list */
  3313. return NULL;
  3314. }
  3315. /* Skip over leading LWS */
  3316. while (*list == ' ' || *list == '\t')
  3317. list++;
  3318. val->ptr = list;
  3319. if ((list = strchr(val->ptr, ',')) != NULL) {
  3320. /* Comma found. Store length and shift the list ptr */
  3321. val->len = ((size_t)(list - val->ptr));
  3322. list++;
  3323. } else {
  3324. /* This value is the last one */
  3325. list = val->ptr + strlen(val->ptr);
  3326. val->len = ((size_t)(list - val->ptr));
  3327. }
  3328. /* Adjust length for trailing LWS */
  3329. end = (int)val->len - 1;
  3330. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3331. end--;
  3332. val->len = (size_t)(end) + (size_t)(1);
  3333. if (val->len == 0) {
  3334. /* Ignore any empty entries. */
  3335. goto reparse;
  3336. }
  3337. if (eq_val != NULL) {
  3338. /* Value has form "x=y", adjust pointers and lengths
  3339. * so that val points to "x", and eq_val points to "y". */
  3340. eq_val->len = 0;
  3341. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3342. if (eq_val->ptr != NULL) {
  3343. eq_val->ptr++; /* Skip over '=' character */
  3344. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3345. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3346. }
  3347. }
  3348. return list;
  3349. }
  3350. /* A helper function for checking if a comma separated list of values
  3351. * contains
  3352. * the given option (case insensitvely).
  3353. * 'header' can be NULL, in which case false is returned. */
  3354. static int
  3355. header_has_option(const char *header, const char *option)
  3356. {
  3357. struct vec opt_vec;
  3358. struct vec eq_vec;
  3359. DEBUG_ASSERT(option != NULL);
  3360. DEBUG_ASSERT(option[0] != '\0');
  3361. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3362. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3363. return 1;
  3364. }
  3365. return 0;
  3366. }
  3367. /* Sorting function implemented in a separate file */
  3368. #include "sort.inl"
  3369. /* Pattern matching has been reimplemented in a new file */
  3370. #include "match.inl"
  3371. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3372. * This function must tolerate situations when connection info is not
  3373. * set up, for example if request parsing failed. */
  3374. static int
  3375. should_keep_alive(const struct mg_connection *conn)
  3376. {
  3377. const char *http_version;
  3378. const char *header;
  3379. /* First satisfy needs of the server */
  3380. if ((conn == NULL) || conn->must_close) {
  3381. /* Close, if civetweb framework needs to close */
  3382. return 0;
  3383. }
  3384. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3385. /* Close, if keep alive is not enabled */
  3386. return 0;
  3387. }
  3388. /* Check explicit wish of the client */
  3389. header = mg_get_header(conn, "Connection");
  3390. if (header) {
  3391. /* If there is a connection header from the client, obey */
  3392. if (header_has_option(header, "keep-alive")) {
  3393. return 1;
  3394. }
  3395. return 0;
  3396. }
  3397. /* Use default of the standard */
  3398. http_version = get_http_version(conn);
  3399. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3400. /* HTTP 1.1 default is keep alive */
  3401. return 1;
  3402. }
  3403. /* HTTP 1.0 (and earlier) default is to close the connection */
  3404. return 0;
  3405. }
  3406. static int
  3407. should_decode_url(const struct mg_connection *conn)
  3408. {
  3409. if (!conn || !conn->dom_ctx) {
  3410. return 0;
  3411. }
  3412. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3413. }
  3414. static int
  3415. should_decode_query_string(const struct mg_connection *conn)
  3416. {
  3417. if (!conn || !conn->dom_ctx) {
  3418. return 0;
  3419. }
  3420. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3421. == 0);
  3422. }
  3423. static const char *
  3424. suggest_connection_header(const struct mg_connection *conn)
  3425. {
  3426. return should_keep_alive(conn) ? "keep-alive" : "close";
  3427. }
  3428. #include "response.inl"
  3429. static void
  3430. send_no_cache_header(struct mg_connection *conn)
  3431. {
  3432. /* Send all current and obsolete cache opt-out directives. */
  3433. mg_response_header_add(conn,
  3434. "Cache-Control",
  3435. "no-cache, no-store, "
  3436. "must-revalidate, private, max-age=0",
  3437. -1);
  3438. mg_response_header_add(conn, "Expires", "0", -1);
  3439. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3440. /* Obsolete, but still send it for HTTP/1.0 */
  3441. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3442. }
  3443. }
  3444. static void
  3445. send_static_cache_header(struct mg_connection *conn)
  3446. {
  3447. #if !defined(NO_CACHING)
  3448. int max_age;
  3449. char val[64];
  3450. const char *cache_control =
  3451. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3452. /* If there is a full cache-control option configured,0 use it */
  3453. if (cache_control != NULL) {
  3454. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3455. return;
  3456. }
  3457. /* Read the server config to check how long a file may be cached.
  3458. * The configuration is in seconds. */
  3459. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3460. if (max_age <= 0) {
  3461. /* 0 means "do not cache". All values <0 are reserved
  3462. * and may be used differently in the future. */
  3463. /* If a file should not be cached, do not only send
  3464. * max-age=0, but also pragmas and Expires headers. */
  3465. send_no_cache_header(conn);
  3466. return;
  3467. }
  3468. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3469. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3470. /* See also https://www.mnot.net/cache_docs/ */
  3471. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3472. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3473. * leap
  3474. * year to 31622400 seconds. For the moment, we just send whatever has
  3475. * been configured, still the behavior for >1 year should be considered
  3476. * as undefined. */
  3477. mg_snprintf(
  3478. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3479. mg_response_header_add(conn, "Cache-Control", val, -1);
  3480. #else /* NO_CACHING */
  3481. send_no_cache_header(conn);
  3482. #endif /* !NO_CACHING */
  3483. }
  3484. static void
  3485. send_additional_header(struct mg_connection *conn)
  3486. {
  3487. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3488. #if !defined(NO_SSL)
  3489. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3490. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3491. if (max_age >= 0) {
  3492. char val[64];
  3493. mg_snprintf(conn,
  3494. NULL,
  3495. val,
  3496. sizeof(val),
  3497. "max-age=%lu",
  3498. (unsigned long)max_age);
  3499. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3500. }
  3501. }
  3502. #endif
  3503. // Content-Security-Policy
  3504. if (header && header[0]) {
  3505. mg_response_header_add_lines(conn, header);
  3506. }
  3507. }
  3508. static void
  3509. send_cors_header(struct mg_connection *conn)
  3510. {
  3511. const char *origin_hdr = mg_get_header(conn, "Origin");
  3512. const char *cors_orig_cfg =
  3513. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3514. const char *cors_cred_cfg =
  3515. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  3516. const char *cors_hdr_cfg =
  3517. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  3518. const char *cors_exphdr_cfg =
  3519. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  3520. const char *cors_meth_cfg =
  3521. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  3522. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3523. /* Cross-origin resource sharing (CORS), see
  3524. * http://www.html5rocks.com/en/tutorials/cors/,
  3525. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3526. * CORS preflight is not supported for files. */
  3527. mg_response_header_add(conn,
  3528. "Access-Control-Allow-Origin",
  3529. cors_orig_cfg,
  3530. -1);
  3531. }
  3532. if (cors_cred_cfg && *cors_cred_cfg && origin_hdr && *origin_hdr) {
  3533. /* Cross-origin resource sharing (CORS), see
  3534. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  3535. */
  3536. mg_response_header_add(conn,
  3537. "Access-Control-Allow-Credentials",
  3538. cors_cred_cfg,
  3539. -1);
  3540. }
  3541. if (cors_hdr_cfg && *cors_hdr_cfg) {
  3542. mg_response_header_add(conn,
  3543. "Access-Control-Allow-Headers",
  3544. cors_hdr_cfg,
  3545. -1);
  3546. }
  3547. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  3548. mg_response_header_add(conn,
  3549. "Access-Control-Expose-Headers",
  3550. cors_exphdr_cfg,
  3551. -1);
  3552. }
  3553. if (cors_meth_cfg && *cors_meth_cfg) {
  3554. mg_response_header_add(conn,
  3555. "Access-Control-Allow-Methods",
  3556. cors_meth_cfg,
  3557. -1);
  3558. }
  3559. }
  3560. #if !defined(NO_FILESYSTEMS)
  3561. static void handle_file_based_request(struct mg_connection *conn,
  3562. const char *path,
  3563. struct mg_file *filep);
  3564. #endif /* NO_FILESYSTEMS */
  3565. CIVETWEB_API const char *
  3566. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3567. {
  3568. /* See IANA HTTP status code assignment:
  3569. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3570. */
  3571. switch (response_code) {
  3572. /* RFC2616 Section 10.1 - Informational 1xx */
  3573. case 100:
  3574. return "Continue"; /* RFC2616 Section 10.1.1 */
  3575. case 101:
  3576. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3577. case 102:
  3578. return "Processing"; /* RFC2518 Section 10.1 */
  3579. /* RFC2616 Section 10.2 - Successful 2xx */
  3580. case 200:
  3581. return "OK"; /* RFC2616 Section 10.2.1 */
  3582. case 201:
  3583. return "Created"; /* RFC2616 Section 10.2.2 */
  3584. case 202:
  3585. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3586. case 203:
  3587. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3588. case 204:
  3589. return "No Content"; /* RFC2616 Section 10.2.5 */
  3590. case 205:
  3591. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3592. case 206:
  3593. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3594. case 207:
  3595. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3596. */
  3597. case 208:
  3598. return "Already Reported"; /* RFC5842 Section 7.1 */
  3599. case 226:
  3600. return "IM used"; /* RFC3229 Section 10.4.1 */
  3601. /* RFC2616 Section 10.3 - Redirection 3xx */
  3602. case 300:
  3603. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3604. case 301:
  3605. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3606. case 302:
  3607. return "Found"; /* RFC2616 Section 10.3.3 */
  3608. case 303:
  3609. return "See Other"; /* RFC2616 Section 10.3.4 */
  3610. case 304:
  3611. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3612. case 305:
  3613. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3614. case 307:
  3615. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3616. case 308:
  3617. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3618. /* RFC2616 Section 10.4 - Client Error 4xx */
  3619. case 400:
  3620. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3621. case 401:
  3622. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3623. case 402:
  3624. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3625. case 403:
  3626. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3627. case 404:
  3628. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3629. case 405:
  3630. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3631. case 406:
  3632. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3633. case 407:
  3634. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3635. case 408:
  3636. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3637. case 409:
  3638. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3639. case 410:
  3640. return "Gone"; /* RFC2616 Section 10.4.11 */
  3641. case 411:
  3642. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3643. case 412:
  3644. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3645. case 413:
  3646. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3647. case 414:
  3648. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3649. case 415:
  3650. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3651. case 416:
  3652. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3653. */
  3654. case 417:
  3655. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3656. case 421:
  3657. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3658. case 422:
  3659. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3660. * Section 11.2 */
  3661. case 423:
  3662. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3663. case 424:
  3664. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3665. * Section 11.4 */
  3666. case 426:
  3667. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3668. case 428:
  3669. return "Precondition Required"; /* RFC 6585, Section 3 */
  3670. case 429:
  3671. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3672. case 431:
  3673. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3674. case 451:
  3675. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3676. * Section 3 */
  3677. /* RFC2616 Section 10.5 - Server Error 5xx */
  3678. case 500:
  3679. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3680. case 501:
  3681. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3682. case 502:
  3683. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3684. case 503:
  3685. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3686. case 504:
  3687. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3688. case 505:
  3689. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3690. case 506:
  3691. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3692. case 507:
  3693. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3694. * Section 11.5 */
  3695. case 508:
  3696. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3697. case 510:
  3698. return "Not Extended"; /* RFC 2774, Section 7 */
  3699. case 511:
  3700. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3701. /* Other status codes, not shown in the IANA HTTP status code
  3702. * assignment.
  3703. * E.g., "de facto" standards due to common use, ... */
  3704. case 418:
  3705. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3706. case 419:
  3707. return "Authentication Timeout"; /* common use */
  3708. case 420:
  3709. return "Enhance Your Calm"; /* common use */
  3710. case 440:
  3711. return "Login Timeout"; /* common use */
  3712. case 509:
  3713. return "Bandwidth Limit Exceeded"; /* common use */
  3714. default:
  3715. /* This error code is unknown. This should not happen. */
  3716. if (conn) {
  3717. mg_cry_internal(conn,
  3718. "Unknown HTTP response code: %u",
  3719. response_code);
  3720. }
  3721. /* Return at least a category according to RFC 2616 Section 10. */
  3722. if (response_code >= 100 && response_code < 200) {
  3723. /* Unknown informational status code */
  3724. return "Information";
  3725. }
  3726. if (response_code >= 200 && response_code < 300) {
  3727. /* Unknown success code */
  3728. return "Success";
  3729. }
  3730. if (response_code >= 300 && response_code < 400) {
  3731. /* Unknown redirection code */
  3732. return "Redirection";
  3733. }
  3734. if (response_code >= 400 && response_code < 500) {
  3735. /* Unknown request error code */
  3736. return "Client Error";
  3737. }
  3738. if (response_code >= 500 && response_code < 600) {
  3739. /* Unknown server error code */
  3740. return "Server Error";
  3741. }
  3742. /* Response code not even within reasonable range */
  3743. return "";
  3744. }
  3745. }
  3746. static int
  3747. mg_send_http_error_impl(struct mg_connection *conn,
  3748. int status,
  3749. const char *fmt,
  3750. va_list args)
  3751. {
  3752. char errmsg_buf[MG_BUF_LEN];
  3753. va_list ap;
  3754. int has_body;
  3755. #if !defined(NO_FILESYSTEMS)
  3756. char path_buf[UTF8_PATH_MAX];
  3757. int len, i, page_handler_found, scope, truncated;
  3758. const char *error_handler = NULL;
  3759. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3760. const char *error_page_file_ext, *tstr;
  3761. #endif /* NO_FILESYSTEMS */
  3762. int handled_by_callback = 0;
  3763. if ((conn == NULL) || (fmt == NULL)) {
  3764. return -2;
  3765. }
  3766. /* Set status (for log) */
  3767. conn->status_code = status;
  3768. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3769. has_body = ((status > 199) && (status != 204) && (status != 304));
  3770. /* Prepare message in buf, if required */
  3771. if (has_body
  3772. || (!conn->in_error_handler
  3773. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3774. /* Store error message in errmsg_buf */
  3775. va_copy(ap, args);
  3776. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3777. va_end(ap);
  3778. /* In a debug build, print all html errors */
  3779. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3780. }
  3781. /* If there is a http_error callback, call it.
  3782. * But don't do it recursively, if callback calls mg_send_http_error again.
  3783. */
  3784. if (!conn->in_error_handler
  3785. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3786. /* Mark in_error_handler to avoid recursion and call user callback. */
  3787. conn->in_error_handler = 1;
  3788. handled_by_callback =
  3789. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3790. == 0);
  3791. conn->in_error_handler = 0;
  3792. }
  3793. if (!handled_by_callback) {
  3794. /* Check for recursion */
  3795. if (conn->in_error_handler) {
  3796. DEBUG_TRACE(
  3797. "Recursion when handling error %u - fall back to default",
  3798. status);
  3799. #if !defined(NO_FILESYSTEMS)
  3800. } else {
  3801. /* Send user defined error pages, if defined */
  3802. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3803. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3804. page_handler_found = 0;
  3805. if (error_handler != NULL) {
  3806. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3807. switch (scope) {
  3808. case 1: /* Handler for specific error, e.g. 404 error */
  3809. mg_snprintf(conn,
  3810. &truncated,
  3811. path_buf,
  3812. sizeof(path_buf) - 32,
  3813. "%serror%03u.",
  3814. error_handler,
  3815. status);
  3816. break;
  3817. case 2: /* Handler for error group, e.g., 5xx error
  3818. * handler
  3819. * for all server errors (500-599) */
  3820. mg_snprintf(conn,
  3821. &truncated,
  3822. path_buf,
  3823. sizeof(path_buf) - 32,
  3824. "%serror%01uxx.",
  3825. error_handler,
  3826. status / 100);
  3827. break;
  3828. default: /* Handler for all errors */
  3829. mg_snprintf(conn,
  3830. &truncated,
  3831. path_buf,
  3832. sizeof(path_buf) - 32,
  3833. "%serror.",
  3834. error_handler);
  3835. break;
  3836. }
  3837. /* String truncation in buf may only occur if
  3838. * error_handler is too long. This string is
  3839. * from the config, not from a client. */
  3840. (void)truncated;
  3841. /* The following code is redundant, but it should avoid
  3842. * false positives in static source code analyzers and
  3843. * vulnerability scanners.
  3844. */
  3845. path_buf[sizeof(path_buf) - 32] = 0;
  3846. len = (int)strlen(path_buf);
  3847. if (len > (int)sizeof(path_buf) - 32) {
  3848. len = (int)sizeof(path_buf) - 32;
  3849. }
  3850. /* Start with the file extension from the configuration. */
  3851. tstr = strchr(error_page_file_ext, '.');
  3852. while (tstr) {
  3853. for (i = 1;
  3854. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3855. i++) {
  3856. /* buffer overrun is not possible here, since
  3857. * (i < 32) && (len < sizeof(path_buf) - 32)
  3858. * ==> (i + len) < sizeof(path_buf) */
  3859. path_buf[len + i - 1] = tstr[i];
  3860. }
  3861. /* buffer overrun is not possible here, since
  3862. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3863. * ==> (i + len) <= sizeof(path_buf) */
  3864. path_buf[len + i - 1] = 0;
  3865. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3866. DEBUG_TRACE("Check error page %s - found",
  3867. path_buf);
  3868. page_handler_found = 1;
  3869. break;
  3870. }
  3871. DEBUG_TRACE("Check error page %s - not found",
  3872. path_buf);
  3873. /* Continue with the next file extension from the
  3874. * configuration (if there is a next one). */
  3875. tstr = strchr(tstr + i, '.');
  3876. }
  3877. }
  3878. }
  3879. if (page_handler_found) {
  3880. conn->in_error_handler = 1;
  3881. handle_file_based_request(conn, path_buf, &error_page_file);
  3882. conn->in_error_handler = 0;
  3883. return 0;
  3884. }
  3885. #endif /* NO_FILESYSTEMS */
  3886. }
  3887. /* No custom error page. Send default error page. */
  3888. conn->must_close = 1;
  3889. mg_response_header_start(conn, status);
  3890. send_no_cache_header(conn);
  3891. send_additional_header(conn);
  3892. send_cors_header(conn);
  3893. if (has_body) {
  3894. mg_response_header_add(conn,
  3895. "Content-Type",
  3896. "text/plain; charset=utf-8",
  3897. -1);
  3898. }
  3899. mg_response_header_send(conn);
  3900. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3901. if (has_body) {
  3902. /* For other errors, send a generic error message. */
  3903. const char *status_text = mg_get_response_code_text(conn, status);
  3904. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3905. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3906. } else {
  3907. /* No body allowed. Close the connection. */
  3908. DEBUG_TRACE("Error %i", status);
  3909. }
  3910. }
  3911. return 0;
  3912. }
  3913. CIVETWEB_API int
  3914. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3915. {
  3916. va_list ap;
  3917. int ret;
  3918. va_start(ap, fmt);
  3919. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3920. va_end(ap);
  3921. return ret;
  3922. }
  3923. CIVETWEB_API int
  3924. mg_send_http_ok(struct mg_connection *conn,
  3925. const char *mime_type,
  3926. long long content_length)
  3927. {
  3928. if ((mime_type == NULL) || (*mime_type == 0)) {
  3929. /* No content type defined: default to text/html */
  3930. mime_type = "text/html";
  3931. }
  3932. mg_response_header_start(conn, 200);
  3933. send_no_cache_header(conn);
  3934. send_additional_header(conn);
  3935. send_cors_header(conn);
  3936. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3937. if (content_length < 0) {
  3938. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3939. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3940. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3941. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3942. }
  3943. } else {
  3944. char len[32];
  3945. int trunc = 0;
  3946. mg_snprintf(conn,
  3947. &trunc,
  3948. len,
  3949. sizeof(len),
  3950. "%" UINT64_FMT,
  3951. (uint64_t)content_length);
  3952. if (!trunc) {
  3953. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3954. * !trunc is always true */
  3955. mg_response_header_add(conn, "Content-Length", len, -1);
  3956. }
  3957. }
  3958. mg_response_header_send(conn);
  3959. return 0;
  3960. }
  3961. CIVETWEB_API int
  3962. mg_send_http_redirect(struct mg_connection *conn,
  3963. const char *target_url,
  3964. int redirect_code)
  3965. {
  3966. /* Send a 30x redirect response.
  3967. *
  3968. * Redirect types (status codes):
  3969. *
  3970. * Status | Perm/Temp | Method | Version
  3971. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3972. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3973. * 303 | temporary | always use GET | HTTP/1.1
  3974. * 307 | temporary | always keep method | HTTP/1.1
  3975. * 308 | permanent | always keep method | HTTP/1.1
  3976. */
  3977. #if defined(MG_SEND_REDIRECT_BODY)
  3978. char redirect_body[MG_BUF_LEN];
  3979. size_t content_len = 0;
  3980. char content_len_text[32];
  3981. #endif
  3982. /* In case redirect_code=0, use 307. */
  3983. if (redirect_code == 0) {
  3984. redirect_code = 307;
  3985. }
  3986. /* In case redirect_code is none of the above, return error. */
  3987. if ((redirect_code != 301) && (redirect_code != 302)
  3988. && (redirect_code != 303) && (redirect_code != 307)
  3989. && (redirect_code != 308)) {
  3990. /* Parameter error */
  3991. return -2;
  3992. }
  3993. /* If target_url is not defined, redirect to "/". */
  3994. if ((target_url == NULL) || (*target_url == 0)) {
  3995. target_url = "/";
  3996. }
  3997. #if defined(MG_SEND_REDIRECT_BODY)
  3998. /* TODO: condition name? */
  3999. /* Prepare a response body with a hyperlink.
  4000. *
  4001. * According to RFC2616 (and RFC1945 before):
  4002. * Unless the request method was HEAD, the entity of the
  4003. * response SHOULD contain a short hypertext note with a hyperlink to
  4004. * the new URI(s).
  4005. *
  4006. * However, this response body is not useful in M2M communication.
  4007. * Probably the original reason in the RFC was, clients not supporting
  4008. * a 30x HTTP redirect could still show the HTML page and let the user
  4009. * press the link. Since current browsers support 30x HTTP, the additional
  4010. * HTML body does not seem to make sense anymore.
  4011. *
  4012. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4013. * but it only notes:
  4014. * The server's response payload usually contains a short
  4015. * hypertext note with a hyperlink to the new URI(s).
  4016. *
  4017. * Deactivated by default. If you need the 30x body, set the define.
  4018. */
  4019. mg_snprintf(
  4020. conn,
  4021. NULL /* ignore truncation */,
  4022. redirect_body,
  4023. sizeof(redirect_body),
  4024. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4025. redirect_text,
  4026. target_url,
  4027. target_url);
  4028. content_len = strlen(reply);
  4029. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4030. #endif
  4031. /* Send all required headers */
  4032. mg_response_header_start(conn, redirect_code);
  4033. mg_response_header_add(conn, "Location", target_url, -1);
  4034. if ((redirect_code == 301) || (redirect_code == 308)) {
  4035. /* Permanent redirect */
  4036. send_static_cache_header(conn);
  4037. } else {
  4038. /* Temporary redirect */
  4039. send_no_cache_header(conn);
  4040. }
  4041. send_additional_header(conn);
  4042. send_cors_header(conn);
  4043. #if defined(MG_SEND_REDIRECT_BODY)
  4044. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4045. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4046. #else
  4047. mg_response_header_add(conn, "Content-Length", "0", 1);
  4048. #endif
  4049. mg_response_header_send(conn);
  4050. #if defined(MG_SEND_REDIRECT_BODY)
  4051. /* Send response body */
  4052. /* ... unless it is a HEAD request */
  4053. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4054. ret = mg_write(conn, redirect_body, content_len);
  4055. }
  4056. #endif
  4057. return 1;
  4058. }
  4059. #if defined(_WIN32)
  4060. /* Create substitutes for POSIX functions in Win32. */
  4061. #if defined(GCC_DIAGNOSTIC)
  4062. /* Show no warning in case system functions are not used. */
  4063. #pragma GCC diagnostic push
  4064. #pragma GCC diagnostic ignored "-Wunused-function"
  4065. #endif
  4066. static int
  4067. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4068. {
  4069. (void)unused;
  4070. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4071. InitializeCriticalSection(&mutex->sec);
  4072. return 0;
  4073. }
  4074. static int
  4075. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4076. {
  4077. DeleteCriticalSection(&mutex->sec);
  4078. return 0;
  4079. }
  4080. static int
  4081. pthread_mutex_lock(pthread_mutex_t *mutex)
  4082. {
  4083. EnterCriticalSection(&mutex->sec);
  4084. return 0;
  4085. }
  4086. static int
  4087. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4088. {
  4089. LeaveCriticalSection(&mutex->sec);
  4090. return 0;
  4091. }
  4092. FUNCTION_MAY_BE_UNUSED
  4093. static int
  4094. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4095. {
  4096. (void)unused;
  4097. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4098. cv->waiting_thread = NULL;
  4099. return 0;
  4100. }
  4101. FUNCTION_MAY_BE_UNUSED
  4102. static int
  4103. pthread_cond_timedwait(pthread_cond_t *cv,
  4104. pthread_mutex_t *mutex,
  4105. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4106. {
  4107. struct mg_workerTLS **ptls,
  4108. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4109. int ok;
  4110. uint64_t nsnow, nswaitabs;
  4111. int64_t nswaitrel;
  4112. DWORD mswaitrel;
  4113. pthread_mutex_lock(&cv->threadIdSec);
  4114. /* Add this thread to cv's waiting list */
  4115. ptls = &cv->waiting_thread;
  4116. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4117. ;
  4118. tls->next_waiting_thread = NULL;
  4119. *ptls = tls;
  4120. pthread_mutex_unlock(&cv->threadIdSec);
  4121. if (abstime) {
  4122. nsnow = mg_get_current_time_ns();
  4123. nswaitabs =
  4124. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4125. nswaitrel = nswaitabs - nsnow;
  4126. if (nswaitrel < 0) {
  4127. nswaitrel = 0;
  4128. }
  4129. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4130. } else {
  4131. mswaitrel = (DWORD)INFINITE;
  4132. }
  4133. pthread_mutex_unlock(mutex);
  4134. ok = (WAIT_OBJECT_0
  4135. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4136. if (!ok) {
  4137. ok = 1;
  4138. pthread_mutex_lock(&cv->threadIdSec);
  4139. ptls = &cv->waiting_thread;
  4140. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4141. if (*ptls == tls) {
  4142. *ptls = tls->next_waiting_thread;
  4143. ok = 0;
  4144. break;
  4145. }
  4146. }
  4147. pthread_mutex_unlock(&cv->threadIdSec);
  4148. if (ok) {
  4149. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4150. (DWORD)INFINITE);
  4151. }
  4152. }
  4153. /* This thread has been removed from cv's waiting list */
  4154. pthread_mutex_lock(mutex);
  4155. return ok ? 0 : -1;
  4156. }
  4157. FUNCTION_MAY_BE_UNUSED
  4158. static int
  4159. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4160. {
  4161. return pthread_cond_timedwait(cv, mutex, NULL);
  4162. }
  4163. FUNCTION_MAY_BE_UNUSED
  4164. static int
  4165. pthread_cond_signal(pthread_cond_t *cv)
  4166. {
  4167. HANDLE wkup = NULL;
  4168. BOOL ok = FALSE;
  4169. pthread_mutex_lock(&cv->threadIdSec);
  4170. if (cv->waiting_thread) {
  4171. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4172. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4173. ok = SetEvent(wkup);
  4174. DEBUG_ASSERT(ok);
  4175. }
  4176. pthread_mutex_unlock(&cv->threadIdSec);
  4177. return ok ? 0 : 1;
  4178. }
  4179. FUNCTION_MAY_BE_UNUSED
  4180. static int
  4181. pthread_cond_broadcast(pthread_cond_t *cv)
  4182. {
  4183. pthread_mutex_lock(&cv->threadIdSec);
  4184. while (cv->waiting_thread) {
  4185. pthread_cond_signal(cv);
  4186. }
  4187. pthread_mutex_unlock(&cv->threadIdSec);
  4188. return 0;
  4189. }
  4190. FUNCTION_MAY_BE_UNUSED
  4191. static int
  4192. pthread_cond_destroy(pthread_cond_t *cv)
  4193. {
  4194. pthread_mutex_lock(&cv->threadIdSec);
  4195. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4196. pthread_mutex_unlock(&cv->threadIdSec);
  4197. pthread_mutex_destroy(&cv->threadIdSec);
  4198. return 0;
  4199. }
  4200. #if defined(ALTERNATIVE_QUEUE)
  4201. FUNCTION_MAY_BE_UNUSED
  4202. static void *
  4203. event_create(void)
  4204. {
  4205. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4206. }
  4207. FUNCTION_MAY_BE_UNUSED
  4208. static int
  4209. event_wait(void *eventhdl)
  4210. {
  4211. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4212. return (res == WAIT_OBJECT_0);
  4213. }
  4214. FUNCTION_MAY_BE_UNUSED
  4215. static int
  4216. event_signal(void *eventhdl)
  4217. {
  4218. return (int)SetEvent((HANDLE)eventhdl);
  4219. }
  4220. FUNCTION_MAY_BE_UNUSED
  4221. static void
  4222. event_destroy(void *eventhdl)
  4223. {
  4224. CloseHandle((HANDLE)eventhdl);
  4225. }
  4226. #endif
  4227. #if defined(GCC_DIAGNOSTIC)
  4228. /* Enable unused function warning again */
  4229. #pragma GCC diagnostic pop
  4230. #endif
  4231. /* For Windows, change all slashes to backslashes in path names. */
  4232. static void
  4233. change_slashes_to_backslashes(char *path)
  4234. {
  4235. int i;
  4236. for (i = 0; path[i] != '\0'; i++) {
  4237. if (path[i] == '/') {
  4238. path[i] = '\\';
  4239. }
  4240. /* remove double backslash (check i > 0 to preserve UNC paths,
  4241. * like \\server\file.txt) */
  4242. if ((i > 0) && (path[i] == '\\')) {
  4243. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4244. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4245. }
  4246. }
  4247. }
  4248. }
  4249. static int
  4250. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4251. {
  4252. int diff;
  4253. do {
  4254. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4255. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4256. s1++;
  4257. s2++;
  4258. } while ((diff == 0) && (s1[-1] != L'\0'));
  4259. return diff;
  4260. }
  4261. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4262. * wbuf and wbuf_len is a target buffer and its length. */
  4263. static void
  4264. path_to_unicode(const struct mg_connection *conn,
  4265. const char *path,
  4266. wchar_t *wbuf,
  4267. size_t wbuf_len)
  4268. {
  4269. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4270. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4271. DWORD long_len, err;
  4272. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4273. mg_strlcpy(buf, path, sizeof(buf));
  4274. change_slashes_to_backslashes(buf);
  4275. /* Convert to Unicode and back. If doubly-converted string does not
  4276. * match the original, something is fishy, reject. */
  4277. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4278. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4279. WideCharToMultiByte(
  4280. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4281. if (strcmp(buf, buf2) != 0) {
  4282. wbuf[0] = L'\0';
  4283. }
  4284. /* Windows file systems are not case sensitive, but you can still use
  4285. * uppercase and lowercase letters (on all modern file systems).
  4286. * The server can check if the URI uses the same upper/lowercase
  4287. * letters an the file system, effectively making Windows servers
  4288. * case sensitive (like Linux servers are). It is still not possible
  4289. * to use two files with the same name in different cases on Windows
  4290. * (like /a and /A) - this would be possible in Linux.
  4291. * As a default, Windows is not case sensitive, but the case sensitive
  4292. * file name check can be activated by an additional configuration. */
  4293. if (conn) {
  4294. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4295. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4296. "yes")) {
  4297. /* Use case sensitive compare function */
  4298. fcompare = wcscmp;
  4299. }
  4300. }
  4301. (void)conn; /* conn is currently unused */
  4302. /* Only accept a full file path, not a Windows short (8.3) path. */
  4303. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4304. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4305. if (long_len == 0) {
  4306. err = GetLastError();
  4307. if (err == ERROR_FILE_NOT_FOUND) {
  4308. /* File does not exist. This is not always a problem here. */
  4309. return;
  4310. }
  4311. }
  4312. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4313. /* Short name is used. */
  4314. wbuf[0] = L'\0';
  4315. }
  4316. }
  4317. #if !defined(NO_FILESYSTEMS)
  4318. /* Get file information, return 1 if file exists, 0 if not */
  4319. static int
  4320. mg_stat(const struct mg_connection *conn,
  4321. const char *path,
  4322. struct mg_file_stat *filep)
  4323. {
  4324. wchar_t wbuf[UTF16_PATH_MAX];
  4325. WIN32_FILE_ATTRIBUTE_DATA info;
  4326. time_t creation_time;
  4327. size_t len;
  4328. if (!filep) {
  4329. return 0;
  4330. }
  4331. memset(filep, 0, sizeof(*filep));
  4332. if (mg_path_suspicious(conn, path)) {
  4333. return 0;
  4334. }
  4335. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4336. /* Windows happily opens files with some garbage at the end of file name.
  4337. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4338. * "a.cgi", despite one would expect an error back. */
  4339. len = strlen(path);
  4340. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4341. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4342. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4343. filep->last_modified =
  4344. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4345. info.ftLastWriteTime.dwHighDateTime);
  4346. /* On Windows, the file creation time can be higher than the
  4347. * modification time, e.g. when a file is copied.
  4348. * Since the Last-Modified timestamp is used for caching
  4349. * it should be based on the most recent timestamp. */
  4350. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4351. info.ftCreationTime.dwHighDateTime);
  4352. if (creation_time > filep->last_modified) {
  4353. filep->last_modified = creation_time;
  4354. }
  4355. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4356. return 1;
  4357. }
  4358. return 0;
  4359. }
  4360. #endif
  4361. static int
  4362. mg_remove(const struct mg_connection *conn, const char *path)
  4363. {
  4364. wchar_t wbuf[UTF16_PATH_MAX];
  4365. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4366. return DeleteFileW(wbuf) ? 0 : -1;
  4367. }
  4368. static int
  4369. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4370. {
  4371. wchar_t wbuf[UTF16_PATH_MAX];
  4372. (void)mode;
  4373. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4374. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4375. }
  4376. /* Create substitutes for POSIX functions in Win32. */
  4377. #if defined(GCC_DIAGNOSTIC)
  4378. /* Show no warning in case system functions are not used. */
  4379. #pragma GCC diagnostic push
  4380. #pragma GCC diagnostic ignored "-Wunused-function"
  4381. #endif
  4382. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4383. FUNCTION_MAY_BE_UNUSED
  4384. static DIR *
  4385. mg_opendir(const struct mg_connection *conn, const char *name)
  4386. {
  4387. DIR *dir = NULL;
  4388. wchar_t wpath[UTF16_PATH_MAX];
  4389. DWORD attrs;
  4390. if (name == NULL) {
  4391. SetLastError(ERROR_BAD_ARGUMENTS);
  4392. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4393. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4394. } else {
  4395. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4396. attrs = GetFileAttributesW(wpath);
  4397. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4398. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4399. (void)wcscat(wpath, L"\\*");
  4400. dir->handle = FindFirstFileW(wpath, &dir->info);
  4401. dir->result.d_name[0] = '\0';
  4402. } else {
  4403. mg_free(dir);
  4404. dir = NULL;
  4405. }
  4406. }
  4407. return dir;
  4408. }
  4409. FUNCTION_MAY_BE_UNUSED
  4410. static int
  4411. mg_closedir(DIR *dir)
  4412. {
  4413. int result = 0;
  4414. if (dir != NULL) {
  4415. if (dir->handle != INVALID_HANDLE_VALUE)
  4416. result = FindClose(dir->handle) ? 0 : -1;
  4417. mg_free(dir);
  4418. } else {
  4419. result = -1;
  4420. SetLastError(ERROR_BAD_ARGUMENTS);
  4421. }
  4422. return result;
  4423. }
  4424. FUNCTION_MAY_BE_UNUSED
  4425. static struct dirent *
  4426. mg_readdir(DIR *dir)
  4427. {
  4428. struct dirent *result = 0;
  4429. if (dir) {
  4430. if (dir->handle != INVALID_HANDLE_VALUE) {
  4431. result = &dir->result;
  4432. (void)WideCharToMultiByte(CP_UTF8,
  4433. 0,
  4434. dir->info.cFileName,
  4435. -1,
  4436. result->d_name,
  4437. sizeof(result->d_name),
  4438. NULL,
  4439. NULL);
  4440. if (!FindNextFileW(dir->handle, &dir->info)) {
  4441. (void)FindClose(dir->handle);
  4442. dir->handle = INVALID_HANDLE_VALUE;
  4443. }
  4444. } else {
  4445. SetLastError(ERROR_FILE_NOT_FOUND);
  4446. }
  4447. } else {
  4448. SetLastError(ERROR_BAD_ARGUMENTS);
  4449. }
  4450. return result;
  4451. }
  4452. #if !defined(HAVE_POLL)
  4453. #undef POLLIN
  4454. #undef POLLPRI
  4455. #undef POLLOUT
  4456. #undef POLLERR
  4457. #define POLLIN (1) /* Data ready - read will not block. */
  4458. #define POLLPRI (2) /* Priority data ready. */
  4459. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4460. #define POLLERR (8) /* Error event */
  4461. FUNCTION_MAY_BE_UNUSED
  4462. static int
  4463. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4464. {
  4465. struct timeval tv;
  4466. fd_set rset;
  4467. fd_set wset;
  4468. fd_set eset;
  4469. unsigned int i;
  4470. int result;
  4471. SOCKET maxfd = 0;
  4472. memset(&tv, 0, sizeof(tv));
  4473. tv.tv_sec = milliseconds / 1000;
  4474. tv.tv_usec = (milliseconds % 1000) * 1000;
  4475. FD_ZERO(&rset);
  4476. FD_ZERO(&wset);
  4477. FD_ZERO(&eset);
  4478. for (i = 0; i < n; i++) {
  4479. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4480. if (pfd[i].events & POLLIN) {
  4481. FD_SET(pfd[i].fd, &rset);
  4482. }
  4483. if (pfd[i].events & POLLOUT) {
  4484. FD_SET(pfd[i].fd, &wset);
  4485. }
  4486. /* Check for errors for any FD in the set */
  4487. FD_SET(pfd[i].fd, &eset);
  4488. }
  4489. pfd[i].revents = 0;
  4490. if (pfd[i].fd > maxfd) {
  4491. maxfd = pfd[i].fd;
  4492. }
  4493. }
  4494. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4495. for (i = 0; i < n; i++) {
  4496. if (FD_ISSET(pfd[i].fd, &rset)) {
  4497. pfd[i].revents |= POLLIN;
  4498. }
  4499. if (FD_ISSET(pfd[i].fd, &wset)) {
  4500. pfd[i].revents |= POLLOUT;
  4501. }
  4502. if (FD_ISSET(pfd[i].fd, &eset)) {
  4503. pfd[i].revents |= POLLERR;
  4504. }
  4505. }
  4506. }
  4507. /* We should subtract the time used in select from remaining
  4508. * "milliseconds", in particular if called from mg_poll with a
  4509. * timeout quantum.
  4510. * Unfortunately, the remaining time is not stored in "tv" in all
  4511. * implementations, so the result in "tv" must be considered undefined.
  4512. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4513. return result;
  4514. }
  4515. #endif /* HAVE_POLL */
  4516. #if defined(GCC_DIAGNOSTIC)
  4517. /* Enable unused function warning again */
  4518. #pragma GCC diagnostic pop
  4519. #endif
  4520. static void
  4521. set_close_on_exec(SOCKET sock,
  4522. const struct mg_connection *conn /* may be null */,
  4523. struct mg_context *ctx /* may be null */)
  4524. {
  4525. (void)conn; /* Unused. */
  4526. (void)ctx;
  4527. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4528. }
  4529. CIVETWEB_API int
  4530. mg_start_thread(mg_thread_func_t f, void *p)
  4531. {
  4532. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4533. /* Compile-time option to control stack size, e.g.
  4534. * -DUSE_STACK_SIZE=16384
  4535. */
  4536. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4537. == ((uintptr_t)(-1L)))
  4538. ? -1
  4539. : 0);
  4540. #else
  4541. return (
  4542. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4543. ? -1
  4544. : 0);
  4545. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4546. }
  4547. /* Start a thread storing the thread context. */
  4548. static int
  4549. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4550. void *p,
  4551. pthread_t *threadidptr)
  4552. {
  4553. uintptr_t uip;
  4554. HANDLE threadhandle;
  4555. int result = -1;
  4556. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4557. threadhandle = (HANDLE)uip;
  4558. if ((uip != 0) && (threadidptr != NULL)) {
  4559. *threadidptr = threadhandle;
  4560. result = 0;
  4561. }
  4562. return result;
  4563. }
  4564. /* Wait for a thread to finish. */
  4565. static int
  4566. mg_join_thread(pthread_t threadid)
  4567. {
  4568. int result;
  4569. DWORD dwevent;
  4570. result = -1;
  4571. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4572. if (dwevent == WAIT_FAILED) {
  4573. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4574. } else {
  4575. if (dwevent == WAIT_OBJECT_0) {
  4576. CloseHandle(threadid);
  4577. result = 0;
  4578. }
  4579. }
  4580. return result;
  4581. }
  4582. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4583. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4584. /* Create substitutes for POSIX functions in Win32. */
  4585. #if defined(GCC_DIAGNOSTIC)
  4586. /* Show no warning in case system functions are not used. */
  4587. #pragma GCC diagnostic push
  4588. #pragma GCC diagnostic ignored "-Wunused-function"
  4589. #endif
  4590. FUNCTION_MAY_BE_UNUSED
  4591. static HANDLE
  4592. dlopen(const char *dll_name, int flags)
  4593. {
  4594. wchar_t wbuf[UTF16_PATH_MAX];
  4595. (void)flags;
  4596. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4597. return LoadLibraryW(wbuf);
  4598. }
  4599. FUNCTION_MAY_BE_UNUSED
  4600. static int
  4601. dlclose(void *handle)
  4602. {
  4603. int result;
  4604. if (FreeLibrary((HMODULE)handle) != 0) {
  4605. result = 0;
  4606. } else {
  4607. result = -1;
  4608. }
  4609. return result;
  4610. }
  4611. #if defined(GCC_DIAGNOSTIC)
  4612. /* Enable unused function warning again */
  4613. #pragma GCC diagnostic pop
  4614. #endif
  4615. #endif
  4616. #if !defined(NO_CGI)
  4617. #define SIGKILL (0)
  4618. static int
  4619. kill(pid_t pid, int sig_num)
  4620. {
  4621. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4622. (void)CloseHandle((HANDLE)pid);
  4623. return 0;
  4624. }
  4625. #if !defined(WNOHANG)
  4626. #define WNOHANG (1)
  4627. #endif
  4628. static pid_t
  4629. waitpid(pid_t pid, int *status, int flags)
  4630. {
  4631. DWORD timeout = INFINITE;
  4632. DWORD waitres;
  4633. (void)status; /* Currently not used by any client here */
  4634. if ((flags | WNOHANG) == WNOHANG) {
  4635. timeout = 0;
  4636. }
  4637. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4638. if (waitres == WAIT_OBJECT_0) {
  4639. return pid;
  4640. }
  4641. if (waitres == WAIT_TIMEOUT) {
  4642. return 0;
  4643. }
  4644. return (pid_t)-1;
  4645. }
  4646. static void
  4647. trim_trailing_whitespaces(char *s)
  4648. {
  4649. char *e = s + strlen(s);
  4650. while ((e > s) && isspace((unsigned char)e[-1])) {
  4651. *(--e) = '\0';
  4652. }
  4653. }
  4654. static pid_t
  4655. spawn_process(struct mg_connection *conn,
  4656. const char *prog,
  4657. char *envblk,
  4658. char *envp[],
  4659. int fdin[2],
  4660. int fdout[2],
  4661. int fderr[2],
  4662. const char *dir,
  4663. int cgi_config_idx)
  4664. {
  4665. HANDLE me;
  4666. char *interp;
  4667. char *interp_arg = 0;
  4668. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4669. int truncated;
  4670. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4671. STARTUPINFOA si;
  4672. PROCESS_INFORMATION pi = {0};
  4673. (void)envp;
  4674. memset(&si, 0, sizeof(si));
  4675. si.cb = sizeof(si);
  4676. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4677. si.wShowWindow = SW_HIDE;
  4678. me = GetCurrentProcess();
  4679. DuplicateHandle(me,
  4680. (HANDLE)_get_osfhandle(fdin[0]),
  4681. me,
  4682. &si.hStdInput,
  4683. 0,
  4684. TRUE,
  4685. DUPLICATE_SAME_ACCESS);
  4686. DuplicateHandle(me,
  4687. (HANDLE)_get_osfhandle(fdout[1]),
  4688. me,
  4689. &si.hStdOutput,
  4690. 0,
  4691. TRUE,
  4692. DUPLICATE_SAME_ACCESS);
  4693. DuplicateHandle(me,
  4694. (HANDLE)_get_osfhandle(fderr[1]),
  4695. me,
  4696. &si.hStdError,
  4697. 0,
  4698. TRUE,
  4699. DUPLICATE_SAME_ACCESS);
  4700. /* Mark handles that should not be inherited. See
  4701. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4702. */
  4703. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4704. HANDLE_FLAG_INHERIT,
  4705. 0);
  4706. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4707. HANDLE_FLAG_INHERIT,
  4708. 0);
  4709. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4710. HANDLE_FLAG_INHERIT,
  4711. 0);
  4712. /* First check, if there is a CGI interpreter configured for all CGI
  4713. * scripts. */
  4714. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4715. if (interp != NULL) {
  4716. /* If there is a configured interpreter, check for additional arguments
  4717. */
  4718. interp_arg =
  4719. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4720. } else {
  4721. /* Otherwise, the interpreter must be stated in the first line of the
  4722. * CGI script file, after a #! (shebang) mark. */
  4723. buf[0] = buf[1] = '\0';
  4724. /* Get the full script path */
  4725. mg_snprintf(
  4726. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4727. if (truncated) {
  4728. pi.hProcess = (pid_t)-1;
  4729. goto spawn_cleanup;
  4730. }
  4731. /* Open the script file, to read the first line */
  4732. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4733. /* Read the first line of the script into the buffer */
  4734. mg_fgets(buf, sizeof(buf), &file);
  4735. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4736. buf[sizeof(buf) - 1] = '\0';
  4737. }
  4738. if ((buf[0] == '#') && (buf[1] == '!')) {
  4739. trim_trailing_whitespaces(buf + 2);
  4740. } else {
  4741. buf[2] = '\0';
  4742. }
  4743. interp = buf + 2;
  4744. }
  4745. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4746. if (interp[0] != '\0') {
  4747. /* This is an interpreted script file. We must call the interpreter. */
  4748. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4749. mg_snprintf(conn,
  4750. &truncated,
  4751. cmdline,
  4752. sizeof(cmdline),
  4753. "\"%s\" %s \"%s\\%s\"",
  4754. interp,
  4755. interp_arg,
  4756. full_dir,
  4757. prog);
  4758. } else {
  4759. mg_snprintf(conn,
  4760. &truncated,
  4761. cmdline,
  4762. sizeof(cmdline),
  4763. "\"%s\" \"%s\\%s\"",
  4764. interp,
  4765. full_dir,
  4766. prog);
  4767. }
  4768. } else {
  4769. /* This is (probably) a compiled program. We call it directly. */
  4770. mg_snprintf(conn,
  4771. &truncated,
  4772. cmdline,
  4773. sizeof(cmdline),
  4774. "\"%s\\%s\"",
  4775. full_dir,
  4776. prog);
  4777. }
  4778. if (truncated) {
  4779. pi.hProcess = (pid_t)-1;
  4780. goto spawn_cleanup;
  4781. }
  4782. DEBUG_TRACE("Running [%s]", cmdline);
  4783. if (CreateProcessA(NULL,
  4784. cmdline,
  4785. NULL,
  4786. NULL,
  4787. TRUE,
  4788. CREATE_NEW_PROCESS_GROUP,
  4789. envblk,
  4790. NULL,
  4791. &si,
  4792. &pi)
  4793. == 0) {
  4794. mg_cry_internal(
  4795. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4796. pi.hProcess = (pid_t)-1;
  4797. /* goto spawn_cleanup; */
  4798. }
  4799. spawn_cleanup:
  4800. (void)CloseHandle(si.hStdOutput);
  4801. (void)CloseHandle(si.hStdError);
  4802. (void)CloseHandle(si.hStdInput);
  4803. if (pi.hThread != NULL) {
  4804. (void)CloseHandle(pi.hThread);
  4805. }
  4806. return (pid_t)pi.hProcess;
  4807. }
  4808. #endif /* !NO_CGI */
  4809. static int
  4810. set_blocking_mode(SOCKET sock)
  4811. {
  4812. unsigned long non_blocking = 0;
  4813. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4814. }
  4815. static int
  4816. set_non_blocking_mode(SOCKET sock)
  4817. {
  4818. unsigned long non_blocking = 1;
  4819. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4820. }
  4821. #else
  4822. #if !defined(NO_FILESYSTEMS)
  4823. static int
  4824. mg_stat(const struct mg_connection *conn,
  4825. const char *path,
  4826. struct mg_file_stat *filep)
  4827. {
  4828. struct stat st;
  4829. if (!filep) {
  4830. return 0;
  4831. }
  4832. memset(filep, 0, sizeof(*filep));
  4833. if (mg_path_suspicious(conn, path)) {
  4834. return 0;
  4835. }
  4836. if (0 == stat(path, &st)) {
  4837. filep->size = (uint64_t)(st.st_size);
  4838. filep->last_modified = st.st_mtime;
  4839. filep->is_directory = S_ISDIR(st.st_mode);
  4840. return 1;
  4841. }
  4842. return 0;
  4843. }
  4844. #endif /* NO_FILESYSTEMS */
  4845. static void
  4846. set_close_on_exec(int fd,
  4847. const struct mg_connection *conn /* may be null */,
  4848. struct mg_context *ctx /* may be null */)
  4849. {
  4850. #if defined(__ZEPHYR__)
  4851. (void)fd;
  4852. (void)conn;
  4853. (void)ctx;
  4854. #else
  4855. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4856. if (conn || ctx) {
  4857. struct mg_connection fc;
  4858. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4859. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4860. __func__,
  4861. strerror(ERRNO));
  4862. }
  4863. }
  4864. #endif
  4865. }
  4866. CIVETWEB_API int
  4867. mg_start_thread(mg_thread_func_t func, void *param)
  4868. {
  4869. pthread_t thread_id;
  4870. pthread_attr_t attr;
  4871. int result;
  4872. (void)pthread_attr_init(&attr);
  4873. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4874. #if defined(__ZEPHYR__)
  4875. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4876. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4877. /* Compile-time option to control stack size,
  4878. * e.g. -DUSE_STACK_SIZE=16384 */
  4879. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4880. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4881. result = pthread_create(&thread_id, &attr, func, param);
  4882. pthread_attr_destroy(&attr);
  4883. return result;
  4884. }
  4885. /* Start a thread storing the thread context. */
  4886. static int
  4887. mg_start_thread_with_id(mg_thread_func_t func,
  4888. void *param,
  4889. pthread_t *threadidptr)
  4890. {
  4891. pthread_t thread_id;
  4892. pthread_attr_t attr;
  4893. int result;
  4894. (void)pthread_attr_init(&attr);
  4895. #if defined(__ZEPHYR__)
  4896. pthread_attr_setstack(&attr,
  4897. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4898. ZEPHYR_STACK_SIZE);
  4899. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4900. /* Compile-time option to control stack size,
  4901. * e.g. -DUSE_STACK_SIZE=16384 */
  4902. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4903. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4904. result = pthread_create(&thread_id, &attr, func, param);
  4905. pthread_attr_destroy(&attr);
  4906. if ((result == 0) && (threadidptr != NULL)) {
  4907. *threadidptr = thread_id;
  4908. }
  4909. return result;
  4910. }
  4911. /* Wait for a thread to finish. */
  4912. static int
  4913. mg_join_thread(pthread_t threadid)
  4914. {
  4915. int result;
  4916. result = pthread_join(threadid, NULL);
  4917. return result;
  4918. }
  4919. #if !defined(NO_CGI)
  4920. static pid_t
  4921. spawn_process(struct mg_connection *conn,
  4922. const char *prog,
  4923. char *envblk,
  4924. char *envp[],
  4925. int fdin[2],
  4926. int fdout[2],
  4927. int fderr[2],
  4928. const char *dir,
  4929. int cgi_config_idx)
  4930. {
  4931. pid_t pid;
  4932. const char *interp;
  4933. (void)envblk;
  4934. if ((pid = fork()) == -1) {
  4935. /* Parent */
  4936. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4937. } else if (pid != 0) {
  4938. /* Make sure children close parent-side descriptors.
  4939. * The caller will close the child-side immediately. */
  4940. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4941. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4942. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4943. } else {
  4944. /* Child */
  4945. if (chdir(dir) != 0) {
  4946. mg_cry_internal(
  4947. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4948. } else if (dup2(fdin[0], 0) == -1) {
  4949. mg_cry_internal(conn,
  4950. "%s: dup2(%d, 0): %s",
  4951. __func__,
  4952. fdin[0],
  4953. strerror(ERRNO));
  4954. } else if (dup2(fdout[1], 1) == -1) {
  4955. mg_cry_internal(conn,
  4956. "%s: dup2(%d, 1): %s",
  4957. __func__,
  4958. fdout[1],
  4959. strerror(ERRNO));
  4960. } else if (dup2(fderr[1], 2) == -1) {
  4961. mg_cry_internal(conn,
  4962. "%s: dup2(%d, 2): %s",
  4963. __func__,
  4964. fderr[1],
  4965. strerror(ERRNO));
  4966. } else {
  4967. struct sigaction sa;
  4968. /* Keep stderr and stdout in two different pipes.
  4969. * Stdout will be sent back to the client,
  4970. * stderr should go into a server error log. */
  4971. (void)close(fdin[0]);
  4972. (void)close(fdout[1]);
  4973. (void)close(fderr[1]);
  4974. /* Close write end fdin and read end fdout and fderr */
  4975. (void)close(fdin[1]);
  4976. (void)close(fdout[0]);
  4977. (void)close(fderr[0]);
  4978. /* After exec, all signal handlers are restored to their default
  4979. * values, with one exception of SIGCHLD. According to
  4980. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4981. * will leave unchanged after exec if it was set to be ignored.
  4982. * Restore it to default action. */
  4983. memset(&sa, 0, sizeof(sa));
  4984. sa.sa_handler = SIG_DFL;
  4985. sigaction(SIGCHLD, &sa, NULL);
  4986. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4987. if (interp == NULL) {
  4988. /* no interpreter configured, call the program directly */
  4989. (void)execle(prog, prog, NULL, envp);
  4990. mg_cry_internal(conn,
  4991. "%s: execle(%s): %s",
  4992. __func__,
  4993. prog,
  4994. strerror(ERRNO));
  4995. } else {
  4996. /* call the configured interpreter */
  4997. const char *interp_args =
  4998. conn->dom_ctx
  4999. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5000. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5001. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5002. } else {
  5003. (void)execle(interp, interp, prog, NULL, envp);
  5004. }
  5005. mg_cry_internal(conn,
  5006. "%s: execle(%s %s): %s",
  5007. __func__,
  5008. interp,
  5009. prog,
  5010. strerror(ERRNO));
  5011. }
  5012. }
  5013. exit(EXIT_FAILURE);
  5014. }
  5015. return pid;
  5016. }
  5017. #endif /* !NO_CGI */
  5018. static int
  5019. set_non_blocking_mode(SOCKET sock)
  5020. {
  5021. int flags = fcntl(sock, F_GETFL, 0);
  5022. if (flags < 0) {
  5023. return -1;
  5024. }
  5025. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5026. return -1;
  5027. }
  5028. return 0;
  5029. }
  5030. static int
  5031. set_blocking_mode(SOCKET sock)
  5032. {
  5033. int flags = fcntl(sock, F_GETFL, 0);
  5034. if (flags < 0) {
  5035. return -1;
  5036. }
  5037. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5038. return -1;
  5039. }
  5040. return 0;
  5041. }
  5042. #endif /* _WIN32 / else */
  5043. /* End of initial operating system specific define block. */
  5044. /* Get a random number (independent of C rand function) */
  5045. static uint64_t
  5046. get_random(void)
  5047. {
  5048. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5049. static uint64_t lcg = 0; /* Linear congruential generator */
  5050. uint64_t now = mg_get_current_time_ns();
  5051. if (lfsr == 0) {
  5052. /* lfsr will be only 0 if has not been initialized,
  5053. * so this code is called only once. */
  5054. lfsr = mg_get_current_time_ns();
  5055. lcg = mg_get_current_time_ns();
  5056. } else {
  5057. /* Get the next step of both random number generators. */
  5058. lfsr = (lfsr >> 1)
  5059. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5060. << 63);
  5061. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5062. }
  5063. /* Combining two pseudo-random number generators and a high resolution
  5064. * part
  5065. * of the current server time will make it hard (impossible?) to guess
  5066. * the
  5067. * next number. */
  5068. return (lfsr ^ lcg ^ now);
  5069. }
  5070. static int
  5071. mg_poll(struct mg_pollfd *pfd,
  5072. unsigned int n,
  5073. int milliseconds,
  5074. const stop_flag_t *stop_flag)
  5075. {
  5076. /* Call poll, but only for a maximum time of a few seconds.
  5077. * This will allow to stop the server after some seconds, instead
  5078. * of having to wait for a long socket timeout. */
  5079. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5080. int check_pollerr = 0;
  5081. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5082. /* If we wait for only one file descriptor, wait on error as well */
  5083. pfd[0].events |= POLLERR;
  5084. check_pollerr = 1;
  5085. }
  5086. do {
  5087. int result;
  5088. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5089. /* Shut down signal */
  5090. return -2;
  5091. }
  5092. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5093. ms_now = milliseconds;
  5094. }
  5095. result = poll(pfd, n, ms_now);
  5096. if (result != 0) {
  5097. int err = ERRNO;
  5098. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5099. /* Poll returned either success (1) or error (-1).
  5100. * Forward both to the caller. */
  5101. if ((check_pollerr)
  5102. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5103. == POLLERR)) {
  5104. /* One and only file descriptor returned error */
  5105. return -1;
  5106. }
  5107. return result;
  5108. }
  5109. }
  5110. /* Poll returned timeout (0). */
  5111. if (milliseconds > 0) {
  5112. milliseconds -= ms_now;
  5113. }
  5114. } while (milliseconds > 0);
  5115. /* timeout: return 0 */
  5116. return 0;
  5117. }
  5118. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5119. * descriptor.
  5120. * Return value:
  5121. * >=0 .. number of bytes successfully written
  5122. * -1 .. timeout
  5123. * -2 .. error
  5124. */
  5125. static int
  5126. push_inner(struct mg_context *ctx,
  5127. FILE *fp,
  5128. SOCKET sock,
  5129. SSL *ssl,
  5130. const char *buf,
  5131. int len,
  5132. double timeout)
  5133. {
  5134. uint64_t start = 0, now = 0, timeout_ns = 0;
  5135. int n, err;
  5136. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5137. #if defined(_WIN32)
  5138. typedef int len_t;
  5139. #else
  5140. typedef size_t len_t;
  5141. #endif
  5142. if (timeout > 0) {
  5143. now = mg_get_current_time_ns();
  5144. start = now;
  5145. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5146. }
  5147. if (ctx == NULL) {
  5148. return -2;
  5149. }
  5150. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5151. if (ssl) {
  5152. return -2;
  5153. }
  5154. #endif
  5155. /* Try to read until it succeeds, fails, times out, or the server
  5156. * shuts down. */
  5157. for (;;) {
  5158. #if defined(USE_MBEDTLS)
  5159. if (ssl != NULL) {
  5160. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5161. if (n <= 0) {
  5162. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5163. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5164. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5165. n = 0;
  5166. } else {
  5167. fprintf(stderr, "SSL write failed, error %d\n", n);
  5168. return -2;
  5169. }
  5170. } else {
  5171. err = 0;
  5172. }
  5173. } else
  5174. #elif !defined(NO_SSL)
  5175. if (ssl != NULL) {
  5176. ERR_clear_error();
  5177. n = SSL_write(ssl, buf, len);
  5178. if (n <= 0) {
  5179. err = SSL_get_error(ssl, n);
  5180. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5181. err = ERRNO;
  5182. } else if ((err == SSL_ERROR_WANT_READ)
  5183. || (err == SSL_ERROR_WANT_WRITE)) {
  5184. n = 0;
  5185. } else {
  5186. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5187. ERR_clear_error();
  5188. return -2;
  5189. }
  5190. ERR_clear_error();
  5191. } else {
  5192. err = 0;
  5193. }
  5194. } else
  5195. #endif
  5196. if (fp != NULL) {
  5197. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5198. if (ferror(fp)) {
  5199. n = -1;
  5200. err = ERRNO;
  5201. } else {
  5202. err = 0;
  5203. }
  5204. } else {
  5205. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5206. err = (n < 0) ? ERRNO : 0;
  5207. if (ERROR_TRY_AGAIN(err)) {
  5208. err = 0;
  5209. n = 0;
  5210. }
  5211. if (n < 0) {
  5212. /* shutdown of the socket at client side */
  5213. return -2;
  5214. }
  5215. }
  5216. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5217. return -2;
  5218. }
  5219. if ((n > 0) || ((n == 0) && (len == 0))) {
  5220. /* some data has been read, or no data was requested */
  5221. return n;
  5222. }
  5223. if (n < 0) {
  5224. /* socket error - check errno */
  5225. DEBUG_TRACE("send() failed, error %d", err);
  5226. /* TODO (mid): error handling depending on the error code.
  5227. * These codes are different between Windows and Linux.
  5228. * Currently there is no problem with failing send calls,
  5229. * if there is a reproducible situation, it should be
  5230. * investigated in detail.
  5231. */
  5232. return -2;
  5233. }
  5234. /* Only in case n=0 (timeout), repeat calling the write function */
  5235. /* If send failed, wait before retry */
  5236. if (fp != NULL) {
  5237. /* For files, just wait a fixed time.
  5238. * Maybe it helps, maybe not. */
  5239. mg_sleep(5);
  5240. } else {
  5241. /* For sockets, wait for the socket using poll */
  5242. struct mg_pollfd pfd[2];
  5243. int pollres;
  5244. unsigned int num_sock = 1;
  5245. pfd[0].fd = sock;
  5246. pfd[0].events = POLLOUT;
  5247. if (ctx->context_type == CONTEXT_SERVER) {
  5248. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  5249. pfd[num_sock].events = POLLIN;
  5250. num_sock++;
  5251. }
  5252. pollres = mg_poll(pfd, num_sock, (int)(ms_wait), &(ctx->stop_flag));
  5253. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5254. return -2;
  5255. }
  5256. if (pollres > 0) {
  5257. continue;
  5258. }
  5259. }
  5260. if (timeout > 0) {
  5261. now = mg_get_current_time_ns();
  5262. if ((now - start) > timeout_ns) {
  5263. /* Timeout */
  5264. break;
  5265. }
  5266. }
  5267. }
  5268. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5269. used */
  5270. return -1;
  5271. }
  5272. static int
  5273. push_all(struct mg_context *ctx,
  5274. FILE *fp,
  5275. SOCKET sock,
  5276. SSL *ssl,
  5277. const char *buf,
  5278. int len)
  5279. {
  5280. double timeout = -1.0;
  5281. int n, nwritten = 0;
  5282. if (ctx == NULL) {
  5283. return -1;
  5284. }
  5285. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5286. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5287. }
  5288. if (timeout <= 0.0) {
  5289. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5290. / 1000.0;
  5291. }
  5292. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5293. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5294. if (n < 0) {
  5295. if (nwritten == 0) {
  5296. nwritten = -1; /* Propagate the error */
  5297. }
  5298. break;
  5299. } else if (n == 0) {
  5300. break; /* No more data to write */
  5301. } else {
  5302. nwritten += n;
  5303. len -= n;
  5304. }
  5305. }
  5306. return nwritten;
  5307. }
  5308. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5309. * Return value:
  5310. * >=0 .. number of bytes successfully read
  5311. * -1 .. timeout
  5312. * -2 .. error
  5313. */
  5314. static int
  5315. pull_inner(FILE *fp,
  5316. struct mg_connection *conn,
  5317. char *buf,
  5318. int len,
  5319. double timeout)
  5320. {
  5321. int nread, err = 0;
  5322. #if defined(_WIN32)
  5323. typedef int len_t;
  5324. #else
  5325. typedef size_t len_t;
  5326. #endif
  5327. /* We need an additional wait loop around this, because in some cases
  5328. * with TLSwe may get data from the socket but not from SSL_read.
  5329. * In this case we need to repeat at least once.
  5330. */
  5331. if (fp != NULL) {
  5332. /* Use read() instead of fread(), because if we're reading from the
  5333. * CGI pipe, fread() may block until IO buffer is filled up. We
  5334. * cannot afford to block and must pass all read bytes immediately
  5335. * to the client. */
  5336. nread = (int)read(fileno(fp), buf, (size_t)len);
  5337. err = (nread < 0) ? ERRNO : 0;
  5338. if ((nread == 0) && (len > 0)) {
  5339. /* Should get data, but got EOL */
  5340. return -2;
  5341. }
  5342. #if defined(USE_MBEDTLS)
  5343. } else if (conn->ssl != NULL) {
  5344. struct mg_pollfd pfd[2];
  5345. int to_read;
  5346. int pollres;
  5347. unsigned int num_sock = 1;
  5348. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5349. if (to_read > 0) {
  5350. /* We already know there is no more data buffered in conn->buf
  5351. * but there is more available in the SSL layer. So don't poll
  5352. * conn->client.sock yet. */
  5353. pollres = 1;
  5354. if (to_read > len)
  5355. to_read = len;
  5356. } else {
  5357. pfd[0].fd = conn->client.sock;
  5358. pfd[0].events = POLLIN;
  5359. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5360. pfd[num_sock].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  5361. pfd[num_sock].events = POLLIN;
  5362. num_sock++;
  5363. }
  5364. to_read = len;
  5365. pollres = mg_poll(pfd,
  5366. num_sock,
  5367. (int)(timeout * 1000.0),
  5368. &(conn->phys_ctx->stop_flag));
  5369. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5370. return -2;
  5371. }
  5372. }
  5373. if (pollres > 0) {
  5374. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5375. if (nread <= 0) {
  5376. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5377. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5378. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5379. nread = 0;
  5380. } else {
  5381. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5382. return -2;
  5383. }
  5384. } else {
  5385. err = 0;
  5386. }
  5387. } else if (pollres < 0) {
  5388. /* Error */
  5389. return -2;
  5390. } else {
  5391. /* pollres = 0 means timeout */
  5392. nread = 0;
  5393. }
  5394. #elif !defined(NO_SSL)
  5395. } else if (conn->ssl != NULL) {
  5396. int ssl_pending;
  5397. struct mg_pollfd pfd[2];
  5398. int pollres;
  5399. unsigned int num_sock = 1;
  5400. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5401. /* We already know there is no more data buffered in conn->buf
  5402. * but there is more available in the SSL layer. So don't poll
  5403. * conn->client.sock yet. */
  5404. if (ssl_pending > len) {
  5405. ssl_pending = len;
  5406. }
  5407. pollres = 1;
  5408. } else {
  5409. pfd[0].fd = conn->client.sock;
  5410. pfd[0].events = POLLIN;
  5411. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5412. pfd[num_sock].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  5413. pfd[num_sock].events = POLLIN;
  5414. num_sock++;
  5415. }
  5416. pollres = mg_poll(pfd,
  5417. num_sock,
  5418. (int)(timeout * 1000.0),
  5419. &(conn->phys_ctx->stop_flag));
  5420. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5421. return -2;
  5422. }
  5423. }
  5424. if (pollres > 0) {
  5425. ERR_clear_error();
  5426. nread =
  5427. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5428. if (nread <= 0) {
  5429. err = SSL_get_error(conn->ssl, nread);
  5430. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5431. err = ERRNO;
  5432. } else if ((err == SSL_ERROR_WANT_READ)
  5433. || (err == SSL_ERROR_WANT_WRITE)) {
  5434. nread = 0;
  5435. } else {
  5436. /* All errors should return -2 */
  5437. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5438. ERR_clear_error();
  5439. return -2;
  5440. }
  5441. ERR_clear_error();
  5442. } else {
  5443. err = 0;
  5444. }
  5445. } else if (pollres < 0) {
  5446. /* Error */
  5447. return -2;
  5448. } else {
  5449. /* pollres = 0 means timeout */
  5450. nread = 0;
  5451. }
  5452. #endif
  5453. } else {
  5454. struct mg_pollfd pfd[2];
  5455. int pollres;
  5456. unsigned int num_sock = 1;
  5457. pfd[0].fd = conn->client.sock;
  5458. pfd[0].events = POLLIN;
  5459. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5460. pfd[num_sock].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  5461. pfd[num_sock].events = POLLIN;
  5462. num_sock++;
  5463. }
  5464. pollres = mg_poll(pfd,
  5465. num_sock,
  5466. (int)(timeout * 1000.0),
  5467. &(conn->phys_ctx->stop_flag));
  5468. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5469. return -2;
  5470. }
  5471. if (pollres > 0) {
  5472. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5473. err = (nread < 0) ? ERRNO : 0;
  5474. if (nread <= 0) {
  5475. /* shutdown of the socket at client side */
  5476. return -2;
  5477. }
  5478. } else if (pollres < 0) {
  5479. /* error calling poll */
  5480. return -2;
  5481. } else {
  5482. /* pollres = 0 means timeout */
  5483. nread = 0;
  5484. }
  5485. }
  5486. if (conn != NULL && !STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5487. return -2;
  5488. }
  5489. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5490. /* some data has been read, or no data was requested */
  5491. return nread;
  5492. }
  5493. if (nread < 0) {
  5494. /* socket error - check errno */
  5495. #if defined(_WIN32)
  5496. if (err == WSAEWOULDBLOCK) {
  5497. /* TODO (low): check if this is still required */
  5498. /* standard case if called from close_socket_gracefully */
  5499. return -2;
  5500. } else if (err == WSAETIMEDOUT) {
  5501. /* TODO (low): check if this is still required */
  5502. /* timeout is handled by the while loop */
  5503. return 0;
  5504. } else if (err == WSAECONNABORTED) {
  5505. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5506. return -2;
  5507. } else {
  5508. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5509. return -2;
  5510. }
  5511. #else
  5512. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5513. * if the timeout is reached and if the socket was set to non-
  5514. * blocking in close_socket_gracefully, so we can not distinguish
  5515. * here. We have to wait for the timeout in both cases for now.
  5516. */
  5517. if (ERROR_TRY_AGAIN(err)) {
  5518. /* TODO (low): check if this is still required */
  5519. /* EAGAIN/EWOULDBLOCK:
  5520. * standard case if called from close_socket_gracefully
  5521. * => should return -1 */
  5522. /* or timeout occurred
  5523. * => the code must stay in the while loop */
  5524. /* EINTR can be generated on a socket with a timeout set even
  5525. * when SA_RESTART is effective for all relevant signals
  5526. * (see signal(7)).
  5527. * => stay in the while loop */
  5528. } else {
  5529. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5530. return -2;
  5531. }
  5532. #endif
  5533. }
  5534. /* Timeout occurred, but no data available. */
  5535. return -1;
  5536. }
  5537. static int
  5538. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5539. {
  5540. int n, nread = 0;
  5541. double timeout = -1.0;
  5542. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5543. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5544. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5545. }
  5546. if (timeout <= 0.0) {
  5547. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5548. / 1000.0;
  5549. }
  5550. start_time = mg_get_current_time_ns();
  5551. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5552. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5553. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5554. if (n == -2) {
  5555. if (nread == 0) {
  5556. nread = -1; /* Propagate the error */
  5557. }
  5558. break;
  5559. } else if (n == -1) {
  5560. /* timeout */
  5561. if (timeout >= 0.0) {
  5562. now = mg_get_current_time_ns();
  5563. if ((now - start_time) <= timeout_ns) {
  5564. continue;
  5565. }
  5566. }
  5567. break;
  5568. } else if (n == 0) {
  5569. break; /* No more data to read */
  5570. } else {
  5571. nread += n;
  5572. len -= n;
  5573. }
  5574. }
  5575. return nread;
  5576. }
  5577. static void
  5578. discard_unread_request_data(struct mg_connection *conn)
  5579. {
  5580. char buf[MG_BUF_LEN];
  5581. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5582. ;
  5583. }
  5584. static int
  5585. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5586. {
  5587. int64_t content_len, n, buffered_len, nread;
  5588. int64_t len64 =
  5589. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5590. * int, we may not read more
  5591. * bytes */
  5592. const char *body;
  5593. if (conn == NULL) {
  5594. return 0;
  5595. }
  5596. /* If Content-Length is not set for a response with body data,
  5597. * we do not know in advance how much data should be read. */
  5598. content_len = conn->content_len;
  5599. if (content_len < 0) {
  5600. /* The body data is completed when the connection is closed. */
  5601. content_len = INT64_MAX;
  5602. }
  5603. nread = 0;
  5604. if (conn->consumed_content < content_len) {
  5605. /* Adjust number of bytes to read. */
  5606. int64_t left_to_read = content_len - conn->consumed_content;
  5607. if (left_to_read < len64) {
  5608. /* Do not read more than the total content length of the
  5609. * request.
  5610. */
  5611. len64 = left_to_read;
  5612. }
  5613. /* Return buffered data */
  5614. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5615. - conn->consumed_content;
  5616. if (buffered_len > 0) {
  5617. if (len64 < buffered_len) {
  5618. buffered_len = len64;
  5619. }
  5620. body = conn->buf + conn->request_len + conn->consumed_content;
  5621. memcpy(buf, body, (size_t)buffered_len);
  5622. len64 -= buffered_len;
  5623. conn->consumed_content += buffered_len;
  5624. nread += buffered_len;
  5625. buf = (char *)buf + buffered_len;
  5626. }
  5627. /* We have returned all buffered data. Read new data from the remote
  5628. * socket.
  5629. */
  5630. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5631. conn->consumed_content += n;
  5632. nread += n;
  5633. } else {
  5634. nread = ((nread > 0) ? nread : n);
  5635. }
  5636. }
  5637. return (int)nread;
  5638. }
  5639. /* Forward declarations */
  5640. static void handle_request(struct mg_connection *);
  5641. static void log_access(const struct mg_connection *);
  5642. /* Handle request, update statistics and call access log */
  5643. static void
  5644. handle_request_stat_log(struct mg_connection *conn)
  5645. {
  5646. #if defined(USE_SERVER_STATS)
  5647. struct timespec tnow;
  5648. conn->conn_state = 4; /* processing */
  5649. #endif
  5650. handle_request(conn);
  5651. #if defined(USE_SERVER_STATS)
  5652. conn->conn_state = 5; /* processed */
  5653. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5654. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5655. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5656. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5657. conn->num_bytes_sent);
  5658. #endif
  5659. DEBUG_TRACE("%s", "handle_request done");
  5660. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5661. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5662. DEBUG_TRACE("%s", "end_request callback done");
  5663. }
  5664. log_access(conn);
  5665. }
  5666. #if defined(USE_HTTP2)
  5667. #if defined(NO_SSL)
  5668. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5669. #endif
  5670. #define USE_ALPN
  5671. #include "http2.inl"
  5672. /* Not supported with HTTP/2 */
  5673. #define HTTP1_only \
  5674. { \
  5675. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5676. http2_must_use_http1(conn); \
  5677. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5678. return; \
  5679. } \
  5680. }
  5681. #else
  5682. #define HTTP1_only
  5683. #endif
  5684. CIVETWEB_API int
  5685. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5686. {
  5687. if (len > INT_MAX) {
  5688. len = INT_MAX;
  5689. }
  5690. if (conn == NULL) {
  5691. return 0;
  5692. }
  5693. if (conn->is_chunked) {
  5694. size_t all_read = 0;
  5695. while (len > 0) {
  5696. if (conn->is_chunked >= 3) {
  5697. /* No more data left to read */
  5698. return 0;
  5699. }
  5700. if (conn->is_chunked != 1) {
  5701. /* Has error */
  5702. return -1;
  5703. }
  5704. if (conn->consumed_content != conn->content_len) {
  5705. /* copy from the current chunk */
  5706. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5707. if (read_ret < 1) {
  5708. /* read error */
  5709. conn->is_chunked = 2;
  5710. return -1;
  5711. }
  5712. all_read += (size_t)read_ret;
  5713. len -= (size_t)read_ret;
  5714. if (conn->consumed_content == conn->content_len) {
  5715. /* Add data bytes in the current chunk have been read,
  5716. * so we are expecting \r\n now. */
  5717. char x[2];
  5718. conn->content_len += 2;
  5719. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5720. || (x[1] != '\n')) {
  5721. /* Protocol violation */
  5722. conn->is_chunked = 2;
  5723. return -1;
  5724. }
  5725. }
  5726. } else {
  5727. /* fetch a new chunk */
  5728. size_t i;
  5729. char lenbuf[64];
  5730. char *end = NULL;
  5731. unsigned long chunkSize = 0;
  5732. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5733. conn->content_len++;
  5734. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5735. lenbuf[i] = 0;
  5736. }
  5737. if ((i > 0) && (lenbuf[i] == ';')) {
  5738. // chunk extension --> skip chars until next CR
  5739. //
  5740. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5741. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5742. //
  5743. // chunk = chunk-size [ chunk-extension ] CRLF
  5744. // chunk-data CRLF
  5745. // ...
  5746. // chunk-extension= *( ";" chunk-ext-name [ "="
  5747. // chunk-ext-val ] )
  5748. do
  5749. ++conn->content_len;
  5750. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5751. && lenbuf[i] != '\r');
  5752. }
  5753. if ((i > 0) && (lenbuf[i] == '\r')
  5754. && (lenbuf[i - 1] != '\r')) {
  5755. continue;
  5756. }
  5757. if ((i > 1) && (lenbuf[i] == '\n')
  5758. && (lenbuf[i - 1] == '\r')) {
  5759. lenbuf[i + 1] = 0;
  5760. chunkSize = strtoul(lenbuf, &end, 16);
  5761. if (chunkSize == 0) {
  5762. /* regular end of content */
  5763. conn->is_chunked = 3;
  5764. }
  5765. break;
  5766. }
  5767. if (!isxdigit((unsigned char)lenbuf[i])) {
  5768. /* illegal character for chunk length */
  5769. conn->is_chunked = 2;
  5770. return -1;
  5771. }
  5772. }
  5773. if ((end == NULL) || (*end != '\r')) {
  5774. /* chunksize not set correctly */
  5775. conn->is_chunked = 2;
  5776. return -1;
  5777. }
  5778. if (conn->is_chunked == 3) {
  5779. /* try discarding trailer for keep-alive */
  5780. // We found the last chunk (length 0) including the
  5781. // CRLF that terminates that chunk. Now follows a possibly
  5782. // empty trailer and a final CRLF.
  5783. //
  5784. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5785. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5786. //
  5787. // Chunked-Body = *chunk
  5788. // last-chunk
  5789. // trailer
  5790. // CRLF
  5791. // ...
  5792. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5793. // ...
  5794. // trailer = *(entity-header CRLF)
  5795. int crlf_count = 2; // one CRLF already determined
  5796. while (crlf_count < 4 && conn->is_chunked == 3) {
  5797. ++conn->content_len;
  5798. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5799. if ((crlf_count == 0 || crlf_count == 2)) {
  5800. if (lenbuf[0] == '\r')
  5801. ++crlf_count;
  5802. else
  5803. crlf_count = 0;
  5804. } else {
  5805. // previous character was a CR
  5806. // --> next character must be LF
  5807. if (lenbuf[0] == '\n')
  5808. ++crlf_count;
  5809. else
  5810. conn->is_chunked = 2;
  5811. }
  5812. } else
  5813. // premature end of trailer
  5814. conn->is_chunked = 2;
  5815. }
  5816. if (conn->is_chunked == 2)
  5817. return -1;
  5818. else
  5819. conn->is_chunked = 4;
  5820. break;
  5821. }
  5822. /* append a new chunk */
  5823. conn->content_len += (int64_t)chunkSize;
  5824. }
  5825. }
  5826. return (int)all_read;
  5827. }
  5828. return mg_read_inner(conn, buf, len);
  5829. }
  5830. CIVETWEB_API int
  5831. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5832. {
  5833. time_t now;
  5834. int n, total, allowed;
  5835. if (conn == NULL) {
  5836. return 0;
  5837. }
  5838. if (len > INT_MAX) {
  5839. return -1;
  5840. }
  5841. /* Mark connection as "data sent" */
  5842. conn->request_state = 10;
  5843. #if defined(USE_HTTP2)
  5844. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5845. http2_data_frame_head(conn, len, 0);
  5846. }
  5847. #endif
  5848. if (conn->throttle > 0) {
  5849. if ((now = time(NULL)) != conn->last_throttle_time) {
  5850. conn->last_throttle_time = now;
  5851. conn->last_throttle_bytes = 0;
  5852. }
  5853. allowed = conn->throttle - conn->last_throttle_bytes;
  5854. if (allowed > (int)len) {
  5855. allowed = (int)len;
  5856. }
  5857. total = push_all(conn->phys_ctx,
  5858. NULL,
  5859. conn->client.sock,
  5860. conn->ssl,
  5861. (const char *)buf,
  5862. allowed);
  5863. if (total == allowed) {
  5864. buf = (const char *)buf + total;
  5865. conn->last_throttle_bytes += total;
  5866. while ((total < (int)len)
  5867. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5868. allowed = (conn->throttle > ((int)len - total))
  5869. ? (int)len - total
  5870. : conn->throttle;
  5871. n = push_all(conn->phys_ctx,
  5872. NULL,
  5873. conn->client.sock,
  5874. conn->ssl,
  5875. (const char *)buf,
  5876. allowed);
  5877. if (n != allowed) {
  5878. break;
  5879. }
  5880. sleep(1);
  5881. conn->last_throttle_bytes = allowed;
  5882. conn->last_throttle_time = time(NULL);
  5883. buf = (const char *)buf + n;
  5884. total += n;
  5885. }
  5886. }
  5887. } else {
  5888. total = push_all(conn->phys_ctx,
  5889. NULL,
  5890. conn->client.sock,
  5891. conn->ssl,
  5892. (const char *)buf,
  5893. (int)len);
  5894. }
  5895. if (total > 0) {
  5896. conn->num_bytes_sent += total;
  5897. }
  5898. return total;
  5899. }
  5900. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5901. CIVETWEB_API int
  5902. mg_send_chunk(struct mg_connection *conn,
  5903. const char *chunk,
  5904. unsigned int chunk_len)
  5905. {
  5906. char lenbuf[16];
  5907. size_t lenbuf_len;
  5908. int ret;
  5909. int t;
  5910. /* First store the length information in a text buffer. */
  5911. sprintf(lenbuf, "%x\r\n", chunk_len);
  5912. lenbuf_len = strlen(lenbuf);
  5913. /* Then send length information, chunk and terminating \r\n. */
  5914. ret = mg_write(conn, lenbuf, lenbuf_len);
  5915. if (ret != (int)lenbuf_len) {
  5916. return -1;
  5917. }
  5918. t = ret;
  5919. ret = mg_write(conn, chunk, chunk_len);
  5920. if (ret != (int)chunk_len) {
  5921. return -1;
  5922. }
  5923. t += ret;
  5924. ret = mg_write(conn, "\r\n", 2);
  5925. if (ret != 2) {
  5926. return -1;
  5927. }
  5928. t += ret;
  5929. return t;
  5930. }
  5931. #if defined(GCC_DIAGNOSTIC)
  5932. /* This block forwards format strings to printf implementations,
  5933. * so we need to disable the format-nonliteral warning. */
  5934. #pragma GCC diagnostic push
  5935. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5936. #endif
  5937. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5938. static int
  5939. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5940. {
  5941. va_list ap_copy;
  5942. size_t size = MG_BUF_LEN / 4;
  5943. int len = -1;
  5944. *buf = NULL;
  5945. while (len < 0) {
  5946. if (*buf) {
  5947. mg_free(*buf);
  5948. }
  5949. size *= 4;
  5950. *buf = (char *)mg_malloc(size);
  5951. if (!*buf) {
  5952. break;
  5953. }
  5954. va_copy(ap_copy, ap);
  5955. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5956. va_end(ap_copy);
  5957. (*buf)[size - 1] = 0;
  5958. }
  5959. return len;
  5960. }
  5961. /* Print message to buffer. If buffer is large enough to hold the message,
  5962. * return buffer. If buffer is to small, allocate large enough buffer on
  5963. * heap,
  5964. * and return allocated buffer. */
  5965. static int
  5966. alloc_vprintf(char **out_buf,
  5967. char *prealloc_buf,
  5968. size_t prealloc_size,
  5969. const char *fmt,
  5970. va_list ap)
  5971. {
  5972. va_list ap_copy;
  5973. int len;
  5974. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5975. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5976. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5977. * Therefore, we make two passes: on first pass, get required message
  5978. * length.
  5979. * On second pass, actually print the message. */
  5980. va_copy(ap_copy, ap);
  5981. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5982. va_end(ap_copy);
  5983. if (len < 0) {
  5984. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5985. * Switch to alternative code path that uses incremental
  5986. * allocations.
  5987. */
  5988. va_copy(ap_copy, ap);
  5989. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5990. va_end(ap_copy);
  5991. } else if ((size_t)(len) >= prealloc_size) {
  5992. /* The pre-allocated buffer not large enough. */
  5993. /* Allocate a new buffer. */
  5994. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5995. if (!*out_buf) {
  5996. /* Allocation failed. Return -1 as "out of memory" error. */
  5997. return -1;
  5998. }
  5999. /* Buffer allocation successful. Store the string there. */
  6000. va_copy(ap_copy, ap);
  6001. IGNORE_UNUSED_RESULT(
  6002. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6003. va_end(ap_copy);
  6004. } else {
  6005. /* The pre-allocated buffer is large enough.
  6006. * Use it to store the string and return the address. */
  6007. va_copy(ap_copy, ap);
  6008. IGNORE_UNUSED_RESULT(
  6009. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6010. va_end(ap_copy);
  6011. *out_buf = prealloc_buf;
  6012. }
  6013. return len;
  6014. }
  6015. static int
  6016. alloc_printf(char **out_buf, const char *fmt, ...)
  6017. {
  6018. va_list ap;
  6019. int result;
  6020. va_start(ap, fmt);
  6021. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6022. va_end(ap);
  6023. return result;
  6024. }
  6025. #if defined(GCC_DIAGNOSTIC)
  6026. /* Enable format-nonliteral warning again. */
  6027. #pragma GCC diagnostic pop
  6028. #endif
  6029. static int
  6030. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6031. {
  6032. char mem[MG_BUF_LEN];
  6033. char *buf = NULL;
  6034. int len;
  6035. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6036. len = mg_write(conn, buf, (size_t)len);
  6037. }
  6038. if (buf != mem) {
  6039. mg_free(buf);
  6040. }
  6041. return len;
  6042. }
  6043. CIVETWEB_API int
  6044. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6045. {
  6046. va_list ap;
  6047. int result;
  6048. va_start(ap, fmt);
  6049. result = mg_vprintf(conn, fmt, ap);
  6050. va_end(ap);
  6051. return result;
  6052. }
  6053. CIVETWEB_API int
  6054. mg_url_decode(const char *src,
  6055. int src_len,
  6056. char *dst,
  6057. int dst_len,
  6058. int is_form_url_encoded)
  6059. {
  6060. int i, j, a, b;
  6061. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6062. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6063. if ((i < src_len - 2) && (src[i] == '%')
  6064. && isxdigit((unsigned char)src[i + 1])
  6065. && isxdigit((unsigned char)src[i + 2])) {
  6066. a = tolower((unsigned char)src[i + 1]);
  6067. b = tolower((unsigned char)src[i + 2]);
  6068. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6069. i += 2;
  6070. } else if (is_form_url_encoded && (src[i] == '+')) {
  6071. dst[j] = ' ';
  6072. } else {
  6073. dst[j] = src[i];
  6074. }
  6075. }
  6076. dst[j] = '\0'; /* Null-terminate the destination */
  6077. return (i >= src_len) ? j : -1;
  6078. }
  6079. /* form url decoding of an entire string */
  6080. static void
  6081. url_decode_in_place(char *buf)
  6082. {
  6083. int len = (int)strlen(buf);
  6084. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6085. }
  6086. CIVETWEB_API int
  6087. mg_get_var(const char *data,
  6088. size_t data_len,
  6089. const char *name,
  6090. char *dst,
  6091. size_t dst_len)
  6092. {
  6093. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6094. }
  6095. CIVETWEB_API int
  6096. mg_get_var2(const char *data,
  6097. size_t data_len,
  6098. const char *name,
  6099. char *dst,
  6100. size_t dst_len,
  6101. size_t occurrence)
  6102. {
  6103. const char *p, *e, *s;
  6104. size_t name_len;
  6105. int len;
  6106. if ((dst == NULL) || (dst_len == 0)) {
  6107. len = -2;
  6108. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6109. len = -1;
  6110. dst[0] = '\0';
  6111. } else {
  6112. name_len = strlen(name);
  6113. e = data + data_len;
  6114. len = -1;
  6115. dst[0] = '\0';
  6116. /* data is "var1=val1&var2=val2...". Find variable first */
  6117. for (p = data; p + name_len < e; p++) {
  6118. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6119. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6120. /* Point p to variable value */
  6121. p += name_len + 1;
  6122. /* Point s to the end of the value */
  6123. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6124. if (s == NULL) {
  6125. s = e;
  6126. }
  6127. DEBUG_ASSERT(s >= p);
  6128. if (s < p) {
  6129. return -3;
  6130. }
  6131. /* Decode variable into destination buffer */
  6132. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6133. /* Redirect error code from -1 to -2 (destination buffer too
  6134. * small). */
  6135. if (len == -1) {
  6136. len = -2;
  6137. }
  6138. break;
  6139. }
  6140. }
  6141. }
  6142. return len;
  6143. }
  6144. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6145. CIVETWEB_API int
  6146. mg_split_form_urlencoded(char *data,
  6147. struct mg_header *form_fields,
  6148. unsigned num_form_fields)
  6149. {
  6150. char *b;
  6151. int i;
  6152. int num = 0;
  6153. if (data == NULL) {
  6154. /* parameter error */
  6155. return -1;
  6156. }
  6157. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6158. /* determine the number of expected fields */
  6159. if (data[0] == 0) {
  6160. return 0;
  6161. }
  6162. /* count number of & to return the number of key-value-pairs */
  6163. num = 1;
  6164. while (*data) {
  6165. if (*data == '&') {
  6166. num++;
  6167. }
  6168. data++;
  6169. }
  6170. return num;
  6171. }
  6172. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6173. /* parameter error */
  6174. return -1;
  6175. }
  6176. for (i = 0; i < (int)num_form_fields; i++) {
  6177. /* extract key-value pairs from input data */
  6178. while ((*data == ' ') || (*data == '\t')) {
  6179. /* skip initial spaces */
  6180. data++;
  6181. }
  6182. if (*data == 0) {
  6183. /* end of string reached */
  6184. break;
  6185. }
  6186. form_fields[num].name = data;
  6187. /* find & or = */
  6188. b = data;
  6189. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6190. b++;
  6191. }
  6192. if (*b == 0) {
  6193. /* last key without value */
  6194. form_fields[num].value = NULL;
  6195. } else if (*b == '&') {
  6196. /* mid key without value */
  6197. form_fields[num].value = NULL;
  6198. } else {
  6199. /* terminate string */
  6200. *b = 0;
  6201. /* value starts after '=' */
  6202. data = b + 1;
  6203. form_fields[num].value = data;
  6204. }
  6205. /* new field is stored */
  6206. num++;
  6207. /* find a next key */
  6208. b = strchr(data, '&');
  6209. if (b == 0) {
  6210. /* no more data */
  6211. break;
  6212. } else {
  6213. /* terminate value of last field at '&' */
  6214. *b = 0;
  6215. /* next key-value-pairs starts after '&' */
  6216. data = b + 1;
  6217. }
  6218. }
  6219. /* Decode all values */
  6220. for (i = 0; i < num; i++) {
  6221. if (form_fields[i].name) {
  6222. url_decode_in_place((char *)form_fields[i].name);
  6223. }
  6224. if (form_fields[i].value) {
  6225. url_decode_in_place((char *)form_fields[i].value);
  6226. }
  6227. }
  6228. /* return number of fields found */
  6229. return num;
  6230. }
  6231. /* HCP24: some changes to compare whole var_name */
  6232. CIVETWEB_API int
  6233. mg_get_cookie(const char *cookie_header,
  6234. const char *var_name,
  6235. char *dst,
  6236. size_t dst_size)
  6237. {
  6238. const char *s, *p, *end;
  6239. int name_len, len = -1;
  6240. if ((dst == NULL) || (dst_size == 0)) {
  6241. return -2;
  6242. }
  6243. dst[0] = '\0';
  6244. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6245. return -1;
  6246. }
  6247. name_len = (int)strlen(var_name);
  6248. end = s + strlen(s);
  6249. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6250. if (s[name_len] == '=') {
  6251. /* HCP24: now check is it a substring or a full cookie name */
  6252. if ((s == cookie_header) || (s[-1] == ' ')) {
  6253. s += name_len + 1;
  6254. if ((p = strchr(s, ' ')) == NULL) {
  6255. p = end;
  6256. }
  6257. if (p[-1] == ';') {
  6258. p--;
  6259. }
  6260. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6261. s++;
  6262. p--;
  6263. }
  6264. if ((size_t)(p - s) < dst_size) {
  6265. len = (int)(p - s);
  6266. mg_strlcpy(dst, s, (size_t)len + 1);
  6267. } else {
  6268. len = -3;
  6269. }
  6270. break;
  6271. }
  6272. }
  6273. }
  6274. return len;
  6275. }
  6276. CIVETWEB_API int
  6277. mg_base64_encode(const unsigned char *src,
  6278. size_t src_len,
  6279. char *dst,
  6280. size_t *dst_len)
  6281. {
  6282. static const char *b64 =
  6283. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6284. size_t i, j;
  6285. int a, b, c;
  6286. if (dst_len != NULL) {
  6287. /* Expected length including 0 termination: */
  6288. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6289. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6290. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6291. if (*dst_len < expected_len) {
  6292. if (*dst_len > 0) {
  6293. dst[0] = '\0';
  6294. }
  6295. *dst_len = expected_len;
  6296. return 0;
  6297. }
  6298. }
  6299. for (i = j = 0; i < src_len; i += 3) {
  6300. a = src[i];
  6301. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6302. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6303. dst[j++] = b64[a >> 2];
  6304. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6305. if (i + 1 < src_len) {
  6306. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6307. }
  6308. if (i + 2 < src_len) {
  6309. dst[j++] = b64[c & 63];
  6310. }
  6311. }
  6312. while (j % 4 != 0) {
  6313. dst[j++] = '=';
  6314. }
  6315. dst[j++] = '\0';
  6316. if (dst_len != NULL) {
  6317. *dst_len = (size_t)j;
  6318. }
  6319. /* Return -1 for "OK" */
  6320. return -1;
  6321. }
  6322. static unsigned char
  6323. b64reverse(char letter)
  6324. {
  6325. if ((letter >= 'A') && (letter <= 'Z')) {
  6326. return (unsigned char)(letter - 'A');
  6327. }
  6328. if ((letter >= 'a') && (letter <= 'z')) {
  6329. return (unsigned char)(letter - 'a' + 26);
  6330. }
  6331. if ((letter >= '0') && (letter <= '9')) {
  6332. return (unsigned char)(letter - '0' + 52);
  6333. }
  6334. if (letter == '+') {
  6335. return 62;
  6336. }
  6337. if (letter == '/') {
  6338. return 63;
  6339. }
  6340. if (letter == '=') {
  6341. return 255; /* normal end */
  6342. }
  6343. return 254; /* error */
  6344. }
  6345. CIVETWEB_API int
  6346. mg_base64_decode(const char *src,
  6347. size_t src_len,
  6348. unsigned char *dst,
  6349. size_t *dst_len)
  6350. {
  6351. size_t i;
  6352. unsigned char a, b, c, d;
  6353. size_t dst_len_limit = (size_t)-1;
  6354. size_t dst_len_used = 0;
  6355. if (dst_len != NULL) {
  6356. dst_len_limit = *dst_len;
  6357. *dst_len = 0;
  6358. }
  6359. for (i = 0; i < src_len; i += 4) {
  6360. /* Read 4 characters from BASE64 string */
  6361. a = b64reverse(src[i]);
  6362. if (a >= 254) {
  6363. return (int)i;
  6364. }
  6365. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6366. if (b >= 254) {
  6367. return (int)i + 1;
  6368. }
  6369. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6370. if (c == 254) {
  6371. return (int)i + 2;
  6372. }
  6373. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6374. if (d == 254) {
  6375. return (int)i + 3;
  6376. }
  6377. /* Add first (of 3) decoded character */
  6378. if (dst_len_used < dst_len_limit) {
  6379. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6380. + (unsigned char)(b >> 4));
  6381. }
  6382. dst_len_used++;
  6383. if (c != 255) {
  6384. if (dst_len_used < dst_len_limit) {
  6385. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6386. + (unsigned char)(c >> 2));
  6387. }
  6388. dst_len_used++;
  6389. if (d != 255) {
  6390. if (dst_len_used < dst_len_limit) {
  6391. dst[dst_len_used] =
  6392. (unsigned char)((unsigned char)(c << 6) + d);
  6393. }
  6394. dst_len_used++;
  6395. }
  6396. }
  6397. }
  6398. /* Add terminating zero */
  6399. if (dst_len_used < dst_len_limit) {
  6400. dst[dst_len_used] = '\0';
  6401. }
  6402. dst_len_used++;
  6403. if (dst_len != NULL) {
  6404. *dst_len = dst_len_used;
  6405. }
  6406. if (dst_len_used > dst_len_limit) {
  6407. /* Out of memory */
  6408. return 0;
  6409. }
  6410. /* Return -1 for "OK" */
  6411. return -1;
  6412. }
  6413. static int
  6414. is_put_or_delete_method(const struct mg_connection *conn)
  6415. {
  6416. if (conn) {
  6417. const char *s = conn->request_info.request_method;
  6418. if (s != NULL) {
  6419. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6420. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6421. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6422. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6423. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6424. || !strcmp(s, "COPY"));
  6425. }
  6426. }
  6427. return 0;
  6428. }
  6429. static int
  6430. is_civetweb_webdav_method(const struct mg_connection *conn)
  6431. {
  6432. /* Note: Here we only have to identify the WebDav methods that need special
  6433. * handling in the CivetWeb code - not all methods used in WebDav. In
  6434. * particular, methods used on directories (when using Windows Explorer as
  6435. * WebDav client).
  6436. */
  6437. if (conn) {
  6438. const char *s = conn->request_info.request_method;
  6439. if (s != NULL) {
  6440. /* These are the civetweb builtin DAV methods */
  6441. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6442. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6443. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6444. }
  6445. }
  6446. return 0;
  6447. }
  6448. #if !defined(NO_FILES)
  6449. static int
  6450. extention_matches_script(
  6451. struct mg_connection *conn, /* in: request (must be valid) */
  6452. const char *filename /* in: filename (must be valid) */
  6453. )
  6454. {
  6455. #if !defined(NO_CGI)
  6456. int cgi_config_idx, inc, max;
  6457. #endif
  6458. #if defined(USE_LUA)
  6459. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6460. filename)
  6461. > 0) {
  6462. return 1;
  6463. }
  6464. #endif
  6465. #if defined(USE_DUKTAPE)
  6466. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6467. filename)
  6468. > 0) {
  6469. return 1;
  6470. }
  6471. #endif
  6472. #if !defined(NO_CGI)
  6473. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6474. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6475. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6476. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6477. && (match_prefix_strlen(
  6478. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6479. filename)
  6480. > 0)) {
  6481. return 1;
  6482. }
  6483. }
  6484. #endif
  6485. /* filename and conn could be unused, if all preocessor conditions
  6486. * are false (no script language supported). */
  6487. (void)filename;
  6488. (void)conn;
  6489. return 0;
  6490. }
  6491. static int
  6492. extention_matches_template_text(
  6493. struct mg_connection *conn, /* in: request (must be valid) */
  6494. const char *filename /* in: filename (must be valid) */
  6495. )
  6496. {
  6497. #if defined(USE_LUA)
  6498. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6499. filename)
  6500. > 0) {
  6501. return 1;
  6502. }
  6503. #endif
  6504. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6505. > 0) {
  6506. return 1;
  6507. }
  6508. return 0;
  6509. }
  6510. /* For given directory path, substitute it to valid index file.
  6511. * Return 1 if index file has been found, 0 if not found.
  6512. * If the file is found, it's stats is returned in stp. */
  6513. static int
  6514. substitute_index_file_aux(struct mg_connection *conn,
  6515. char *path,
  6516. size_t path_len,
  6517. struct mg_file_stat *filestat)
  6518. {
  6519. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6520. struct vec filename_vec;
  6521. size_t n = strlen(path);
  6522. int found = 0;
  6523. /* The 'path' given to us points to the directory. Remove all trailing
  6524. * directory separator characters from the end of the path, and
  6525. * then append single directory separator character. */
  6526. while ((n > 0) && (path[n - 1] == '/')) {
  6527. n--;
  6528. }
  6529. path[n] = '/';
  6530. /* Traverse index files list. For each entry, append it to the given
  6531. * path and see if the file exists. If it exists, break the loop */
  6532. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6533. /* Ignore too long entries that may overflow path buffer */
  6534. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6535. continue;
  6536. }
  6537. /* Prepare full path to the index file */
  6538. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6539. /* Does it exist? */
  6540. if (mg_stat(conn, path, filestat)) {
  6541. /* Yes it does, break the loop */
  6542. found = 1;
  6543. break;
  6544. }
  6545. }
  6546. /* If no index file exists, restore directory path */
  6547. if (!found) {
  6548. path[n] = '\0';
  6549. }
  6550. return found;
  6551. }
  6552. /* Same as above, except if the first try fails and a fallback-root is
  6553. * configured, we'll try there also */
  6554. static int
  6555. substitute_index_file(struct mg_connection *conn,
  6556. char *path,
  6557. size_t path_len,
  6558. struct mg_file_stat *filestat)
  6559. {
  6560. int ret = substitute_index_file_aux(conn, path, path_len, filestat);
  6561. if (ret == 0) {
  6562. const char *root_prefix = conn->dom_ctx->config[DOCUMENT_ROOT];
  6563. const char *fallback_root_prefix =
  6564. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT];
  6565. if ((root_prefix) && (fallback_root_prefix)) {
  6566. const size_t root_prefix_len = strlen(root_prefix);
  6567. if ((strncmp(path, root_prefix, root_prefix_len) == 0)) {
  6568. char scratch_path[UTF8_PATH_MAX]; /* separate storage, to avoid
  6569. side effects if we fail */
  6570. size_t sub_path_len;
  6571. const size_t fallback_root_prefix_len =
  6572. strlen(fallback_root_prefix);
  6573. const char *sub_path = path + root_prefix_len;
  6574. while (*sub_path == '/') {
  6575. sub_path++;
  6576. }
  6577. sub_path_len = strlen(sub_path);
  6578. if (((fallback_root_prefix_len + 1 + sub_path_len + 1)
  6579. < sizeof(scratch_path))) {
  6580. /* The concatenations below are all safe because we
  6581. * pre-verified string lengths above */
  6582. char *nul;
  6583. strcpy(scratch_path, fallback_root_prefix);
  6584. nul = strchr(scratch_path, '\0');
  6585. if ((nul > scratch_path) && (*(nul - 1) != '/')) {
  6586. *nul++ = '/';
  6587. *nul = '\0';
  6588. }
  6589. strcat(scratch_path, sub_path);
  6590. if (substitute_index_file_aux(conn,
  6591. scratch_path,
  6592. sizeof(scratch_path),
  6593. filestat)) {
  6594. mg_strlcpy(path, scratch_path, path_len);
  6595. return 1;
  6596. }
  6597. }
  6598. }
  6599. }
  6600. }
  6601. return ret;
  6602. }
  6603. #endif
  6604. static void
  6605. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6606. char *filename, /* out: filename */
  6607. size_t filename_buf_len, /* in: size of filename buffer */
  6608. struct mg_file_stat *filestat, /* out: file status structure */
  6609. int *is_found, /* out: file found (directly) */
  6610. int *is_script_resource, /* out: handled by a script? */
  6611. int *is_websocket_request, /* out: websocket connection? */
  6612. int *is_put_or_delete_request, /* out: put/delete a file? */
  6613. int *is_webdav_request, /* out: webdav request? */
  6614. int *is_template_text /* out: SSI file or LSP file? */
  6615. )
  6616. {
  6617. char const *accept_encoding;
  6618. #if !defined(NO_FILES)
  6619. const char *uri = conn->request_info.local_uri;
  6620. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT],
  6621. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT],
  6622. NULL};
  6623. int fileExists = 0;
  6624. const char *rewrite;
  6625. struct vec a, b;
  6626. ptrdiff_t match_len;
  6627. char gz_path[UTF8_PATH_MAX];
  6628. int truncated;
  6629. int i;
  6630. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6631. char *tmp_str;
  6632. size_t tmp_str_len, sep_pos;
  6633. int allow_substitute_script_subresources;
  6634. #endif
  6635. #else
  6636. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6637. #endif
  6638. /* Step 1: Set all initially unknown outputs to zero */
  6639. memset(filestat, 0, sizeof(*filestat));
  6640. *filename = 0;
  6641. *is_found = 0;
  6642. *is_script_resource = 0;
  6643. *is_template_text = 0;
  6644. /* Step 2: Classify the request method */
  6645. /* Step 2a: Check if the request attempts to modify the file system */
  6646. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6647. /* Step 2b: Check if the request uses WebDav method that requires special
  6648. * handling */
  6649. *is_webdav_request = is_civetweb_webdav_method(conn);
  6650. /* Step 3: Check if it is a websocket request, and modify the document
  6651. * root if required */
  6652. #if defined(USE_WEBSOCKET)
  6653. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6654. #if !defined(NO_FILES)
  6655. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6656. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6657. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6658. }
  6659. #endif /* !NO_FILES */
  6660. #else /* USE_WEBSOCKET */
  6661. *is_websocket_request = 0;
  6662. #endif /* USE_WEBSOCKET */
  6663. /* Step 4: Check if gzip encoded response is allowed */
  6664. conn->accept_gzip = 0;
  6665. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6666. if (strstr(accept_encoding, "gzip") != NULL) {
  6667. conn->accept_gzip = 1;
  6668. }
  6669. }
  6670. #if !defined(NO_FILES)
  6671. /* Step 5: If there is no root directory, don't look for files. */
  6672. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6673. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6674. * config is not required. */
  6675. if (roots[0] == NULL) {
  6676. /* all file related outputs have already been set to 0, just return
  6677. */
  6678. return;
  6679. }
  6680. for (i = 0; roots[i] != NULL; i++) {
  6681. /* Step 6: Determine the local file path from the root path and the
  6682. * request uri. */
  6683. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6684. * part of the path one byte on the right. */
  6685. truncated = 0;
  6686. mg_snprintf(conn,
  6687. &truncated,
  6688. filename,
  6689. filename_buf_len - 1,
  6690. "%s%s",
  6691. roots[i],
  6692. uri);
  6693. if (truncated) {
  6694. goto interpret_cleanup;
  6695. }
  6696. /* Step 7: URI rewriting */
  6697. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6698. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6699. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6700. mg_snprintf(conn,
  6701. &truncated,
  6702. filename,
  6703. filename_buf_len - 1,
  6704. "%.*s%s",
  6705. (int)b.len,
  6706. b.ptr,
  6707. uri + match_len);
  6708. break;
  6709. }
  6710. }
  6711. if (truncated) {
  6712. goto interpret_cleanup;
  6713. }
  6714. /* Step 8: Check if the file exists at the server */
  6715. /* Local file path and name, corresponding to requested URI
  6716. * is now stored in "filename" variable. */
  6717. if (mg_stat(conn, filename, filestat)) {
  6718. fileExists = 1;
  6719. break;
  6720. }
  6721. }
  6722. if (fileExists) {
  6723. int uri_len = (int)strlen(uri);
  6724. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6725. /* 8.1: File exists. */
  6726. *is_found = 1;
  6727. /* 8.2: Check if it is a script type. */
  6728. if (extention_matches_script(conn, filename)) {
  6729. /* The request addresses a CGI resource, Lua script or
  6730. * server-side javascript.
  6731. * The URI corresponds to the script itself (like
  6732. * /path/script.cgi), and there is no additional resource
  6733. * path (like /path/script.cgi/something).
  6734. * Requests that modify (replace or delete) a resource, like
  6735. * PUT and DELETE requests, should replace/delete the script
  6736. * file.
  6737. * Requests that read or write from/to a resource, like GET and
  6738. * POST requests, should call the script and return the
  6739. * generated response. */
  6740. *is_script_resource = (!*is_put_or_delete_request);
  6741. }
  6742. /* 8.3: Check for SSI and LSP files */
  6743. if (extention_matches_template_text(conn, filename)) {
  6744. /* Same as above, but for *.lsp and *.shtml files. */
  6745. /* A "template text" is a file delivered directly to the client,
  6746. * but with some text tags replaced by dynamic content.
  6747. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6748. * (LP, LSP) file. */
  6749. *is_template_text = (!*is_put_or_delete_request);
  6750. }
  6751. /* 8.4: If the request target is a directory, there could be
  6752. * a substitute file (index.html, index.cgi, ...). */
  6753. /* But do not substitute a directory for a WebDav request */
  6754. if (filestat->is_directory && is_uri_end_slash
  6755. && (!*is_webdav_request)) {
  6756. /* Use a local copy here, since substitute_index_file will
  6757. * change the content of the file status */
  6758. struct mg_file_stat tmp_filestat;
  6759. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6760. if (substitute_index_file(
  6761. conn, filename, filename_buf_len, &tmp_filestat)) {
  6762. /* Substitute file found. Copy stat to the output, then
  6763. * check if the file is a script file */
  6764. *filestat = tmp_filestat;
  6765. if (extention_matches_script(conn, filename)) {
  6766. /* Substitute file is a script file */
  6767. *is_script_resource = 1;
  6768. } else if (extention_matches_template_text(conn, filename)) {
  6769. /* Substitute file is a LSP or SSI file */
  6770. *is_template_text = 1;
  6771. } else {
  6772. /* Substitute file is a regular file */
  6773. *is_script_resource = 0;
  6774. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6775. }
  6776. }
  6777. /* If there is no substitute file, the server could return
  6778. * a directory listing in a later step */
  6779. }
  6780. return;
  6781. }
  6782. /* Step 9: Check for zipped files: */
  6783. /* If we can't find the actual file, look for the file
  6784. * with the same name but a .gz extension. If we find it,
  6785. * use that and set the gzipped flag in the file struct
  6786. * to indicate that the response need to have the content-
  6787. * encoding: gzip header.
  6788. * We can only do this if the browser declares support. */
  6789. if (conn->accept_gzip) {
  6790. mg_snprintf(
  6791. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6792. if (truncated) {
  6793. goto interpret_cleanup;
  6794. }
  6795. if (mg_stat(conn, gz_path, filestat)) {
  6796. if (filestat) {
  6797. filestat->is_gzipped = 1;
  6798. *is_found = 1;
  6799. }
  6800. /* Currently gz files can not be scripts. */
  6801. return;
  6802. }
  6803. }
  6804. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6805. /* Step 10: Script resources may handle sub-resources */
  6806. /* Support PATH_INFO for CGI scripts. */
  6807. tmp_str_len = strlen(filename);
  6808. tmp_str =
  6809. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6810. if (!tmp_str) {
  6811. /* Out of memory */
  6812. goto interpret_cleanup;
  6813. }
  6814. memcpy(tmp_str, filename, tmp_str_len + 1);
  6815. /* Check config, if index scripts may have sub-resources */
  6816. allow_substitute_script_subresources =
  6817. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6818. "yes");
  6819. if (*is_webdav_request) {
  6820. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6821. * PROPFIND for their subresources? */
  6822. /* allow_substitute_script_subresources = 0; */
  6823. }
  6824. sep_pos = tmp_str_len;
  6825. while (sep_pos > 0) {
  6826. sep_pos--;
  6827. if (tmp_str[sep_pos] == '/') {
  6828. int is_script = 0, does_exist = 0;
  6829. tmp_str[sep_pos] = 0;
  6830. if (tmp_str[0]) {
  6831. is_script = extention_matches_script(conn, tmp_str);
  6832. does_exist = mg_stat(conn, tmp_str, filestat);
  6833. }
  6834. if (does_exist && is_script) {
  6835. filename[sep_pos] = 0;
  6836. memmove(filename + sep_pos + 2,
  6837. filename + sep_pos + 1,
  6838. strlen(filename + sep_pos + 1) + 1);
  6839. conn->path_info = filename + sep_pos + 1;
  6840. filename[sep_pos + 1] = '/';
  6841. *is_script_resource = 1;
  6842. *is_found = 1;
  6843. break;
  6844. }
  6845. if (allow_substitute_script_subresources) {
  6846. if (substitute_index_file(
  6847. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6848. /* some intermediate directory has an index file */
  6849. if (extention_matches_script(conn, tmp_str)) {
  6850. size_t script_name_len = strlen(tmp_str);
  6851. /* subres_name read before this memory locatio will be
  6852. overwritten */
  6853. char *subres_name = filename + sep_pos;
  6854. size_t subres_name_len = strlen(subres_name);
  6855. DEBUG_TRACE("Substitute script %s serving path %s",
  6856. tmp_str,
  6857. filename);
  6858. /* this index file is a script */
  6859. if ((script_name_len + subres_name_len + 2)
  6860. >= filename_buf_len) {
  6861. mg_free(tmp_str);
  6862. goto interpret_cleanup;
  6863. }
  6864. conn->path_info =
  6865. filename + script_name_len + 1; /* new target */
  6866. memmove(conn->path_info, subres_name, subres_name_len);
  6867. conn->path_info[subres_name_len] = 0;
  6868. memcpy(filename, tmp_str, script_name_len + 1);
  6869. *is_script_resource = 1;
  6870. *is_found = 1;
  6871. break;
  6872. } else {
  6873. DEBUG_TRACE("Substitute file %s serving path %s",
  6874. tmp_str,
  6875. filename);
  6876. /* non-script files will not have sub-resources */
  6877. filename[sep_pos] = 0;
  6878. conn->path_info = 0;
  6879. *is_script_resource = 0;
  6880. *is_found = 0;
  6881. break;
  6882. }
  6883. }
  6884. }
  6885. tmp_str[sep_pos] = '/';
  6886. }
  6887. }
  6888. mg_free(tmp_str);
  6889. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6890. #endif /* !defined(NO_FILES) */
  6891. return;
  6892. #if !defined(NO_FILES)
  6893. /* Reset all outputs */
  6894. interpret_cleanup:
  6895. memset(filestat, 0, sizeof(*filestat));
  6896. *filename = 0;
  6897. *is_found = 0;
  6898. *is_script_resource = 0;
  6899. *is_websocket_request = 0;
  6900. *is_put_or_delete_request = 0;
  6901. #endif /* !defined(NO_FILES) */
  6902. }
  6903. /* Check whether full request is buffered. Return:
  6904. * -1 if request or response is malformed
  6905. * 0 if request or response is not yet fully buffered
  6906. * >0 actual request length, including last \r\n\r\n */
  6907. static int
  6908. get_http_header_len(const char *buf, int buflen)
  6909. {
  6910. int i;
  6911. for (i = 0; i < buflen; i++) {
  6912. /* Do an unsigned comparison in some conditions below */
  6913. const unsigned char c = (unsigned char)buf[i];
  6914. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6915. && !isprint(c)) {
  6916. /* abort scan as soon as one malformed character is found */
  6917. return -1;
  6918. }
  6919. if (i < buflen - 1) {
  6920. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6921. /* Two newline, no carriage return - not standard compliant,
  6922. * but it should be accepted */
  6923. return i + 2;
  6924. }
  6925. }
  6926. if (i < buflen - 3) {
  6927. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6928. && (buf[i + 3] == '\n')) {
  6929. /* Two \r\n - standard compliant */
  6930. return i + 4;
  6931. }
  6932. }
  6933. }
  6934. return 0;
  6935. }
  6936. #if !defined(NO_CACHING)
  6937. /* Convert month to the month number. Return -1 on error, or month number */
  6938. static int
  6939. get_month_index(const char *s)
  6940. {
  6941. size_t i;
  6942. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6943. if (!strcmp(s, month_names[i])) {
  6944. return (int)i;
  6945. }
  6946. }
  6947. return -1;
  6948. }
  6949. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6950. static time_t
  6951. parse_date_string(const char *datetime)
  6952. {
  6953. char month_str[32] = {0};
  6954. int second, minute, hour, day, month, year;
  6955. time_t result = (time_t)0;
  6956. struct tm tm;
  6957. if ((sscanf(datetime,
  6958. "%d/%3s/%d %d:%d:%d",
  6959. &day,
  6960. month_str,
  6961. &year,
  6962. &hour,
  6963. &minute,
  6964. &second)
  6965. == 6)
  6966. || (sscanf(datetime,
  6967. "%d %3s %d %d:%d:%d",
  6968. &day,
  6969. month_str,
  6970. &year,
  6971. &hour,
  6972. &minute,
  6973. &second)
  6974. == 6)
  6975. || (sscanf(datetime,
  6976. "%*3s, %d %3s %d %d:%d:%d",
  6977. &day,
  6978. month_str,
  6979. &year,
  6980. &hour,
  6981. &minute,
  6982. &second)
  6983. == 6)
  6984. || (sscanf(datetime,
  6985. "%d-%3s-%d %d:%d:%d",
  6986. &day,
  6987. month_str,
  6988. &year,
  6989. &hour,
  6990. &minute,
  6991. &second)
  6992. == 6)) {
  6993. month = get_month_index(month_str);
  6994. if ((month >= 0) && (year >= 1970)) {
  6995. memset(&tm, 0, sizeof(tm));
  6996. tm.tm_year = year - 1900;
  6997. tm.tm_mon = month;
  6998. tm.tm_mday = day;
  6999. tm.tm_hour = hour;
  7000. tm.tm_min = minute;
  7001. tm.tm_sec = second;
  7002. result = timegm(&tm);
  7003. }
  7004. }
  7005. return result;
  7006. }
  7007. #endif /* !NO_CACHING */
  7008. /* Pre-process URIs according to RFC + protect against directory disclosure
  7009. * attacks by removing '..', excessive '/' and '\' characters */
  7010. static void
  7011. remove_dot_segments(char *inout)
  7012. {
  7013. /* Windows backend protection
  7014. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7015. * in URI by slash */
  7016. char *out_end = inout;
  7017. char *in = inout;
  7018. if (!in) {
  7019. /* Param error. */
  7020. return;
  7021. }
  7022. while (*in) {
  7023. if (*in == '\\') {
  7024. *in = '/';
  7025. }
  7026. in++;
  7027. }
  7028. /* Algorithm "remove_dot_segments" from
  7029. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7030. /* Step 1:
  7031. * The input buffer is initialized.
  7032. * The output buffer is initialized to the empty string.
  7033. */
  7034. in = inout;
  7035. /* Step 2:
  7036. * While the input buffer is not empty, loop as follows:
  7037. */
  7038. /* Less than out_end of the inout buffer is used as output, so keep
  7039. * condition: out_end <= in */
  7040. while (*in) {
  7041. /* Step 2a:
  7042. * If the input buffer begins with a prefix of "../" or "./",
  7043. * then remove that prefix from the input buffer;
  7044. */
  7045. if (!strncmp(in, "../", 3)) {
  7046. in += 3;
  7047. } else if (!strncmp(in, "./", 2)) {
  7048. in += 2;
  7049. }
  7050. /* otherwise */
  7051. /* Step 2b:
  7052. * if the input buffer begins with a prefix of "/./" or "/.",
  7053. * where "." is a complete path segment, then replace that
  7054. * prefix with "/" in the input buffer;
  7055. */
  7056. else if (!strncmp(in, "/./", 3)) {
  7057. in += 2;
  7058. } else if (!strcmp(in, "/.")) {
  7059. in[1] = 0;
  7060. }
  7061. /* otherwise */
  7062. /* Step 2c:
  7063. * if the input buffer begins with a prefix of "/../" or "/..",
  7064. * where ".." is a complete path segment, then replace that
  7065. * prefix with "/" in the input buffer and remove the last
  7066. * segment and its preceding "/" (if any) from the output
  7067. * buffer;
  7068. */
  7069. else if (!strncmp(in, "/../", 4)) {
  7070. in += 3;
  7071. if (inout != out_end) {
  7072. /* remove last segment */
  7073. do {
  7074. out_end--;
  7075. } while ((inout != out_end) && (*out_end != '/'));
  7076. }
  7077. } else if (!strcmp(in, "/..")) {
  7078. in[1] = 0;
  7079. if (inout != out_end) {
  7080. /* remove last segment */
  7081. do {
  7082. out_end--;
  7083. } while ((inout != out_end) && (*out_end != '/'));
  7084. }
  7085. }
  7086. /* otherwise */
  7087. /* Step 2d:
  7088. * if the input buffer consists only of "." or "..", then remove
  7089. * that from the input buffer;
  7090. */
  7091. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7092. *in = 0;
  7093. }
  7094. /* otherwise */
  7095. /* Step 2e:
  7096. * move the first path segment in the input buffer to the end of
  7097. * the output buffer, including the initial "/" character (if
  7098. * any) and any subsequent characters up to, but not including,
  7099. * the next "/" character or the end of the input buffer.
  7100. */
  7101. else {
  7102. do {
  7103. *out_end = *in;
  7104. out_end++;
  7105. in++;
  7106. } while ((*in != 0) && (*in != '/'));
  7107. }
  7108. }
  7109. /* Step 3:
  7110. * Finally, the output buffer is returned as the result of
  7111. * remove_dot_segments.
  7112. */
  7113. /* Terminate output */
  7114. *out_end = 0;
  7115. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7116. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7117. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7118. * or "//" anymore.
  7119. */
  7120. out_end = in = inout;
  7121. while (*in) {
  7122. if (*in == '.') {
  7123. /* remove . at the end or preceding of / */
  7124. char *in_ahead = in;
  7125. do {
  7126. in_ahead++;
  7127. } while (*in_ahead == '.');
  7128. if (*in_ahead == '/') {
  7129. in = in_ahead;
  7130. if ((out_end != inout) && (out_end[-1] == '/')) {
  7131. /* remove generated // */
  7132. out_end--;
  7133. }
  7134. } else if (*in_ahead == 0) {
  7135. in = in_ahead;
  7136. } else {
  7137. do {
  7138. *out_end++ = '.';
  7139. in++;
  7140. } while (in != in_ahead);
  7141. }
  7142. } else if (*in == '/') {
  7143. /* replace // by / */
  7144. *out_end++ = '/';
  7145. do {
  7146. in++;
  7147. } while (*in == '/');
  7148. } else {
  7149. *out_end++ = *in;
  7150. in++;
  7151. }
  7152. }
  7153. *out_end = 0;
  7154. }
  7155. static const struct {
  7156. const char *extension;
  7157. size_t ext_len;
  7158. const char *mime_type;
  7159. } builtin_mime_types[] = {
  7160. /* IANA registered MIME types
  7161. * (http://www.iana.org/assignments/media-types)
  7162. * application types */
  7163. {".bin", 4, "application/octet-stream"},
  7164. {".deb", 4, "application/octet-stream"},
  7165. {".dmg", 4, "application/octet-stream"},
  7166. {".dll", 4, "application/octet-stream"},
  7167. {".doc", 4, "application/msword"},
  7168. {".eps", 4, "application/postscript"},
  7169. {".exe", 4, "application/octet-stream"},
  7170. {".iso", 4, "application/octet-stream"},
  7171. {".js", 3, "application/javascript"},
  7172. {".json", 5, "application/json"},
  7173. {".mjs", 4, "application/javascript"},
  7174. {".msi", 4, "application/octet-stream"},
  7175. {".pdf", 4, "application/pdf"},
  7176. {".ps", 3, "application/postscript"},
  7177. {".rtf", 4, "application/rtf"},
  7178. {".wasm", 5, "application/wasm"},
  7179. {".xhtml", 6, "application/xhtml+xml"},
  7180. {".xsl", 4, "application/xml"},
  7181. {".xslt", 5, "application/xml"},
  7182. /* fonts */
  7183. {".ttf", 4, "application/font-sfnt"},
  7184. {".cff", 4, "application/font-sfnt"},
  7185. {".otf", 4, "application/font-sfnt"},
  7186. {".aat", 4, "application/font-sfnt"},
  7187. {".sil", 4, "application/font-sfnt"},
  7188. {".pfr", 4, "application/font-tdpfr"},
  7189. {".woff", 5, "application/font-woff"},
  7190. {".woff2", 6, "application/font-woff2"},
  7191. /* audio */
  7192. {".mp3", 4, "audio/mpeg"},
  7193. {".oga", 4, "audio/ogg"},
  7194. {".ogg", 4, "audio/ogg"},
  7195. /* image */
  7196. {".gif", 4, "image/gif"},
  7197. {".ief", 4, "image/ief"},
  7198. {".jpeg", 5, "image/jpeg"},
  7199. {".jpg", 4, "image/jpeg"},
  7200. {".jpm", 4, "image/jpm"},
  7201. {".jpx", 4, "image/jpx"},
  7202. {".png", 4, "image/png"},
  7203. {".svg", 4, "image/svg+xml"},
  7204. {".tif", 4, "image/tiff"},
  7205. {".tiff", 5, "image/tiff"},
  7206. /* model */
  7207. {".wrl", 4, "model/vrml"},
  7208. /* text */
  7209. {".css", 4, "text/css"},
  7210. {".csv", 4, "text/csv"},
  7211. {".htm", 4, "text/html"},
  7212. {".html", 5, "text/html"},
  7213. {".sgm", 4, "text/sgml"},
  7214. {".shtm", 5, "text/html"},
  7215. {".shtml", 6, "text/html"},
  7216. {".txt", 4, "text/plain"},
  7217. {".xml", 4, "text/xml"},
  7218. /* video */
  7219. {".mov", 4, "video/quicktime"},
  7220. {".mp4", 4, "video/mp4"},
  7221. {".mpeg", 5, "video/mpeg"},
  7222. {".mpg", 4, "video/mpeg"},
  7223. {".ogv", 4, "video/ogg"},
  7224. {".qt", 3, "video/quicktime"},
  7225. /* not registered types
  7226. * (http://reference.sitepoint.com/html/mime-types-full,
  7227. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7228. {".arj", 4, "application/x-arj-compressed"},
  7229. {".gz", 3, "application/x-gunzip"},
  7230. {".rar", 4, "application/x-arj-compressed"},
  7231. {".swf", 4, "application/x-shockwave-flash"},
  7232. {".tar", 4, "application/x-tar"},
  7233. {".tgz", 4, "application/x-tar-gz"},
  7234. {".torrent", 8, "application/x-bittorrent"},
  7235. {".ppt", 4, "application/x-mspowerpoint"},
  7236. {".xls", 4, "application/x-msexcel"},
  7237. {".zip", 4, "application/x-zip-compressed"},
  7238. {".aac",
  7239. 4,
  7240. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7241. {".flac", 5, "audio/flac"},
  7242. {".aif", 4, "audio/x-aif"},
  7243. {".m3u", 4, "audio/x-mpegurl"},
  7244. {".mid", 4, "audio/x-midi"},
  7245. {".ra", 3, "audio/x-pn-realaudio"},
  7246. {".ram", 4, "audio/x-pn-realaudio"},
  7247. {".wav", 4, "audio/x-wav"},
  7248. {".bmp", 4, "image/bmp"},
  7249. {".ico", 4, "image/x-icon"},
  7250. {".pct", 4, "image/x-pct"},
  7251. {".pict", 5, "image/pict"},
  7252. {".rgb", 4, "image/x-rgb"},
  7253. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7254. {".asf", 4, "video/x-ms-asf"},
  7255. {".avi", 4, "video/x-msvideo"},
  7256. {".m4v", 4, "video/x-m4v"},
  7257. {NULL, 0, NULL}};
  7258. CIVETWEB_API const char *
  7259. mg_get_builtin_mime_type(const char *path)
  7260. {
  7261. const char *ext;
  7262. size_t i, path_len;
  7263. path_len = strlen(path);
  7264. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7265. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7266. if ((path_len > builtin_mime_types[i].ext_len)
  7267. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7268. return builtin_mime_types[i].mime_type;
  7269. }
  7270. }
  7271. return "text/plain";
  7272. }
  7273. /* Look at the "path" extension and figure what mime type it has.
  7274. * Store mime type in the vector. */
  7275. static void
  7276. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7277. {
  7278. struct vec ext_vec, mime_vec;
  7279. const char *list, *ext;
  7280. size_t path_len;
  7281. path_len = strlen(path);
  7282. if ((conn == NULL) || (vec == NULL)) {
  7283. if (vec != NULL) {
  7284. memset(vec, '\0', sizeof(struct vec));
  7285. }
  7286. return;
  7287. }
  7288. /* Scan user-defined mime types first, in case user wants to
  7289. * override default mime types. */
  7290. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7291. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7292. /* ext now points to the path suffix */
  7293. ext = path + path_len - ext_vec.len;
  7294. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7295. *vec = mime_vec;
  7296. return;
  7297. }
  7298. }
  7299. vec->ptr = mg_get_builtin_mime_type(path);
  7300. vec->len = strlen(vec->ptr);
  7301. }
  7302. /* Stringify binary data. Output buffer must be twice as big as input,
  7303. * because each byte takes 2 bytes in string representation */
  7304. static void
  7305. bin2str(char *to, const unsigned char *p, size_t len)
  7306. {
  7307. static const char *hex = "0123456789abcdef";
  7308. for (; len--; p++) {
  7309. *to++ = hex[p[0] >> 4];
  7310. *to++ = hex[p[0] & 0x0f];
  7311. }
  7312. *to = '\0';
  7313. }
  7314. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7315. */
  7316. CIVETWEB_API char *
  7317. mg_md5(char buf[33], ...)
  7318. {
  7319. md5_byte_t hash[16];
  7320. const char *p;
  7321. va_list ap;
  7322. md5_state_t ctx;
  7323. md5_init(&ctx);
  7324. va_start(ap, buf);
  7325. while ((p = va_arg(ap, const char *)) != NULL) {
  7326. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7327. }
  7328. va_end(ap);
  7329. md5_finish(&ctx, hash);
  7330. bin2str(buf, hash, sizeof(hash));
  7331. return buf;
  7332. }
  7333. /* Check the user's password, return 1 if OK */
  7334. static int
  7335. check_password_digest(const char *method,
  7336. const char *ha1,
  7337. const char *uri,
  7338. const char *nonce,
  7339. const char *nc,
  7340. const char *cnonce,
  7341. const char *qop,
  7342. const char *response)
  7343. {
  7344. char ha2[32 + 1], expected_response[32 + 1];
  7345. /* Some of the parameters may be NULL */
  7346. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7347. || (qop == NULL) || (response == NULL)) {
  7348. return 0;
  7349. }
  7350. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7351. if (strlen(response) != 32) {
  7352. return 0;
  7353. }
  7354. mg_md5(ha2, method, ":", uri, NULL);
  7355. mg_md5(expected_response,
  7356. ha1,
  7357. ":",
  7358. nonce,
  7359. ":",
  7360. nc,
  7361. ":",
  7362. cnonce,
  7363. ":",
  7364. qop,
  7365. ":",
  7366. ha2,
  7367. NULL);
  7368. return mg_strcasecmp(response, expected_response) == 0;
  7369. }
  7370. #if !defined(NO_FILESYSTEMS)
  7371. /* Use the global passwords file, if specified by auth_gpass option,
  7372. * or search for .htpasswd in the requested directory. */
  7373. static void
  7374. open_auth_file(struct mg_connection *conn,
  7375. const char *path,
  7376. struct mg_file *filep)
  7377. {
  7378. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7379. char name[UTF8_PATH_MAX];
  7380. const char *p, *e,
  7381. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7382. int truncated;
  7383. if (gpass != NULL) {
  7384. /* Use global passwords file */
  7385. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7386. #if defined(DEBUG)
  7387. /* Use mg_cry_internal here, since gpass has been
  7388. * configured. */
  7389. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7390. #endif
  7391. }
  7392. /* Important: using local struct mg_file to test path for
  7393. * is_directory flag. If filep is used, mg_stat() makes it
  7394. * appear as if auth file was opened.
  7395. * TODO(mid): Check if this is still required after rewriting
  7396. * mg_stat */
  7397. } else if (mg_stat(conn, path, &filep->stat)
  7398. && filep->stat.is_directory) {
  7399. mg_snprintf(conn,
  7400. &truncated,
  7401. name,
  7402. sizeof(name),
  7403. "%s/%s",
  7404. path,
  7405. PASSWORDS_FILE_NAME);
  7406. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7407. #if defined(DEBUG)
  7408. /* Don't use mg_cry_internal here, but only a trace, since
  7409. * this is a typical case. It will occur for every directory
  7410. * without a password file. */
  7411. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7412. #endif
  7413. }
  7414. } else {
  7415. /* Try to find .htpasswd in requested directory. */
  7416. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7417. if (e[0] == '/') {
  7418. break;
  7419. }
  7420. }
  7421. mg_snprintf(conn,
  7422. &truncated,
  7423. name,
  7424. sizeof(name),
  7425. "%.*s/%s",
  7426. (int)(e - p),
  7427. p,
  7428. PASSWORDS_FILE_NAME);
  7429. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7430. #if defined(DEBUG)
  7431. /* Don't use mg_cry_internal here, but only a trace, since
  7432. * this is a typical case. It will occur for every directory
  7433. * without a password file. */
  7434. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7435. #endif
  7436. }
  7437. }
  7438. }
  7439. }
  7440. #endif /* NO_FILESYSTEMS */
  7441. /* Parsed Authorization header */
  7442. struct auth_header {
  7443. char *user;
  7444. int type; /* 1 = basic, 2 = digest */
  7445. char *plain_password; /* Basic only */
  7446. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7447. };
  7448. /* Return 1 on success. Always initializes the auth_header structure. */
  7449. static int
  7450. parse_auth_header(struct mg_connection *conn,
  7451. char *buf,
  7452. size_t buf_size,
  7453. struct auth_header *auth_header)
  7454. {
  7455. char *name, *value, *s;
  7456. const char *ah;
  7457. uint64_t nonce;
  7458. if (!auth_header || !conn) {
  7459. return 0;
  7460. }
  7461. (void)memset(auth_header, 0, sizeof(*auth_header));
  7462. ah = mg_get_header(conn, "Authorization");
  7463. if (ah == NULL) {
  7464. /* No Authorization header at all */
  7465. return 0;
  7466. }
  7467. if (0 == mg_strncasecmp(ah, "Basic ", 6)) {
  7468. /* Basic Auth (we never asked for this, but some client may send it) */
  7469. char *split;
  7470. const char *userpw_b64 = ah + 6;
  7471. size_t userpw_b64_len = strlen(userpw_b64);
  7472. size_t buf_len_r = buf_size;
  7473. if (mg_base64_decode(
  7474. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7475. != -1) {
  7476. return 0; /* decode error */
  7477. }
  7478. split = strchr(buf, ':');
  7479. if (!split) {
  7480. return 0; /* Format error */
  7481. }
  7482. /* Separate string at ':' */
  7483. *split = 0;
  7484. /* User name is before ':', Password is after ':' */
  7485. auth_header->user = buf;
  7486. auth_header->type = 1;
  7487. auth_header->plain_password = split + 1;
  7488. return 1;
  7489. } else if (0 == mg_strncasecmp(ah, "Digest ", 7)) {
  7490. /* Digest Auth ... implemented below */
  7491. auth_header->type = 2;
  7492. } else {
  7493. /* Unknown or invalid Auth method */
  7494. return 0;
  7495. }
  7496. /* Make modifiable copy of the auth header */
  7497. (void)mg_strlcpy(buf, ah + 7, buf_size);
  7498. s = buf;
  7499. /* Parse authorization header */
  7500. for (;;) {
  7501. /* Gobble initial spaces */
  7502. while (isspace((unsigned char)*s)) {
  7503. s++;
  7504. }
  7505. name = skip_quoted(&s, "=", " ", 0);
  7506. /* Value is either quote-delimited, or ends at first comma or space.
  7507. */
  7508. if (s[0] == '\"') {
  7509. s++;
  7510. value = skip_quoted(&s, "\"", " ", '\\');
  7511. if (s[0] == ',') {
  7512. s++;
  7513. }
  7514. } else {
  7515. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7516. * uses spaces */
  7517. }
  7518. if (*name == '\0') {
  7519. break;
  7520. }
  7521. if (!strcmp(name, "username")) {
  7522. auth_header->user = value;
  7523. } else if (!strcmp(name, "cnonce")) {
  7524. auth_header->cnonce = value;
  7525. } else if (!strcmp(name, "response")) {
  7526. auth_header->response = value;
  7527. } else if (!strcmp(name, "uri")) {
  7528. auth_header->uri = value;
  7529. } else if (!strcmp(name, "qop")) {
  7530. auth_header->qop = value;
  7531. } else if (!strcmp(name, "nc")) {
  7532. auth_header->nc = value;
  7533. } else if (!strcmp(name, "nonce")) {
  7534. auth_header->nonce = value;
  7535. }
  7536. }
  7537. #if !defined(NO_NONCE_CHECK)
  7538. /* Read the nonce from the response. */
  7539. if (auth_header->nonce == NULL) {
  7540. return 0;
  7541. }
  7542. s = NULL;
  7543. nonce = strtoull(auth_header->nonce, &s, 10);
  7544. if ((s == NULL) || (*s != 0)) {
  7545. return 0;
  7546. }
  7547. /* Convert the nonce from the client to a number. */
  7548. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7549. /* The converted number corresponds to the time the nounce has been
  7550. * created. This should not be earlier than the server start. */
  7551. /* Server side nonce check is valuable in all situations but one:
  7552. * if the server restarts frequently, but the client should not see
  7553. * that, so the server should accept nonces from previous starts. */
  7554. /* However, the reasonable default is to not accept a nonce from a
  7555. * previous start, so if anyone changed the access rights between
  7556. * two restarts, a new login is required. */
  7557. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7558. /* nonce is from a previous start of the server and no longer valid
  7559. * (replay attack?) */
  7560. return 0;
  7561. }
  7562. /* Check if the nonce is too high, so it has not (yet) been used by the
  7563. * server. */
  7564. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7565. + conn->dom_ctx->nonce_count)) {
  7566. return 0;
  7567. }
  7568. #else
  7569. (void)nonce;
  7570. #endif
  7571. return (auth_header->user != NULL);
  7572. }
  7573. static const char *
  7574. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7575. {
  7576. if (!filep) {
  7577. return NULL;
  7578. }
  7579. if (filep->access.fp != NULL) {
  7580. return fgets(buf, (int)size, filep->access.fp);
  7581. } else {
  7582. return NULL;
  7583. }
  7584. }
  7585. /* Define the initial recursion depth for procesesing htpasswd files that
  7586. * include other htpasswd
  7587. * (or even the same) files. It is not difficult to provide a file or files
  7588. * s.t. they force civetweb
  7589. * to infinitely recurse and then crash.
  7590. */
  7591. #define INITIAL_DEPTH 9
  7592. #if INITIAL_DEPTH <= 0
  7593. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7594. #endif
  7595. #if !defined(NO_FILESYSTEMS)
  7596. struct read_auth_file_struct {
  7597. struct mg_connection *conn;
  7598. struct auth_header auth_header;
  7599. const char *domain;
  7600. char buf[256 + 256 + 40];
  7601. const char *f_user;
  7602. const char *f_domain;
  7603. const char *f_ha1;
  7604. };
  7605. static int
  7606. read_auth_file(struct mg_file *filep,
  7607. struct read_auth_file_struct *workdata,
  7608. int depth)
  7609. {
  7610. int is_authorized = 0;
  7611. struct mg_file fp;
  7612. size_t l;
  7613. if (!filep || !workdata || (0 == depth)) {
  7614. return 0;
  7615. }
  7616. /* Loop over passwords file */
  7617. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7618. l = strlen(workdata->buf);
  7619. while (l > 0) {
  7620. if (isspace((unsigned char)workdata->buf[l - 1])
  7621. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7622. l--;
  7623. workdata->buf[l] = 0;
  7624. } else
  7625. break;
  7626. }
  7627. if (l < 1) {
  7628. continue;
  7629. }
  7630. workdata->f_user = workdata->buf;
  7631. if (workdata->f_user[0] == ':') {
  7632. /* user names may not contain a ':' and may not be empty,
  7633. * so lines starting with ':' may be used for a special purpose
  7634. */
  7635. if (workdata->f_user[1] == '#') {
  7636. /* :# is a comment */
  7637. continue;
  7638. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7639. if (mg_fopen(workdata->conn,
  7640. workdata->f_user + 9,
  7641. MG_FOPEN_MODE_READ,
  7642. &fp)) {
  7643. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7644. (void)mg_fclose(
  7645. &fp.access); /* ignore error on read only file */
  7646. /* No need to continue processing files once we have a
  7647. * match, since nothing will reset it back
  7648. * to 0.
  7649. */
  7650. if (is_authorized) {
  7651. return is_authorized;
  7652. }
  7653. } else {
  7654. mg_cry_internal(workdata->conn,
  7655. "%s: cannot open authorization file: %s",
  7656. __func__,
  7657. workdata->buf);
  7658. }
  7659. continue;
  7660. }
  7661. /* everything is invalid for the moment (might change in the
  7662. * future) */
  7663. mg_cry_internal(workdata->conn,
  7664. "%s: syntax error in authorization file: %s",
  7665. __func__,
  7666. workdata->buf);
  7667. continue;
  7668. }
  7669. workdata->f_domain = strchr(workdata->f_user, ':');
  7670. if (workdata->f_domain == NULL) {
  7671. mg_cry_internal(workdata->conn,
  7672. "%s: syntax error in authorization file: %s",
  7673. __func__,
  7674. workdata->buf);
  7675. continue;
  7676. }
  7677. *(char *)(workdata->f_domain) = 0;
  7678. (workdata->f_domain)++;
  7679. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7680. if (workdata->f_ha1 == NULL) {
  7681. mg_cry_internal(workdata->conn,
  7682. "%s: syntax error in authorization file: %s",
  7683. __func__,
  7684. workdata->buf);
  7685. continue;
  7686. }
  7687. *(char *)(workdata->f_ha1) = 0;
  7688. (workdata->f_ha1)++;
  7689. if (!strcmp(workdata->auth_header.user, workdata->f_user)
  7690. && !strcmp(workdata->domain, workdata->f_domain)) {
  7691. switch (workdata->auth_header.type) {
  7692. case 1: /* Basic */
  7693. {
  7694. char md5[33];
  7695. mg_md5(md5,
  7696. workdata->f_user,
  7697. ":",
  7698. workdata->domain,
  7699. ":",
  7700. workdata->auth_header.plain_password,
  7701. NULL);
  7702. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7703. }
  7704. case 2: /* Digest */
  7705. return check_password_digest(
  7706. workdata->conn->request_info.request_method,
  7707. workdata->f_ha1,
  7708. workdata->auth_header.uri,
  7709. workdata->auth_header.nonce,
  7710. workdata->auth_header.nc,
  7711. workdata->auth_header.cnonce,
  7712. workdata->auth_header.qop,
  7713. workdata->auth_header.response);
  7714. default: /* None/Other/Unknown */
  7715. return 0;
  7716. }
  7717. }
  7718. }
  7719. return is_authorized;
  7720. }
  7721. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7722. static int
  7723. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7724. {
  7725. struct read_auth_file_struct workdata;
  7726. char buf[MG_BUF_LEN];
  7727. if (!conn || !conn->dom_ctx) {
  7728. return 0;
  7729. }
  7730. memset(&workdata, 0, sizeof(workdata));
  7731. workdata.conn = conn;
  7732. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.auth_header)) {
  7733. return 0;
  7734. }
  7735. /* CGI needs it as REMOTE_USER */
  7736. conn->request_info.remote_user =
  7737. mg_strdup_ctx(workdata.auth_header.user, conn->phys_ctx);
  7738. if (realm) {
  7739. workdata.domain = realm;
  7740. } else {
  7741. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7742. }
  7743. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7744. }
  7745. /* Public function to check http digest authentication header */
  7746. CIVETWEB_API int
  7747. mg_check_digest_access_authentication(struct mg_connection *conn,
  7748. const char *realm,
  7749. const char *filename)
  7750. {
  7751. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7752. int auth;
  7753. if (!conn || !filename) {
  7754. return -1;
  7755. }
  7756. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7757. return -2;
  7758. }
  7759. auth = authorize(conn, &file, realm);
  7760. mg_fclose(&file.access);
  7761. return auth;
  7762. }
  7763. #endif /* NO_FILESYSTEMS */
  7764. /* Return 1 if request is authorised, 0 otherwise. */
  7765. static int
  7766. check_authorization(struct mg_connection *conn, const char *path)
  7767. {
  7768. #if !defined(NO_FILESYSTEMS)
  7769. char fname[UTF8_PATH_MAX];
  7770. struct vec uri_vec, filename_vec;
  7771. const char *list;
  7772. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7773. int authorized = 1, truncated;
  7774. if (!conn || !conn->dom_ctx) {
  7775. return 0;
  7776. }
  7777. list = conn->dom_ctx->config[PROTECT_URI];
  7778. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7779. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7780. mg_snprintf(conn,
  7781. &truncated,
  7782. fname,
  7783. sizeof(fname),
  7784. "%.*s",
  7785. (int)filename_vec.len,
  7786. filename_vec.ptr);
  7787. if (truncated
  7788. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7789. mg_cry_internal(conn,
  7790. "%s: cannot open %s: %s",
  7791. __func__,
  7792. fname,
  7793. strerror(errno));
  7794. }
  7795. break;
  7796. }
  7797. }
  7798. if (!is_file_opened(&file.access)) {
  7799. open_auth_file(conn, path, &file);
  7800. }
  7801. if (is_file_opened(&file.access)) {
  7802. authorized = authorize(conn, &file, NULL);
  7803. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7804. }
  7805. return authorized;
  7806. #else
  7807. (void)conn;
  7808. (void)path;
  7809. return 1;
  7810. #endif /* NO_FILESYSTEMS */
  7811. }
  7812. /* Internal function. Assumes conn is valid */
  7813. static void
  7814. send_authorization_request(struct mg_connection *conn, const char *realm)
  7815. {
  7816. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7817. int trunc = 0;
  7818. char buf[128];
  7819. if (!realm) {
  7820. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7821. }
  7822. mg_lock_context(conn->phys_ctx);
  7823. nonce += conn->dom_ctx->nonce_count;
  7824. ++conn->dom_ctx->nonce_count;
  7825. mg_unlock_context(conn->phys_ctx);
  7826. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7827. conn->must_close = 1;
  7828. /* Create 401 response */
  7829. mg_response_header_start(conn, 401);
  7830. send_no_cache_header(conn);
  7831. send_additional_header(conn);
  7832. mg_response_header_add(conn, "Content-Length", "0", -1);
  7833. /* Content for "WWW-Authenticate" header */
  7834. mg_snprintf(conn,
  7835. &trunc,
  7836. buf,
  7837. sizeof(buf),
  7838. "Digest qop=\"auth\", realm=\"%s\", "
  7839. "nonce=\"%" UINT64_FMT "\"",
  7840. realm,
  7841. nonce);
  7842. if (!trunc) {
  7843. /* !trunc should always be true */
  7844. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7845. }
  7846. /* Send all headers */
  7847. mg_response_header_send(conn);
  7848. }
  7849. /* Interface function. Parameters are provided by the user, so do
  7850. * at least some basic checks.
  7851. */
  7852. CIVETWEB_API int
  7853. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7854. const char *realm)
  7855. {
  7856. if (conn && conn->dom_ctx) {
  7857. send_authorization_request(conn, realm);
  7858. return 0;
  7859. }
  7860. return -1;
  7861. }
  7862. #if !defined(NO_FILES)
  7863. static int
  7864. is_authorized_for_put(struct mg_connection *conn)
  7865. {
  7866. int ret = 0;
  7867. if (conn) {
  7868. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7869. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7870. if (passfile != NULL
  7871. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7872. ret = authorize(conn, &file, NULL);
  7873. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7874. }
  7875. }
  7876. DEBUG_TRACE("file write authorization: %i", ret);
  7877. return ret;
  7878. }
  7879. #endif
  7880. CIVETWEB_API int
  7881. mg_modify_passwords_file_ha1(const char *fname,
  7882. const char *domain,
  7883. const char *user,
  7884. const char *ha1)
  7885. {
  7886. int found = 0, i, result = 1;
  7887. char line[512], u[256], d[256], h[256];
  7888. struct stat st = {0};
  7889. FILE *fp = NULL;
  7890. char *temp_file = NULL;
  7891. int temp_file_offs = 0;
  7892. /* Regard empty password as no password - remove user record. */
  7893. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7894. ha1 = NULL;
  7895. }
  7896. /* Other arguments must not be empty */
  7897. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7898. return 0;
  7899. }
  7900. /* Using the given file format, user name and domain must not contain
  7901. * the ':' character */
  7902. if (strchr(user, ':') != NULL) {
  7903. return 0;
  7904. }
  7905. if (strchr(domain, ':') != NULL) {
  7906. return 0;
  7907. }
  7908. /* Do not allow control characters like newline in user name and domain.
  7909. * Do not allow excessively long names either. */
  7910. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7911. if (iscntrl((unsigned char)user[i])) {
  7912. return 0;
  7913. }
  7914. }
  7915. if (user[i]) {
  7916. return 0; /* user name too long */
  7917. }
  7918. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7919. if (iscntrl((unsigned char)domain[i])) {
  7920. return 0;
  7921. }
  7922. }
  7923. if (domain[i]) {
  7924. return 0; /* domain name too long */
  7925. }
  7926. /* The maximum length of the path to the password file is limited */
  7927. if (strlen(fname) >= UTF8_PATH_MAX) {
  7928. return 0;
  7929. }
  7930. /* Check if the file exists, and get file size */
  7931. if (0 == stat(fname, &st)) {
  7932. int temp_buf_len;
  7933. if (st.st_size > 10485760) {
  7934. /* Some funster provided a >10 MB text file */
  7935. return 0;
  7936. }
  7937. /* Add enough space for one more line */
  7938. temp_buf_len = (int)st.st_size + 1024;
  7939. /* Allocate memory (instead of using a temporary file) */
  7940. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  7941. if (!temp_file) {
  7942. /* Out of memory */
  7943. return 0;
  7944. }
  7945. /* File exists. Read it into a memory buffer. */
  7946. fp = fopen(fname, "r");
  7947. if (fp == NULL) {
  7948. /* Cannot read file. No permission? */
  7949. mg_free(temp_file);
  7950. return 0;
  7951. }
  7952. /* Read content and store in memory */
  7953. while ((fgets(line, sizeof(line), fp) != NULL)
  7954. && ((temp_file_offs + 600) < temp_buf_len)) {
  7955. /* file format is "user:domain:hash\n" */
  7956. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7957. continue;
  7958. }
  7959. u[255] = 0;
  7960. d[255] = 0;
  7961. h[255] = 0;
  7962. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7963. /* Found the user: change the password hash or drop the user
  7964. */
  7965. if ((ha1 != NULL) && (!found)) {
  7966. i = sprintf(temp_file + temp_file_offs,
  7967. "%s:%s:%s\n",
  7968. user,
  7969. domain,
  7970. ha1);
  7971. if (i < 1) {
  7972. fclose(fp);
  7973. mg_free(temp_file);
  7974. return 0;
  7975. }
  7976. temp_file_offs += i;
  7977. }
  7978. found = 1;
  7979. } else {
  7980. /* Copy existing user, including password hash */
  7981. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7982. if (i < 1) {
  7983. fclose(fp);
  7984. mg_free(temp_file);
  7985. return 0;
  7986. }
  7987. temp_file_offs += i;
  7988. }
  7989. }
  7990. fclose(fp);
  7991. }
  7992. /* Create new file */
  7993. fp = fopen(fname, "w");
  7994. if (!fp) {
  7995. mg_free(temp_file);
  7996. return 0;
  7997. }
  7998. #if !defined(_WIN32)
  7999. /* On Linux & co., restrict file read/write permissions to the owner */
  8000. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  8001. result = 0;
  8002. }
  8003. #endif
  8004. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  8005. /* Store buffered content of old file */
  8006. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  8007. != (size_t)temp_file_offs) {
  8008. result = 0;
  8009. }
  8010. }
  8011. /* If new user, just add it */
  8012. if ((ha1 != NULL) && (!found)) {
  8013. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  8014. result = 0;
  8015. }
  8016. }
  8017. /* All data written */
  8018. if (fclose(fp) != 0) {
  8019. result = 0;
  8020. }
  8021. mg_free(temp_file);
  8022. return result;
  8023. }
  8024. CIVETWEB_API int
  8025. mg_modify_passwords_file(const char *fname,
  8026. const char *domain,
  8027. const char *user,
  8028. const char *pass)
  8029. {
  8030. char ha1buf[33];
  8031. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8032. return 0;
  8033. }
  8034. if ((pass == NULL) || (pass[0] == 0)) {
  8035. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  8036. }
  8037. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  8038. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  8039. }
  8040. static int
  8041. is_valid_port(unsigned long port)
  8042. {
  8043. return (port <= 0xffff);
  8044. }
  8045. static int
  8046. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8047. {
  8048. struct addrinfo hints, *res, *ressave;
  8049. int func_ret = 0;
  8050. int gai_ret;
  8051. memset(&hints, 0, sizeof(struct addrinfo));
  8052. hints.ai_family = af;
  8053. if (!resolve_src) {
  8054. hints.ai_flags = AI_NUMERICHOST;
  8055. }
  8056. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8057. if (gai_ret != 0) {
  8058. /* gai_strerror could be used to convert gai_ret to a string */
  8059. /* POSIX return values: see
  8060. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8061. */
  8062. /* Windows return values: see
  8063. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8064. */
  8065. return 0;
  8066. }
  8067. ressave = res;
  8068. while (res) {
  8069. if ((dstlen >= (size_t)res->ai_addrlen)
  8070. && (res->ai_addr->sa_family == af)) {
  8071. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8072. func_ret = 1;
  8073. }
  8074. res = res->ai_next;
  8075. }
  8076. freeaddrinfo(ressave);
  8077. return func_ret;
  8078. }
  8079. static int
  8080. connect_socket(
  8081. struct mg_context *ctx /* may be NULL */,
  8082. const char *host,
  8083. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  8084. int use_ssl, /* 0 or 1 */
  8085. struct mg_error_data *error,
  8086. SOCKET *sock /* output: socket, must not be NULL */,
  8087. union usa *sa /* output: socket address, must not be NULL */
  8088. )
  8089. {
  8090. int ip_ver = 0;
  8091. int conn_ret = -1;
  8092. int sockerr = 0;
  8093. *sock = INVALID_SOCKET;
  8094. memset(sa, 0, sizeof(*sa));
  8095. if (host == NULL) {
  8096. if (error != NULL) {
  8097. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8098. mg_snprintf(NULL,
  8099. NULL, /* No truncation check for ebuf */
  8100. error->text,
  8101. error->text_buffer_size,
  8102. "%s",
  8103. "NULL host");
  8104. }
  8105. return 0;
  8106. }
  8107. #if defined(USE_X_DOM_SOCKET)
  8108. if (port == -99) {
  8109. /* Unix domain socket */
  8110. size_t hostlen = strlen(host);
  8111. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8112. if (error != NULL) {
  8113. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8114. mg_snprintf(NULL,
  8115. NULL, /* No truncation check for ebuf */
  8116. error->text,
  8117. error->text_buffer_size,
  8118. "%s",
  8119. "host length exceeds limit");
  8120. }
  8121. return 0;
  8122. }
  8123. } else
  8124. #endif
  8125. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8126. if (error != NULL) {
  8127. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8128. mg_snprintf(NULL,
  8129. NULL, /* No truncation check for ebuf */
  8130. error->text,
  8131. error->text_buffer_size,
  8132. "%s",
  8133. "invalid port");
  8134. }
  8135. return 0;
  8136. }
  8137. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  8138. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8139. if (use_ssl && (TLS_client_method == NULL)) {
  8140. if (error != NULL) {
  8141. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8142. mg_snprintf(NULL,
  8143. NULL, /* No truncation check for ebuf */
  8144. error->text,
  8145. error->text_buffer_size,
  8146. "%s",
  8147. "SSL is not initialized");
  8148. }
  8149. return 0;
  8150. }
  8151. #else
  8152. if (use_ssl && (SSLv23_client_method == NULL)) {
  8153. if (error != 0) {
  8154. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8155. mg_snprintf(NULL,
  8156. NULL, /* No truncation check for ebuf */
  8157. error->text,
  8158. error->text_buffer_size,
  8159. "%s",
  8160. "SSL is not initialized");
  8161. }
  8162. return 0;
  8163. }
  8164. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8165. #else
  8166. (void)use_ssl;
  8167. #endif /* NO SSL */
  8168. #if defined(USE_X_DOM_SOCKET)
  8169. if (port == -99) {
  8170. size_t hostlen = strlen(host);
  8171. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8172. ip_ver = -99;
  8173. sa->sun.sun_family = AF_UNIX;
  8174. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8175. memcpy(sa->sun.sun_path, host, hostlen);
  8176. } else
  8177. #endif
  8178. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8179. sa->sin.sin_port = htons((uint16_t)port);
  8180. ip_ver = 4;
  8181. #if defined(USE_IPV6)
  8182. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8183. sa->sin6.sin6_port = htons((uint16_t)port);
  8184. ip_ver = 6;
  8185. } else if (host[0] == '[') {
  8186. /* While getaddrinfo on Windows will work with [::1],
  8187. * getaddrinfo on Linux only works with ::1 (without []). */
  8188. size_t l = strlen(host + 1);
  8189. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8190. if (h) {
  8191. h[l - 1] = 0;
  8192. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8193. sa->sin6.sin6_port = htons((uint16_t)port);
  8194. ip_ver = 6;
  8195. }
  8196. mg_free(h);
  8197. }
  8198. #endif
  8199. }
  8200. if (ip_ver == 0) {
  8201. if (error != NULL) {
  8202. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8203. mg_snprintf(NULL,
  8204. NULL, /* No truncation check for ebuf */
  8205. error->text,
  8206. error->text_buffer_size,
  8207. "%s",
  8208. "host not found");
  8209. }
  8210. return 0;
  8211. }
  8212. if (ip_ver == 4) {
  8213. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8214. }
  8215. #if defined(USE_IPV6)
  8216. else if (ip_ver == 6) {
  8217. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8218. }
  8219. #endif
  8220. #if defined(USE_X_DOM_SOCKET)
  8221. else if (ip_ver == -99) {
  8222. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8223. }
  8224. #endif
  8225. if (*sock == INVALID_SOCKET) {
  8226. if (error != NULL) {
  8227. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8228. error->code_sub = (unsigned)ERRNO;
  8229. mg_snprintf(NULL,
  8230. NULL, /* No truncation check for ebuf */
  8231. error->text,
  8232. error->text_buffer_size,
  8233. "socket(): %s",
  8234. strerror(ERRNO));
  8235. }
  8236. return 0;
  8237. }
  8238. if (0 != set_non_blocking_mode(*sock)) {
  8239. if (error != NULL) {
  8240. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8241. error->code_sub = (unsigned)ERRNO;
  8242. mg_snprintf(NULL,
  8243. NULL, /* No truncation check for ebuf */
  8244. error->text,
  8245. error->text_buffer_size,
  8246. "Cannot set socket to non-blocking: %s",
  8247. strerror(ERRNO));
  8248. }
  8249. closesocket(*sock);
  8250. *sock = INVALID_SOCKET;
  8251. return 0;
  8252. }
  8253. set_close_on_exec(*sock, NULL, ctx);
  8254. if (ip_ver == 4) {
  8255. /* connected with IPv4 */
  8256. conn_ret = connect(*sock,
  8257. (struct sockaddr *)((void *)&sa->sin),
  8258. sizeof(sa->sin));
  8259. }
  8260. #if defined(USE_IPV6)
  8261. else if (ip_ver == 6) {
  8262. /* connected with IPv6 */
  8263. conn_ret = connect(*sock,
  8264. (struct sockaddr *)((void *)&sa->sin6),
  8265. sizeof(sa->sin6));
  8266. }
  8267. #endif
  8268. #if defined(USE_X_DOM_SOCKET)
  8269. else if (ip_ver == -99) {
  8270. /* connected to domain socket */
  8271. conn_ret = connect(*sock,
  8272. (struct sockaddr *)((void *)&sa->sun),
  8273. sizeof(sa->sun));
  8274. }
  8275. #endif
  8276. if (conn_ret != 0) {
  8277. sockerr = ERRNO;
  8278. }
  8279. #if defined(_WIN32)
  8280. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8281. #else
  8282. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8283. #endif
  8284. /* Data for getsockopt */
  8285. void *psockerr = &sockerr;
  8286. int ret;
  8287. #if defined(_WIN32)
  8288. int len = (int)sizeof(sockerr);
  8289. #else
  8290. socklen_t len = (socklen_t)sizeof(sockerr);
  8291. #endif
  8292. /* Data for poll */
  8293. struct mg_pollfd pfd[2];
  8294. int pollres;
  8295. int ms_wait = 10000; /* 10 second timeout */
  8296. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8297. unsigned int num_sock = 1; /* use one or two sockets */
  8298. /* For a non-blocking socket, the connect sequence is:
  8299. * 1) call connect (will not block)
  8300. * 2) wait until the socket is ready for writing (select or poll)
  8301. * 3) check connection state with getsockopt
  8302. */
  8303. pfd[0].fd = *sock;
  8304. pfd[0].events = POLLOUT;
  8305. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  8306. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  8307. pfd[num_sock].events = POLLIN;
  8308. num_sock++;
  8309. }
  8310. pollres =
  8311. mg_poll(pfd, num_sock, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8312. if (pollres != 1) {
  8313. /* Not connected */
  8314. if (error != NULL) {
  8315. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8316. mg_snprintf(NULL,
  8317. NULL, /* No truncation check for ebuf */
  8318. error->text,
  8319. error->text_buffer_size,
  8320. "connect(%s:%d): timeout",
  8321. host,
  8322. port);
  8323. }
  8324. closesocket(*sock);
  8325. *sock = INVALID_SOCKET;
  8326. return 0;
  8327. }
  8328. #if defined(_WIN32)
  8329. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8330. #else
  8331. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8332. #endif
  8333. if ((ret == 0) && (sockerr == 0)) {
  8334. conn_ret = 0;
  8335. }
  8336. }
  8337. if (conn_ret != 0) {
  8338. /* Not connected */
  8339. if (error != NULL) {
  8340. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8341. error->code_sub = (unsigned)ERRNO;
  8342. mg_snprintf(NULL,
  8343. NULL, /* No truncation check for ebuf */
  8344. error->text,
  8345. error->text_buffer_size,
  8346. "connect(%s:%d): error %s",
  8347. host,
  8348. port,
  8349. strerror(sockerr));
  8350. }
  8351. closesocket(*sock);
  8352. *sock = INVALID_SOCKET;
  8353. return 0;
  8354. }
  8355. return 1;
  8356. }
  8357. CIVETWEB_API int
  8358. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8359. {
  8360. static const char *dont_escape = "._-$,;~()";
  8361. static const char *hex = "0123456789abcdef";
  8362. char *pos = dst;
  8363. const char *end = dst + dst_len - 1;
  8364. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8365. if (isalnum((unsigned char)*src)
  8366. || (strchr(dont_escape, *src) != NULL)) {
  8367. *pos = *src;
  8368. } else if (pos + 2 < end) {
  8369. pos[0] = '%';
  8370. pos[1] = hex[(unsigned char)*src >> 4];
  8371. pos[2] = hex[(unsigned char)*src & 0xf];
  8372. pos += 2;
  8373. } else {
  8374. break;
  8375. }
  8376. }
  8377. *pos = '\0';
  8378. return (*src == '\0') ? (int)(pos - dst) : -1;
  8379. }
  8380. /* Return 0 on success, non-zero if an error occurs. */
  8381. static int
  8382. print_dir_entry(struct mg_connection *conn, struct de *de)
  8383. {
  8384. size_t namesize, escsize, i;
  8385. char *href, *esc, *p;
  8386. char size[64], mod[64];
  8387. #if defined(REENTRANT_TIME)
  8388. struct tm _tm;
  8389. struct tm *tm = &_tm;
  8390. #else
  8391. struct tm *tm;
  8392. #endif
  8393. /* Estimate worst case size for encoding and escaping */
  8394. namesize = strlen(de->file_name) + 1;
  8395. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8396. href = (char *)mg_malloc(namesize * 3 + escsize);
  8397. if (href == NULL) {
  8398. return -1;
  8399. }
  8400. mg_url_encode(de->file_name, href, namesize * 3);
  8401. esc = NULL;
  8402. if (escsize > 0) {
  8403. /* HTML escaping needed */
  8404. esc = href + namesize * 3;
  8405. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8406. mg_strlcpy(p, de->file_name + i, 2);
  8407. if (*p == '&') {
  8408. strcpy(p, "&amp;");
  8409. } else if (*p == '<') {
  8410. strcpy(p, "&lt;");
  8411. } else if (*p == '>') {
  8412. strcpy(p, "&gt;");
  8413. }
  8414. }
  8415. }
  8416. if (de->file.is_directory) {
  8417. mg_snprintf(conn,
  8418. NULL, /* Buffer is big enough */
  8419. size,
  8420. sizeof(size),
  8421. "%s",
  8422. "[DIRECTORY]");
  8423. } else {
  8424. /* We use (signed) cast below because MSVC 6 compiler cannot
  8425. * convert unsigned __int64 to double. Sigh. */
  8426. if (de->file.size < 1024) {
  8427. mg_snprintf(conn,
  8428. NULL, /* Buffer is big enough */
  8429. size,
  8430. sizeof(size),
  8431. "%d",
  8432. (int)de->file.size);
  8433. } else if (de->file.size < 0x100000) {
  8434. mg_snprintf(conn,
  8435. NULL, /* Buffer is big enough */
  8436. size,
  8437. sizeof(size),
  8438. "%.1fk",
  8439. (double)de->file.size / 1024.0);
  8440. } else if (de->file.size < 0x40000000) {
  8441. mg_snprintf(conn,
  8442. NULL, /* Buffer is big enough */
  8443. size,
  8444. sizeof(size),
  8445. "%.1fM",
  8446. (double)de->file.size / 1048576);
  8447. } else {
  8448. mg_snprintf(conn,
  8449. NULL, /* Buffer is big enough */
  8450. size,
  8451. sizeof(size),
  8452. "%.1fG",
  8453. (double)de->file.size / 1073741824);
  8454. }
  8455. }
  8456. /* Note: mg_snprintf will not cause a buffer overflow above.
  8457. * So, string truncation checks are not required here. */
  8458. #if defined(REENTRANT_TIME)
  8459. localtime_r(&de->file.last_modified, tm);
  8460. #else
  8461. tm = localtime(&de->file.last_modified);
  8462. #endif
  8463. if (tm != NULL) {
  8464. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8465. } else {
  8466. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8467. }
  8468. mg_printf(conn,
  8469. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8470. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8471. href,
  8472. de->file.is_directory ? "/" : "",
  8473. esc ? esc : de->file_name,
  8474. de->file.is_directory ? "/" : "",
  8475. mod,
  8476. size);
  8477. mg_free(href);
  8478. return 0;
  8479. }
  8480. /* This function is called from send_directory() and used for
  8481. * sorting directory entries by size, name, or modification time. */
  8482. static int
  8483. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8484. {
  8485. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8486. if (p1 && p2) {
  8487. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8488. int cmp_result = 0;
  8489. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8490. query_string = "n";
  8491. }
  8492. /* Sort Directories vs Files */
  8493. if (a->file.is_directory && !b->file.is_directory) {
  8494. return -1; /* Always put directories on top */
  8495. } else if (!a->file.is_directory && b->file.is_directory) {
  8496. return 1; /* Always put directories on top */
  8497. }
  8498. /* Sort by size or date */
  8499. if (*query_string == 's') {
  8500. cmp_result = (a->file.size == b->file.size)
  8501. ? 0
  8502. : ((a->file.size > b->file.size) ? 1 : -1);
  8503. } else if (*query_string == 'd') {
  8504. cmp_result =
  8505. (a->file.last_modified == b->file.last_modified)
  8506. ? 0
  8507. : ((a->file.last_modified > b->file.last_modified) ? 1
  8508. : -1);
  8509. }
  8510. /* Sort by name:
  8511. * if (*query_string == 'n') ...
  8512. * but also sort files of same size/date by name as secondary criterion.
  8513. */
  8514. if (cmp_result == 0) {
  8515. cmp_result = strcmp(a->file_name, b->file_name);
  8516. }
  8517. /* For descending order, invert result */
  8518. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8519. }
  8520. return 0;
  8521. }
  8522. static int
  8523. must_hide_file(struct mg_connection *conn, const char *path)
  8524. {
  8525. if (conn && conn->dom_ctx) {
  8526. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8527. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8528. return (match_prefix_strlen(pw_pattern, path) > 0)
  8529. || (match_prefix_strlen(pattern, path) > 0);
  8530. }
  8531. return 0;
  8532. }
  8533. #if !defined(NO_FILESYSTEMS)
  8534. static int
  8535. scan_directory(struct mg_connection *conn,
  8536. const char *dir,
  8537. void *data,
  8538. int (*cb)(struct de *, void *))
  8539. {
  8540. char path[UTF8_PATH_MAX];
  8541. struct dirent *dp;
  8542. DIR *dirp;
  8543. struct de de;
  8544. int truncated;
  8545. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8546. return 0;
  8547. } else {
  8548. while ((dp = mg_readdir(dirp)) != NULL) {
  8549. /* Do not show current dir and hidden files */
  8550. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8551. || must_hide_file(conn, dp->d_name)) {
  8552. continue;
  8553. }
  8554. mg_snprintf(
  8555. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8556. /* If we don't memset stat structure to zero, mtime will have
  8557. * garbage and strftime() will segfault later on in
  8558. * print_dir_entry(). memset is required only if mg_stat()
  8559. * fails. For more details, see
  8560. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8561. memset(&de.file, 0, sizeof(de.file));
  8562. if (truncated) {
  8563. /* If the path is not complete, skip processing. */
  8564. continue;
  8565. }
  8566. if (!mg_stat(conn, path, &de.file)) {
  8567. mg_cry_internal(conn,
  8568. "%s: mg_stat(%s) failed: %s",
  8569. __func__,
  8570. path,
  8571. strerror(ERRNO));
  8572. }
  8573. de.file_name = dp->d_name;
  8574. if (cb(&de, data)) {
  8575. /* stopped */
  8576. break;
  8577. }
  8578. }
  8579. (void)mg_closedir(dirp);
  8580. }
  8581. return 1;
  8582. }
  8583. #endif /* NO_FILESYSTEMS */
  8584. #if !defined(NO_FILES)
  8585. static int
  8586. remove_directory(struct mg_connection *conn, const char *dir)
  8587. {
  8588. char path[UTF8_PATH_MAX];
  8589. struct dirent *dp;
  8590. DIR *dirp;
  8591. struct de de;
  8592. int truncated;
  8593. int ok = 1;
  8594. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8595. return 0;
  8596. } else {
  8597. while ((dp = mg_readdir(dirp)) != NULL) {
  8598. /* Do not show current dir (but show hidden files as they will
  8599. * also be removed) */
  8600. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8601. continue;
  8602. }
  8603. mg_snprintf(
  8604. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8605. /* If we don't memset stat structure to zero, mtime will have
  8606. * garbage and strftime() will segfault later on in
  8607. * print_dir_entry(). memset is required only if mg_stat()
  8608. * fails. For more details, see
  8609. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8610. memset(&de.file, 0, sizeof(de.file));
  8611. if (truncated) {
  8612. /* Do not delete anything shorter */
  8613. ok = 0;
  8614. continue;
  8615. }
  8616. if (!mg_stat(conn, path, &de.file)) {
  8617. mg_cry_internal(conn,
  8618. "%s: mg_stat(%s) failed: %s",
  8619. __func__,
  8620. path,
  8621. strerror(ERRNO));
  8622. ok = 0;
  8623. }
  8624. if (de.file.is_directory) {
  8625. if (remove_directory(conn, path) == 0) {
  8626. ok = 0;
  8627. }
  8628. } else {
  8629. /* This will fail file is the file is in memory */
  8630. if (mg_remove(conn, path) == 0) {
  8631. ok = 0;
  8632. }
  8633. }
  8634. }
  8635. (void)mg_closedir(dirp);
  8636. IGNORE_UNUSED_RESULT(rmdir(dir));
  8637. }
  8638. return ok;
  8639. }
  8640. #endif
  8641. struct dir_scan_data {
  8642. struct de *entries;
  8643. size_t num_entries;
  8644. size_t arr_size;
  8645. };
  8646. #if !defined(NO_FILESYSTEMS)
  8647. static int
  8648. dir_scan_callback(struct de *de, void *data)
  8649. {
  8650. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8651. struct de *entries = dsd->entries;
  8652. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8653. /* Here "entries" is a temporary pointer and can be replaced,
  8654. * "dsd->entries" is the original pointer */
  8655. entries =
  8656. (struct de *)mg_realloc(entries,
  8657. dsd->arr_size * 2 * sizeof(entries[0]));
  8658. if (entries == NULL) {
  8659. /* stop scan */
  8660. return 1;
  8661. }
  8662. dsd->entries = entries;
  8663. dsd->arr_size *= 2;
  8664. }
  8665. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8666. if (entries[dsd->num_entries].file_name == NULL) {
  8667. /* stop scan */
  8668. return 1;
  8669. }
  8670. entries[dsd->num_entries].file = de->file;
  8671. dsd->num_entries++;
  8672. return 0;
  8673. }
  8674. static void
  8675. handle_directory_request(struct mg_connection *conn, const char *dir)
  8676. {
  8677. size_t i;
  8678. int sort_direction;
  8679. struct dir_scan_data data = {NULL, 0, 128};
  8680. char date[64], *esc, *p;
  8681. const char *title;
  8682. time_t curtime = time(NULL);
  8683. if (!conn) {
  8684. return;
  8685. }
  8686. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8687. mg_send_http_error(conn,
  8688. 500,
  8689. "Error: Cannot open directory\nopendir(%s): %s",
  8690. dir,
  8691. strerror(ERRNO));
  8692. return;
  8693. }
  8694. gmt_time_string(date, sizeof(date), &curtime);
  8695. esc = NULL;
  8696. title = conn->request_info.local_uri;
  8697. if (title[strcspn(title, "&<>")]) {
  8698. /* HTML escaping needed */
  8699. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8700. if (esc) {
  8701. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8702. mg_strlcpy(p, title + i, 2);
  8703. if (*p == '&') {
  8704. strcpy(p, "&amp;");
  8705. } else if (*p == '<') {
  8706. strcpy(p, "&lt;");
  8707. } else if (*p == '>') {
  8708. strcpy(p, "&gt;");
  8709. }
  8710. }
  8711. } else {
  8712. title = "";
  8713. }
  8714. }
  8715. sort_direction = ((conn->request_info.query_string != NULL)
  8716. && (conn->request_info.query_string[0] != '\0')
  8717. && (conn->request_info.query_string[1] == 'd'))
  8718. ? 'a'
  8719. : 'd';
  8720. conn->must_close = 1;
  8721. /* Create 200 OK response */
  8722. mg_response_header_start(conn, 200);
  8723. send_static_cache_header(conn);
  8724. send_additional_header(conn);
  8725. mg_response_header_add(conn,
  8726. "Content-Type",
  8727. "text/html; charset=utf-8",
  8728. -1);
  8729. /* Send all headers */
  8730. mg_response_header_send(conn);
  8731. /* Body */
  8732. mg_printf(conn,
  8733. "<!DOCTYPE html>"
  8734. "<html><head><title>Index of %s</title>"
  8735. "<style>th {text-align: left;}</style></head>"
  8736. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8737. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8738. "<th><a href=\"?d%c\">Modified</a></th>"
  8739. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8740. "<tr><td colspan=\"3\"><hr></td></tr>",
  8741. esc ? esc : title,
  8742. esc ? esc : title,
  8743. sort_direction,
  8744. sort_direction,
  8745. sort_direction);
  8746. mg_free(esc);
  8747. /* Print first entry - link to a parent directory */
  8748. mg_printf(conn,
  8749. "<tr><td><a href=\"%s\">%s</a></td>"
  8750. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8751. "..",
  8752. "Parent directory",
  8753. "-",
  8754. "-");
  8755. /* Sort and print directory entries */
  8756. if (data.entries != NULL) {
  8757. mg_sort(data.entries,
  8758. data.num_entries,
  8759. sizeof(data.entries[0]),
  8760. compare_dir_entries,
  8761. (void *)conn->request_info.query_string);
  8762. for (i = 0; i < data.num_entries; i++) {
  8763. print_dir_entry(conn, &data.entries[i]);
  8764. mg_free(data.entries[i].file_name);
  8765. }
  8766. mg_free(data.entries);
  8767. }
  8768. mg_printf(conn, "%s", "</table></pre></body></html>");
  8769. conn->status_code = 200;
  8770. }
  8771. #endif /* NO_FILESYSTEMS */
  8772. /* Send len bytes from the opened file to the client. */
  8773. static void
  8774. send_file_data(struct mg_connection *conn,
  8775. struct mg_file *filep,
  8776. int64_t offset,
  8777. int64_t len,
  8778. int no_buffering)
  8779. {
  8780. char buf[MG_BUF_LEN];
  8781. int to_read, num_read, num_written;
  8782. int64_t size;
  8783. if (!filep || !conn) {
  8784. return;
  8785. }
  8786. /* Sanity check the offset */
  8787. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8788. : (int64_t)(filep->stat.size);
  8789. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8790. if (len > 0 && filep->access.fp != NULL) {
  8791. /* file stored on disk */
  8792. #if defined(__linux__)
  8793. /* sendfile is only available for Linux */
  8794. if ((conn->ssl == 0) && (conn->throttle == 0)
  8795. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8796. "yes"))) {
  8797. off_t sf_offs = (off_t)offset;
  8798. ssize_t sf_sent;
  8799. int sf_file = fileno(filep->access.fp);
  8800. int loop_cnt = 0;
  8801. do {
  8802. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8803. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8804. size_t sf_tosend =
  8805. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8806. sf_sent =
  8807. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8808. if (sf_sent > 0) {
  8809. len -= sf_sent;
  8810. offset += sf_sent;
  8811. } else if (loop_cnt == 0) {
  8812. /* This file can not be sent using sendfile.
  8813. * This might be the case for pseudo-files in the
  8814. * /sys/ and /proc/ file system.
  8815. * Use the regular user mode copy code instead. */
  8816. break;
  8817. } else if (sf_sent == 0) {
  8818. /* No error, but 0 bytes sent. May be EOF? */
  8819. return;
  8820. }
  8821. loop_cnt++;
  8822. } while ((len > 0) && (sf_sent >= 0));
  8823. if (sf_sent > 0) {
  8824. return; /* OK */
  8825. }
  8826. /* sf_sent<0 means error, thus fall back to the classic way */
  8827. /* This is always the case, if sf_file is not a "normal" file,
  8828. * e.g., for sending data from the output of a CGI process. */
  8829. offset = (int64_t)sf_offs;
  8830. }
  8831. #endif
  8832. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8833. mg_cry_internal(conn,
  8834. "%s: fseeko() failed: %s",
  8835. __func__,
  8836. strerror(ERRNO));
  8837. mg_send_http_error(
  8838. conn,
  8839. 500,
  8840. "%s",
  8841. "Error: Unable to access file at requested position.");
  8842. } else {
  8843. while (len > 0) {
  8844. /* Calculate how much to read from the file into the buffer. */
  8845. /* If no_buffering is set, we should not wait until the
  8846. * CGI->Server buffer is filled, but send everything
  8847. * immediately. In theory buffering could be turned off using
  8848. * setbuf(filep->access.fp, NULL);
  8849. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8850. * but in practice this does not work. A "Linux only" solution
  8851. * may be to use select(). The only portable way is to read byte
  8852. * by byte, but this is quite inefficient from a performance
  8853. * point of view. */
  8854. to_read = no_buffering ? 1 : sizeof(buf);
  8855. if ((int64_t)to_read > len) {
  8856. to_read = (int)len;
  8857. }
  8858. /* Read from file, exit the loop on error */
  8859. if ((num_read =
  8860. pull_inner(filep->access.fp, NULL, buf, to_read, /* unused */ 0.0))
  8861. <= 0) {
  8862. break;
  8863. }
  8864. /* Send read bytes to the client, exit the loop on error */
  8865. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8866. != num_read) {
  8867. break;
  8868. }
  8869. /* Both read and were successful, adjust counters */
  8870. len -= num_written;
  8871. }
  8872. }
  8873. }
  8874. }
  8875. static int
  8876. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8877. {
  8878. return sscanf(header,
  8879. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8880. a,
  8881. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8882. // to an integer value, but function will not report
  8883. // conversion errors; consider using 'strtol' instead
  8884. }
  8885. static void
  8886. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8887. {
  8888. if ((filestat != NULL) && (buf != NULL)) {
  8889. mg_snprintf(NULL,
  8890. NULL, /* All calls to construct_etag use 64 byte buffer */
  8891. buf,
  8892. buf_len,
  8893. "\"%lx.%" INT64_FMT "\"",
  8894. (unsigned long)filestat->last_modified,
  8895. filestat->size);
  8896. }
  8897. }
  8898. static void
  8899. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8900. {
  8901. if (filep != NULL && filep->fp != NULL) {
  8902. #if defined(_WIN32)
  8903. (void)conn; /* Unused. */
  8904. #else
  8905. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8906. mg_cry_internal(conn,
  8907. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8908. __func__,
  8909. strerror(ERRNO));
  8910. }
  8911. #endif
  8912. }
  8913. }
  8914. #if defined(USE_ZLIB)
  8915. #include "mod_zlib.inl"
  8916. #endif
  8917. #if !defined(NO_FILESYSTEMS)
  8918. static void
  8919. handle_static_file_request(struct mg_connection *conn,
  8920. const char *path,
  8921. struct mg_file *filep,
  8922. const char *mime_type,
  8923. const char *additional_headers)
  8924. {
  8925. char lm[64], etag[64];
  8926. char range[128]; /* large enough, so there will be no overflow */
  8927. const char *range_hdr;
  8928. int64_t cl, r1, r2;
  8929. struct vec mime_vec;
  8930. int n, truncated;
  8931. char gz_path[UTF8_PATH_MAX];
  8932. const char *encoding = 0;
  8933. int is_head_request;
  8934. #if defined(USE_ZLIB)
  8935. /* Compression is allowed, unless there is a reason not to use
  8936. * compression. If the file is already compressed, too small or a
  8937. * "range" request was made, on the fly compression is not possible. */
  8938. int allow_on_the_fly_compression = 1;
  8939. #endif
  8940. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8941. return;
  8942. }
  8943. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8944. if (mime_type == NULL) {
  8945. get_mime_type(conn, path, &mime_vec);
  8946. } else {
  8947. mime_vec.ptr = mime_type;
  8948. mime_vec.len = strlen(mime_type);
  8949. }
  8950. if (filep->stat.size > INT64_MAX) {
  8951. mg_send_http_error(conn,
  8952. 500,
  8953. "Error: File size is too large to send\n%" INT64_FMT,
  8954. filep->stat.size);
  8955. return;
  8956. }
  8957. cl = (int64_t)filep->stat.size;
  8958. conn->status_code = 200;
  8959. range[0] = '\0';
  8960. #if defined(USE_ZLIB)
  8961. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8962. * it's important to rewrite the filename after resolving
  8963. * the mime type from it, to preserve the actual file's type */
  8964. if (!conn->accept_gzip) {
  8965. allow_on_the_fly_compression = 0;
  8966. }
  8967. #endif
  8968. /* Check if there is a range header */
  8969. range_hdr = mg_get_header(conn, "Range");
  8970. /* For gzipped files, add *.gz */
  8971. if (filep->stat.is_gzipped) {
  8972. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8973. if (truncated) {
  8974. mg_send_http_error(conn,
  8975. 500,
  8976. "Error: Path of zipped file too long (%s)",
  8977. path);
  8978. return;
  8979. }
  8980. path = gz_path;
  8981. encoding = "gzip";
  8982. #if defined(USE_ZLIB)
  8983. /* File is already compressed. No "on the fly" compression. */
  8984. allow_on_the_fly_compression = 0;
  8985. #endif
  8986. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8987. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8988. struct mg_file_stat file_stat;
  8989. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8990. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8991. && !file_stat.is_directory) {
  8992. file_stat.is_gzipped = 1;
  8993. filep->stat = file_stat;
  8994. cl = (int64_t)filep->stat.size;
  8995. path = gz_path;
  8996. encoding = "gzip";
  8997. #if defined(USE_ZLIB)
  8998. /* File is already compressed. No "on the fly" compression. */
  8999. allow_on_the_fly_compression = 0;
  9000. #endif
  9001. }
  9002. }
  9003. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9004. mg_send_http_error(conn,
  9005. 500,
  9006. "Error: Cannot open file\nfopen(%s): %s",
  9007. path,
  9008. strerror(ERRNO));
  9009. return;
  9010. }
  9011. fclose_on_exec(&filep->access, conn);
  9012. /* If "Range" request was made: parse header, send only selected part
  9013. * of the file. */
  9014. r1 = r2 = 0;
  9015. if ((range_hdr != NULL)
  9016. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  9017. && (r2 >= 0)) {
  9018. /* actually, range requests don't play well with a pre-gzipped
  9019. * file (since the range is specified in the uncompressed space) */
  9020. if (filep->stat.is_gzipped) {
  9021. mg_send_http_error(
  9022. conn,
  9023. 416, /* 416 = Range Not Satisfiable */
  9024. "%s",
  9025. "Error: Range requests in gzipped files are not supported");
  9026. (void)mg_fclose(
  9027. &filep->access); /* ignore error on read only file */
  9028. return;
  9029. }
  9030. conn->status_code = 206;
  9031. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  9032. mg_snprintf(conn,
  9033. NULL, /* range buffer is big enough */
  9034. range,
  9035. sizeof(range),
  9036. "bytes "
  9037. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  9038. r1,
  9039. r1 + cl - 1,
  9040. filep->stat.size);
  9041. #if defined(USE_ZLIB)
  9042. /* Do not compress ranges. */
  9043. allow_on_the_fly_compression = 0;
  9044. #endif
  9045. }
  9046. /* Do not compress small files. Small files do not benefit from file
  9047. * compression, but there is still some overhead. */
  9048. #if defined(USE_ZLIB)
  9049. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  9050. /* File is below the size limit. */
  9051. allow_on_the_fly_compression = 0;
  9052. }
  9053. #endif
  9054. /* Prepare Etag, and Last-Modified headers. */
  9055. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9056. construct_etag(etag, sizeof(etag), &filep->stat);
  9057. /* Create 2xx (200, 206) response */
  9058. mg_response_header_start(conn, conn->status_code);
  9059. send_static_cache_header(conn);
  9060. send_additional_header(conn);
  9061. send_cors_header(conn);
  9062. mg_response_header_add(conn,
  9063. "Content-Type",
  9064. mime_vec.ptr,
  9065. (int)mime_vec.len);
  9066. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9067. mg_response_header_add(conn, "Etag", etag, -1);
  9068. #if defined(USE_ZLIB)
  9069. /* On the fly compression allowed */
  9070. if (allow_on_the_fly_compression) {
  9071. /* For on the fly compression, we don't know the content size in
  9072. * advance, so we have to use chunked encoding */
  9073. encoding = "gzip";
  9074. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9075. /* HTTP/2 is always using "chunks" (frames) */
  9076. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9077. }
  9078. } else
  9079. #endif
  9080. {
  9081. /* Without on-the-fly compression, we know the content-length
  9082. * and we can use ranges (with on-the-fly compression we cannot).
  9083. * So we send these response headers only in this case. */
  9084. char len[32];
  9085. int trunc = 0;
  9086. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9087. if (!trunc) {
  9088. mg_response_header_add(conn, "Content-Length", len, -1);
  9089. }
  9090. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9091. }
  9092. if (encoding) {
  9093. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9094. }
  9095. if (range[0] != 0) {
  9096. mg_response_header_add(conn, "Content-Range", range, -1);
  9097. }
  9098. /* The code above does not add any header starting with X- to make
  9099. * sure no one of the additional_headers is included twice */
  9100. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9101. mg_response_header_add_lines(conn, additional_headers);
  9102. }
  9103. /* Send all headers */
  9104. mg_response_header_send(conn);
  9105. if (!is_head_request) {
  9106. #if defined(USE_ZLIB)
  9107. if (allow_on_the_fly_compression) {
  9108. /* Compress and send */
  9109. send_compressed_data(conn, filep);
  9110. } else
  9111. #endif
  9112. {
  9113. /* Send file directly */
  9114. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9115. }
  9116. }
  9117. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9118. }
  9119. CIVETWEB_API int
  9120. mg_send_file_body(struct mg_connection *conn, const char *path)
  9121. {
  9122. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9123. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9124. return -1;
  9125. }
  9126. fclose_on_exec(&file.access, conn);
  9127. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9128. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9129. return 0; /* >= 0 for OK */
  9130. }
  9131. #endif /* NO_FILESYSTEMS */
  9132. #if !defined(NO_CACHING)
  9133. /* Return True if we should reply 304 Not Modified. */
  9134. static int
  9135. is_not_modified(const struct mg_connection *conn,
  9136. const struct mg_file_stat *filestat)
  9137. {
  9138. char etag[64];
  9139. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9140. const char *inm = mg_get_header(conn, "If-None-Match");
  9141. construct_etag(etag, sizeof(etag), filestat);
  9142. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9143. || ((ims != NULL)
  9144. && (filestat->last_modified <= parse_date_string(ims)));
  9145. }
  9146. static void
  9147. handle_not_modified_static_file_request(struct mg_connection *conn,
  9148. struct mg_file *filep)
  9149. {
  9150. char lm[64], etag[64];
  9151. if ((conn == NULL) || (filep == NULL)) {
  9152. return;
  9153. }
  9154. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9155. construct_etag(etag, sizeof(etag), &filep->stat);
  9156. /* Create 304 "not modified" response */
  9157. mg_response_header_start(conn, 304);
  9158. send_static_cache_header(conn);
  9159. send_additional_header(conn);
  9160. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9161. mg_response_header_add(conn, "Etag", etag, -1);
  9162. /* Send all headers */
  9163. mg_response_header_send(conn);
  9164. }
  9165. #endif
  9166. #if !defined(NO_FILESYSTEMS)
  9167. CIVETWEB_API void
  9168. mg_send_file(struct mg_connection *conn, const char *path)
  9169. {
  9170. mg_send_mime_file2(conn, path, NULL, NULL);
  9171. }
  9172. CIVETWEB_API void
  9173. mg_send_mime_file(struct mg_connection *conn,
  9174. const char *path,
  9175. const char *mime_type)
  9176. {
  9177. mg_send_mime_file2(conn, path, mime_type, NULL);
  9178. }
  9179. CIVETWEB_API void
  9180. mg_send_mime_file2(struct mg_connection *conn,
  9181. const char *path,
  9182. const char *mime_type,
  9183. const char *additional_headers)
  9184. {
  9185. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9186. if (!conn) {
  9187. /* No conn */
  9188. return;
  9189. }
  9190. if (mg_stat(conn, path, &file.stat)) {
  9191. #if !defined(NO_CACHING)
  9192. if (is_not_modified(conn, &file.stat)) {
  9193. /* Send 304 "Not Modified" - this must not send any body data */
  9194. handle_not_modified_static_file_request(conn, &file);
  9195. } else
  9196. #endif /* NO_CACHING */
  9197. if (file.stat.is_directory) {
  9198. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9199. "yes")) {
  9200. handle_directory_request(conn, path);
  9201. } else {
  9202. mg_send_http_error(conn,
  9203. 403,
  9204. "%s",
  9205. "Error: Directory listing denied");
  9206. }
  9207. } else {
  9208. handle_static_file_request(
  9209. conn, path, &file, mime_type, additional_headers);
  9210. }
  9211. } else {
  9212. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9213. }
  9214. }
  9215. /* For a given PUT path, create all intermediate subdirectories.
  9216. * Return 0 if the path itself is a directory.
  9217. * Return 1 if the path leads to a file.
  9218. * Return -1 for if the path is too long.
  9219. * Return -2 if path can not be created.
  9220. */
  9221. static int
  9222. put_dir(struct mg_connection *conn, const char *path)
  9223. {
  9224. char buf[UTF8_PATH_MAX];
  9225. const char *s, *p;
  9226. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9227. size_t len;
  9228. int res = 1;
  9229. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9230. len = (size_t)(p - path);
  9231. if (len >= sizeof(buf)) {
  9232. /* path too long */
  9233. res = -1;
  9234. break;
  9235. }
  9236. memcpy(buf, path, len);
  9237. buf[len] = '\0';
  9238. /* Try to create intermediate directory */
  9239. DEBUG_TRACE("mkdir(%s)", buf);
  9240. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9241. /* path does not exist and can not be created */
  9242. res = -2;
  9243. break;
  9244. }
  9245. /* Is path itself a directory? */
  9246. if (p[1] == '\0') {
  9247. res = 0;
  9248. }
  9249. }
  9250. return res;
  9251. }
  9252. static void
  9253. remove_bad_file(const struct mg_connection *conn, const char *path)
  9254. {
  9255. int r = mg_remove(conn, path);
  9256. if (r != 0) {
  9257. mg_cry_internal(conn,
  9258. "%s: Cannot remove invalid file %s",
  9259. __func__,
  9260. path);
  9261. }
  9262. }
  9263. CIVETWEB_API long long
  9264. mg_store_body(struct mg_connection *conn, const char *path)
  9265. {
  9266. char buf[MG_BUF_LEN];
  9267. long long len = 0;
  9268. int ret, n;
  9269. struct mg_file fi;
  9270. if (conn->consumed_content != 0) {
  9271. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9272. return -11;
  9273. }
  9274. ret = put_dir(conn, path);
  9275. if (ret < 0) {
  9276. /* -1 for path too long,
  9277. * -2 for path can not be created. */
  9278. return ret;
  9279. }
  9280. if (ret != 1) {
  9281. /* Return 0 means, path itself is a directory. */
  9282. return 0;
  9283. }
  9284. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9285. return -12;
  9286. }
  9287. ret = mg_read(conn, buf, sizeof(buf));
  9288. while (ret > 0) {
  9289. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9290. if (n != ret) {
  9291. (void)mg_fclose(
  9292. &fi.access); /* File is bad and will be removed anyway. */
  9293. remove_bad_file(conn, path);
  9294. return -13;
  9295. }
  9296. len += ret;
  9297. ret = mg_read(conn, buf, sizeof(buf));
  9298. }
  9299. /* File is open for writing. If fclose fails, there was probably an
  9300. * error flushing the buffer to disk, so the file on disk might be
  9301. * broken. Delete it and return an error to the caller. */
  9302. if (mg_fclose(&fi.access) != 0) {
  9303. remove_bad_file(conn, path);
  9304. return -14;
  9305. }
  9306. return len;
  9307. }
  9308. #endif /* NO_FILESYSTEMS */
  9309. /* Parse a buffer:
  9310. * Forward the string pointer till the end of a word, then
  9311. * terminate it and forward till the begin of the next word.
  9312. */
  9313. static int
  9314. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9315. {
  9316. /* Forward until a space is found - use isgraph here */
  9317. /* Extended ASCII characters are also treated as word characters. */
  9318. /* See http://www.cplusplus.com/reference/cctype/ */
  9319. while ((unsigned char)**ppw > 127 || isgraph((unsigned char)**ppw)) {
  9320. (*ppw)++;
  9321. }
  9322. /* Check end of word */
  9323. if (eol) {
  9324. /* must be a end of line */
  9325. if ((**ppw != '\r') && (**ppw != '\n')) {
  9326. return -1;
  9327. }
  9328. } else {
  9329. /* must be a end of a word, but not a line */
  9330. if (**ppw != ' ') {
  9331. return -1;
  9332. }
  9333. }
  9334. /* Terminate and forward to the next word */
  9335. do {
  9336. **ppw = 0;
  9337. (*ppw)++;
  9338. } while (isspace((unsigned char)**ppw));
  9339. /* Check after term */
  9340. if (!eol) {
  9341. /* if it's not the end of line, there must be a next word */
  9342. if (!isgraph((unsigned char)**ppw)) {
  9343. return -1;
  9344. }
  9345. }
  9346. /* ok */
  9347. return 1;
  9348. }
  9349. /* Parse HTTP headers from the given buffer, advance buf pointer
  9350. * to the point where parsing stopped.
  9351. * All parameters must be valid pointers (not NULL).
  9352. * Return <0 on error. */
  9353. static int
  9354. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9355. {
  9356. int i;
  9357. int num_headers = 0;
  9358. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9359. char *dp = *buf;
  9360. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9361. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9362. dp++;
  9363. }
  9364. if (dp == *buf) {
  9365. /* End of headers reached. */
  9366. break;
  9367. }
  9368. /* Drop all spaces after header name before : */
  9369. while (*dp == ' ') {
  9370. *dp = 0;
  9371. dp++;
  9372. }
  9373. if (*dp != ':') {
  9374. /* This is not a valid field. */
  9375. return -1;
  9376. }
  9377. /* End of header key (*dp == ':') */
  9378. /* Truncate here and set the key name */
  9379. *dp = 0;
  9380. hdr[i].name = *buf;
  9381. /* Skip all spaces */
  9382. do {
  9383. dp++;
  9384. } while ((*dp == ' ') || (*dp == '\t'));
  9385. /* The rest of the line is the value */
  9386. hdr[i].value = dp;
  9387. /* Find end of line */
  9388. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9389. dp++;
  9390. };
  9391. /* eliminate \r */
  9392. if (*dp == '\r') {
  9393. *dp = 0;
  9394. dp++;
  9395. if (*dp != '\n') {
  9396. /* This is not a valid line. */
  9397. return -1;
  9398. }
  9399. }
  9400. /* here *dp is either 0 or '\n' */
  9401. /* in any case, we have a new header */
  9402. num_headers = i + 1;
  9403. if (*dp) {
  9404. *dp = 0;
  9405. dp++;
  9406. *buf = dp;
  9407. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9408. /* This is the end of the header */
  9409. break;
  9410. }
  9411. } else {
  9412. *buf = dp;
  9413. break;
  9414. }
  9415. }
  9416. return num_headers;
  9417. }
  9418. struct mg_http_method_info {
  9419. const char *name;
  9420. int request_has_body;
  9421. int response_has_body;
  9422. int is_safe;
  9423. int is_idempotent;
  9424. int is_cacheable;
  9425. };
  9426. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9427. static const struct mg_http_method_info http_methods[] = {
  9428. /* HTTP (RFC 2616) */
  9429. {"GET", 0, 1, 1, 1, 1},
  9430. {"POST", 1, 1, 0, 0, 0},
  9431. {"PUT", 1, 0, 0, 1, 0},
  9432. {"DELETE", 0, 0, 0, 1, 0},
  9433. {"HEAD", 0, 0, 1, 1, 1},
  9434. {"OPTIONS", 0, 0, 1, 1, 0},
  9435. {"CONNECT", 1, 1, 0, 0, 0},
  9436. /* TRACE method (RFC 2616) is not supported for security reasons */
  9437. /* PATCH method (RFC 5789) */
  9438. {"PATCH", 1, 0, 0, 0, 0},
  9439. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9440. /* WEBDAV (RFC 2518) */
  9441. {"PROPFIND", 0, 1, 1, 1, 0},
  9442. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9443. * Some PROPFIND results MAY be cached, with care,
  9444. * as there is no cache validation mechanism for
  9445. * most properties. This method is both safe and
  9446. * idempotent (see Section 9.1 of [RFC2616]). */
  9447. {"MKCOL", 0, 0, 0, 1, 0},
  9448. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9449. * When MKCOL is invoked without a request body,
  9450. * the newly created collection SHOULD have no
  9451. * members. A MKCOL request message may contain
  9452. * a message body. The precise behavior of a MKCOL
  9453. * request when the body is present is undefined,
  9454. * ... ==> We do not support MKCOL with body data.
  9455. * This method is idempotent, but not safe (see
  9456. * Section 9.1 of [RFC2616]). Responses to this
  9457. * method MUST NOT be cached. */
  9458. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9459. {"LOCK", 1, 1, 0, 0, 0},
  9460. {"UNLOCK", 1, 0, 0, 0, 0},
  9461. {"PROPPATCH", 1, 1, 0, 0, 0},
  9462. {"COPY", 1, 0, 0, 0, 0},
  9463. {"MOVE", 1, 1, 0, 0, 0},
  9464. /* Unsupported WEBDAV Methods: */
  9465. /* + 11 methods from RFC 3253 */
  9466. /* ORDERPATCH (RFC 3648) */
  9467. /* ACL (RFC 3744) */
  9468. /* SEARCH (RFC 5323) */
  9469. /* + MicroSoft extensions
  9470. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9471. /* REPORT method (RFC 3253) */
  9472. {"REPORT", 1, 1, 1, 1, 1},
  9473. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9474. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9475. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9476. * to be useful for REST in case a "GET request with body" is
  9477. * required. */
  9478. {NULL, 0, 0, 0, 0, 0}
  9479. /* end of list */
  9480. };
  9481. /* All method names */
  9482. static char *all_methods = NULL; /* Built by mg_init_library */
  9483. static const struct mg_http_method_info *
  9484. get_http_method_info(const char *method)
  9485. {
  9486. /* Check if the method is known to the server. The list of all known
  9487. * HTTP methods can be found here at
  9488. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9489. */
  9490. const struct mg_http_method_info *m = http_methods;
  9491. while (m->name) {
  9492. if (!strcmp(m->name, method)) {
  9493. return m;
  9494. }
  9495. m++;
  9496. }
  9497. return NULL;
  9498. }
  9499. static int
  9500. is_valid_http_method(const char *method)
  9501. {
  9502. return (get_http_method_info(method) != NULL);
  9503. }
  9504. /* Parse HTTP request, fill in mg_request_info structure.
  9505. * This function modifies the buffer by NUL-terminating
  9506. * HTTP request components, header names and header values.
  9507. * Parameters:
  9508. * buf (in/out): pointer to the HTTP header to parse and split
  9509. * len (in): length of HTTP header buffer
  9510. * re (out): parsed header as mg_request_info
  9511. * buf and ri must be valid pointers (not NULL), len>0.
  9512. * Returns <0 on error. */
  9513. static int
  9514. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9515. {
  9516. int request_length;
  9517. int init_skip = 0;
  9518. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9519. * remote_port */
  9520. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9521. NULL;
  9522. ri->num_headers = 0;
  9523. /* RFC says that all initial whitespaces should be ignored */
  9524. /* This included all leading \r and \n (isspace) */
  9525. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9526. while ((len > 0) && isspace((unsigned char)*buf)) {
  9527. buf++;
  9528. len--;
  9529. init_skip++;
  9530. }
  9531. if (len == 0) {
  9532. /* Incomplete request */
  9533. return 0;
  9534. }
  9535. /* Control characters are not allowed, including zero */
  9536. if (iscntrl((unsigned char)*buf)) {
  9537. return -1;
  9538. }
  9539. /* Find end of HTTP header */
  9540. request_length = get_http_header_len(buf, len);
  9541. if (request_length <= 0) {
  9542. return request_length;
  9543. }
  9544. buf[request_length - 1] = '\0';
  9545. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9546. return -1;
  9547. }
  9548. /* The first word has to be the HTTP method */
  9549. ri->request_method = buf;
  9550. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9551. return -1;
  9552. }
  9553. /* The second word is the URI */
  9554. ri->request_uri = buf;
  9555. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9556. return -1;
  9557. }
  9558. /* Next would be the HTTP version */
  9559. ri->http_version = buf;
  9560. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9561. return -1;
  9562. }
  9563. /* Check for a valid HTTP version key */
  9564. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9565. /* Invalid request */
  9566. return -1;
  9567. }
  9568. ri->http_version += 5;
  9569. /* Check for a valid http method */
  9570. if (!is_valid_http_method(ri->request_method)) {
  9571. return -1;
  9572. }
  9573. /* Parse all HTTP headers */
  9574. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9575. if (ri->num_headers < 0) {
  9576. /* Error while parsing headers */
  9577. return -1;
  9578. }
  9579. return request_length + init_skip;
  9580. }
  9581. static int
  9582. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9583. {
  9584. int response_length;
  9585. int init_skip = 0;
  9586. char *tmp, *tmp2;
  9587. long l;
  9588. /* Initialize elements. */
  9589. ri->http_version = ri->status_text = NULL;
  9590. ri->num_headers = ri->status_code = 0;
  9591. /* RFC says that all initial whitespaces should be ignored */
  9592. /* This included all leading \r and \n (isspace) */
  9593. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9594. while ((len > 0) && isspace((unsigned char)*buf)) {
  9595. buf++;
  9596. len--;
  9597. init_skip++;
  9598. }
  9599. if (len == 0) {
  9600. /* Incomplete request */
  9601. return 0;
  9602. }
  9603. /* Control characters are not allowed, including zero */
  9604. if (iscntrl((unsigned char)*buf)) {
  9605. return -1;
  9606. }
  9607. /* Find end of HTTP header */
  9608. response_length = get_http_header_len(buf, len);
  9609. if (response_length <= 0) {
  9610. return response_length;
  9611. }
  9612. buf[response_length - 1] = '\0';
  9613. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9614. return -1;
  9615. }
  9616. /* The first word is the HTTP version */
  9617. /* Check for a valid HTTP version key */
  9618. if (strncmp(buf, "HTTP/", 5) != 0) {
  9619. /* Invalid request */
  9620. return -1;
  9621. }
  9622. buf += 5;
  9623. if (!isgraph((unsigned char)buf[0])) {
  9624. /* Invalid request */
  9625. return -1;
  9626. }
  9627. ri->http_version = buf;
  9628. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9629. return -1;
  9630. }
  9631. /* The second word is the status as a number */
  9632. tmp = buf;
  9633. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9634. return -1;
  9635. }
  9636. l = strtol(tmp, &tmp2, 10);
  9637. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9638. /* Everything else but a 3 digit code is invalid */
  9639. return -1;
  9640. }
  9641. ri->status_code = (int)l;
  9642. /* The rest of the line is the status text */
  9643. ri->status_text = buf;
  9644. /* Find end of status text */
  9645. /* isgraph or isspace = isprint */
  9646. while (isprint((unsigned char)*buf)) {
  9647. buf++;
  9648. }
  9649. if ((*buf != '\r') && (*buf != '\n')) {
  9650. return -1;
  9651. }
  9652. /* Terminate string and forward buf to next line */
  9653. do {
  9654. *buf = 0;
  9655. buf++;
  9656. } while (isspace((unsigned char)*buf));
  9657. /* Parse all HTTP headers */
  9658. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9659. if (ri->num_headers < 0) {
  9660. /* Error while parsing headers */
  9661. return -1;
  9662. }
  9663. return response_length + init_skip;
  9664. }
  9665. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9666. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9667. * buffer (which marks the end of HTTP request). Buffer buf may already
  9668. * have some data. The length of the data is stored in nread.
  9669. * Upon every read operation, increase nread by the number of bytes read. */
  9670. static int
  9671. read_message(FILE *fp,
  9672. struct mg_connection *conn,
  9673. char *buf,
  9674. int bufsiz,
  9675. int *nread)
  9676. {
  9677. int request_len, n = 0;
  9678. struct timespec last_action_time;
  9679. double request_timeout;
  9680. if (!conn) {
  9681. return 0;
  9682. }
  9683. memset(&last_action_time, 0, sizeof(last_action_time));
  9684. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9685. /* value of request_timeout is in seconds, config in milliseconds */
  9686. request_timeout =
  9687. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9688. } else {
  9689. request_timeout =
  9690. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9691. / 1000.0;
  9692. }
  9693. if (conn->handled_requests > 0) {
  9694. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9695. request_timeout =
  9696. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9697. / 1000.0;
  9698. }
  9699. }
  9700. request_len = get_http_header_len(buf, *nread);
  9701. while (request_len == 0) {
  9702. /* Full request not yet received */
  9703. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9704. /* Server is to be stopped. */
  9705. return -1;
  9706. }
  9707. if (*nread >= bufsiz) {
  9708. /* Request too long */
  9709. return -2;
  9710. }
  9711. n = pull_inner(
  9712. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9713. if (n == -2) {
  9714. /* Receive error */
  9715. return -1;
  9716. }
  9717. /* update clock after every read request */
  9718. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9719. if (n > 0) {
  9720. *nread += n;
  9721. request_len = get_http_header_len(buf, *nread);
  9722. }
  9723. if ((n <= 0) && (request_timeout >= 0)) {
  9724. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9725. > request_timeout) {
  9726. /* Timeout */
  9727. return -3;
  9728. }
  9729. }
  9730. }
  9731. return request_len;
  9732. }
  9733. #if !defined(NO_CGI) || !defined(NO_FILES)
  9734. static int
  9735. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9736. {
  9737. const char *expect;
  9738. char buf[MG_BUF_LEN];
  9739. int success = 0;
  9740. if (!conn) {
  9741. return 0;
  9742. }
  9743. expect = mg_get_header(conn, "Expect");
  9744. DEBUG_ASSERT(fp != NULL);
  9745. if (!fp) {
  9746. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9747. return 0;
  9748. }
  9749. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9750. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9751. */
  9752. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9753. } else {
  9754. if (expect != NULL) {
  9755. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9756. conn->status_code = 100;
  9757. } else {
  9758. conn->status_code = 200;
  9759. }
  9760. DEBUG_ASSERT(conn->consumed_content == 0);
  9761. if (conn->consumed_content != 0) {
  9762. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9763. return 0;
  9764. }
  9765. for (;;) {
  9766. int nread = mg_read(conn, buf, sizeof(buf));
  9767. if (nread <= 0) {
  9768. success = (nread == 0);
  9769. break;
  9770. }
  9771. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9772. break;
  9773. }
  9774. }
  9775. /* Each error code path in this function must send an error */
  9776. if (!success) {
  9777. /* NOTE: Maybe some data has already been sent. */
  9778. /* TODO (low): If some data has been sent, a correct error
  9779. * reply can no longer be sent, so just close the connection */
  9780. mg_send_http_error(conn, 500, "%s", "");
  9781. }
  9782. }
  9783. return success;
  9784. }
  9785. #endif
  9786. #if defined(USE_TIMERS)
  9787. #define TIMER_API static
  9788. #include "timer.inl"
  9789. #endif /* USE_TIMERS */
  9790. #if !defined(NO_CGI)
  9791. /* This structure helps to create an environment for the spawned CGI
  9792. * program.
  9793. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9794. * last element must be NULL.
  9795. * However, on Windows there is a requirement that all these
  9796. * VARIABLE=VALUE\0
  9797. * strings must reside in a contiguous buffer. The end of the buffer is
  9798. * marked by two '\0' characters.
  9799. * We satisfy both worlds: we create an envp array (which is vars), all
  9800. * entries are actually pointers inside buf. */
  9801. struct cgi_environment {
  9802. struct mg_connection *conn;
  9803. /* Data block */
  9804. char *buf; /* Environment buffer */
  9805. size_t buflen; /* Space available in buf */
  9806. size_t bufused; /* Space taken in buf */
  9807. /* Index block */
  9808. char **var; /* char **envp */
  9809. size_t varlen; /* Number of variables available in var */
  9810. size_t varused; /* Number of variables stored in var */
  9811. };
  9812. static void addenv(struct cgi_environment *env,
  9813. PRINTF_FORMAT_STRING(const char *fmt),
  9814. ...) PRINTF_ARGS(2, 3);
  9815. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9816. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9817. static void
  9818. addenv(struct cgi_environment *env, const char *fmt, ...)
  9819. {
  9820. size_t i, n, space;
  9821. int truncated = 0;
  9822. char *added;
  9823. va_list ap;
  9824. if ((env->varlen - env->varused) < 2) {
  9825. mg_cry_internal(env->conn,
  9826. "%s: Cannot register CGI variable [%s]",
  9827. __func__,
  9828. fmt);
  9829. return;
  9830. }
  9831. /* Calculate how much space is left in the buffer */
  9832. space = (env->buflen - env->bufused);
  9833. do {
  9834. /* Space for "\0\0" is always needed. */
  9835. if (space <= 2) {
  9836. /* Allocate new buffer */
  9837. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9838. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9839. if (!added) {
  9840. /* Out of memory */
  9841. mg_cry_internal(
  9842. env->conn,
  9843. "%s: Cannot allocate memory for CGI variable [%s]",
  9844. __func__,
  9845. fmt);
  9846. return;
  9847. }
  9848. /* Retarget pointers */
  9849. env->buf = added;
  9850. env->buflen = n;
  9851. for (i = 0, n = 0; i < env->varused; i++) {
  9852. env->var[i] = added + n;
  9853. n += strlen(added + n) + 1;
  9854. }
  9855. space = (env->buflen - env->bufused);
  9856. }
  9857. /* Make a pointer to the free space int the buffer */
  9858. added = env->buf + env->bufused;
  9859. /* Copy VARIABLE=VALUE\0 string into the free space */
  9860. va_start(ap, fmt);
  9861. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9862. va_end(ap);
  9863. /* Do not add truncated strings to the environment */
  9864. if (truncated) {
  9865. /* Reallocate the buffer */
  9866. space = 0;
  9867. }
  9868. } while (truncated);
  9869. /* Calculate number of bytes added to the environment */
  9870. n = strlen(added) + 1;
  9871. env->bufused += n;
  9872. /* Append a pointer to the added string into the envp array */
  9873. env->var[env->varused] = added;
  9874. env->varused++;
  9875. }
  9876. /* Return 0 on success, non-zero if an error occurs. */
  9877. static int
  9878. prepare_cgi_environment(struct mg_connection *conn,
  9879. const char *prog,
  9880. struct cgi_environment *env,
  9881. int cgi_config_idx)
  9882. {
  9883. const char *s;
  9884. struct vec var_vec;
  9885. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9886. int i, truncated, uri_len;
  9887. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9888. return -1;
  9889. }
  9890. env->conn = conn;
  9891. env->buflen = CGI_ENVIRONMENT_SIZE;
  9892. env->bufused = 0;
  9893. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9894. if (env->buf == NULL) {
  9895. mg_cry_internal(conn,
  9896. "%s: Not enough memory for environmental buffer",
  9897. __func__);
  9898. return -1;
  9899. }
  9900. env->varlen = MAX_CGI_ENVIR_VARS;
  9901. env->varused = 0;
  9902. env->var =
  9903. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9904. if (env->var == NULL) {
  9905. mg_cry_internal(conn,
  9906. "%s: Not enough memory for environmental variables",
  9907. __func__);
  9908. mg_free(env->buf);
  9909. return -1;
  9910. }
  9911. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9912. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9913. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9914. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  9915. addenv(env,
  9916. "FALLBACK_DOCUMENT_ROOT=%s",
  9917. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  9918. }
  9919. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9920. /* Prepare the environment block */
  9921. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9922. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9923. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9924. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9925. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9926. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9927. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9928. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9929. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9930. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9931. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9932. /* SCRIPT_NAME */
  9933. uri_len = (int)strlen(conn->request_info.local_uri);
  9934. if (conn->path_info == NULL) {
  9935. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9936. /* URI: /path_to_script/script.cgi */
  9937. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9938. } else {
  9939. /* URI: /path_to_script/ ... using index.cgi */
  9940. const char *index_file = strrchr(prog, '/');
  9941. if (index_file) {
  9942. addenv(env,
  9943. "SCRIPT_NAME=%s%s",
  9944. conn->request_info.local_uri,
  9945. index_file + 1);
  9946. }
  9947. }
  9948. } else {
  9949. /* URI: /path_to_script/script.cgi/path_info */
  9950. addenv(env,
  9951. "SCRIPT_NAME=%.*s",
  9952. uri_len - (int)strlen(conn->path_info),
  9953. conn->request_info.local_uri);
  9954. }
  9955. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9956. if (conn->path_info == NULL) {
  9957. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9958. } else {
  9959. addenv(env,
  9960. "PATH_TRANSLATED=%s%s",
  9961. conn->dom_ctx->config[DOCUMENT_ROOT],
  9962. conn->path_info);
  9963. }
  9964. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9965. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9966. addenv(env, "CONTENT_TYPE=%s", s);
  9967. }
  9968. if (conn->request_info.query_string != NULL) {
  9969. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9970. }
  9971. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9972. addenv(env, "CONTENT_LENGTH=%s", s);
  9973. }
  9974. if ((s = getenv("PATH")) != NULL) {
  9975. addenv(env, "PATH=%s", s);
  9976. }
  9977. if (conn->path_info != NULL) {
  9978. addenv(env, "PATH_INFO=%s", conn->path_info);
  9979. }
  9980. if (conn->status_code > 0) {
  9981. /* CGI error handler should show the status code */
  9982. addenv(env, "STATUS=%d", conn->status_code);
  9983. }
  9984. #if defined(_WIN32)
  9985. if ((s = getenv("COMSPEC")) != NULL) {
  9986. addenv(env, "COMSPEC=%s", s);
  9987. }
  9988. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9989. addenv(env, "SYSTEMROOT=%s", s);
  9990. }
  9991. if ((s = getenv("SystemDrive")) != NULL) {
  9992. addenv(env, "SystemDrive=%s", s);
  9993. }
  9994. if ((s = getenv("ProgramFiles")) != NULL) {
  9995. addenv(env, "ProgramFiles=%s", s);
  9996. }
  9997. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9998. addenv(env, "ProgramFiles(x86)=%s", s);
  9999. }
  10000. #else
  10001. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  10002. addenv(env, "LD_LIBRARY_PATH=%s", s);
  10003. }
  10004. #endif /* _WIN32 */
  10005. if ((s = getenv("PERLLIB")) != NULL) {
  10006. addenv(env, "PERLLIB=%s", s);
  10007. }
  10008. if (conn->request_info.remote_user != NULL) {
  10009. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  10010. addenv(env, "%s", "AUTH_TYPE=Digest");
  10011. }
  10012. /* Add all headers as HTTP_* variables */
  10013. for (i = 0; i < conn->request_info.num_headers; i++) {
  10014. (void)mg_snprintf(conn,
  10015. &truncated,
  10016. http_var_name,
  10017. sizeof(http_var_name),
  10018. "HTTP_%s",
  10019. conn->request_info.http_headers[i].name);
  10020. if (truncated) {
  10021. mg_cry_internal(conn,
  10022. "%s: HTTP header variable too long [%s]",
  10023. __func__,
  10024. conn->request_info.http_headers[i].name);
  10025. continue;
  10026. }
  10027. /* Convert variable name into uppercase, and change - to _ */
  10028. for (p = http_var_name; *p != '\0'; p++) {
  10029. if (*p == '-') {
  10030. *p = '_';
  10031. }
  10032. *p = (char)toupper((unsigned char)*p);
  10033. }
  10034. addenv(env,
  10035. "%s=%s",
  10036. http_var_name,
  10037. conn->request_info.http_headers[i].value);
  10038. }
  10039. /* Add user-specified variables */
  10040. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  10041. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  10042. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  10043. }
  10044. env->var[env->varused] = NULL;
  10045. env->buf[env->bufused] = '\0';
  10046. return 0;
  10047. }
  10048. /* Data for CGI process control: PID and number of references */
  10049. struct process_control_data {
  10050. pid_t pid;
  10051. ptrdiff_t references;
  10052. };
  10053. static int
  10054. abort_cgi_process(void *data)
  10055. {
  10056. /* Waitpid checks for child status and won't work for a pid that does
  10057. * not identify a child of the current process. Thus, if the pid is
  10058. * reused, we will not affect a different process. */
  10059. struct process_control_data *proc = (struct process_control_data *)data;
  10060. int status = 0;
  10061. ptrdiff_t refs;
  10062. pid_t ret_pid;
  10063. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  10064. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  10065. /* Stop child process */
  10066. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  10067. kill(proc->pid, SIGABRT);
  10068. /* Wait until process is terminated (don't leave zombies) */
  10069. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  10070. ;
  10071. } else {
  10072. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10073. }
  10074. /* Dec reference counter */
  10075. refs = mg_atomic_dec(&proc->references);
  10076. if (refs == 0) {
  10077. /* no more references - free data */
  10078. mg_free(data);
  10079. }
  10080. return 0;
  10081. }
  10082. /* Local (static) function assumes all arguments are valid. */
  10083. static void
  10084. handle_cgi_request(struct mg_connection *conn,
  10085. const char *prog,
  10086. int cgi_config_idx)
  10087. {
  10088. char *buf;
  10089. size_t buflen;
  10090. int headers_len, data_len, i, truncated;
  10091. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10092. const char *status, *status_text;
  10093. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10094. struct mg_request_info ri;
  10095. struct cgi_environment blk;
  10096. FILE *in = NULL, *out = NULL, *err = NULL;
  10097. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10098. pid_t pid = (pid_t)-1;
  10099. struct process_control_data *proc = NULL;
  10100. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  10101. int no_buffering = 0;
  10102. #if defined(USE_TIMERS)
  10103. double cgi_timeout;
  10104. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  10105. /* Get timeout in seconds */
  10106. cgi_timeout =
  10107. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  10108. } else {
  10109. cgi_timeout =
  10110. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10111. }
  10112. #endif
  10113. if (cfg_buffering != NULL) {
  10114. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10115. no_buffering = 1;
  10116. }
  10117. }
  10118. buf = NULL;
  10119. buflen = conn->phys_ctx->max_request_size;
  10120. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10121. if (i != 0) {
  10122. blk.buf = NULL;
  10123. blk.var = NULL;
  10124. goto done;
  10125. }
  10126. /* CGI must be executed in its own directory. 'dir' must point to the
  10127. * directory containing executable program, 'p' must point to the
  10128. * executable program name relative to 'dir'. */
  10129. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10130. if (truncated) {
  10131. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10132. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10133. goto done;
  10134. }
  10135. if ((p = strrchr(dir, '/')) != NULL) {
  10136. *p++ = '\0';
  10137. } else {
  10138. dir[0] = '.';
  10139. dir[1] = '\0';
  10140. p = (char *)prog;
  10141. }
  10142. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10143. status = strerror(ERRNO);
  10144. mg_cry_internal(
  10145. conn,
  10146. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10147. prog,
  10148. status);
  10149. mg_send_http_error(conn,
  10150. 500,
  10151. "Error: Cannot create CGI pipe: %s",
  10152. status);
  10153. goto done;
  10154. }
  10155. proc = (struct process_control_data *)
  10156. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10157. if (proc == NULL) {
  10158. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10159. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10160. goto done;
  10161. }
  10162. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10163. pid = spawn_process(
  10164. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10165. if (pid == (pid_t)-1) {
  10166. status = strerror(ERRNO);
  10167. mg_cry_internal(
  10168. conn,
  10169. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10170. prog,
  10171. status);
  10172. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10173. mg_free(proc);
  10174. proc = NULL;
  10175. goto done;
  10176. }
  10177. /* Store data in shared process_control_data */
  10178. proc->pid = pid;
  10179. proc->references = 1;
  10180. #if defined(USE_TIMERS)
  10181. if (cgi_timeout > 0.0) {
  10182. proc->references = 2;
  10183. // Start a timer for CGI
  10184. timer_add(conn->phys_ctx,
  10185. cgi_timeout /* in seconds */,
  10186. 0.0,
  10187. 1,
  10188. abort_cgi_process,
  10189. (void *)proc,
  10190. NULL);
  10191. }
  10192. #endif
  10193. /* Parent closes only one side of the pipes.
  10194. * If we don't mark them as closed, close() attempt before
  10195. * return from this function throws an exception on Windows.
  10196. * Windows does not like when closed descriptor is closed again. */
  10197. (void)close(fdin[0]);
  10198. (void)close(fdout[1]);
  10199. (void)close(fderr[1]);
  10200. fdin[0] = fdout[1] = fderr[1] = -1;
  10201. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10202. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10203. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10204. status = strerror(ERRNO);
  10205. mg_cry_internal(conn,
  10206. "Error: CGI program \"%s\": Can not open fd: %s",
  10207. prog,
  10208. status);
  10209. mg_send_http_error(conn,
  10210. 500,
  10211. "Error: CGI can not open fd\nfdopen: %s",
  10212. status);
  10213. goto done;
  10214. }
  10215. setbuf(in, NULL);
  10216. setbuf(out, NULL);
  10217. setbuf(err, NULL);
  10218. fout.access.fp = out;
  10219. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10220. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10221. conn->content_len);
  10222. /* This is a POST/PUT request, or another request with body data. */
  10223. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10224. /* Error sending the body data */
  10225. mg_cry_internal(
  10226. conn,
  10227. "Error: CGI program \"%s\": Forward body data failed",
  10228. prog);
  10229. goto done;
  10230. }
  10231. }
  10232. /* Close so child gets an EOF. */
  10233. fclose(in);
  10234. in = NULL;
  10235. fdin[1] = -1;
  10236. /* Now read CGI reply into a buffer. We need to set correct
  10237. * status code, thus we need to see all HTTP headers first.
  10238. * Do not send anything back to client, until we buffer in all
  10239. * HTTP headers. */
  10240. data_len = 0;
  10241. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10242. if (buf == NULL) {
  10243. mg_send_http_error(conn,
  10244. 500,
  10245. "Error: Not enough memory for CGI buffer (%u bytes)",
  10246. (unsigned int)buflen);
  10247. mg_cry_internal(
  10248. conn,
  10249. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10250. "bytes)",
  10251. prog,
  10252. (unsigned int)buflen);
  10253. goto done;
  10254. }
  10255. DEBUG_TRACE("CGI: %s", "wait for response");
  10256. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10257. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10258. if (headers_len <= 0) {
  10259. /* Could not parse the CGI response. Check if some error message on
  10260. * stderr. */
  10261. i = pull_all(err, conn, buf, (int)buflen);
  10262. if (i > 0) {
  10263. /* CGI program explicitly sent an error */
  10264. /* Write the error message to the internal log */
  10265. mg_cry_internal(conn,
  10266. "Error: CGI program \"%s\" sent error "
  10267. "message: [%.*s]",
  10268. prog,
  10269. i,
  10270. buf);
  10271. /* Don't send the error message back to the client */
  10272. mg_send_http_error(conn,
  10273. 500,
  10274. "Error: CGI program \"%s\" failed.",
  10275. prog);
  10276. } else {
  10277. /* CGI program did not explicitly send an error, but a broken
  10278. * respon header */
  10279. mg_cry_internal(conn,
  10280. "Error: CGI program sent malformed or too big "
  10281. "(>%u bytes) HTTP headers: [%.*s]",
  10282. (unsigned)buflen,
  10283. data_len,
  10284. buf);
  10285. mg_send_http_error(conn,
  10286. 500,
  10287. "Error: CGI program sent malformed or too big "
  10288. "(>%u bytes) HTTP headers: [%.*s]",
  10289. (unsigned)buflen,
  10290. data_len,
  10291. buf);
  10292. }
  10293. /* in both cases, abort processing CGI */
  10294. goto done;
  10295. }
  10296. pbuf = buf;
  10297. buf[headers_len - 1] = '\0';
  10298. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10299. /* Make up and send the status line */
  10300. status_text = "OK";
  10301. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10302. != NULL) {
  10303. conn->status_code = atoi(status);
  10304. status_text = status;
  10305. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10306. status_text++;
  10307. }
  10308. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10309. != NULL) {
  10310. conn->status_code = 307;
  10311. } else {
  10312. conn->status_code = 200;
  10313. }
  10314. if (!should_keep_alive(conn)) {
  10315. conn->must_close = 1;
  10316. }
  10317. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10318. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10319. /* Send headers */
  10320. for (i = 0; i < ri.num_headers; i++) {
  10321. DEBUG_TRACE("CGI header: %s: %s",
  10322. ri.http_headers[i].name,
  10323. ri.http_headers[i].value);
  10324. mg_printf(conn,
  10325. "%s: %s\r\n",
  10326. ri.http_headers[i].name,
  10327. ri.http_headers[i].value);
  10328. }
  10329. mg_write(conn, "\r\n", 2);
  10330. /* Send chunk of data that may have been read after the headers */
  10331. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10332. /* Read the rest of CGI output and send to the client */
  10333. DEBUG_TRACE("CGI: %s", "forward all data");
  10334. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10335. DEBUG_TRACE("CGI: %s", "all data sent");
  10336. done:
  10337. mg_free(blk.var);
  10338. mg_free(blk.buf);
  10339. if (pid != (pid_t)-1) {
  10340. abort_cgi_process((void *)proc);
  10341. }
  10342. if (fdin[0] != -1) {
  10343. close(fdin[0]);
  10344. }
  10345. if (fdout[1] != -1) {
  10346. close(fdout[1]);
  10347. }
  10348. if (fderr[1] != -1) {
  10349. close(fderr[1]);
  10350. }
  10351. if (in != NULL) {
  10352. fclose(in);
  10353. } else if (fdin[1] != -1) {
  10354. close(fdin[1]);
  10355. }
  10356. if (out != NULL) {
  10357. fclose(out);
  10358. } else if (fdout[0] != -1) {
  10359. close(fdout[0]);
  10360. }
  10361. if (err != NULL) {
  10362. fclose(err);
  10363. } else if (fderr[0] != -1) {
  10364. close(fderr[0]);
  10365. }
  10366. mg_free(buf);
  10367. }
  10368. #endif /* !NO_CGI */
  10369. #if !defined(NO_FILES)
  10370. static void
  10371. dav_mkcol(struct mg_connection *conn, const char *path)
  10372. {
  10373. int rc, body_len;
  10374. struct de de;
  10375. if (conn == NULL) {
  10376. return;
  10377. }
  10378. /* TODO (mid): Check the mg_send_http_error situations in this function
  10379. */
  10380. memset(&de.file, 0, sizeof(de.file));
  10381. if (!mg_stat(conn, path, &de.file)) {
  10382. mg_cry_internal(conn,
  10383. "%s: mg_stat(%s) failed: %s",
  10384. __func__,
  10385. path,
  10386. strerror(ERRNO));
  10387. }
  10388. if (de.file.last_modified) {
  10389. /* TODO (mid): This check does not seem to make any sense ! */
  10390. /* TODO (mid): Add a webdav unit test first, before changing
  10391. * anything here. */
  10392. mg_send_http_error(
  10393. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10394. return;
  10395. }
  10396. body_len = conn->data_len - conn->request_len;
  10397. if (body_len > 0) {
  10398. mg_send_http_error(
  10399. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10400. return;
  10401. }
  10402. rc = mg_mkdir(conn, path, 0755);
  10403. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10404. if (rc == 0) {
  10405. /* Create 201 "Created" response */
  10406. mg_response_header_start(conn, 201);
  10407. send_static_cache_header(conn);
  10408. send_additional_header(conn);
  10409. mg_response_header_add(conn, "Content-Length", "0", -1);
  10410. /* Send all headers - there is no body */
  10411. mg_response_header_send(conn);
  10412. } else {
  10413. int http_status = 500;
  10414. switch (errno) {
  10415. case EEXIST:
  10416. http_status = 405;
  10417. break;
  10418. case EACCES:
  10419. http_status = 403;
  10420. break;
  10421. case ENOENT:
  10422. http_status = 409;
  10423. break;
  10424. }
  10425. mg_send_http_error(conn,
  10426. http_status,
  10427. "Error processing %s: %s",
  10428. path,
  10429. strerror(ERRNO));
  10430. }
  10431. }
  10432. /* Forward decrlaration */
  10433. static int get_uri_type(const char *uri);
  10434. static const char *
  10435. get_rel_url_at_current_server(const char *uri,
  10436. const struct mg_connection *conn);
  10437. static void
  10438. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10439. {
  10440. const char *overwrite_hdr;
  10441. const char *destination_hdr;
  10442. const char *root;
  10443. int rc, dest_uri_type;
  10444. int http_status = 400;
  10445. int do_overwrite = 0;
  10446. int destination_ok = 0;
  10447. char dest_path[UTF8_PATH_MAX];
  10448. struct mg_file_stat ignored;
  10449. if (conn == NULL) {
  10450. return;
  10451. }
  10452. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10453. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10454. destination_hdr = mg_get_header(conn, "Destination");
  10455. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10456. do_overwrite = 1;
  10457. }
  10458. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10459. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10460. return;
  10461. }
  10462. if (root != NULL) {
  10463. char *local_dest = NULL;
  10464. dest_uri_type = get_uri_type(destination_hdr);
  10465. if (dest_uri_type == 2) {
  10466. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10467. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10468. const char *h =
  10469. get_rel_url_at_current_server(destination_hdr, conn);
  10470. if (h) {
  10471. size_t len = strlen(h);
  10472. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10473. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10474. }
  10475. }
  10476. if (local_dest != NULL) {
  10477. remove_dot_segments(local_dest);
  10478. if (local_dest[0] == '/') {
  10479. int trunc_check = 0;
  10480. mg_snprintf(conn,
  10481. &trunc_check,
  10482. dest_path,
  10483. sizeof(dest_path),
  10484. "%s/%s",
  10485. root,
  10486. local_dest);
  10487. if (trunc_check == 0) {
  10488. destination_ok = 1;
  10489. }
  10490. }
  10491. mg_free(local_dest);
  10492. }
  10493. }
  10494. if (!destination_ok) {
  10495. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10496. return;
  10497. }
  10498. /* Check now if this file exists */
  10499. if (mg_stat(conn, dest_path, &ignored)) {
  10500. /* File exists */
  10501. if (do_overwrite) {
  10502. /* Overwrite allowed: delete the file first */
  10503. if (0 != remove(dest_path)) {
  10504. /* No overwrite: return error */
  10505. mg_send_http_error(conn,
  10506. 403,
  10507. "Cannot overwrite file: %s",
  10508. dest_path);
  10509. return;
  10510. }
  10511. } else {
  10512. /* No overwrite: return error */
  10513. mg_send_http_error(conn,
  10514. 412,
  10515. "Destination already exists: %s",
  10516. dest_path);
  10517. return;
  10518. }
  10519. }
  10520. /* Copy / Move / Rename operation. */
  10521. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10522. #if defined(_WIN32)
  10523. {
  10524. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10525. wchar_t wSource[UTF16_PATH_MAX];
  10526. wchar_t wDest[UTF16_PATH_MAX];
  10527. BOOL ok;
  10528. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10529. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10530. if (do_copy) {
  10531. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10532. } else {
  10533. ok = MoveFileExW(wSource,
  10534. wDest,
  10535. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10536. }
  10537. if (ok) {
  10538. rc = 0;
  10539. } else {
  10540. DWORD lastErr = GetLastError();
  10541. if (lastErr == ERROR_ALREADY_EXISTS) {
  10542. mg_send_http_error(conn,
  10543. 412,
  10544. "Destination already exists: %s",
  10545. dest_path);
  10546. return;
  10547. }
  10548. rc = -1;
  10549. http_status = 400;
  10550. }
  10551. }
  10552. #else
  10553. {
  10554. /* Linux uses already UTF-8, we don't need to convert file names. */
  10555. if (do_copy) {
  10556. /* TODO: COPY for Linux. */
  10557. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10558. return;
  10559. }
  10560. rc = rename(path, dest_path);
  10561. if (rc) {
  10562. switch (errno) {
  10563. case EEXIST:
  10564. http_status = 412;
  10565. break;
  10566. case EACCES:
  10567. http_status = 403;
  10568. break;
  10569. case ENOENT:
  10570. http_status = 409;
  10571. break;
  10572. }
  10573. }
  10574. }
  10575. #endif
  10576. if (rc == 0) {
  10577. /* Create 204 "No Content" response */
  10578. mg_response_header_start(conn, 204);
  10579. mg_response_header_add(conn, "Content-Length", "0", -1);
  10580. /* Send all headers - there is no body */
  10581. mg_response_header_send(conn);
  10582. } else {
  10583. mg_send_http_error(conn, http_status, "Operation failed");
  10584. }
  10585. }
  10586. static void
  10587. put_file(struct mg_connection *conn, const char *path)
  10588. {
  10589. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10590. const char *range;
  10591. int64_t r1, r2;
  10592. int rc;
  10593. if (conn == NULL) {
  10594. return;
  10595. }
  10596. DEBUG_TRACE("store %s", path);
  10597. if (mg_stat(conn, path, &file.stat)) {
  10598. /* File already exists */
  10599. conn->status_code = 200;
  10600. if (file.stat.is_directory) {
  10601. /* This is an already existing directory,
  10602. * so there is nothing to do for the server. */
  10603. rc = 0;
  10604. } else {
  10605. /* File exists and is not a directory. */
  10606. /* Can it be replaced? */
  10607. /* Check if the server may write this file */
  10608. if (access(path, W_OK) == 0) {
  10609. /* Access granted */
  10610. rc = 1;
  10611. } else {
  10612. mg_send_http_error(
  10613. conn,
  10614. 403,
  10615. "Error: Put not possible\nReplacing %s is not allowed",
  10616. path);
  10617. return;
  10618. }
  10619. }
  10620. } else {
  10621. /* File should be created */
  10622. conn->status_code = 201;
  10623. rc = put_dir(conn, path);
  10624. }
  10625. if (rc == 0) {
  10626. /* put_dir returns 0 if path is a directory */
  10627. /* Create response */
  10628. mg_response_header_start(conn, conn->status_code);
  10629. send_no_cache_header(conn);
  10630. send_additional_header(conn);
  10631. mg_response_header_add(conn, "Content-Length", "0", -1);
  10632. /* Send all headers - there is no body */
  10633. mg_response_header_send(conn);
  10634. /* Request to create a directory has been fulfilled successfully.
  10635. * No need to put a file. */
  10636. return;
  10637. }
  10638. if (rc == -1) {
  10639. /* put_dir returns -1 if the path is too long */
  10640. mg_send_http_error(conn,
  10641. 414,
  10642. "Error: Path too long\nput_dir(%s): %s",
  10643. path,
  10644. strerror(ERRNO));
  10645. return;
  10646. }
  10647. if (rc == -2) {
  10648. /* put_dir returns -2 if the directory can not be created */
  10649. mg_send_http_error(conn,
  10650. 500,
  10651. "Error: Can not create directory\nput_dir(%s): %s",
  10652. path,
  10653. strerror(ERRNO));
  10654. return;
  10655. }
  10656. /* A file should be created or overwritten. */
  10657. /* Currently CivetWeb does not need read+write access. */
  10658. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10659. || file.access.fp == NULL) {
  10660. (void)mg_fclose(&file.access);
  10661. mg_send_http_error(conn,
  10662. 500,
  10663. "Error: Can not create file\nfopen(%s): %s",
  10664. path,
  10665. strerror(ERRNO));
  10666. return;
  10667. }
  10668. fclose_on_exec(&file.access, conn);
  10669. range = mg_get_header(conn, "Content-Range");
  10670. r1 = r2 = 0;
  10671. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10672. conn->status_code = 206; /* Partial content */
  10673. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10674. mg_send_http_error(conn,
  10675. 500,
  10676. "Error: Internal error processing file %s",
  10677. path);
  10678. return;
  10679. }
  10680. }
  10681. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10682. /* forward_body_data failed.
  10683. * The error code has already been sent to the client,
  10684. * and conn->status_code is already set. */
  10685. (void)mg_fclose(&file.access);
  10686. return;
  10687. }
  10688. if (mg_fclose(&file.access) != 0) {
  10689. /* fclose failed. This might have different reasons, but a likely
  10690. * one is "no space on disk", http 507. */
  10691. conn->status_code = 507;
  10692. }
  10693. /* Create response (status_code has been set before) */
  10694. mg_response_header_start(conn, conn->status_code);
  10695. send_no_cache_header(conn);
  10696. send_additional_header(conn);
  10697. mg_response_header_add(conn, "Content-Length", "0", -1);
  10698. /* Send all headers - there is no body */
  10699. mg_response_header_send(conn);
  10700. }
  10701. static void
  10702. delete_file(struct mg_connection *conn, const char *path)
  10703. {
  10704. struct de de;
  10705. memset(&de.file, 0, sizeof(de.file));
  10706. if (!mg_stat(conn, path, &de.file)) {
  10707. /* mg_stat returns 0 if the file does not exist */
  10708. mg_send_http_error(conn,
  10709. 404,
  10710. "Error: Cannot delete file\nFile %s not found",
  10711. path);
  10712. return;
  10713. }
  10714. DEBUG_TRACE("delete %s", path);
  10715. if (de.file.is_directory) {
  10716. if (remove_directory(conn, path)) {
  10717. /* Delete is successful: Return 204 without content. */
  10718. mg_send_http_error(conn, 204, "%s", "");
  10719. } else {
  10720. /* Delete is not successful: Return 500 (Server error). */
  10721. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10722. }
  10723. return;
  10724. }
  10725. /* This is an existing file (not a directory).
  10726. * Check if write permission is granted. */
  10727. if (access(path, W_OK) != 0) {
  10728. /* File is read only */
  10729. mg_send_http_error(
  10730. conn,
  10731. 403,
  10732. "Error: Delete not possible\nDeleting %s is not allowed",
  10733. path);
  10734. return;
  10735. }
  10736. /* Try to delete it. */
  10737. if (mg_remove(conn, path) == 0) {
  10738. /* Delete was successful: Return 204 without content. */
  10739. mg_response_header_start(conn, 204);
  10740. send_no_cache_header(conn);
  10741. send_additional_header(conn);
  10742. mg_response_header_add(conn, "Content-Length", "0", -1);
  10743. mg_response_header_send(conn);
  10744. } else {
  10745. /* Delete not successful (file locked). */
  10746. mg_send_http_error(conn,
  10747. 423,
  10748. "Error: Cannot delete file\nremove(%s): %s",
  10749. path,
  10750. strerror(ERRNO));
  10751. }
  10752. }
  10753. #endif /* !NO_FILES */
  10754. #if !defined(NO_FILESYSTEMS)
  10755. static void
  10756. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10757. static void
  10758. do_ssi_include(struct mg_connection *conn,
  10759. const char *ssi,
  10760. char *tag,
  10761. int include_level)
  10762. {
  10763. char file_name[MG_BUF_LEN], path[512], *p;
  10764. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10765. size_t len;
  10766. int truncated = 0;
  10767. if (conn == NULL) {
  10768. return;
  10769. }
  10770. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10771. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10772. * always < MG_BUF_LEN. */
  10773. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10774. /* File name is relative to the webserver root */
  10775. file_name[511] = 0;
  10776. (void)mg_snprintf(conn,
  10777. &truncated,
  10778. path,
  10779. sizeof(path),
  10780. "%s/%s",
  10781. conn->dom_ctx->config[DOCUMENT_ROOT],
  10782. file_name);
  10783. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10784. /* File name is relative to the webserver working directory
  10785. * or it is absolute system path */
  10786. file_name[511] = 0;
  10787. (void)
  10788. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10789. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10790. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10791. /* File name is relative to the current document */
  10792. file_name[511] = 0;
  10793. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10794. if (!truncated) {
  10795. if ((p = strrchr(path, '/')) != NULL) {
  10796. p[1] = '\0';
  10797. }
  10798. len = strlen(path);
  10799. (void)mg_snprintf(conn,
  10800. &truncated,
  10801. path + len,
  10802. sizeof(path) - len,
  10803. "%s",
  10804. file_name);
  10805. }
  10806. } else {
  10807. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10808. return;
  10809. }
  10810. if (truncated) {
  10811. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10812. return;
  10813. }
  10814. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10815. mg_cry_internal(conn,
  10816. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10817. tag,
  10818. path,
  10819. strerror(ERRNO));
  10820. } else {
  10821. fclose_on_exec(&file.access, conn);
  10822. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10823. > 0) {
  10824. send_ssi_file(conn, path, &file, include_level + 1);
  10825. } else {
  10826. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10827. }
  10828. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10829. }
  10830. }
  10831. #if !defined(NO_POPEN)
  10832. static void
  10833. do_ssi_exec(struct mg_connection *conn, char *tag)
  10834. {
  10835. char cmd[1024] = "";
  10836. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10837. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10838. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10839. } else {
  10840. cmd[1023] = 0;
  10841. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10842. mg_cry_internal(conn,
  10843. "Cannot SSI #exec: [%s]: %s",
  10844. cmd,
  10845. strerror(ERRNO));
  10846. } else {
  10847. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10848. pclose(file.access.fp);
  10849. }
  10850. }
  10851. }
  10852. #endif /* !NO_POPEN */
  10853. static int
  10854. mg_fgetc(struct mg_file *filep)
  10855. {
  10856. if (filep == NULL) {
  10857. return EOF;
  10858. }
  10859. if (filep->access.fp != NULL) {
  10860. return fgetc(filep->access.fp);
  10861. } else {
  10862. return EOF;
  10863. }
  10864. }
  10865. static void
  10866. send_ssi_file(struct mg_connection *conn,
  10867. const char *path,
  10868. struct mg_file *filep,
  10869. int include_level)
  10870. {
  10871. char buf[MG_BUF_LEN];
  10872. int ch, len, in_tag, in_ssi_tag;
  10873. if (include_level > 10) {
  10874. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10875. return;
  10876. }
  10877. in_tag = in_ssi_tag = len = 0;
  10878. /* Read file, byte by byte, and look for SSI include tags */
  10879. while ((ch = mg_fgetc(filep)) != EOF) {
  10880. if (in_tag) {
  10881. /* We are in a tag, either SSI tag or html tag */
  10882. if (ch == '>') {
  10883. /* Tag is closing */
  10884. buf[len++] = '>';
  10885. if (in_ssi_tag) {
  10886. /* Handle SSI tag */
  10887. buf[len] = 0;
  10888. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10889. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10890. #if !defined(NO_POPEN)
  10891. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10892. do_ssi_exec(conn, buf + 9);
  10893. #endif /* !NO_POPEN */
  10894. } else {
  10895. mg_cry_internal(conn,
  10896. "%s: unknown SSI "
  10897. "command: \"%s\"",
  10898. path,
  10899. buf);
  10900. }
  10901. len = 0;
  10902. in_ssi_tag = in_tag = 0;
  10903. } else {
  10904. /* Not an SSI tag */
  10905. /* Flush buffer */
  10906. (void)mg_write(conn, buf, (size_t)len);
  10907. len = 0;
  10908. in_tag = 0;
  10909. }
  10910. } else {
  10911. /* Tag is still open */
  10912. buf[len++] = (char)(ch & 0xff);
  10913. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10914. /* All SSI tags start with <!--# */
  10915. in_ssi_tag = 1;
  10916. }
  10917. if ((len + 2) > (int)sizeof(buf)) {
  10918. /* Tag to long for buffer */
  10919. mg_cry_internal(conn, "%s: tag is too large", path);
  10920. return;
  10921. }
  10922. }
  10923. } else {
  10924. /* We are not in a tag yet. */
  10925. if (ch == '<') {
  10926. /* Tag is opening */
  10927. in_tag = 1;
  10928. if (len > 0) {
  10929. /* Flush current buffer.
  10930. * Buffer is filled with "len" bytes. */
  10931. (void)mg_write(conn, buf, (size_t)len);
  10932. }
  10933. /* Store the < */
  10934. len = 1;
  10935. buf[0] = '<';
  10936. } else {
  10937. /* No Tag */
  10938. /* Add data to buffer */
  10939. buf[len++] = (char)(ch & 0xff);
  10940. /* Flush if buffer is full */
  10941. if (len == (int)sizeof(buf)) {
  10942. mg_write(conn, buf, (size_t)len);
  10943. len = 0;
  10944. }
  10945. }
  10946. }
  10947. }
  10948. /* Send the rest of buffered data */
  10949. if (len > 0) {
  10950. mg_write(conn, buf, (size_t)len);
  10951. }
  10952. }
  10953. static void
  10954. handle_ssi_file_request(struct mg_connection *conn,
  10955. const char *path,
  10956. struct mg_file *filep)
  10957. {
  10958. char date[64];
  10959. time_t curtime = time(NULL);
  10960. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10961. return;
  10962. }
  10963. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10964. /* File exists (precondition for calling this function),
  10965. * but can not be opened by the server. */
  10966. mg_send_http_error(conn,
  10967. 500,
  10968. "Error: Cannot read file\nfopen(%s): %s",
  10969. path,
  10970. strerror(ERRNO));
  10971. } else {
  10972. /* Set "must_close" for HTTP/1.x, since we do not know the
  10973. * content length */
  10974. conn->must_close = 1;
  10975. gmt_time_string(date, sizeof(date), &curtime);
  10976. fclose_on_exec(&filep->access, conn);
  10977. /* 200 OK response */
  10978. mg_response_header_start(conn, 200);
  10979. send_no_cache_header(conn);
  10980. send_additional_header(conn);
  10981. send_cors_header(conn);
  10982. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10983. mg_response_header_send(conn);
  10984. /* Header sent, now send body */
  10985. send_ssi_file(conn, path, filep, 0);
  10986. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10987. }
  10988. }
  10989. #endif /* NO_FILESYSTEMS */
  10990. #if !defined(NO_FILES)
  10991. static void
  10992. send_options(struct mg_connection *conn)
  10993. {
  10994. if (!conn || !all_methods) {
  10995. return;
  10996. }
  10997. /* We do not set a "Cache-Control" header here, but leave the default.
  10998. * Since browsers do not send an OPTIONS request, we can not test the
  10999. * effect anyway. */
  11000. mg_response_header_start(conn, 200);
  11001. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11002. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  11003. /* Use the same as before */
  11004. mg_response_header_add(conn, "Allow", all_methods, -1);
  11005. mg_response_header_add(conn, "DAV", "1", -1);
  11006. } else {
  11007. /* TODO: Check this later for HTTP/2 */
  11008. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  11009. }
  11010. send_additional_header(conn);
  11011. mg_response_header_send(conn);
  11012. }
  11013. /* Writes PROPFIND properties for a collection element */
  11014. static int
  11015. print_props(struct mg_connection *conn,
  11016. const char *uri,
  11017. const char *name,
  11018. struct mg_file_stat *filep)
  11019. {
  11020. size_t i;
  11021. char mtime[64];
  11022. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11023. char *link_concat;
  11024. size_t link_concat_len;
  11025. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  11026. return 0;
  11027. }
  11028. link_concat_len = strlen(uri) + strlen(name) + 1;
  11029. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  11030. if (!link_concat) {
  11031. return 0;
  11032. }
  11033. strcpy(link_concat, uri);
  11034. strcat(link_concat, name);
  11035. /* Get full link used in request */
  11036. mg_construct_local_link(
  11037. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  11038. /*
  11039. OutputDebugStringA("print_props:\n uri: ");
  11040. OutputDebugStringA(uri);
  11041. OutputDebugStringA("\n name: ");
  11042. OutputDebugStringA(name);
  11043. OutputDebugStringA("\n link: ");
  11044. OutputDebugStringA(link_buf);
  11045. OutputDebugStringA("\n");
  11046. */
  11047. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  11048. mg_printf(conn,
  11049. "<d:response>"
  11050. "<d:href>%s</d:href>"
  11051. "<d:propstat>"
  11052. "<d:prop>"
  11053. "<d:resourcetype>%s</d:resourcetype>"
  11054. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  11055. "<d:getlastmodified>%s</d:getlastmodified>"
  11056. "<d:lockdiscovery>",
  11057. link_buf,
  11058. filep->is_directory ? "<d:collection/>" : "",
  11059. filep->size,
  11060. mtime);
  11061. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11062. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11063. if (!strcmp(dav_lock[i].path, link_buf)) {
  11064. mg_printf(conn,
  11065. "<d:activelock>"
  11066. "<d:locktype><d:write/></d:locktype>"
  11067. "<d:lockscope><d:exclusive/></d:lockscope>"
  11068. "<d:depth>0</d:depth>"
  11069. "<d:owner>%s</d:owner>"
  11070. "<d:timeout>Second-%u</d:timeout>"
  11071. "<d:locktoken>"
  11072. "<d:href>%s</d:href>"
  11073. "</d:locktoken>"
  11074. "</d:activelock>\n",
  11075. dav_lock[i].user,
  11076. (unsigned)LOCK_DURATION_S,
  11077. dav_lock[i].token);
  11078. }
  11079. }
  11080. mg_printf(conn,
  11081. "</d:lockdiscovery>"
  11082. "</d:prop>"
  11083. "<d:status>HTTP/1.1 200 OK</d:status>"
  11084. "</d:propstat>"
  11085. "</d:response>\n");
  11086. mg_free(link_concat);
  11087. return 1;
  11088. }
  11089. static int
  11090. print_dav_dir_entry(struct de *de, void *data)
  11091. {
  11092. struct mg_connection *conn = (struct mg_connection *)data;
  11093. if (!de || !conn
  11094. || !print_props(
  11095. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  11096. /* stop scan */
  11097. return 1;
  11098. }
  11099. return 0;
  11100. }
  11101. static void
  11102. handle_propfind(struct mg_connection *conn,
  11103. const char *path,
  11104. struct mg_file_stat *filep)
  11105. {
  11106. const char *depth = mg_get_header(conn, "Depth");
  11107. if (!conn || !path || !filep || !conn->dom_ctx) {
  11108. return;
  11109. }
  11110. /* return 207 "Multi-Status" */
  11111. conn->must_close = 1;
  11112. mg_response_header_start(conn, 207);
  11113. send_static_cache_header(conn);
  11114. send_additional_header(conn);
  11115. mg_response_header_add(conn,
  11116. "Content-Type",
  11117. "application/xml; charset=utf-8",
  11118. -1);
  11119. mg_response_header_send(conn);
  11120. /* Content */
  11121. mg_printf(conn,
  11122. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11123. "<d:multistatus xmlns:d='DAV:'>\n");
  11124. /* Print properties for the requested resource itself */
  11125. print_props(conn, conn->request_info.local_uri, "", filep);
  11126. /* If it is a directory, print directory entries too if Depth is not 0
  11127. */
  11128. if (filep->is_directory
  11129. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11130. "yes")
  11131. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11132. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11133. }
  11134. mg_printf(conn, "%s\n", "</d:multistatus>");
  11135. }
  11136. static void
  11137. dav_lock_file(struct mg_connection *conn, const char *path)
  11138. {
  11139. /* internal function - therefore conn is assumed to be valid */
  11140. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11141. uint64_t new_locktime;
  11142. int lock_index = -1;
  11143. int i;
  11144. uint64_t LOCK_DURATION_NS =
  11145. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11146. struct twebdav_lock *dav_lock = NULL;
  11147. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11148. || !conn->phys_ctx) {
  11149. return;
  11150. }
  11151. dav_lock = conn->phys_ctx->webdav_lock;
  11152. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11153. /* const char *refresh = mg_get_header(conn, "If"); */
  11154. /* Link refresh should have an "If" header:
  11155. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11156. * But it seems Windows Explorer does not send them.
  11157. */
  11158. mg_lock_context(conn->phys_ctx);
  11159. new_locktime = mg_get_current_time_ns();
  11160. /* Find a slot for a lock */
  11161. while (lock_index < 0) {
  11162. /* find existing lock */
  11163. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11164. if (!strcmp(dav_lock[i].path, link_buf)) {
  11165. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11166. /* locked by the same user */
  11167. dav_lock[i].locktime = new_locktime;
  11168. lock_index = i;
  11169. break;
  11170. } else {
  11171. /* already locked by someone else */
  11172. if (new_locktime
  11173. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11174. /* Lock expired */
  11175. dav_lock[i].path[0] = 0;
  11176. } else {
  11177. /* Lock still valid */
  11178. mg_unlock_context(conn->phys_ctx);
  11179. mg_send_http_error(conn, 423, "%s", "Already locked");
  11180. return;
  11181. }
  11182. }
  11183. }
  11184. }
  11185. /* create new lock token */
  11186. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11187. if (dav_lock[i].path[0] == 0) {
  11188. char s[32];
  11189. dav_lock[i].locktime = mg_get_current_time_ns();
  11190. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11191. mg_md5(dav_lock[i].token,
  11192. link_buf,
  11193. "\x01",
  11194. s,
  11195. "\x01",
  11196. conn->request_info.remote_user,
  11197. NULL);
  11198. mg_strlcpy(dav_lock[i].path,
  11199. link_buf,
  11200. sizeof(dav_lock[i].path));
  11201. mg_strlcpy(dav_lock[i].user,
  11202. conn->request_info.remote_user,
  11203. sizeof(dav_lock[i].user));
  11204. lock_index = i;
  11205. break;
  11206. }
  11207. }
  11208. if (lock_index < 0) {
  11209. /* too many locks. Find oldest lock */
  11210. uint64_t oldest_locktime = dav_lock[0].locktime;
  11211. lock_index = 0;
  11212. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11213. if (dav_lock[i].locktime < oldest_locktime) {
  11214. oldest_locktime = dav_lock[i].locktime;
  11215. lock_index = i;
  11216. }
  11217. }
  11218. /* invalidate oldest lock */
  11219. dav_lock[lock_index].path[0] = 0;
  11220. }
  11221. }
  11222. mg_unlock_context(conn->phys_ctx);
  11223. /* return 200 "OK" */
  11224. conn->must_close = 1;
  11225. mg_response_header_start(conn, 200);
  11226. send_static_cache_header(conn);
  11227. send_additional_header(conn);
  11228. mg_response_header_add(conn,
  11229. "Content-Type",
  11230. "application/xml; charset=utf-8",
  11231. -1);
  11232. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11233. mg_response_header_send(conn);
  11234. /* Content */
  11235. mg_printf(conn,
  11236. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11237. "<d:prop xmlns:d=\"DAV:\">\n"
  11238. " <d:lockdiscovery>\n"
  11239. " <d:activelock>\n"
  11240. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11241. " <d:locktype><d:write/></d:locktype>\n"
  11242. " <d:owner>\n"
  11243. " <d:href>%s</d:href>\n"
  11244. " </d:owner>\n"
  11245. " <d:timeout>Second-%u</d:timeout>\n"
  11246. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11247. " <d:lockroot>\n"
  11248. " <d:href>%s</d:href>\n"
  11249. " </d:lockroot>\n"
  11250. " </d:activelock>\n"
  11251. " </d:lockdiscovery>\n"
  11252. " </d:prop>\n",
  11253. dav_lock[lock_index].user,
  11254. (LOCK_DURATION_S),
  11255. dav_lock[lock_index].token,
  11256. dav_lock[lock_index].path);
  11257. }
  11258. static void
  11259. dav_unlock_file(struct mg_connection *conn, const char *path)
  11260. {
  11261. /* internal function - therefore conn is assumed to be valid */
  11262. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11263. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11264. int lock_index;
  11265. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11266. return;
  11267. }
  11268. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11269. mg_lock_context(conn->phys_ctx);
  11270. /* find existing lock */
  11271. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11272. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11273. /* Success: return 204 "No Content" */
  11274. mg_unlock_context(conn->phys_ctx);
  11275. conn->must_close = 1;
  11276. mg_response_header_start(conn, 204);
  11277. mg_response_header_send(conn);
  11278. return;
  11279. }
  11280. }
  11281. mg_unlock_context(conn->phys_ctx);
  11282. /* Error: Cannot unlock a resource that is not locked */
  11283. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11284. }
  11285. static void
  11286. dav_proppatch(struct mg_connection *conn, const char *path)
  11287. {
  11288. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11289. if (!conn || !path || !conn->dom_ctx) {
  11290. return;
  11291. }
  11292. /* return 207 "Multi-Status" */
  11293. conn->must_close = 1;
  11294. mg_response_header_start(conn, 207);
  11295. send_static_cache_header(conn);
  11296. send_additional_header(conn);
  11297. mg_response_header_add(conn,
  11298. "Content-Type",
  11299. "application/xml; charset=utf-8",
  11300. -1);
  11301. mg_response_header_send(conn);
  11302. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11303. /* Content */
  11304. mg_printf(conn,
  11305. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11306. "<d:multistatus xmlns:d='DAV:'>\n"
  11307. "<d:response>\n<d:href>%s</d:href>\n",
  11308. link_buf);
  11309. mg_printf(conn,
  11310. "<d:propstat><d:status>HTTP/1.1 403 "
  11311. "Forbidden</d:status></d:propstat>\n");
  11312. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11313. }
  11314. #endif
  11315. CIVETWEB_API void
  11316. mg_lock_connection(struct mg_connection *conn)
  11317. {
  11318. if (conn) {
  11319. (void)pthread_mutex_lock(&conn->mutex);
  11320. }
  11321. }
  11322. CIVETWEB_API void
  11323. mg_unlock_connection(struct mg_connection *conn)
  11324. {
  11325. if (conn) {
  11326. (void)pthread_mutex_unlock(&conn->mutex);
  11327. }
  11328. }
  11329. CIVETWEB_API void
  11330. mg_lock_context(struct mg_context *ctx)
  11331. {
  11332. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11333. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11334. }
  11335. }
  11336. CIVETWEB_API void
  11337. mg_unlock_context(struct mg_context *ctx)
  11338. {
  11339. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11340. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11341. }
  11342. }
  11343. #if defined(USE_LUA)
  11344. #include "mod_lua.inl"
  11345. #endif /* USE_LUA */
  11346. #if defined(USE_DUKTAPE)
  11347. #include "mod_duktape.inl"
  11348. #endif /* USE_DUKTAPE */
  11349. #if defined(USE_WEBSOCKET)
  11350. #if !defined(NO_SSL_DL)
  11351. #if !defined(OPENSSL_API_3_0)
  11352. #define SHA_API static
  11353. #include "sha1.inl"
  11354. #endif
  11355. #endif
  11356. static int
  11357. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11358. {
  11359. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11360. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11361. size_t dst_len = sizeof(b64_sha);
  11362. #if !defined(OPENSSL_API_3_0)
  11363. SHA_CTX sha_ctx;
  11364. #endif
  11365. int truncated;
  11366. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11367. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11368. if (truncated) {
  11369. conn->must_close = 1;
  11370. return 0;
  11371. }
  11372. DEBUG_TRACE("%s", "Send websocket handshake");
  11373. #if defined(OPENSSL_API_3_0)
  11374. EVP_Digest((unsigned char *)buf,
  11375. (uint32_t)strlen(buf),
  11376. (unsigned char *)sha,
  11377. NULL,
  11378. EVP_get_digestbyname("sha1"),
  11379. NULL);
  11380. #else
  11381. SHA1_Init(&sha_ctx);
  11382. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11383. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11384. #endif
  11385. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11386. mg_printf(conn,
  11387. "HTTP/1.1 101 Switching Protocols\r\n"
  11388. "Upgrade: websocket\r\n"
  11389. "Connection: Upgrade\r\n"
  11390. "Sec-WebSocket-Accept: %s\r\n",
  11391. b64_sha);
  11392. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11393. // Send negotiated compression extension parameters
  11394. websocket_deflate_response(conn);
  11395. #endif
  11396. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11397. mg_printf(conn,
  11398. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11399. conn->request_info.acceptedWebSocketSubprotocol);
  11400. } else {
  11401. mg_printf(conn, "%s", "\r\n");
  11402. }
  11403. return 1;
  11404. }
  11405. #if !defined(MG_MAX_UNANSWERED_PING)
  11406. /* Configuration of the maximum number of websocket PINGs that might
  11407. * stay unanswered before the connection is considered broken.
  11408. * Note: The name of this define may still change (until it is
  11409. * defined as a compile parameter in a documentation).
  11410. */
  11411. #define MG_MAX_UNANSWERED_PING (5)
  11412. #endif
  11413. static void
  11414. read_websocket(struct mg_connection *conn,
  11415. mg_websocket_data_handler ws_data_handler,
  11416. void *callback_data)
  11417. {
  11418. /* Pointer to the beginning of the portion of the incoming websocket
  11419. * message queue.
  11420. * The original websocket upgrade request is never removed, so the queue
  11421. * begins after it. */
  11422. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11423. int n, error, exit_by_callback;
  11424. int ret;
  11425. /* body_len is the length of the entire queue in bytes
  11426. * len is the length of the current message
  11427. * data_len is the length of the current message's data payload
  11428. * header_len is the length of the current message's header */
  11429. size_t i, len, mask_len = 0, header_len, body_len;
  11430. uint64_t data_len = 0;
  11431. /* "The masking key is a 32-bit value chosen at random by the client."
  11432. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11433. */
  11434. unsigned char mask[4];
  11435. /* data points to the place where the message is stored when passed to
  11436. * the websocket_data callback. This is either mem on the stack, or a
  11437. * dynamically allocated buffer if it is too large. */
  11438. unsigned char mem[4096];
  11439. unsigned char mop; /* mask flag and opcode */
  11440. /* Variables used for connection monitoring */
  11441. double timeout = -1.0;
  11442. int enable_ping_pong = 0;
  11443. int ping_count = 0;
  11444. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11445. enable_ping_pong =
  11446. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11447. "yes");
  11448. }
  11449. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11450. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11451. }
  11452. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11453. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11454. }
  11455. if (timeout <= 0.0) {
  11456. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11457. }
  11458. /* Enter data processing loop */
  11459. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11460. conn->request_info.remote_addr,
  11461. conn->request_info.remote_port);
  11462. conn->in_websocket_handling = 1;
  11463. mg_set_thread_name("wsock");
  11464. /* Loop continuously, reading messages from the socket, invoking the
  11465. * callback, and waiting repeatedly until an error occurs. */
  11466. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11467. && (!conn->must_close)) {
  11468. header_len = 0;
  11469. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11470. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11471. len = buf[1] & 127;
  11472. mask_len = (buf[1] & 128) ? 4 : 0;
  11473. if ((len < 126) && (body_len >= mask_len)) {
  11474. /* inline 7-bit length field */
  11475. data_len = len;
  11476. header_len = 2 + mask_len;
  11477. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11478. /* 16-bit length field */
  11479. header_len = 4 + mask_len;
  11480. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11481. } else if (body_len >= (10 + mask_len)) {
  11482. /* 64-bit length field */
  11483. uint32_t l1, l2;
  11484. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11485. memcpy(&l2, &buf[6], 4);
  11486. header_len = 10 + mask_len;
  11487. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11488. if (data_len > (uint64_t)0x7FFF0000ul) {
  11489. /* no can do */
  11490. mg_cry_internal(
  11491. conn,
  11492. "%s",
  11493. "websocket out of memory; closing connection");
  11494. break;
  11495. }
  11496. }
  11497. }
  11498. if ((header_len > 0) && (body_len >= header_len)) {
  11499. /* Allocate space to hold websocket payload */
  11500. unsigned char *data = mem;
  11501. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11502. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11503. conn->phys_ctx);
  11504. if (data == NULL) {
  11505. /* Allocation failed, exit the loop and then close the
  11506. * connection */
  11507. mg_cry_internal(
  11508. conn,
  11509. "%s",
  11510. "websocket out of memory; closing connection");
  11511. break;
  11512. }
  11513. }
  11514. /* Copy the mask before we shift the queue and destroy it */
  11515. if (mask_len > 0) {
  11516. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11517. } else {
  11518. memset(mask, 0, sizeof(mask));
  11519. }
  11520. /* Read frame payload from the first message in the queue into
  11521. * data and advance the queue by moving the memory in place. */
  11522. DEBUG_ASSERT(body_len >= header_len);
  11523. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11524. mop = buf[0]; /* current mask and opcode */
  11525. /* Overflow case */
  11526. len = body_len - header_len;
  11527. memcpy(data, buf + header_len, len);
  11528. error = 0;
  11529. while ((uint64_t)len < data_len) {
  11530. n = pull_inner(NULL,
  11531. conn,
  11532. (char *)(data + len),
  11533. (int)(data_len - len),
  11534. timeout);
  11535. if (n <= -2) {
  11536. error = 1;
  11537. break;
  11538. } else if (n > 0) {
  11539. len += (size_t)n;
  11540. } else {
  11541. /* Timeout: should retry */
  11542. /* TODO: retry condition */
  11543. }
  11544. }
  11545. if (error) {
  11546. mg_cry_internal(
  11547. conn,
  11548. "%s",
  11549. "Websocket pull failed; closing connection");
  11550. if (data != mem) {
  11551. mg_free(data);
  11552. }
  11553. break;
  11554. }
  11555. conn->data_len = conn->request_len;
  11556. } else {
  11557. mop = buf[0]; /* current mask and opcode, overwritten by
  11558. * memmove() */
  11559. /* Length of the message being read at the front of the
  11560. * queue. Cast to 31 bit is OK, since we limited
  11561. * data_len before. */
  11562. len = (size_t)data_len + header_len;
  11563. /* Copy the data payload into the data pointer for the
  11564. * callback. Cast to 31 bit is OK, since we
  11565. * limited data_len */
  11566. memcpy(data, buf + header_len, (size_t)data_len);
  11567. /* Move the queue forward len bytes */
  11568. memmove(buf, buf + len, body_len - len);
  11569. /* Mark the queue as advanced */
  11570. conn->data_len -= (int)len;
  11571. }
  11572. /* Apply mask if necessary */
  11573. if (mask_len > 0) {
  11574. for (i = 0; i < (size_t)data_len; i++) {
  11575. data[i] ^= mask[i & 3];
  11576. }
  11577. }
  11578. exit_by_callback = 0;
  11579. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11580. /* filter PONG messages */
  11581. DEBUG_TRACE("PONG from %s:%u",
  11582. conn->request_info.remote_addr,
  11583. conn->request_info.remote_port);
  11584. /* No unanwered PINGs left */
  11585. ping_count = 0;
  11586. } else if (enable_ping_pong
  11587. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11588. /* reply PING messages */
  11589. DEBUG_TRACE("Reply PING from %s:%u",
  11590. conn->request_info.remote_addr,
  11591. conn->request_info.remote_port);
  11592. ret = mg_websocket_write(conn,
  11593. MG_WEBSOCKET_OPCODE_PONG,
  11594. (char *)data,
  11595. (size_t)data_len);
  11596. if (ret <= 0) {
  11597. /* Error: send failed */
  11598. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11599. break;
  11600. }
  11601. } else {
  11602. /* Exit the loop if callback signals to exit (server side),
  11603. * or "connection close" opcode received (client side). */
  11604. if (ws_data_handler != NULL) {
  11605. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11606. if (mop & 0x40) {
  11607. /* Inflate the data received if bit RSV1 is set. */
  11608. if (!conn->websocket_deflate_initialized) {
  11609. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11610. exit_by_callback = 1;
  11611. }
  11612. if (!exit_by_callback) {
  11613. size_t inflate_buf_size_old = 0;
  11614. size_t inflate_buf_size =
  11615. data_len
  11616. * 4; // Initial guess of the inflated message
  11617. // size. We double the memory when needed.
  11618. Bytef *inflated = NULL;
  11619. Bytef *new_mem = NULL;
  11620. conn->websocket_inflate_state.avail_in =
  11621. (uInt)(data_len + 4);
  11622. conn->websocket_inflate_state.next_in = data;
  11623. // Add trailing 0x00 0x00 0xff 0xff bytes
  11624. data[data_len] = '\x00';
  11625. data[data_len + 1] = '\x00';
  11626. data[data_len + 2] = '\xff';
  11627. data[data_len + 3] = '\xff';
  11628. do {
  11629. if (inflate_buf_size_old == 0) {
  11630. new_mem =
  11631. (Bytef *)mg_calloc(inflate_buf_size,
  11632. sizeof(Bytef));
  11633. } else {
  11634. inflate_buf_size *= 2;
  11635. new_mem =
  11636. (Bytef *)mg_realloc(inflated,
  11637. inflate_buf_size);
  11638. }
  11639. if (new_mem == NULL) {
  11640. mg_cry_internal(
  11641. conn,
  11642. "Out of memory: Cannot allocate "
  11643. "inflate buffer of %lu bytes",
  11644. (unsigned long)inflate_buf_size);
  11645. exit_by_callback = 1;
  11646. break;
  11647. }
  11648. inflated = new_mem;
  11649. conn->websocket_inflate_state.avail_out =
  11650. (uInt)(inflate_buf_size
  11651. - inflate_buf_size_old);
  11652. conn->websocket_inflate_state.next_out =
  11653. inflated + inflate_buf_size_old;
  11654. ret = inflate(&conn->websocket_inflate_state,
  11655. Z_SYNC_FLUSH);
  11656. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11657. || ret == Z_MEM_ERROR) {
  11658. mg_cry_internal(
  11659. conn,
  11660. "ZLIB inflate error: %i %s",
  11661. ret,
  11662. (conn->websocket_inflate_state.msg
  11663. ? conn->websocket_inflate_state.msg
  11664. : "<no error message>"));
  11665. exit_by_callback = 1;
  11666. break;
  11667. }
  11668. inflate_buf_size_old = inflate_buf_size;
  11669. } while (conn->websocket_inflate_state.avail_out
  11670. == 0);
  11671. inflate_buf_size -=
  11672. conn->websocket_inflate_state.avail_out;
  11673. if (!ws_data_handler(conn,
  11674. mop,
  11675. (char *)inflated,
  11676. inflate_buf_size,
  11677. callback_data)) {
  11678. exit_by_callback = 1;
  11679. }
  11680. mg_free(inflated);
  11681. }
  11682. } else
  11683. #endif
  11684. if (!ws_data_handler(conn,
  11685. mop,
  11686. (char *)data,
  11687. (size_t)data_len,
  11688. callback_data)) {
  11689. exit_by_callback = 1;
  11690. }
  11691. }
  11692. }
  11693. /* It a buffer has been allocated, free it again */
  11694. if (data != mem) {
  11695. mg_free(data);
  11696. }
  11697. if (exit_by_callback) {
  11698. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11699. conn->request_info.remote_addr,
  11700. conn->request_info.remote_port);
  11701. break;
  11702. }
  11703. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11704. /* Opcode == 8, connection close */
  11705. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11706. conn->request_info.remote_addr,
  11707. conn->request_info.remote_port);
  11708. break;
  11709. }
  11710. /* Not breaking the loop, process next websocket frame. */
  11711. } else {
  11712. /* Read from the socket into the next available location in the
  11713. * message queue. */
  11714. n = pull_inner(NULL,
  11715. conn,
  11716. conn->buf + conn->data_len,
  11717. conn->buf_size - conn->data_len,
  11718. timeout);
  11719. if (n <= -2) {
  11720. /* Error, no bytes read */
  11721. DEBUG_TRACE("PULL from %s:%u failed",
  11722. conn->request_info.remote_addr,
  11723. conn->request_info.remote_port);
  11724. break;
  11725. }
  11726. if (n > 0) {
  11727. conn->data_len += n;
  11728. /* Reset open PING count */
  11729. ping_count = 0;
  11730. } else {
  11731. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11732. && (!conn->must_close)) {
  11733. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11734. /* Stop sending PING */
  11735. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11736. "- closing connection",
  11737. ping_count,
  11738. conn->request_info.remote_addr,
  11739. conn->request_info.remote_port);
  11740. break;
  11741. }
  11742. if (enable_ping_pong) {
  11743. /* Send Websocket PING message */
  11744. DEBUG_TRACE("PING to %s:%u",
  11745. conn->request_info.remote_addr,
  11746. conn->request_info.remote_port);
  11747. ret = mg_websocket_write(conn,
  11748. MG_WEBSOCKET_OPCODE_PING,
  11749. NULL,
  11750. 0);
  11751. if (ret <= 0) {
  11752. /* Error: send failed */
  11753. DEBUG_TRACE("Send PING failed (%i)", ret);
  11754. break;
  11755. }
  11756. ping_count++;
  11757. }
  11758. }
  11759. /* Timeout: should retry */
  11760. /* TODO: get timeout def */
  11761. }
  11762. }
  11763. }
  11764. /* Leave data processing loop */
  11765. mg_set_thread_name("worker");
  11766. conn->in_websocket_handling = 0;
  11767. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11768. conn->request_info.remote_addr,
  11769. conn->request_info.remote_port);
  11770. }
  11771. static int
  11772. mg_websocket_write_exec(struct mg_connection *conn,
  11773. int opcode,
  11774. const char *data,
  11775. size_t dataLen,
  11776. uint32_t masking_key)
  11777. {
  11778. unsigned char header[14];
  11779. size_t headerLen;
  11780. int retval;
  11781. #if defined(GCC_DIAGNOSTIC)
  11782. /* Disable spurious conversion warning for GCC */
  11783. #pragma GCC diagnostic push
  11784. #pragma GCC diagnostic ignored "-Wconversion"
  11785. #endif
  11786. /* Note that POSIX/Winsock's send() is threadsafe
  11787. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11788. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11789. * push(), although that is only a problem if the packet is large or
  11790. * outgoing buffer is full). */
  11791. /* TODO: Check if this lock should be moved to user land.
  11792. * Currently the server sets this lock for websockets, but
  11793. * not for any other connection. It must be set for every
  11794. * conn read/written by more than one thread, no matter if
  11795. * it is a websocket or regular connection. */
  11796. (void)mg_lock_connection(conn);
  11797. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11798. size_t deflated_size = 0;
  11799. Bytef *deflated = 0;
  11800. // Deflate websocket messages over 100kb
  11801. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11802. if (use_deflate) {
  11803. if (!conn->websocket_deflate_initialized) {
  11804. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11805. return 0;
  11806. }
  11807. // Deflating the message
  11808. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11809. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11810. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11811. deflated_size = (size_t)compressBound((uLong)dataLen);
  11812. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11813. if (deflated == NULL) {
  11814. mg_cry_internal(
  11815. conn,
  11816. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11817. (unsigned long)deflated_size);
  11818. mg_unlock_connection(conn);
  11819. return -1;
  11820. }
  11821. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11822. conn->websocket_deflate_state.next_out = deflated;
  11823. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11824. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11825. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11826. } else
  11827. #endif
  11828. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11829. #if defined(GCC_DIAGNOSTIC)
  11830. #pragma GCC diagnostic pop
  11831. #endif
  11832. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11833. if (dataLen < 126) {
  11834. /* inline 7-bit length field */
  11835. header[1] = (unsigned char)dataLen;
  11836. headerLen = 2;
  11837. } else if (dataLen <= 0xFFFF) {
  11838. /* 16-bit length field */
  11839. uint16_t len = htons((uint16_t)dataLen);
  11840. header[1] = 126;
  11841. memcpy(header + 2, &len, 2);
  11842. headerLen = 4;
  11843. } else {
  11844. /* 64-bit length field */
  11845. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11846. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11847. header[1] = 127;
  11848. memcpy(header + 2, &len1, 4);
  11849. memcpy(header + 6, &len2, 4);
  11850. headerLen = 10;
  11851. }
  11852. if (masking_key) {
  11853. /* add mask */
  11854. header[1] |= 0x80;
  11855. memcpy(header + headerLen, &masking_key, 4);
  11856. headerLen += 4;
  11857. }
  11858. retval = mg_write(conn, header, headerLen);
  11859. if (retval != (int)headerLen) {
  11860. /* Did not send complete header */
  11861. retval = -1;
  11862. } else {
  11863. if (dataLen > 0) {
  11864. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11865. if (use_deflate) {
  11866. retval = mg_write(conn, deflated, dataLen);
  11867. mg_free(deflated);
  11868. } else
  11869. #endif
  11870. retval = mg_write(conn, data, dataLen);
  11871. }
  11872. /* if dataLen == 0, the header length (2) is returned */
  11873. }
  11874. /* TODO: Remove this unlock as well, when lock is removed. */
  11875. mg_unlock_connection(conn);
  11876. return retval;
  11877. }
  11878. CIVETWEB_API int
  11879. mg_websocket_write(struct mg_connection *conn,
  11880. int opcode,
  11881. const char *data,
  11882. size_t dataLen)
  11883. {
  11884. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11885. }
  11886. static void
  11887. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11888. {
  11889. size_t i = 0;
  11890. i = 0;
  11891. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11892. /* Convert in 32 bit words, if data is 4 byte aligned */
  11893. while (i < (in_len - 3)) {
  11894. *(uint32_t *)(void *)(out + i) =
  11895. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11896. i += 4;
  11897. }
  11898. }
  11899. if (i != in_len) {
  11900. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11901. while (i < in_len) {
  11902. *(uint8_t *)(void *)(out + i) =
  11903. *(uint8_t *)(void *)(in + i)
  11904. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11905. i++;
  11906. }
  11907. }
  11908. }
  11909. CIVETWEB_API int
  11910. mg_websocket_client_write(struct mg_connection *conn,
  11911. int opcode,
  11912. const char *data,
  11913. size_t dataLen)
  11914. {
  11915. int retval = -1;
  11916. char *masked_data =
  11917. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11918. uint32_t masking_key = 0;
  11919. if (masked_data == NULL) {
  11920. /* Return -1 in an error case */
  11921. mg_cry_internal(conn,
  11922. "%s",
  11923. "Cannot allocate buffer for masked websocket response: "
  11924. "Out of memory");
  11925. return -1;
  11926. }
  11927. do {
  11928. /* Get a masking key - but not 0 */
  11929. masking_key = (uint32_t)get_random();
  11930. } while (masking_key == 0);
  11931. mask_data(data, dataLen, masking_key, masked_data);
  11932. retval = mg_websocket_write_exec(
  11933. conn, opcode, masked_data, dataLen, masking_key);
  11934. mg_free(masked_data);
  11935. return retval;
  11936. }
  11937. static void
  11938. handle_websocket_request(struct mg_connection *conn,
  11939. const char *path,
  11940. int is_callback_resource,
  11941. struct mg_websocket_subprotocols *subprotocols,
  11942. mg_websocket_connect_handler ws_connect_handler,
  11943. mg_websocket_ready_handler ws_ready_handler,
  11944. mg_websocket_data_handler ws_data_handler,
  11945. mg_websocket_close_handler ws_close_handler,
  11946. void *cbData)
  11947. {
  11948. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11949. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11950. ptrdiff_t lua_websock = 0;
  11951. #if !defined(USE_LUA)
  11952. (void)path;
  11953. #endif
  11954. /* Step 1: Check websocket protocol version. */
  11955. /* Step 1.1: Check Sec-WebSocket-Key. */
  11956. if (!websock_key) {
  11957. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11958. * requires a Sec-WebSocket-Key header.
  11959. */
  11960. /* It could be the hixie draft version
  11961. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11962. */
  11963. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11964. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11965. char key3[8];
  11966. if ((key1 != NULL) && (key2 != NULL)) {
  11967. /* This version uses 8 byte body data in a GET request */
  11968. conn->content_len = 8;
  11969. if (8 == mg_read(conn, key3, 8)) {
  11970. /* This is the hixie version */
  11971. mg_send_http_error(conn,
  11972. 426,
  11973. "%s",
  11974. "Protocol upgrade to RFC 6455 required");
  11975. return;
  11976. }
  11977. }
  11978. /* This is an unknown version */
  11979. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11980. return;
  11981. }
  11982. /* Step 1.2: Check websocket protocol version. */
  11983. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11984. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11985. /* Reject wrong versions */
  11986. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11987. return;
  11988. }
  11989. /* Step 1.3: Could check for "Host", but we do not really need this
  11990. * value for anything, so just ignore it. */
  11991. /* Step 2: If a callback is responsible, call it. */
  11992. if (is_callback_resource) {
  11993. /* Step 2.1 check and select subprotocol */
  11994. const char *protocols[64]; // max 64 headers
  11995. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11996. "Sec-WebSocket-Protocol",
  11997. protocols,
  11998. 64);
  11999. if ((nbSubprotocolHeader > 0) && subprotocols) {
  12000. int headerNo, idx;
  12001. size_t len;
  12002. const char *sep, *curSubProtocol,
  12003. *acceptedWebSocketSubprotocol = NULL;
  12004. /* look for matching subprotocol */
  12005. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  12006. /* There might be multiple headers ... */
  12007. const char *protocol = protocols[headerNo];
  12008. curSubProtocol = protocol;
  12009. /* ... and in every header there might be a , separated list */
  12010. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  12011. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  12012. curSubProtocol++;
  12013. sep = strchr(curSubProtocol, ',');
  12014. if (sep) {
  12015. len = (size_t)(sep - curSubProtocol);
  12016. } else {
  12017. len = strlen(curSubProtocol);
  12018. }
  12019. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  12020. // COMPARE: curSubProtocol ==
  12021. // subprotocols->subprotocols[idx]
  12022. if ((strlen(subprotocols->subprotocols[idx]) == len)
  12023. && (strncmp(curSubProtocol,
  12024. subprotocols->subprotocols[idx],
  12025. len)
  12026. == 0)) {
  12027. acceptedWebSocketSubprotocol =
  12028. subprotocols->subprotocols[idx];
  12029. break;
  12030. }
  12031. }
  12032. curSubProtocol += len;
  12033. }
  12034. }
  12035. conn->request_info.acceptedWebSocketSubprotocol =
  12036. acceptedWebSocketSubprotocol;
  12037. }
  12038. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12039. websocket_deflate_negotiate(conn);
  12040. #endif
  12041. if ((ws_connect_handler != NULL)
  12042. && (ws_connect_handler(conn, cbData) != 0)) {
  12043. /* C callback has returned non-zero, do not proceed with
  12044. * handshake.
  12045. */
  12046. /* Note that C callbacks are no longer called when Lua is
  12047. * responsible, so C can no longer filter callbacks for Lua. */
  12048. return;
  12049. }
  12050. }
  12051. #if defined(USE_LUA)
  12052. /* Step 3: No callback. Check if Lua is responsible. */
  12053. else {
  12054. /* Step 3.1: Check if Lua is responsible. */
  12055. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  12056. lua_websock = match_prefix_strlen(
  12057. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  12058. }
  12059. if (lua_websock > 0) {
  12060. /* Step 3.2: Lua is responsible: call it. */
  12061. conn->lua_websocket_state = lua_websocket_new(path, conn);
  12062. if (!conn->lua_websocket_state) {
  12063. /* Lua rejected the new client */
  12064. return;
  12065. }
  12066. }
  12067. }
  12068. #endif
  12069. /* Step 4: Check if there is a responsible websocket handler. */
  12070. if (!is_callback_resource && !lua_websock) {
  12071. /* There is no callback, and Lua is not responsible either. */
  12072. /* Reply with a 404 Not Found. We are still at a standard
  12073. * HTTP request here, before the websocket handshake, so
  12074. * we can still send standard HTTP error replies. */
  12075. mg_send_http_error(conn, 404, "%s", "Not found");
  12076. return;
  12077. }
  12078. /* Step 5: The websocket connection has been accepted */
  12079. if (!send_websocket_handshake(conn, websock_key)) {
  12080. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  12081. return;
  12082. }
  12083. /* Step 6: Call the ready handler */
  12084. if (is_callback_resource) {
  12085. if (ws_ready_handler != NULL) {
  12086. ws_ready_handler(conn, cbData);
  12087. }
  12088. #if defined(USE_LUA)
  12089. } else if (lua_websock) {
  12090. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  12091. /* the ready handler returned false */
  12092. return;
  12093. }
  12094. #endif
  12095. }
  12096. /* Step 7: Enter the read loop */
  12097. if (is_callback_resource) {
  12098. read_websocket(conn, ws_data_handler, cbData);
  12099. #if defined(USE_LUA)
  12100. } else if (lua_websock) {
  12101. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  12102. #endif
  12103. }
  12104. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12105. /* Step 8: Close the deflate & inflate buffers */
  12106. if (conn->websocket_deflate_initialized) {
  12107. deflateEnd(&conn->websocket_deflate_state);
  12108. inflateEnd(&conn->websocket_inflate_state);
  12109. }
  12110. #endif
  12111. /* Step 9: Call the close handler */
  12112. if (ws_close_handler) {
  12113. ws_close_handler(conn, cbData);
  12114. }
  12115. }
  12116. #endif /* !USE_WEBSOCKET */
  12117. /* Is upgrade request:
  12118. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12119. * 1 = upgrade to websocket
  12120. * 2 = upgrade to HTTP/2
  12121. * -1 = upgrade to unknown protocol
  12122. */
  12123. static int
  12124. should_switch_to_protocol(const struct mg_connection *conn)
  12125. {
  12126. const char *connection_headers[8];
  12127. const char *upgrade_to;
  12128. int connection_header_count, i, should_upgrade;
  12129. /* A websocket protocol has the following HTTP headers:
  12130. *
  12131. * Connection: Upgrade
  12132. * Upgrade: Websocket
  12133. *
  12134. * It seems some clients use multiple headers:
  12135. * see https://github.com/civetweb/civetweb/issues/1083
  12136. */
  12137. connection_header_count = get_req_headers(&conn->request_info,
  12138. "Connection",
  12139. connection_headers,
  12140. 8);
  12141. should_upgrade = 0;
  12142. for (i = 0; i < connection_header_count; i++) {
  12143. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12144. should_upgrade = 1;
  12145. }
  12146. }
  12147. if (!should_upgrade) {
  12148. return PROTOCOL_TYPE_HTTP1;
  12149. }
  12150. upgrade_to = mg_get_header(conn, "Upgrade");
  12151. if (upgrade_to == NULL) {
  12152. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12153. return -1;
  12154. }
  12155. /* Upgrade to ... */
  12156. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12157. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12158. * "Sec-WebSocket-Version" are also required.
  12159. * Don't check them here, since even an unsupported websocket protocol
  12160. * request still IS a websocket request (in contrast to a standard HTTP
  12161. * request). It will fail later in handle_websocket_request.
  12162. */
  12163. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12164. }
  12165. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12166. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12167. }
  12168. /* Upgrade to another protocol */
  12169. return -1;
  12170. }
  12171. static int
  12172. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12173. {
  12174. int n;
  12175. unsigned int a, b, c, d, slash;
  12176. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12177. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12178. // integer value, but function will not report conversion
  12179. // errors; consider using 'strtol' instead
  12180. slash = 32;
  12181. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12182. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12183. // an integer value, but function will not report conversion
  12184. // errors; consider using 'strtol' instead
  12185. n = 0;
  12186. }
  12187. }
  12188. if ((n > 0) && ((size_t)n == vec->len)) {
  12189. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12190. /* IPv4 format */
  12191. if (sa->sa.sa_family == AF_INET) {
  12192. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12193. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12194. | ((uint32_t)c << 8) | (uint32_t)d;
  12195. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12196. return (ip & mask) == net;
  12197. }
  12198. return 0;
  12199. }
  12200. }
  12201. #if defined(USE_IPV6)
  12202. else {
  12203. char ad[50];
  12204. const char *p;
  12205. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12206. slash = 128;
  12207. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12208. n = 0;
  12209. }
  12210. }
  12211. if ((n <= 0) && no_strict) {
  12212. /* no square brackets? */
  12213. p = strchr(vec->ptr, '/');
  12214. if (p && (p < (vec->ptr + vec->len))) {
  12215. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12216. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12217. n += (int)(p - vec->ptr);
  12218. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12219. } else {
  12220. n = 0;
  12221. }
  12222. } else if (vec->len < sizeof(ad)) {
  12223. n = (int)vec->len;
  12224. slash = 128;
  12225. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12226. }
  12227. }
  12228. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12229. p = ad;
  12230. c = 0;
  12231. /* zone indexes are unsupported, at least two colons are needed */
  12232. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12233. if (*(p++) == ':') {
  12234. c++;
  12235. }
  12236. }
  12237. if ((*p == '\0') && (c >= 2)) {
  12238. struct sockaddr_in6 sin6;
  12239. unsigned int i;
  12240. /* for strict validation, an actual IPv6 argument is needed */
  12241. if (sa->sa.sa_family != AF_INET6) {
  12242. return 0;
  12243. }
  12244. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12245. /* IPv6 format */
  12246. for (i = 0; i < 16; i++) {
  12247. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12248. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12249. uint8_t mask = 0;
  12250. if (8 * i + 8 < slash) {
  12251. mask = 0xFFu;
  12252. } else if (8 * i < slash) {
  12253. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12254. }
  12255. if ((ip & mask) != net) {
  12256. return 0;
  12257. }
  12258. }
  12259. return 1;
  12260. }
  12261. }
  12262. }
  12263. }
  12264. #else
  12265. (void)no_strict;
  12266. #endif
  12267. /* malformed */
  12268. return -1;
  12269. }
  12270. static int
  12271. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12272. {
  12273. int throttle = 0;
  12274. struct vec vec, val;
  12275. char mult;
  12276. double v;
  12277. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12278. mult = ',';
  12279. if ((val.ptr == NULL)
  12280. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12281. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12282. // to an integer value, but function will not report
  12283. // conversion errors; consider using 'strtol' instead
  12284. || (v < 0)
  12285. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12286. && (mult != ','))) {
  12287. continue;
  12288. }
  12289. v *= (lowercase(&mult) == 'k')
  12290. ? 1024
  12291. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12292. if (vec.len == 1 && vec.ptr[0] == '*') {
  12293. throttle = (int)v;
  12294. } else {
  12295. int matched = parse_match_net(&vec, rsa, 0);
  12296. if (matched >= 0) {
  12297. /* a valid IP subnet */
  12298. if (matched) {
  12299. throttle = (int)v;
  12300. }
  12301. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12302. throttle = (int)v;
  12303. }
  12304. }
  12305. }
  12306. return throttle;
  12307. }
  12308. /* The mg_upload function is superseded by mg_handle_form_request. */
  12309. #include "handle_form.inl"
  12310. static int
  12311. get_first_ssl_listener_index(const struct mg_context *ctx)
  12312. {
  12313. unsigned int i;
  12314. int idx = -1;
  12315. if (ctx) {
  12316. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12317. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12318. }
  12319. }
  12320. return idx;
  12321. }
  12322. /* Return host (without port) */
  12323. static void
  12324. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12325. {
  12326. const char *host_header =
  12327. get_header(ri->http_headers, ri->num_headers, "Host");
  12328. host->ptr = NULL;
  12329. host->len = 0;
  12330. if (host_header != NULL) {
  12331. const char *pos;
  12332. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12333. * is found. */
  12334. if (*host_header == '[') {
  12335. pos = strchr(host_header, ']');
  12336. if (!pos) {
  12337. /* Malformed hostname starts with '[', but no ']' found */
  12338. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12339. return;
  12340. }
  12341. /* terminate after ']' */
  12342. host->ptr = host_header;
  12343. host->len = (size_t)(pos + 1 - host_header);
  12344. } else {
  12345. /* Otherwise, a ':' separates hostname and port number */
  12346. pos = strchr(host_header, ':');
  12347. if (pos != NULL) {
  12348. host->len = (size_t)(pos - host_header);
  12349. } else {
  12350. host->len = strlen(host_header);
  12351. }
  12352. host->ptr = host_header;
  12353. }
  12354. }
  12355. }
  12356. static int
  12357. switch_domain_context(struct mg_connection *conn)
  12358. {
  12359. struct vec host;
  12360. get_host_from_request_info(&host, &conn->request_info);
  12361. if (host.ptr) {
  12362. if (conn->ssl) {
  12363. /* This is a HTTPS connection, maybe we have a hostname
  12364. * from SNI (set in ssl_servername_callback). */
  12365. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12366. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12367. /* We are not using the default domain */
  12368. if ((strlen(sslhost) != host.len)
  12369. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12370. /* Mismatch between SNI domain and HTTP domain */
  12371. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12372. sslhost,
  12373. (int)host.len,
  12374. host.ptr);
  12375. return 0;
  12376. }
  12377. }
  12378. } else {
  12379. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12380. while (dom) {
  12381. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12382. size_t domNameLen = strlen(domName);
  12383. if ((domNameLen == host.len)
  12384. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12385. /* Found matching domain */
  12386. DEBUG_TRACE("HTTP domain %s found",
  12387. dom->config[AUTHENTICATION_DOMAIN]);
  12388. /* TODO: Check if this is a HTTP or HTTPS domain */
  12389. conn->dom_ctx = dom;
  12390. break;
  12391. }
  12392. mg_lock_context(conn->phys_ctx);
  12393. dom = dom->next;
  12394. mg_unlock_context(conn->phys_ctx);
  12395. }
  12396. }
  12397. DEBUG_TRACE("HTTP%s Host: %.*s",
  12398. conn->ssl ? "S" : "",
  12399. (int)host.len,
  12400. host.ptr);
  12401. } else {
  12402. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12403. return 1;
  12404. }
  12405. return 1;
  12406. }
  12407. static void
  12408. redirect_to_https_port(struct mg_connection *conn, int port)
  12409. {
  12410. char target_url[MG_BUF_LEN];
  12411. int truncated = 0;
  12412. const char *expect_proto =
  12413. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12414. /* Use "308 Permanent Redirect" */
  12415. int redirect_code = 308;
  12416. /* In any case, close the current connection */
  12417. conn->must_close = 1;
  12418. /* Send host, port, uri and (if it exists) ?query_string */
  12419. if (mg_construct_local_link(
  12420. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12421. < 0) {
  12422. truncated = 1;
  12423. } else if (conn->request_info.query_string != NULL) {
  12424. size_t slen1 = strlen(target_url);
  12425. size_t slen2 = strlen(conn->request_info.query_string);
  12426. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12427. target_url[slen1] = '?';
  12428. memcpy(target_url + slen1 + 1,
  12429. conn->request_info.query_string,
  12430. slen2);
  12431. target_url[slen1 + slen2 + 1] = 0;
  12432. } else {
  12433. truncated = 1;
  12434. }
  12435. }
  12436. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12437. * is used as buffer size) */
  12438. if (truncated) {
  12439. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12440. return;
  12441. }
  12442. /* Use redirect helper function */
  12443. mg_send_http_redirect(conn, target_url, redirect_code);
  12444. }
  12445. static void
  12446. mg_set_handler_type(struct mg_context *phys_ctx,
  12447. struct mg_domain_context *dom_ctx,
  12448. const char *uri,
  12449. int handler_type,
  12450. int is_delete_request,
  12451. mg_request_handler handler,
  12452. struct mg_websocket_subprotocols *subprotocols,
  12453. mg_websocket_connect_handler connect_handler,
  12454. mg_websocket_ready_handler ready_handler,
  12455. mg_websocket_data_handler data_handler,
  12456. mg_websocket_close_handler close_handler,
  12457. mg_authorization_handler auth_handler,
  12458. void *cbdata)
  12459. {
  12460. struct mg_handler_info *tmp_rh, **lastref;
  12461. size_t urilen = strlen(uri);
  12462. if (handler_type == WEBSOCKET_HANDLER) {
  12463. DEBUG_ASSERT(handler == NULL);
  12464. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12465. || ready_handler != NULL || data_handler != NULL
  12466. || close_handler != NULL);
  12467. DEBUG_ASSERT(auth_handler == NULL);
  12468. if (handler != NULL) {
  12469. return;
  12470. }
  12471. if (!is_delete_request && (connect_handler == NULL)
  12472. && (ready_handler == NULL) && (data_handler == NULL)
  12473. && (close_handler == NULL)) {
  12474. return;
  12475. }
  12476. if (auth_handler != NULL) {
  12477. return;
  12478. }
  12479. } else if (handler_type == REQUEST_HANDLER) {
  12480. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12481. && data_handler == NULL && close_handler == NULL);
  12482. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12483. DEBUG_ASSERT(auth_handler == NULL);
  12484. if ((connect_handler != NULL) || (ready_handler != NULL)
  12485. || (data_handler != NULL) || (close_handler != NULL)) {
  12486. return;
  12487. }
  12488. if (!is_delete_request && (handler == NULL)) {
  12489. return;
  12490. }
  12491. if (auth_handler != NULL) {
  12492. return;
  12493. }
  12494. } else if (handler_type == AUTH_HANDLER) {
  12495. DEBUG_ASSERT(handler == NULL);
  12496. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12497. && data_handler == NULL && close_handler == NULL);
  12498. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12499. if (handler != NULL) {
  12500. return;
  12501. }
  12502. if ((connect_handler != NULL) || (ready_handler != NULL)
  12503. || (data_handler != NULL) || (close_handler != NULL)) {
  12504. return;
  12505. }
  12506. if (!is_delete_request && (auth_handler == NULL)) {
  12507. return;
  12508. }
  12509. } else {
  12510. /* Unknown handler type. */
  12511. return;
  12512. }
  12513. if (!phys_ctx || !dom_ctx) {
  12514. /* no context available */
  12515. return;
  12516. }
  12517. mg_lock_context(phys_ctx);
  12518. /* first try to find an existing handler */
  12519. do {
  12520. lastref = &(dom_ctx->handlers);
  12521. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12522. tmp_rh = tmp_rh->next) {
  12523. if (tmp_rh->handler_type == handler_type
  12524. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12525. if (!is_delete_request) {
  12526. /* update existing handler */
  12527. if (handler_type == REQUEST_HANDLER) {
  12528. /* Wait for end of use before updating */
  12529. if (tmp_rh->refcount) {
  12530. mg_unlock_context(phys_ctx);
  12531. mg_sleep(1);
  12532. mg_lock_context(phys_ctx);
  12533. /* tmp_rh might have been freed, search again. */
  12534. break;
  12535. }
  12536. /* Ok, the handler is no more use -> Update it */
  12537. tmp_rh->handler = handler;
  12538. } else if (handler_type == WEBSOCKET_HANDLER) {
  12539. tmp_rh->subprotocols = subprotocols;
  12540. tmp_rh->connect_handler = connect_handler;
  12541. tmp_rh->ready_handler = ready_handler;
  12542. tmp_rh->data_handler = data_handler;
  12543. tmp_rh->close_handler = close_handler;
  12544. } else { /* AUTH_HANDLER */
  12545. tmp_rh->auth_handler = auth_handler;
  12546. }
  12547. tmp_rh->cbdata = cbdata;
  12548. } else {
  12549. /* remove existing handler */
  12550. if (handler_type == REQUEST_HANDLER) {
  12551. /* Wait for end of use before removing */
  12552. if (tmp_rh->refcount) {
  12553. tmp_rh->removing = 1;
  12554. mg_unlock_context(phys_ctx);
  12555. mg_sleep(1);
  12556. mg_lock_context(phys_ctx);
  12557. /* tmp_rh might have been freed, search again. */
  12558. break;
  12559. }
  12560. /* Ok, the handler is no more used */
  12561. }
  12562. *lastref = tmp_rh->next;
  12563. mg_free(tmp_rh->uri);
  12564. mg_free(tmp_rh);
  12565. }
  12566. mg_unlock_context(phys_ctx);
  12567. return;
  12568. }
  12569. lastref = &(tmp_rh->next);
  12570. }
  12571. } while (tmp_rh != NULL);
  12572. if (is_delete_request) {
  12573. /* no handler to set, this was a remove request to a non-existing
  12574. * handler */
  12575. mg_unlock_context(phys_ctx);
  12576. return;
  12577. }
  12578. tmp_rh =
  12579. (struct mg_handler_info *)mg_calloc_ctx(1,
  12580. sizeof(struct mg_handler_info),
  12581. phys_ctx);
  12582. if (tmp_rh == NULL) {
  12583. mg_unlock_context(phys_ctx);
  12584. mg_cry_ctx_internal(phys_ctx,
  12585. "%s",
  12586. "Cannot create new request handler struct, OOM");
  12587. return;
  12588. }
  12589. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12590. if (!tmp_rh->uri) {
  12591. mg_unlock_context(phys_ctx);
  12592. mg_free(tmp_rh);
  12593. mg_cry_ctx_internal(phys_ctx,
  12594. "%s",
  12595. "Cannot create new request handler struct, OOM");
  12596. return;
  12597. }
  12598. tmp_rh->uri_len = urilen;
  12599. if (handler_type == REQUEST_HANDLER) {
  12600. tmp_rh->refcount = 0;
  12601. tmp_rh->removing = 0;
  12602. tmp_rh->handler = handler;
  12603. } else if (handler_type == WEBSOCKET_HANDLER) {
  12604. tmp_rh->subprotocols = subprotocols;
  12605. tmp_rh->connect_handler = connect_handler;
  12606. tmp_rh->ready_handler = ready_handler;
  12607. tmp_rh->data_handler = data_handler;
  12608. tmp_rh->close_handler = close_handler;
  12609. } else { /* AUTH_HANDLER */
  12610. tmp_rh->auth_handler = auth_handler;
  12611. }
  12612. tmp_rh->cbdata = cbdata;
  12613. tmp_rh->handler_type = handler_type;
  12614. tmp_rh->next = NULL;
  12615. *lastref = tmp_rh;
  12616. mg_unlock_context(phys_ctx);
  12617. }
  12618. CIVETWEB_API void
  12619. mg_set_request_handler(struct mg_context *ctx,
  12620. const char *uri,
  12621. mg_request_handler handler,
  12622. void *cbdata)
  12623. {
  12624. mg_set_handler_type(ctx,
  12625. &(ctx->dd),
  12626. uri,
  12627. REQUEST_HANDLER,
  12628. handler == NULL,
  12629. handler,
  12630. NULL,
  12631. NULL,
  12632. NULL,
  12633. NULL,
  12634. NULL,
  12635. NULL,
  12636. cbdata);
  12637. }
  12638. CIVETWEB_API void
  12639. mg_set_websocket_handler(struct mg_context *ctx,
  12640. const char *uri,
  12641. mg_websocket_connect_handler connect_handler,
  12642. mg_websocket_ready_handler ready_handler,
  12643. mg_websocket_data_handler data_handler,
  12644. mg_websocket_close_handler close_handler,
  12645. void *cbdata)
  12646. {
  12647. mg_set_websocket_handler_with_subprotocols(ctx,
  12648. uri,
  12649. NULL,
  12650. connect_handler,
  12651. ready_handler,
  12652. data_handler,
  12653. close_handler,
  12654. cbdata);
  12655. }
  12656. CIVETWEB_API void
  12657. mg_set_websocket_handler_with_subprotocols(
  12658. struct mg_context *ctx,
  12659. const char *uri,
  12660. struct mg_websocket_subprotocols *subprotocols,
  12661. mg_websocket_connect_handler connect_handler,
  12662. mg_websocket_ready_handler ready_handler,
  12663. mg_websocket_data_handler data_handler,
  12664. mg_websocket_close_handler close_handler,
  12665. void *cbdata)
  12666. {
  12667. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12668. && (data_handler == NULL)
  12669. && (close_handler == NULL);
  12670. mg_set_handler_type(ctx,
  12671. &(ctx->dd),
  12672. uri,
  12673. WEBSOCKET_HANDLER,
  12674. is_delete_request,
  12675. NULL,
  12676. subprotocols,
  12677. connect_handler,
  12678. ready_handler,
  12679. data_handler,
  12680. close_handler,
  12681. NULL,
  12682. cbdata);
  12683. }
  12684. CIVETWEB_API void
  12685. mg_set_auth_handler(struct mg_context *ctx,
  12686. const char *uri,
  12687. mg_authorization_handler handler,
  12688. void *cbdata)
  12689. {
  12690. mg_set_handler_type(ctx,
  12691. &(ctx->dd),
  12692. uri,
  12693. AUTH_HANDLER,
  12694. handler == NULL,
  12695. NULL,
  12696. NULL,
  12697. NULL,
  12698. NULL,
  12699. NULL,
  12700. NULL,
  12701. handler,
  12702. cbdata);
  12703. }
  12704. static int
  12705. get_request_handler(struct mg_connection *conn,
  12706. int handler_type,
  12707. mg_request_handler *handler,
  12708. struct mg_websocket_subprotocols **subprotocols,
  12709. mg_websocket_connect_handler *connect_handler,
  12710. mg_websocket_ready_handler *ready_handler,
  12711. mg_websocket_data_handler *data_handler,
  12712. mg_websocket_close_handler *close_handler,
  12713. mg_authorization_handler *auth_handler,
  12714. void **cbdata,
  12715. struct mg_handler_info **handler_info)
  12716. {
  12717. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12718. if (request_info) {
  12719. const char *uri = request_info->local_uri;
  12720. size_t urilen = strlen(uri);
  12721. struct mg_handler_info *tmp_rh;
  12722. int step, matched;
  12723. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12724. return 0;
  12725. }
  12726. mg_lock_context(conn->phys_ctx);
  12727. for (step = 0; step < 3; step++) {
  12728. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12729. tmp_rh = tmp_rh->next) {
  12730. if (tmp_rh->handler_type != handler_type) {
  12731. continue;
  12732. }
  12733. if (step == 0) {
  12734. /* first try for an exact match */
  12735. matched = (tmp_rh->uri_len == urilen)
  12736. && (strcmp(tmp_rh->uri, uri) == 0);
  12737. } else if (step == 1) {
  12738. /* next try for a partial match, we will accept
  12739. uri/something */
  12740. matched =
  12741. (tmp_rh->uri_len < urilen)
  12742. && (uri[tmp_rh->uri_len] == '/')
  12743. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12744. } else {
  12745. /* finally try for pattern match */
  12746. matched =
  12747. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12748. }
  12749. if (matched) {
  12750. if (handler_type == WEBSOCKET_HANDLER) {
  12751. *subprotocols = tmp_rh->subprotocols;
  12752. *connect_handler = tmp_rh->connect_handler;
  12753. *ready_handler = tmp_rh->ready_handler;
  12754. *data_handler = tmp_rh->data_handler;
  12755. *close_handler = tmp_rh->close_handler;
  12756. } else if (handler_type == REQUEST_HANDLER) {
  12757. if (tmp_rh->removing) {
  12758. /* Treat as none found */
  12759. step = 2;
  12760. break;
  12761. }
  12762. *handler = tmp_rh->handler;
  12763. /* Acquire handler and give it back */
  12764. tmp_rh->refcount++;
  12765. *handler_info = tmp_rh;
  12766. } else { /* AUTH_HANDLER */
  12767. *auth_handler = tmp_rh->auth_handler;
  12768. }
  12769. *cbdata = tmp_rh->cbdata;
  12770. mg_unlock_context(conn->phys_ctx);
  12771. return 1;
  12772. }
  12773. }
  12774. }
  12775. mg_unlock_context(conn->phys_ctx);
  12776. }
  12777. return 0; /* none found */
  12778. }
  12779. /* Check if the script file is in a path, allowed for script files.
  12780. * This can be used if uploading files is possible not only for the server
  12781. * admin, and the upload mechanism does not check the file extension.
  12782. */
  12783. static int
  12784. is_in_script_path(const struct mg_connection *conn, const char *path)
  12785. {
  12786. /* TODO (Feature): Add config value for allowed script path.
  12787. * Default: All allowed. */
  12788. (void)conn;
  12789. (void)path;
  12790. return 1;
  12791. }
  12792. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12793. static int
  12794. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12795. int bits,
  12796. char *data,
  12797. size_t len,
  12798. void *cbdata)
  12799. {
  12800. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12801. if (pcallbacks->websocket_data) {
  12802. return pcallbacks->websocket_data(conn, bits, data, len);
  12803. }
  12804. /* No handler set - assume "OK" */
  12805. return 1;
  12806. }
  12807. static void
  12808. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12809. void *cbdata)
  12810. {
  12811. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12812. if (pcallbacks->connection_close) {
  12813. pcallbacks->connection_close(conn);
  12814. }
  12815. }
  12816. #endif
  12817. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12818. */
  12819. static void
  12820. release_handler_ref(struct mg_connection *conn,
  12821. struct mg_handler_info *handler_info)
  12822. {
  12823. if (handler_info != NULL) {
  12824. /* Use context lock for ref counter */
  12825. mg_lock_context(conn->phys_ctx);
  12826. handler_info->refcount--;
  12827. mg_unlock_context(conn->phys_ctx);
  12828. }
  12829. }
  12830. /* This is the heart of the Civetweb's logic.
  12831. * This function is called when the request is read, parsed and validated,
  12832. * and Civetweb must decide what action to take: serve a file, or
  12833. * a directory, or call embedded function, etcetera. */
  12834. static void
  12835. handle_request(struct mg_connection *conn)
  12836. {
  12837. struct mg_request_info *ri = &conn->request_info;
  12838. char path[UTF8_PATH_MAX];
  12839. int uri_len, ssl_index;
  12840. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12841. is_put_or_delete_request = 0, is_callback_resource = 0,
  12842. is_template_text_file = 0, is_webdav_request = 0;
  12843. int i;
  12844. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12845. mg_request_handler callback_handler = NULL;
  12846. struct mg_handler_info *handler_info = NULL;
  12847. struct mg_websocket_subprotocols *subprotocols;
  12848. mg_websocket_connect_handler ws_connect_handler = NULL;
  12849. mg_websocket_ready_handler ws_ready_handler = NULL;
  12850. mg_websocket_data_handler ws_data_handler = NULL;
  12851. mg_websocket_close_handler ws_close_handler = NULL;
  12852. void *callback_data = NULL;
  12853. mg_authorization_handler auth_handler = NULL;
  12854. void *auth_callback_data = NULL;
  12855. int handler_type;
  12856. time_t curtime = time(NULL);
  12857. char date[64];
  12858. char *tmp;
  12859. path[0] = 0;
  12860. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12861. conn->request_state = 0;
  12862. /* 1. get the request url */
  12863. /* 1.1. split into url and query string */
  12864. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12865. != NULL) {
  12866. *((char *)conn->request_info.query_string++) = '\0';
  12867. }
  12868. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12869. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12870. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12871. if (ssl_index >= 0) {
  12872. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12873. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12874. redirect_to_https_port(conn, port);
  12875. } else {
  12876. /* A http to https forward port has been specified,
  12877. * but no https port to forward to. */
  12878. mg_send_http_error(conn,
  12879. 503,
  12880. "%s",
  12881. "Error: SSL forward not configured properly");
  12882. mg_cry_internal(conn,
  12883. "%s",
  12884. "Can not redirect to SSL, no SSL port available");
  12885. }
  12886. return;
  12887. }
  12888. uri_len = (int)strlen(ri->local_uri);
  12889. /* 1.3. decode url (if config says so) */
  12890. if (should_decode_url(conn)) {
  12891. url_decode_in_place((char *)ri->local_uri);
  12892. }
  12893. /* URL decode the query-string only if explicitly set in the configuration
  12894. */
  12895. if (conn->request_info.query_string) {
  12896. if (should_decode_query_string(conn)) {
  12897. url_decode_in_place((char *)conn->request_info.query_string);
  12898. }
  12899. }
  12900. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12901. * possible. The fact that we cleaned the URI is stored in that the
  12902. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12903. * ri->local_uri_raw still points to memory allocated in
  12904. * worker_thread_run(). ri->local_uri is private to the request so we
  12905. * don't have to use preallocated memory here. */
  12906. tmp = mg_strdup(ri->local_uri_raw);
  12907. if (!tmp) {
  12908. /* Out of memory. We cannot do anything reasonable here. */
  12909. return;
  12910. }
  12911. remove_dot_segments(tmp);
  12912. ri->local_uri = tmp;
  12913. /* step 1. completed, the url is known now */
  12914. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12915. /* 2. if this ip has limited speed, set it for this connection */
  12916. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12917. &conn->client.rsa,
  12918. ri->local_uri);
  12919. /* 3. call a "handle everything" callback, if registered */
  12920. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12921. /* Note that since V1.7 the "begin_request" function is called
  12922. * before an authorization check. If an authorization check is
  12923. * required, use a request_handler instead. */
  12924. i = conn->phys_ctx->callbacks.begin_request(conn);
  12925. if (i > 0) {
  12926. /* callback already processed the request. Store the
  12927. return value as a status code for the access log. */
  12928. conn->status_code = i;
  12929. if (!conn->must_close) {
  12930. discard_unread_request_data(conn);
  12931. }
  12932. DEBUG_TRACE("%s", "begin_request handled request");
  12933. return;
  12934. } else if (i == 0) {
  12935. /* civetweb should process the request */
  12936. } else {
  12937. /* unspecified - may change with the next version */
  12938. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12939. return;
  12940. }
  12941. }
  12942. /* request not yet handled by a handler or redirect, so the request
  12943. * is processed here */
  12944. /* 4. Check for CORS preflight requests and handle them (if configured).
  12945. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12946. */
  12947. if (!strcmp(ri->request_method, "OPTIONS")) {
  12948. /* Send a response to CORS preflights only if
  12949. * access_control_allow_methods is not NULL and not an empty string.
  12950. * In this case, scripts can still handle CORS. */
  12951. const char *cors_meth_cfg =
  12952. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12953. const char *cors_orig_cfg =
  12954. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12955. const char *cors_origin =
  12956. get_header(ri->http_headers, ri->num_headers, "Origin");
  12957. const char *cors_acrm = get_header(ri->http_headers,
  12958. ri->num_headers,
  12959. "Access-Control-Request-Method");
  12960. /* Todo: check if cors_origin is in cors_orig_cfg.
  12961. * Or, let the client check this. */
  12962. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12963. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12964. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12965. /* This is a valid CORS preflight, and the server is configured
  12966. * to handle it automatically. */
  12967. const char *cors_acrh =
  12968. get_header(ri->http_headers,
  12969. ri->num_headers,
  12970. "Access-Control-Request-Headers");
  12971. const char *cors_cred_cfg =
  12972. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  12973. const char *cors_exphdr_cfg =
  12974. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  12975. gmt_time_string(date, sizeof(date), &curtime);
  12976. mg_printf(conn,
  12977. "HTTP/1.1 200 OK\r\n"
  12978. "Date: %s\r\n"
  12979. "Access-Control-Allow-Origin: %s\r\n"
  12980. "Access-Control-Allow-Methods: %s\r\n"
  12981. "Content-Length: 0\r\n"
  12982. "Connection: %s\r\n",
  12983. date,
  12984. cors_orig_cfg,
  12985. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12986. suggest_connection_header(conn));
  12987. if (cors_cred_cfg && *cors_cred_cfg) {
  12988. mg_printf(conn,
  12989. "Access-Control-Allow-Credentials: %s\r\n",
  12990. cors_cred_cfg);
  12991. }
  12992. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  12993. mg_printf(conn,
  12994. "Access-Control-Expose-Headers: %s\r\n",
  12995. cors_exphdr_cfg);
  12996. }
  12997. if (cors_acrh || (cors_cred_cfg && *cors_cred_cfg)) {
  12998. /* CORS request is asking for additional headers */
  12999. const char *cors_hdr_cfg =
  13000. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  13001. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  13002. /* Allow only if access_control_allow_headers is
  13003. * not NULL and not an empty string. If this
  13004. * configuration is set to *, allow everything.
  13005. * Otherwise this configuration must be a list
  13006. * of allowed HTTP header names. */
  13007. mg_printf(conn,
  13008. "Access-Control-Allow-Headers: %s\r\n",
  13009. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  13010. : cors_hdr_cfg));
  13011. }
  13012. }
  13013. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  13014. mg_printf(conn, "\r\n");
  13015. DEBUG_TRACE("%s", "OPTIONS done");
  13016. return;
  13017. }
  13018. }
  13019. /* 5. interpret the url to find out how the request must be handled
  13020. */
  13021. /* 5.1. first test, if the request targets the regular http(s)://
  13022. * protocol namespace or the websocket ws(s):// protocol namespace.
  13023. */
  13024. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  13025. #if defined(USE_WEBSOCKET)
  13026. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  13027. #else
  13028. handler_type = REQUEST_HANDLER;
  13029. #endif /* defined(USE_WEBSOCKET) */
  13030. if (is_websocket_request) {
  13031. HTTP1_only;
  13032. }
  13033. /* 5.2. check if the request will be handled by a callback */
  13034. if (get_request_handler(conn,
  13035. handler_type,
  13036. &callback_handler,
  13037. &subprotocols,
  13038. &ws_connect_handler,
  13039. &ws_ready_handler,
  13040. &ws_data_handler,
  13041. &ws_close_handler,
  13042. NULL,
  13043. &callback_data,
  13044. &handler_info)) {
  13045. /* 5.2.1. A callback will handle this request. All requests
  13046. * handled by a callback have to be considered as requests
  13047. * to a script resource. */
  13048. is_callback_resource = 1;
  13049. is_script_resource = 1;
  13050. is_put_or_delete_request = is_put_or_delete_method(conn);
  13051. /* Never handle a C callback according to File WebDav rules,
  13052. * even if it is a webdav method */
  13053. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  13054. } else {
  13055. no_callback_resource:
  13056. /* 5.2.2. No callback is responsible for this request. The URI
  13057. * addresses a file based resource (static content or Lua/cgi
  13058. * scripts in the file system). */
  13059. is_callback_resource = 0;
  13060. interpret_uri(conn,
  13061. path,
  13062. sizeof(path),
  13063. &file.stat,
  13064. &is_found,
  13065. &is_script_resource,
  13066. &is_websocket_request,
  13067. &is_put_or_delete_request,
  13068. &is_webdav_request,
  13069. &is_template_text_file);
  13070. }
  13071. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  13072. if (is_webdav_request) {
  13073. /* TODO: Do we need a config option? */
  13074. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  13075. if (webdav_enable[0] != 'y') {
  13076. mg_send_http_error(conn,
  13077. 405,
  13078. "%s method not allowed",
  13079. conn->request_info.request_method);
  13080. DEBUG_TRACE("%s", "webdav rejected");
  13081. return;
  13082. }
  13083. }
  13084. /* 6. authorization check */
  13085. /* 6.1. a custom authorization handler is installed */
  13086. if (get_request_handler(conn,
  13087. AUTH_HANDLER,
  13088. NULL,
  13089. NULL,
  13090. NULL,
  13091. NULL,
  13092. NULL,
  13093. NULL,
  13094. &auth_handler,
  13095. &auth_callback_data,
  13096. NULL)) {
  13097. if (!auth_handler(conn, auth_callback_data)) {
  13098. /* Callback handler will not be used anymore. Release it */
  13099. release_handler_ref(conn, handler_info);
  13100. DEBUG_TRACE("%s", "auth handler rejected request");
  13101. return;
  13102. }
  13103. } else if (is_put_or_delete_request && !is_script_resource
  13104. && !is_callback_resource) {
  13105. HTTP1_only;
  13106. /* 6.2. this request is a PUT/DELETE to a real file */
  13107. /* 6.2.1. thus, the server must have real files */
  13108. #if defined(NO_FILES)
  13109. if (1) {
  13110. #else
  13111. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  13112. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  13113. #endif
  13114. /* This code path will not be called for request handlers */
  13115. DEBUG_ASSERT(handler_info == NULL);
  13116. /* This server does not have any real files, thus the
  13117. * PUT/DELETE methods are not valid. */
  13118. mg_send_http_error(conn,
  13119. 405,
  13120. "%s method not allowed",
  13121. conn->request_info.request_method);
  13122. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  13123. return;
  13124. }
  13125. #if !defined(NO_FILES)
  13126. /* 6.2.2. Check if put authorization for static files is
  13127. * available.
  13128. */
  13129. if (!is_authorized_for_put(conn)) {
  13130. send_authorization_request(conn, NULL);
  13131. DEBUG_TRACE("%s", "file write needs authorization");
  13132. return;
  13133. }
  13134. #endif
  13135. } else {
  13136. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13137. * or it is a PUT or DELETE request to a resource that does not
  13138. * correspond to a file. Check authorization. */
  13139. if (!check_authorization(conn, path)) {
  13140. send_authorization_request(conn, NULL);
  13141. /* Callback handler will not be used anymore. Release it */
  13142. release_handler_ref(conn, handler_info);
  13143. DEBUG_TRACE("%s", "access authorization required");
  13144. return;
  13145. }
  13146. }
  13147. /* request is authorized or does not need authorization */
  13148. /* 7. check if there are request handlers for this uri */
  13149. if (is_callback_resource) {
  13150. HTTP1_only;
  13151. if (!is_websocket_request) {
  13152. i = callback_handler(conn, callback_data);
  13153. /* Callback handler will not be used anymore. Release it */
  13154. release_handler_ref(conn, handler_info);
  13155. if (i > 0) {
  13156. /* Do nothing, callback has served the request. Store
  13157. * then return value as status code for the log and discard
  13158. * all data from the client not used by the callback. */
  13159. conn->status_code = i;
  13160. if (!conn->must_close) {
  13161. discard_unread_request_data(conn);
  13162. }
  13163. } else {
  13164. /* The handler did NOT handle the request. */
  13165. /* Some proper reactions would be:
  13166. * a) close the connections without sending anything
  13167. * b) send a 404 not found
  13168. * c) try if there is a file matching the URI
  13169. * It would be possible to do a, b or c in the callback
  13170. * implementation, and return 1 - we cannot do anything
  13171. * here, that is not possible in the callback.
  13172. *
  13173. * TODO: What would be the best reaction here?
  13174. * (Note: The reaction may change, if there is a better
  13175. * idea.)
  13176. */
  13177. /* For the moment, use option c: We look for a proper file,
  13178. * but since a file request is not always a script resource,
  13179. * the authorization check might be different. */
  13180. callback_handler = NULL;
  13181. /* Here we are at a dead end:
  13182. * According to URI matching, a callback should be
  13183. * responsible for handling the request,
  13184. * we called it, but the callback declared itself
  13185. * not responsible.
  13186. * We use a goto here, to get out of this dead end,
  13187. * and continue with the default handling.
  13188. * A goto here is simpler and better to understand
  13189. * than some curious loop. */
  13190. goto no_callback_resource;
  13191. }
  13192. } else {
  13193. #if defined(USE_WEBSOCKET)
  13194. handle_websocket_request(conn,
  13195. path,
  13196. is_callback_resource,
  13197. subprotocols,
  13198. ws_connect_handler,
  13199. ws_ready_handler,
  13200. ws_data_handler,
  13201. ws_close_handler,
  13202. callback_data);
  13203. #endif
  13204. }
  13205. DEBUG_TRACE("%s", "websocket handling done");
  13206. return;
  13207. }
  13208. /* 8. handle websocket requests */
  13209. #if defined(USE_WEBSOCKET)
  13210. if (is_websocket_request) {
  13211. HTTP1_only;
  13212. if (is_script_resource) {
  13213. if (is_in_script_path(conn, path)) {
  13214. /* Websocket Lua script */
  13215. handle_websocket_request(conn,
  13216. path,
  13217. 0 /* Lua Script */,
  13218. NULL,
  13219. NULL,
  13220. NULL,
  13221. NULL,
  13222. NULL,
  13223. conn->phys_ctx->user_data);
  13224. } else {
  13225. /* Script was in an illegal path */
  13226. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13227. }
  13228. } else {
  13229. mg_send_http_error(conn, 404, "%s", "Not found");
  13230. }
  13231. DEBUG_TRACE("%s", "websocket script done");
  13232. return;
  13233. } else
  13234. #endif
  13235. #if defined(NO_FILES)
  13236. /* 9a. In case the server uses only callbacks, this uri is
  13237. * unknown.
  13238. * Then, all request handling ends here. */
  13239. mg_send_http_error(conn, 404, "%s", "Not Found");
  13240. #else
  13241. /* 9b. This request is either for a static file or resource handled
  13242. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13243. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13244. mg_send_http_error(conn, 404, "%s", "Not Found");
  13245. DEBUG_TRACE("%s", "no document root available");
  13246. return;
  13247. }
  13248. /* 10. Request is handled by a script */
  13249. if (is_script_resource) {
  13250. HTTP1_only;
  13251. handle_file_based_request(conn, path, &file);
  13252. DEBUG_TRACE("%s", "script handling done");
  13253. return;
  13254. }
  13255. /* Request was not handled by a callback or script. It will be
  13256. * handled by a server internal method. */
  13257. /* 11. Handle put/delete/mkcol requests */
  13258. if (is_put_or_delete_request) {
  13259. HTTP1_only;
  13260. /* 11.1. PUT method */
  13261. if (!strcmp(ri->request_method, "PUT")) {
  13262. put_file(conn, path);
  13263. DEBUG_TRACE("handling %s request to %s done",
  13264. ri->request_method,
  13265. path);
  13266. return;
  13267. }
  13268. /* 11.2. DELETE method */
  13269. if (!strcmp(ri->request_method, "DELETE")) {
  13270. delete_file(conn, path);
  13271. DEBUG_TRACE("handling %s request to %s done",
  13272. ri->request_method,
  13273. path);
  13274. return;
  13275. }
  13276. /* 11.3. MKCOL method */
  13277. if (!strcmp(ri->request_method, "MKCOL")) {
  13278. dav_mkcol(conn, path);
  13279. DEBUG_TRACE("handling %s request to %s done",
  13280. ri->request_method,
  13281. path);
  13282. return;
  13283. }
  13284. /* 11.4. MOVE method */
  13285. if (!strcmp(ri->request_method, "MOVE")) {
  13286. dav_move_file(conn, path, 0);
  13287. DEBUG_TRACE("handling %s request to %s done",
  13288. ri->request_method,
  13289. path);
  13290. return;
  13291. }
  13292. if (!strcmp(ri->request_method, "COPY")) {
  13293. dav_move_file(conn, path, 1);
  13294. DEBUG_TRACE("handling %s request to %s done",
  13295. ri->request_method,
  13296. path);
  13297. return;
  13298. }
  13299. /* 11.5. LOCK method */
  13300. if (!strcmp(ri->request_method, "LOCK")) {
  13301. dav_lock_file(conn, path);
  13302. DEBUG_TRACE("handling %s request to %s done",
  13303. ri->request_method,
  13304. path);
  13305. return;
  13306. }
  13307. /* 11.6. UNLOCK method */
  13308. if (!strcmp(ri->request_method, "UNLOCK")) {
  13309. dav_unlock_file(conn, path);
  13310. DEBUG_TRACE("handling %s request to %s done",
  13311. ri->request_method,
  13312. path);
  13313. return;
  13314. }
  13315. /* 11.7. PROPPATCH method */
  13316. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13317. dav_proppatch(conn, path);
  13318. DEBUG_TRACE("handling %s request to %s done",
  13319. ri->request_method,
  13320. path);
  13321. return;
  13322. }
  13323. /* 11.8. Other methods, e.g.: PATCH
  13324. * This method is not supported for static resources,
  13325. * only for scripts (Lua, CGI) and callbacks. */
  13326. mg_send_http_error(conn,
  13327. 405,
  13328. "%s method not allowed",
  13329. conn->request_info.request_method);
  13330. DEBUG_TRACE("method %s on %s is not supported",
  13331. ri->request_method,
  13332. path);
  13333. return;
  13334. }
  13335. /* 11. File does not exist, or it was configured that it should be
  13336. * hidden */
  13337. if (!is_found || (must_hide_file(conn, path))) {
  13338. mg_send_http_error(conn, 404, "%s", "Not found");
  13339. DEBUG_TRACE("handling %s request to %s: file not found",
  13340. ri->request_method,
  13341. path);
  13342. return;
  13343. }
  13344. /* 12. Directory uris should end with a slash */
  13345. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13346. && (ri->local_uri[uri_len - 1] != '/')) {
  13347. /* Path + server root */
  13348. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13349. char *new_path;
  13350. if (ri->query_string) {
  13351. buflen += strlen(ri->query_string);
  13352. }
  13353. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13354. if (!new_path) {
  13355. mg_send_http_error(conn, 500, "out or memory");
  13356. } else {
  13357. mg_get_request_link(conn, new_path, buflen - 1);
  13358. strcat(new_path, "/");
  13359. if (ri->query_string) {
  13360. /* Append ? and query string */
  13361. strcat(new_path, "?");
  13362. strcat(new_path, ri->query_string);
  13363. }
  13364. mg_send_http_redirect(conn, new_path, 301);
  13365. mg_free(new_path);
  13366. }
  13367. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13368. ri->request_method,
  13369. path);
  13370. return;
  13371. }
  13372. /* 13. Handle other methods than GET/HEAD */
  13373. /* 13.1. Handle PROPFIND */
  13374. if (!strcmp(ri->request_method, "PROPFIND")) {
  13375. handle_propfind(conn, path, &file.stat);
  13376. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13377. return;
  13378. }
  13379. /* 13.2. Handle OPTIONS for files */
  13380. if (!strcmp(ri->request_method, "OPTIONS")) {
  13381. /* This standard handler is only used for real files.
  13382. * Scripts should support the OPTIONS method themselves, to allow a
  13383. * maximum flexibility.
  13384. * Lua and CGI scripts may fully support CORS this way (including
  13385. * preflights). */
  13386. send_options(conn);
  13387. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13388. return;
  13389. }
  13390. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13391. if ((0 != strcmp(ri->request_method, "GET"))
  13392. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13393. mg_send_http_error(conn,
  13394. 405,
  13395. "%s method not allowed",
  13396. conn->request_info.request_method);
  13397. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13398. return;
  13399. }
  13400. /* 14. directories */
  13401. if (file.stat.is_directory) {
  13402. /* Substitute files have already been handled above. */
  13403. /* Here we can either generate and send a directory listing,
  13404. * or send an "access denied" error. */
  13405. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13406. "yes")) {
  13407. handle_directory_request(conn, path);
  13408. } else {
  13409. mg_send_http_error(conn,
  13410. 403,
  13411. "%s",
  13412. "Error: Directory listing denied");
  13413. }
  13414. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13415. return;
  13416. }
  13417. /* 15. Files with search/replace patterns: LSP and SSI */
  13418. if (is_template_text_file) {
  13419. HTTP1_only;
  13420. handle_file_based_request(conn, path, &file);
  13421. DEBUG_TRACE("handling %s request to %s done (template)",
  13422. ri->request_method,
  13423. path);
  13424. return;
  13425. }
  13426. /* 16. Static file - maybe cached */
  13427. #if !defined(NO_CACHING)
  13428. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13429. /* Send 304 "Not Modified" - this must not send any body data */
  13430. handle_not_modified_static_file_request(conn, &file);
  13431. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13432. ri->request_method,
  13433. path);
  13434. return;
  13435. }
  13436. #endif /* !NO_CACHING */
  13437. /* 17. Static file - not cached */
  13438. handle_static_file_request(conn, path, &file, NULL, NULL);
  13439. DEBUG_TRACE("handling %s request to %s done (static)",
  13440. ri->request_method,
  13441. path);
  13442. #endif /* !defined(NO_FILES) */
  13443. }
  13444. #if !defined(NO_FILESYSTEMS)
  13445. static void
  13446. handle_file_based_request(struct mg_connection *conn,
  13447. const char *path,
  13448. struct mg_file *file)
  13449. {
  13450. #if !defined(NO_CGI)
  13451. int cgi_config_idx, inc, max;
  13452. #endif
  13453. if (!conn || !conn->dom_ctx) {
  13454. return;
  13455. }
  13456. #if defined(USE_LUA)
  13457. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13458. path)
  13459. > 0) {
  13460. if (is_in_script_path(conn, path)) {
  13461. /* Lua server page: an SSI like page containing mostly plain
  13462. * html code plus some tags with server generated contents. */
  13463. handle_lsp_request(conn, path, file, NULL);
  13464. } else {
  13465. /* Script was in an illegal path */
  13466. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13467. }
  13468. return;
  13469. }
  13470. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13471. > 0) {
  13472. if (is_in_script_path(conn, path)) {
  13473. /* Lua in-server module script: a CGI like script used to
  13474. * generate the entire reply. */
  13475. mg_exec_lua_script(conn, path, NULL);
  13476. } else {
  13477. /* Script was in an illegal path */
  13478. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13479. }
  13480. return;
  13481. }
  13482. #endif
  13483. #if defined(USE_DUKTAPE)
  13484. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13485. path)
  13486. > 0) {
  13487. if (is_in_script_path(conn, path)) {
  13488. /* Call duktape to generate the page */
  13489. mg_exec_duktape_script(conn, path);
  13490. } else {
  13491. /* Script was in an illegal path */
  13492. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13493. }
  13494. return;
  13495. }
  13496. #endif
  13497. #if !defined(NO_CGI)
  13498. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13499. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13500. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13501. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13502. if (match_prefix_strlen(
  13503. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13504. path)
  13505. > 0) {
  13506. if (is_in_script_path(conn, path)) {
  13507. /* CGI scripts may support all HTTP methods */
  13508. handle_cgi_request(conn, path, cgi_config_idx);
  13509. } else {
  13510. /* Script was in an illegal path */
  13511. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13512. }
  13513. return;
  13514. }
  13515. }
  13516. }
  13517. #endif /* !NO_CGI */
  13518. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13519. if (is_in_script_path(conn, path)) {
  13520. handle_ssi_file_request(conn, path, file);
  13521. } else {
  13522. /* Script was in an illegal path */
  13523. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13524. }
  13525. return;
  13526. }
  13527. #if !defined(NO_CACHING)
  13528. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13529. /* Send 304 "Not Modified" - this must not send any body data */
  13530. handle_not_modified_static_file_request(conn, file);
  13531. return;
  13532. }
  13533. #endif /* !NO_CACHING */
  13534. handle_static_file_request(conn, path, file, NULL, NULL);
  13535. }
  13536. #endif /* NO_FILESYSTEMS */
  13537. static void
  13538. close_all_listening_sockets(struct mg_context *ctx)
  13539. {
  13540. unsigned int i;
  13541. if (!ctx) {
  13542. return;
  13543. }
  13544. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13545. closesocket(ctx->listening_sockets[i].sock);
  13546. #if defined(USE_X_DOM_SOCKET)
  13547. /* For unix domain sockets, the socket name represents a file that has
  13548. * to be deleted. */
  13549. /* See
  13550. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13551. */
  13552. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13553. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13554. IGNORE_UNUSED_RESULT(
  13555. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13556. }
  13557. #endif
  13558. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13559. }
  13560. mg_free(ctx->listening_sockets);
  13561. ctx->listening_sockets = NULL;
  13562. mg_free(ctx->listening_socket_fds);
  13563. ctx->listening_socket_fds = NULL;
  13564. }
  13565. /* Valid listening port specification is: [ip_address:]port[s]
  13566. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13567. * Examples for IPv6: [::]:80, [::1]:80,
  13568. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13569. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13570. * In order to bind to both, IPv4 and IPv6, you can either add
  13571. * both ports using 8080,[::]:8080, or the short form +8080.
  13572. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13573. * one only accepting IPv4 the other only IPv6. +8080 creates
  13574. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13575. * environment, they might work differently, or might not work
  13576. * at all - it must be tested what options work best in the
  13577. * relevant network environment.
  13578. */
  13579. static int
  13580. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13581. {
  13582. unsigned int a, b, c, d;
  13583. unsigned port;
  13584. unsigned long portUL;
  13585. int len;
  13586. const char *cb;
  13587. char *endptr;
  13588. #if defined(USE_IPV6)
  13589. char buf[100] = {0};
  13590. #endif
  13591. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13592. * Also, all-zeroes in the socket address means binding to all addresses
  13593. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13594. memset(so, 0, sizeof(*so));
  13595. so->lsa.sin.sin_family = AF_INET;
  13596. *ip_version = 0;
  13597. /* Initialize len as invalid. */
  13598. port = 0;
  13599. len = 0;
  13600. /* Test for different ways to format this string */
  13601. if (sscanf(vec->ptr,
  13602. "%u.%u.%u.%u:%u%n",
  13603. &a,
  13604. &b,
  13605. &c,
  13606. &d,
  13607. &port,
  13608. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13609. // to an integer value, but function will not report
  13610. // conversion errors; consider using 'strtol' instead
  13611. == 5) {
  13612. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13613. so->lsa.sin.sin_addr.s_addr =
  13614. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13615. so->lsa.sin.sin_port = htons((uint16_t)port);
  13616. *ip_version = 4;
  13617. #if defined(USE_IPV6)
  13618. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13619. && ((size_t)len <= vec->len)
  13620. && mg_inet_pton(
  13621. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13622. /* IPv6 address, examples: see above */
  13623. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13624. */
  13625. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13626. *ip_version = 6;
  13627. #endif
  13628. } else if ((vec->ptr[0] == '+')
  13629. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13630. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13631. // string to an integer value, but function will not
  13632. // report conversion errors; consider using 'strtol'
  13633. // instead
  13634. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13635. /* Add 1 to len for the + character we skipped before */
  13636. len++;
  13637. #if defined(USE_IPV6)
  13638. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13639. so->lsa.sin6.sin6_family = AF_INET6;
  13640. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13641. *ip_version = 4 + 6;
  13642. #else
  13643. /* Bind to IPv4 only, since IPv6 is not built in. */
  13644. so->lsa.sin.sin_port = htons((uint16_t)port);
  13645. *ip_version = 4;
  13646. #endif
  13647. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13648. && (vec->ptr != endptr)) {
  13649. len = (int)(endptr - vec->ptr);
  13650. port = (uint16_t)portUL;
  13651. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13652. so->lsa.sin.sin_port = htons((uint16_t)port);
  13653. *ip_version = 4;
  13654. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13655. /* String could be a hostname. This check algorithm
  13656. * will only work for RFC 952 compliant hostnames,
  13657. * starting with a letter, containing only letters,
  13658. * digits and hyphen ('-'). Newer specs may allow
  13659. * more, but this is not guaranteed here, since it
  13660. * may interfere with rules for port option lists. */
  13661. /* According to RFC 1035, hostnames are restricted to 255 characters
  13662. * in total (63 between two dots). */
  13663. char hostname[256];
  13664. size_t hostnlen = (size_t)(cb - vec->ptr);
  13665. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13666. /* This would be invalid in any case */
  13667. *ip_version = 0;
  13668. return 0;
  13669. }
  13670. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13671. if (mg_inet_pton(
  13672. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13673. if (sscanf(cb + 1, "%u%n", &port, &len)
  13674. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13675. // string to an integer value, but function will not
  13676. // report conversion errors; consider using 'strtol'
  13677. // instead
  13678. *ip_version = 4;
  13679. so->lsa.sin.sin_port = htons((uint16_t)port);
  13680. len += (int)(hostnlen + 1);
  13681. } else {
  13682. len = 0;
  13683. }
  13684. #if defined(USE_IPV6)
  13685. } else if (mg_inet_pton(AF_INET6,
  13686. hostname,
  13687. &so->lsa.sin6,
  13688. sizeof(so->lsa.sin6),
  13689. 1)) {
  13690. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13691. *ip_version = 6;
  13692. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13693. len += (int)(hostnlen + 1);
  13694. } else {
  13695. len = 0;
  13696. }
  13697. #endif
  13698. } else {
  13699. len = 0;
  13700. }
  13701. #if defined(USE_X_DOM_SOCKET)
  13702. } else if (vec->ptr[0] == 'x') {
  13703. /* unix (linux) domain socket */
  13704. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13705. len = vec->len;
  13706. so->lsa.sun.sun_family = AF_UNIX;
  13707. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13708. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13709. port = 0;
  13710. *ip_version = 99;
  13711. } else {
  13712. /* String too long */
  13713. len = 0;
  13714. }
  13715. #endif
  13716. } else {
  13717. /* Parsing failure. */
  13718. len = 0;
  13719. }
  13720. /* sscanf and the option splitting code ensure the following condition
  13721. * Make sure the port is valid and vector ends with the port, 'o', 's', or
  13722. * 'r' */
  13723. if ((len > 0) && (is_valid_port(port))) {
  13724. int bad_suffix = 0;
  13725. size_t i;
  13726. /* Parse any suffix character(s) after the port number */
  13727. for (i = len; i < vec->len; i++) {
  13728. unsigned char *opt = NULL;
  13729. switch (vec->ptr[i]) {
  13730. case 'o':
  13731. opt = &so->is_optional;
  13732. break;
  13733. case 'r':
  13734. opt = &so->ssl_redir;
  13735. break;
  13736. case 's':
  13737. opt = &so->is_ssl;
  13738. break;
  13739. default: /* empty */
  13740. break;
  13741. }
  13742. if ((opt) && (*opt == 0))
  13743. *opt = 1;
  13744. else {
  13745. bad_suffix = 1;
  13746. break;
  13747. }
  13748. }
  13749. if ((bad_suffix == 0) && ((so->is_ssl == 0) || (so->ssl_redir == 0))) {
  13750. return 1;
  13751. }
  13752. }
  13753. /* Reset ip_version to 0 if there is an error */
  13754. *ip_version = 0;
  13755. return 0;
  13756. }
  13757. /* Is there any SSL port in use? */
  13758. static int
  13759. is_ssl_port_used(const char *ports)
  13760. {
  13761. if (ports) {
  13762. /* There are several different allowed syntax variants:
  13763. * - "80" for a single port using every network interface
  13764. * - "localhost:80" for a single port using only localhost
  13765. * - "80,localhost:8080" for two ports, one bound to localhost
  13766. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13767. * to IPv4 localhost, one to IPv6 localhost
  13768. * - "+80" use port 80 for IPv4 and IPv6
  13769. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13770. * for both: IPv4 and IPv4
  13771. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13772. * additionally port 8080 bound to localhost connections
  13773. *
  13774. * If we just look for 's' anywhere in the string, "localhost:80"
  13775. * will be detected as SSL (false positive).
  13776. * Looking for 's' after a digit may cause false positives in
  13777. * "my24service:8080".
  13778. * Looking from 's' backward if there are only ':' and numbers
  13779. * before will not work for "24service:8080" (non SSL, port 8080)
  13780. * or "24s" (SSL, port 24).
  13781. *
  13782. * Remark: Initially hostnames were not allowed to start with a
  13783. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13784. * Section 2.1).
  13785. *
  13786. * To get this correct, the entire string must be parsed as a whole,
  13787. * reading it as a list element for element and parsing with an
  13788. * algorithm equivalent to parse_port_string.
  13789. *
  13790. * In fact, we use local interface names here, not arbitrary
  13791. * hostnames, so in most cases the only name will be "localhost".
  13792. *
  13793. * So, for now, we use this simple algorithm, that may still return
  13794. * a false positive in bizarre cases.
  13795. */
  13796. int i;
  13797. int portslen = (int)strlen(ports);
  13798. char prevIsNumber = 0;
  13799. for (i = 0; i < portslen; i++) {
  13800. if (prevIsNumber) {
  13801. int suffixCharIdx = (ports[i] == 'o')
  13802. ? (i + 1)
  13803. : i; /* allow "os" and "or" suffixes */
  13804. if (ports[suffixCharIdx] == 's'
  13805. || ports[suffixCharIdx] == 'r') {
  13806. return 1;
  13807. }
  13808. }
  13809. if (ports[i] >= '0' && ports[i] <= '9') {
  13810. prevIsNumber = 1;
  13811. } else {
  13812. prevIsNumber = 0;
  13813. }
  13814. }
  13815. }
  13816. return 0;
  13817. }
  13818. static int
  13819. set_ports_option(struct mg_context *phys_ctx)
  13820. {
  13821. const char *list;
  13822. int on = 1;
  13823. #if defined(USE_IPV6)
  13824. int off = 0;
  13825. #endif
  13826. struct vec vec;
  13827. struct socket so, *ptr;
  13828. struct mg_pollfd *pfd;
  13829. union usa usa;
  13830. socklen_t len;
  13831. int ip_version;
  13832. int portsTotal = 0;
  13833. int portsOk = 0;
  13834. const char *opt_txt;
  13835. long opt_listen_backlog;
  13836. if (!phys_ctx) {
  13837. return 0;
  13838. }
  13839. memset(&so, 0, sizeof(so));
  13840. memset(&usa, 0, sizeof(usa));
  13841. len = sizeof(usa);
  13842. list = phys_ctx->dd.config[LISTENING_PORTS];
  13843. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13844. portsTotal++;
  13845. if (!parse_port_string(&vec, &so, &ip_version)) {
  13846. mg_cry_ctx_internal(
  13847. phys_ctx,
  13848. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13849. (int)vec.len,
  13850. vec.ptr,
  13851. portsTotal,
  13852. "[IP_ADDRESS:]PORT[s|r]");
  13853. continue;
  13854. }
  13855. #if !defined(NO_SSL)
  13856. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13857. mg_cry_ctx_internal(phys_ctx,
  13858. "Cannot add SSL socket (entry %i)",
  13859. portsTotal);
  13860. continue;
  13861. }
  13862. #endif
  13863. /* Create socket. */
  13864. /* For a list of protocol numbers (e.g., TCP==6) see:
  13865. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13866. */
  13867. if ((so.sock =
  13868. socket(so.lsa.sa.sa_family,
  13869. SOCK_STREAM,
  13870. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13871. == INVALID_SOCKET) {
  13872. mg_cry_ctx_internal(phys_ctx,
  13873. "cannot create socket (entry %i)",
  13874. portsTotal);
  13875. continue;
  13876. }
  13877. #if defined(_WIN32)
  13878. /* Windows SO_REUSEADDR lets many procs binds to a
  13879. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13880. * if someone already has the socket -- DTL */
  13881. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13882. * Windows might need a few seconds before
  13883. * the same port can be used again in the
  13884. * same process, so a short Sleep may be
  13885. * required between mg_stop and mg_start.
  13886. */
  13887. if (setsockopt(so.sock,
  13888. SOL_SOCKET,
  13889. SO_EXCLUSIVEADDRUSE,
  13890. (SOCK_OPT_TYPE)&on,
  13891. sizeof(on))
  13892. != 0) {
  13893. /* Set reuse option, but don't abort on errors. */
  13894. mg_cry_ctx_internal(
  13895. phys_ctx,
  13896. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13897. portsTotal);
  13898. }
  13899. #else
  13900. if (setsockopt(so.sock,
  13901. SOL_SOCKET,
  13902. SO_REUSEADDR,
  13903. (SOCK_OPT_TYPE)&on,
  13904. sizeof(on))
  13905. != 0) {
  13906. /* Set reuse option, but don't abort on errors. */
  13907. mg_cry_ctx_internal(
  13908. phys_ctx,
  13909. "cannot set socket option SO_REUSEADDR (entry %i)",
  13910. portsTotal);
  13911. }
  13912. #endif
  13913. #if defined(USE_X_DOM_SOCKET)
  13914. if (ip_version == 99) {
  13915. /* Unix domain socket */
  13916. } else
  13917. #endif
  13918. if (ip_version > 4) {
  13919. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13920. #if defined(USE_IPV6)
  13921. if (ip_version > 6) {
  13922. if (so.lsa.sa.sa_family == AF_INET6
  13923. && setsockopt(so.sock,
  13924. IPPROTO_IPV6,
  13925. IPV6_V6ONLY,
  13926. (void *)&off,
  13927. sizeof(off))
  13928. != 0) {
  13929. /* Set IPv6 only option, but don't abort on errors. */
  13930. mg_cry_ctx_internal(phys_ctx,
  13931. "cannot set socket option "
  13932. "IPV6_V6ONLY=off (entry %i)",
  13933. portsTotal);
  13934. }
  13935. } else {
  13936. if (so.lsa.sa.sa_family == AF_INET6
  13937. && setsockopt(so.sock,
  13938. IPPROTO_IPV6,
  13939. IPV6_V6ONLY,
  13940. (void *)&on,
  13941. sizeof(on))
  13942. != 0) {
  13943. /* Set IPv6 only option, but don't abort on errors. */
  13944. mg_cry_ctx_internal(phys_ctx,
  13945. "cannot set socket option "
  13946. "IPV6_V6ONLY=on (entry %i)",
  13947. portsTotal);
  13948. }
  13949. }
  13950. #else
  13951. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13952. closesocket(so.sock);
  13953. so.sock = INVALID_SOCKET;
  13954. continue;
  13955. #endif
  13956. }
  13957. if (so.lsa.sa.sa_family == AF_INET) {
  13958. len = sizeof(so.lsa.sin);
  13959. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13960. mg_cry_ctx_internal(phys_ctx,
  13961. "cannot bind to %.*s: %d (%s)",
  13962. (int)vec.len,
  13963. vec.ptr,
  13964. (int)ERRNO,
  13965. strerror(errno));
  13966. closesocket(so.sock);
  13967. so.sock = INVALID_SOCKET;
  13968. if (so.is_optional) {
  13969. portsOk++; /* it's okay if we couldn't bind, this port is
  13970. optional anyway */
  13971. }
  13972. continue;
  13973. }
  13974. }
  13975. #if defined(USE_IPV6)
  13976. else if (so.lsa.sa.sa_family == AF_INET6) {
  13977. len = sizeof(so.lsa.sin6);
  13978. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13979. mg_cry_ctx_internal(phys_ctx,
  13980. "cannot bind to IPv6 %.*s: %d (%s)",
  13981. (int)vec.len,
  13982. vec.ptr,
  13983. (int)ERRNO,
  13984. strerror(errno));
  13985. closesocket(so.sock);
  13986. so.sock = INVALID_SOCKET;
  13987. if (so.is_optional) {
  13988. portsOk++; /* it's okay if we couldn't bind, this port is
  13989. optional anyway */
  13990. }
  13991. continue;
  13992. }
  13993. }
  13994. #endif
  13995. #if defined(USE_X_DOM_SOCKET)
  13996. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13997. len = sizeof(so.lsa.sun);
  13998. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13999. mg_cry_ctx_internal(phys_ctx,
  14000. "cannot bind to unix socket %s: %d (%s)",
  14001. so.lsa.sun.sun_path,
  14002. (int)ERRNO,
  14003. strerror(errno));
  14004. closesocket(so.sock);
  14005. so.sock = INVALID_SOCKET;
  14006. if (so.is_optional) {
  14007. portsOk++; /* it's okay if we couldn't bind, this port is
  14008. optional anyway */
  14009. }
  14010. continue;
  14011. }
  14012. }
  14013. #endif
  14014. else {
  14015. mg_cry_ctx_internal(
  14016. phys_ctx,
  14017. "cannot bind: address family not supported (entry %i)",
  14018. portsTotal);
  14019. closesocket(so.sock);
  14020. so.sock = INVALID_SOCKET;
  14021. continue;
  14022. }
  14023. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  14024. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  14025. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  14026. mg_cry_ctx_internal(phys_ctx,
  14027. "%s value \"%s\" is invalid",
  14028. config_options[LISTEN_BACKLOG_SIZE].name,
  14029. opt_txt);
  14030. closesocket(so.sock);
  14031. so.sock = INVALID_SOCKET;
  14032. continue;
  14033. }
  14034. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  14035. mg_cry_ctx_internal(phys_ctx,
  14036. "cannot listen to %.*s: %d (%s)",
  14037. (int)vec.len,
  14038. vec.ptr,
  14039. (int)ERRNO,
  14040. strerror(errno));
  14041. closesocket(so.sock);
  14042. so.sock = INVALID_SOCKET;
  14043. continue;
  14044. }
  14045. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  14046. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  14047. int err = (int)ERRNO;
  14048. mg_cry_ctx_internal(phys_ctx,
  14049. "call to getsockname failed %.*s: %d (%s)",
  14050. (int)vec.len,
  14051. vec.ptr,
  14052. err,
  14053. strerror(errno));
  14054. closesocket(so.sock);
  14055. so.sock = INVALID_SOCKET;
  14056. continue;
  14057. }
  14058. /* Update lsa port in case of random free ports */
  14059. #if defined(USE_IPV6)
  14060. if (so.lsa.sa.sa_family == AF_INET6) {
  14061. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  14062. } else
  14063. #endif
  14064. {
  14065. so.lsa.sin.sin_port = usa.sin.sin_port;
  14066. }
  14067. if ((ptr = (struct socket *)
  14068. mg_realloc_ctx(phys_ctx->listening_sockets,
  14069. (phys_ctx->num_listening_sockets + 1)
  14070. * sizeof(phys_ctx->listening_sockets[0]),
  14071. phys_ctx))
  14072. == NULL) {
  14073. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14074. closesocket(so.sock);
  14075. so.sock = INVALID_SOCKET;
  14076. continue;
  14077. }
  14078. /* The +2 below includes the original +1 (for the socket we're about to
  14079. * add), plus another +1 for the thread_shutdown_notification_socket
  14080. * that we'll also want to poll() on so that mg_stop() can return
  14081. * quickly
  14082. */
  14083. if ((pfd = (struct mg_pollfd *)
  14084. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  14085. (phys_ctx->num_listening_sockets + 2)
  14086. * sizeof(phys_ctx->listening_socket_fds[0]),
  14087. phys_ctx))
  14088. == NULL) {
  14089. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14090. closesocket(so.sock);
  14091. so.sock = INVALID_SOCKET;
  14092. mg_free(ptr);
  14093. continue;
  14094. }
  14095. set_close_on_exec(so.sock, NULL, phys_ctx);
  14096. phys_ctx->listening_sockets = ptr;
  14097. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  14098. phys_ctx->listening_socket_fds = pfd;
  14099. phys_ctx->num_listening_sockets++;
  14100. portsOk++;
  14101. }
  14102. if (portsOk != portsTotal) {
  14103. close_all_listening_sockets(phys_ctx);
  14104. portsOk = 0;
  14105. }
  14106. return portsOk;
  14107. }
  14108. static const char *
  14109. header_val(const struct mg_connection *conn, const char *header)
  14110. {
  14111. const char *header_value;
  14112. if ((header_value = mg_get_header(conn, header)) == NULL) {
  14113. return "-";
  14114. } else {
  14115. return header_value;
  14116. }
  14117. }
  14118. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  14119. #include "external_log_access.inl"
  14120. #elif !defined(NO_FILESYSTEMS)
  14121. static void
  14122. log_access(const struct mg_connection *conn)
  14123. {
  14124. const struct mg_request_info *ri;
  14125. struct mg_file fi;
  14126. char date[64], src_addr[IP_ADDR_STR_LEN];
  14127. #if defined(REENTRANT_TIME)
  14128. struct tm _tm;
  14129. struct tm *tm = &_tm;
  14130. #else
  14131. struct tm *tm;
  14132. #endif
  14133. const char *referer;
  14134. const char *user_agent;
  14135. char log_buf[4096];
  14136. if (!conn || !conn->dom_ctx) {
  14137. return;
  14138. }
  14139. /* Set log message to "empty" */
  14140. log_buf[0] = 0;
  14141. #if defined(USE_LUA)
  14142. if (conn->phys_ctx->lua_bg_log_available) {
  14143. int ret;
  14144. struct mg_context *ctx = conn->phys_ctx;
  14145. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14146. pthread_mutex_lock(&ctx->lua_bg_mutex);
  14147. /* call "log()" in Lua */
  14148. lua_getglobal(lstate, "log");
  14149. prepare_lua_request_info_inner(conn, lstate);
  14150. push_lua_response_log_data(conn, lstate);
  14151. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  14152. if (ret == 0) {
  14153. int t = lua_type(lstate, -1);
  14154. if (t == LUA_TBOOLEAN) {
  14155. if (lua_toboolean(lstate, -1) == 0) {
  14156. /* log() returned false: do not log */
  14157. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14158. return;
  14159. }
  14160. /* log returned true: continue logging */
  14161. } else if (t == LUA_TSTRING) {
  14162. size_t len;
  14163. const char *txt = lua_tolstring(lstate, -1, &len);
  14164. if ((len == 0) || (*txt == 0)) {
  14165. /* log() returned empty string: do not log */
  14166. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14167. return;
  14168. }
  14169. /* Copy test from Lua into log_buf */
  14170. if (len >= sizeof(log_buf)) {
  14171. len = sizeof(log_buf) - 1;
  14172. }
  14173. memcpy(log_buf, txt, len);
  14174. log_buf[len] = 0;
  14175. }
  14176. } else {
  14177. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14178. }
  14179. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14180. }
  14181. #endif
  14182. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14183. if (mg_fopen(conn,
  14184. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14185. MG_FOPEN_MODE_APPEND,
  14186. &fi)
  14187. == 0) {
  14188. fi.access.fp = NULL;
  14189. }
  14190. } else {
  14191. fi.access.fp = NULL;
  14192. }
  14193. /* Log is written to a file and/or a callback. If both are not set,
  14194. * executing the rest of the function is pointless. */
  14195. if ((fi.access.fp == NULL)
  14196. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14197. return;
  14198. }
  14199. /* If we did not get a log message from Lua, create it here. */
  14200. if (!log_buf[0]) {
  14201. #if defined(REENTRANT_TIME)
  14202. localtime_r(&conn->conn_birth_time, tm);
  14203. #else
  14204. tm = localtime(&conn->conn_birth_time);
  14205. #endif
  14206. if (tm != NULL) {
  14207. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14208. } else {
  14209. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14210. }
  14211. ri = &conn->request_info;
  14212. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14213. referer = header_val(conn, "Referer");
  14214. user_agent = header_val(conn, "User-Agent");
  14215. mg_snprintf(conn,
  14216. NULL, /* Ignore truncation in access log */
  14217. log_buf,
  14218. sizeof(log_buf),
  14219. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14220. " %s %s",
  14221. src_addr,
  14222. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14223. date,
  14224. ri->request_method ? ri->request_method : "-",
  14225. ri->request_uri ? ri->request_uri : "-",
  14226. ri->query_string ? "?" : "",
  14227. ri->query_string ? ri->query_string : "",
  14228. ri->http_version,
  14229. conn->status_code,
  14230. conn->num_bytes_sent,
  14231. referer,
  14232. user_agent);
  14233. }
  14234. /* Here we have a log message in log_buf. Call the callback */
  14235. if (conn->phys_ctx->callbacks.log_access) {
  14236. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14237. /* do not log if callback returns non-zero */
  14238. if (fi.access.fp) {
  14239. mg_fclose(&fi.access);
  14240. }
  14241. return;
  14242. }
  14243. }
  14244. /* Store in file */
  14245. if (fi.access.fp) {
  14246. int ok = 1;
  14247. flockfile(fi.access.fp);
  14248. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14249. ok = 0;
  14250. }
  14251. if (fflush(fi.access.fp) != 0) {
  14252. ok = 0;
  14253. }
  14254. funlockfile(fi.access.fp);
  14255. if (mg_fclose(&fi.access) != 0) {
  14256. ok = 0;
  14257. }
  14258. if (!ok) {
  14259. mg_cry_internal(conn,
  14260. "Error writing log file %s",
  14261. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14262. }
  14263. }
  14264. }
  14265. #else
  14266. #error "Either enable filesystems or provide a custom log_access implementation"
  14267. #endif /* Externally provided function */
  14268. /* Verify given socket address against the ACL.
  14269. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14270. */
  14271. static int
  14272. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14273. {
  14274. int allowed, flag, matched;
  14275. struct vec vec;
  14276. if (phys_ctx) {
  14277. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14278. /* If any ACL is set, deny by default */
  14279. allowed = (list == NULL) ? '+' : '-';
  14280. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14281. flag = vec.ptr[0];
  14282. matched = -1;
  14283. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14284. vec.ptr++;
  14285. vec.len--;
  14286. matched = parse_match_net(&vec, sa, 1);
  14287. }
  14288. if (matched < 0) {
  14289. mg_cry_ctx_internal(phys_ctx,
  14290. "%s: subnet must be [+|-]IP-addr[/x]",
  14291. __func__);
  14292. return -1;
  14293. }
  14294. if (matched) {
  14295. allowed = flag;
  14296. }
  14297. }
  14298. return allowed == '+';
  14299. }
  14300. return -1;
  14301. }
  14302. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14303. static int
  14304. set_uid_option(struct mg_context *phys_ctx)
  14305. {
  14306. int success = 0;
  14307. if (phys_ctx) {
  14308. /* We are currently running as curr_uid. */
  14309. const uid_t curr_uid = getuid();
  14310. /* If set, we want to run as run_as_user. */
  14311. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14312. const struct passwd *to_pw = NULL;
  14313. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14314. /* run_as_user does not exist on the system. We can't proceed
  14315. * further. */
  14316. mg_cry_ctx_internal(phys_ctx,
  14317. "%s: unknown user [%s]",
  14318. __func__,
  14319. run_as_user);
  14320. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14321. /* There was either no request to change user, or we're already
  14322. * running as run_as_user. Nothing else to do.
  14323. */
  14324. success = 1;
  14325. } else {
  14326. /* Valid change request. */
  14327. if (setgid(to_pw->pw_gid) == -1) {
  14328. mg_cry_ctx_internal(phys_ctx,
  14329. "%s: setgid(%s): %s",
  14330. __func__,
  14331. run_as_user,
  14332. strerror(errno));
  14333. } else if (setgroups(0, NULL) == -1) {
  14334. mg_cry_ctx_internal(phys_ctx,
  14335. "%s: setgroups(): %s",
  14336. __func__,
  14337. strerror(errno));
  14338. } else if (setuid(to_pw->pw_uid) == -1) {
  14339. mg_cry_ctx_internal(phys_ctx,
  14340. "%s: setuid(%s): %s",
  14341. __func__,
  14342. run_as_user,
  14343. strerror(errno));
  14344. } else {
  14345. success = 1;
  14346. }
  14347. }
  14348. }
  14349. return success;
  14350. }
  14351. #endif /* !_WIN32 */
  14352. static void
  14353. tls_dtor(void *key)
  14354. {
  14355. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14356. /* key == pthread_getspecific(sTlsKey); */
  14357. if (tls) {
  14358. if (tls->is_master == 2) {
  14359. tls->is_master = -3; /* Mark memory as dead */
  14360. mg_free(tls);
  14361. }
  14362. }
  14363. pthread_setspecific(sTlsKey, NULL);
  14364. }
  14365. #if defined(USE_MBEDTLS)
  14366. /* Check if SSL is required.
  14367. * If so, set up ctx->ssl_ctx pointer. */
  14368. static int
  14369. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14370. {
  14371. if (!phys_ctx) {
  14372. return 0;
  14373. }
  14374. if (!dom_ctx) {
  14375. dom_ctx = &(phys_ctx->dd);
  14376. }
  14377. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14378. /* No SSL port is set. No need to setup SSL. */
  14379. return 1;
  14380. }
  14381. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14382. if (dom_ctx->ssl_ctx == NULL) {
  14383. fprintf(stderr, "ssl_ctx malloc failed\n");
  14384. return 0;
  14385. }
  14386. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14387. == 0
  14388. ? 1
  14389. : 0;
  14390. }
  14391. #elif !defined(NO_SSL)
  14392. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14393. struct mg_domain_context *dom_ctx,
  14394. const char *pem,
  14395. const char *chain);
  14396. static const char *ssl_error(void);
  14397. static int
  14398. refresh_trust(struct mg_connection *conn)
  14399. {
  14400. struct stat cert_buf;
  14401. int64_t t = 0;
  14402. const char *pem;
  14403. const char *chain;
  14404. int should_verify_peer;
  14405. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14406. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14407. * refresh_trust still can not work. */
  14408. return 0;
  14409. }
  14410. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14411. if (chain == NULL) {
  14412. /* pem is not NULL here */
  14413. chain = pem;
  14414. }
  14415. if (*chain == 0) {
  14416. chain = NULL;
  14417. }
  14418. if (stat(pem, &cert_buf) != -1) {
  14419. t = (int64_t)cert_buf.st_mtime;
  14420. }
  14421. mg_lock_context(conn->phys_ctx);
  14422. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14423. conn->dom_ctx->ssl_cert_last_mtime = t;
  14424. should_verify_peer = 0;
  14425. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14426. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14427. == 0) {
  14428. should_verify_peer = 1;
  14429. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14430. "optional")
  14431. == 0) {
  14432. should_verify_peer = 1;
  14433. }
  14434. }
  14435. if (should_verify_peer) {
  14436. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14437. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14438. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14439. ca_file,
  14440. ca_path)
  14441. != 1) {
  14442. mg_unlock_context(conn->phys_ctx);
  14443. mg_cry_ctx_internal(
  14444. conn->phys_ctx,
  14445. "SSL_CTX_load_verify_locations error: %s "
  14446. "ssl_verify_peer requires setting "
  14447. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14448. "present in "
  14449. "the .conf file?",
  14450. ssl_error());
  14451. return 0;
  14452. }
  14453. }
  14454. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14455. mg_unlock_context(conn->phys_ctx);
  14456. return 0;
  14457. }
  14458. }
  14459. mg_unlock_context(conn->phys_ctx);
  14460. return 1;
  14461. }
  14462. #if defined(OPENSSL_API_1_1)
  14463. #else
  14464. static pthread_mutex_t *ssl_mutexes;
  14465. #endif /* OPENSSL_API_1_1 */
  14466. static int
  14467. sslize(struct mg_connection *conn,
  14468. int (*func)(SSL *),
  14469. const struct mg_client_options *client_options)
  14470. {
  14471. int ret, err;
  14472. int short_trust;
  14473. unsigned timeout = 1024;
  14474. unsigned i;
  14475. if (!conn) {
  14476. return 0;
  14477. }
  14478. short_trust =
  14479. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14480. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14481. if (short_trust) {
  14482. int trust_ret = refresh_trust(conn);
  14483. if (!trust_ret) {
  14484. return trust_ret;
  14485. }
  14486. }
  14487. mg_lock_context(conn->phys_ctx);
  14488. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14489. mg_unlock_context(conn->phys_ctx);
  14490. if (conn->ssl == NULL) {
  14491. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14492. OPENSSL_REMOVE_THREAD_STATE();
  14493. return 0;
  14494. }
  14495. SSL_set_app_data(conn->ssl, (char *)conn);
  14496. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14497. if (ret != 1) {
  14498. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14499. SSL_free(conn->ssl);
  14500. conn->ssl = NULL;
  14501. OPENSSL_REMOVE_THREAD_STATE();
  14502. return 0;
  14503. }
  14504. if (client_options) {
  14505. if (client_options->host_name) {
  14506. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14507. }
  14508. }
  14509. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14510. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14511. /* NOTE: The loop below acts as a back-off, so we can end
  14512. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14513. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14514. if (to >= 0) {
  14515. timeout = (unsigned)to;
  14516. }
  14517. }
  14518. /* SSL functions may fail and require to be called again:
  14519. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14520. * Here "func" could be SSL_connect or SSL_accept. */
  14521. for (i = 0; i <= timeout; i += 50) {
  14522. ERR_clear_error();
  14523. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14524. ret = func(conn->ssl);
  14525. if (ret != 1) {
  14526. err = SSL_get_error(conn->ssl, ret);
  14527. if ((err == SSL_ERROR_WANT_CONNECT)
  14528. || (err == SSL_ERROR_WANT_ACCEPT)
  14529. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14530. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14531. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14532. /* Don't wait if the server is going to be stopped. */
  14533. break;
  14534. }
  14535. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14536. /* Simply retry the function call. */
  14537. mg_sleep(50);
  14538. } else {
  14539. /* Need to retry the function call "later".
  14540. * See https://linux.die.net/man/3/ssl_get_error
  14541. * This is typical for non-blocking sockets. */
  14542. struct mg_pollfd pfd[2];
  14543. int pollres;
  14544. unsigned int num_sock = 1;
  14545. pfd[0].fd = conn->client.sock;
  14546. pfd[0].events = ((err == SSL_ERROR_WANT_CONNECT)
  14547. || (err == SSL_ERROR_WANT_WRITE))
  14548. ? POLLOUT
  14549. : POLLIN;
  14550. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14551. pfd[num_sock].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  14552. pfd[num_sock].events = POLLIN;
  14553. num_sock++;
  14554. }
  14555. pollres = mg_poll(pfd, num_sock, 50, &(conn->phys_ctx->stop_flag));
  14556. if (pollres < 0) {
  14557. /* Break if error occurred (-1)
  14558. * or server shutdown (-2) */
  14559. break;
  14560. }
  14561. }
  14562. } else if (err == SSL_ERROR_SYSCALL) {
  14563. /* This is an IO error. Look at errno. */
  14564. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14565. break;
  14566. } else {
  14567. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14568. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14569. break;
  14570. }
  14571. } else {
  14572. /* success */
  14573. break;
  14574. }
  14575. }
  14576. ERR_clear_error();
  14577. if (ret != 1) {
  14578. SSL_free(conn->ssl);
  14579. conn->ssl = NULL;
  14580. OPENSSL_REMOVE_THREAD_STATE();
  14581. return 0;
  14582. }
  14583. return 1;
  14584. }
  14585. /* Return OpenSSL error message (from CRYPTO lib) */
  14586. static const char *
  14587. ssl_error(void)
  14588. {
  14589. unsigned long err;
  14590. err = ERR_get_error();
  14591. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14592. }
  14593. static int
  14594. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14595. {
  14596. int i;
  14597. const char hexdigit[] = "0123456789abcdef";
  14598. if ((memlen <= 0) || (buflen <= 0)) {
  14599. return 0;
  14600. }
  14601. if (buflen < (3 * memlen)) {
  14602. return 0;
  14603. }
  14604. for (i = 0; i < memlen; i++) {
  14605. if (i > 0) {
  14606. buf[3 * i - 1] = ' ';
  14607. }
  14608. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14609. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14610. }
  14611. buf[3 * memlen - 1] = 0;
  14612. return 1;
  14613. }
  14614. static int
  14615. ssl_get_client_cert_info(const struct mg_connection *conn,
  14616. struct mg_client_cert *client_cert)
  14617. {
  14618. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14619. if (cert) {
  14620. char str_buf[1024];
  14621. unsigned char buf[256];
  14622. char *str_serial = NULL;
  14623. unsigned int ulen;
  14624. int ilen;
  14625. unsigned char *tmp_buf;
  14626. unsigned char *tmp_p;
  14627. /* Handle to algorithm used for fingerprint */
  14628. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14629. /* Get Subject and issuer */
  14630. X509_NAME *subj = X509_get_subject_name(cert);
  14631. X509_NAME *iss = X509_get_issuer_name(cert);
  14632. /* Get serial number */
  14633. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14634. /* Translate serial number to a hex string */
  14635. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14636. if (serial_bn) {
  14637. str_serial = BN_bn2hex(serial_bn);
  14638. BN_free(serial_bn);
  14639. }
  14640. client_cert->serial =
  14641. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14642. /* Translate subject and issuer to a string */
  14643. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14644. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14645. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14646. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14647. /* Calculate SHA1 fingerprint and store as a hex string */
  14648. ulen = 0;
  14649. /* ASN1_digest is deprecated. Do the calculation manually,
  14650. * using EVP_Digest. */
  14651. ilen = i2d_X509(cert, NULL);
  14652. tmp_buf = (ilen > 0)
  14653. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14654. conn->phys_ctx)
  14655. : NULL;
  14656. if (tmp_buf) {
  14657. tmp_p = tmp_buf;
  14658. (void)i2d_X509(cert, &tmp_p);
  14659. if (!EVP_Digest(
  14660. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14661. ulen = 0;
  14662. }
  14663. mg_free(tmp_buf);
  14664. }
  14665. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14666. *str_buf = 0;
  14667. }
  14668. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14669. client_cert->peer_cert = (void *)cert;
  14670. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14671. * see https://linux.die.net/man/3/bn_bn2hex */
  14672. OPENSSL_free(str_serial);
  14673. return 1;
  14674. }
  14675. return 0;
  14676. }
  14677. #if defined(OPENSSL_API_1_1)
  14678. #else
  14679. static void
  14680. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14681. {
  14682. (void)line;
  14683. (void)file;
  14684. if (mode & 1) {
  14685. /* 1 is CRYPTO_LOCK */
  14686. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14687. } else {
  14688. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14689. }
  14690. }
  14691. #endif /* OPENSSL_API_1_1 */
  14692. #if !defined(NO_SSL_DL)
  14693. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14694. static void *
  14695. load_tls_dll(char *ebuf,
  14696. size_t ebuf_len,
  14697. const char *dll_name,
  14698. struct ssl_func *sw,
  14699. int *feature_missing)
  14700. {
  14701. union {
  14702. void *p;
  14703. void (*fp)(void);
  14704. } u;
  14705. void *dll_handle;
  14706. struct ssl_func *fp;
  14707. int ok;
  14708. int truncated = 0;
  14709. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14710. mg_snprintf(NULL,
  14711. NULL, /* No truncation check for ebuf */
  14712. ebuf,
  14713. ebuf_len,
  14714. "%s: cannot load %s",
  14715. __func__,
  14716. dll_name);
  14717. return NULL;
  14718. }
  14719. ok = 1;
  14720. for (fp = sw; fp->name != NULL; fp++) {
  14721. #if defined(_WIN32)
  14722. /* GetProcAddress() returns pointer to function */
  14723. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14724. #else
  14725. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14726. * pointers to function pointers. We need to use a union to make a
  14727. * cast. */
  14728. u.p = dlsym(dll_handle, fp->name);
  14729. #endif /* _WIN32 */
  14730. /* Set pointer (might be NULL) */
  14731. fp->ptr = u.fp;
  14732. if (u.fp == NULL) {
  14733. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14734. if (feature_missing) {
  14735. feature_missing[fp->required]++;
  14736. }
  14737. if (fp->required == TLS_Mandatory) {
  14738. /* Mandatory function is missing */
  14739. if (ok) {
  14740. /* This is the first missing function.
  14741. * Create a new error message. */
  14742. mg_snprintf(NULL,
  14743. &truncated,
  14744. ebuf,
  14745. ebuf_len,
  14746. "%s: %s: cannot find %s",
  14747. __func__,
  14748. dll_name,
  14749. fp->name);
  14750. ok = 0;
  14751. } else {
  14752. /* This is yet anothermissing function.
  14753. * Append existing error message. */
  14754. size_t cur_len = strlen(ebuf);
  14755. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14756. mg_snprintf(NULL,
  14757. &truncated,
  14758. ebuf + cur_len,
  14759. ebuf_len - cur_len - 3,
  14760. ", %s",
  14761. fp->name);
  14762. if (truncated) {
  14763. /* If truncated, add "..." */
  14764. strcat(ebuf, "...");
  14765. }
  14766. }
  14767. }
  14768. }
  14769. }
  14770. }
  14771. if (!ok) {
  14772. (void)dlclose(dll_handle);
  14773. return NULL;
  14774. }
  14775. return dll_handle;
  14776. }
  14777. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14778. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14779. #endif /* NO_SSL_DL */
  14780. #if defined(SSL_ALREADY_INITIALIZED)
  14781. static volatile ptrdiff_t cryptolib_users =
  14782. 1; /* Reference counter for crypto library. */
  14783. #else
  14784. static volatile ptrdiff_t cryptolib_users =
  14785. 0; /* Reference counter for crypto library. */
  14786. #endif
  14787. static int
  14788. initialize_openssl(char *ebuf, size_t ebuf_len)
  14789. {
  14790. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14791. int i, num_locks;
  14792. size_t size;
  14793. #endif
  14794. if (ebuf_len > 0) {
  14795. ebuf[0] = 0;
  14796. }
  14797. #if !defined(NO_SSL_DL)
  14798. if (!cryptolib_dll_handle) {
  14799. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14800. cryptolib_dll_handle = load_tls_dll(
  14801. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14802. if (!cryptolib_dll_handle) {
  14803. mg_snprintf(NULL,
  14804. NULL, /* No truncation check for ebuf */
  14805. ebuf,
  14806. ebuf_len,
  14807. "%s: error loading library %s",
  14808. __func__,
  14809. CRYPTO_LIB);
  14810. DEBUG_TRACE("%s", ebuf);
  14811. return 0;
  14812. }
  14813. }
  14814. #endif /* NO_SSL_DL */
  14815. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14816. return 1;
  14817. }
  14818. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14819. /* Initialize locking callbacks, needed for thread safety.
  14820. * http://www.openssl.org/support/faq.html#PROG1
  14821. */
  14822. num_locks = CRYPTO_num_locks();
  14823. if (num_locks < 0) {
  14824. num_locks = 0;
  14825. }
  14826. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14827. /* allocate mutex array, if required */
  14828. if (num_locks == 0) {
  14829. /* No mutex array required */
  14830. ssl_mutexes = NULL;
  14831. } else {
  14832. /* Mutex array required - allocate it */
  14833. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14834. /* Check OOM */
  14835. if (ssl_mutexes == NULL) {
  14836. mg_snprintf(NULL,
  14837. NULL, /* No truncation check for ebuf */
  14838. ebuf,
  14839. ebuf_len,
  14840. "%s: cannot allocate mutexes: %s",
  14841. __func__,
  14842. ssl_error());
  14843. DEBUG_TRACE("%s", ebuf);
  14844. return 0;
  14845. }
  14846. /* initialize mutex array */
  14847. for (i = 0; i < num_locks; i++) {
  14848. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14849. mg_snprintf(NULL,
  14850. NULL, /* No truncation check for ebuf */
  14851. ebuf,
  14852. ebuf_len,
  14853. "%s: error initializing mutex %i of %i",
  14854. __func__,
  14855. i,
  14856. num_locks);
  14857. DEBUG_TRACE("%s", ebuf);
  14858. mg_free(ssl_mutexes);
  14859. return 0;
  14860. }
  14861. }
  14862. }
  14863. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14864. CRYPTO_set_id_callback(&mg_current_thread_id);
  14865. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14866. #if !defined(NO_SSL_DL)
  14867. if (!ssllib_dll_handle) {
  14868. ssllib_dll_handle =
  14869. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14870. if (!ssllib_dll_handle) {
  14871. #if !defined(OPENSSL_API_1_1)
  14872. mg_free(ssl_mutexes);
  14873. #endif
  14874. DEBUG_TRACE("%s", ebuf);
  14875. return 0;
  14876. }
  14877. }
  14878. #endif /* NO_SSL_DL */
  14879. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14880. && !defined(NO_SSL_DL)
  14881. /* Initialize SSL library */
  14882. OPENSSL_init_ssl(0, NULL);
  14883. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14884. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14885. NULL);
  14886. #else
  14887. /* Initialize SSL library */
  14888. SSL_library_init();
  14889. SSL_load_error_strings();
  14890. #endif
  14891. return 1;
  14892. }
  14893. static int
  14894. ssl_use_pem_file(struct mg_context *phys_ctx,
  14895. struct mg_domain_context *dom_ctx,
  14896. const char *pem,
  14897. const char *chain)
  14898. {
  14899. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14900. mg_cry_ctx_internal(phys_ctx,
  14901. "%s: cannot open certificate file %s: %s",
  14902. __func__,
  14903. pem,
  14904. ssl_error());
  14905. return 0;
  14906. }
  14907. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14908. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14909. mg_cry_ctx_internal(phys_ctx,
  14910. "%s: cannot open private key file %s: %s",
  14911. __func__,
  14912. pem,
  14913. ssl_error());
  14914. return 0;
  14915. }
  14916. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14917. mg_cry_ctx_internal(phys_ctx,
  14918. "%s: certificate and private key do not match: %s",
  14919. __func__,
  14920. pem);
  14921. return 0;
  14922. }
  14923. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14924. * chain files that contain private keys and certificates in
  14925. * SSL_CTX_use_certificate_chain_file.
  14926. * The CivetWeb-Server used pem-Files that contained both information.
  14927. * In order to make wolfSSL work, it is split in two files.
  14928. * One file that contains key and certificate used by the server and
  14929. * an optional chain file for the ssl stack.
  14930. */
  14931. if (chain) {
  14932. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14933. mg_cry_ctx_internal(phys_ctx,
  14934. "%s: cannot use certificate chain file %s: %s",
  14935. __func__,
  14936. chain,
  14937. ssl_error());
  14938. return 0;
  14939. }
  14940. }
  14941. return 1;
  14942. }
  14943. #if defined(OPENSSL_API_1_1)
  14944. static unsigned long
  14945. ssl_get_protocol(int version_id)
  14946. {
  14947. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14948. if (version_id > 0)
  14949. ret |= SSL_OP_NO_SSLv2;
  14950. if (version_id > 1)
  14951. ret |= SSL_OP_NO_SSLv3;
  14952. if (version_id > 2)
  14953. ret |= SSL_OP_NO_TLSv1;
  14954. if (version_id > 3)
  14955. ret |= SSL_OP_NO_TLSv1_1;
  14956. if (version_id > 4)
  14957. ret |= SSL_OP_NO_TLSv1_2;
  14958. #if defined(SSL_OP_NO_TLSv1_3)
  14959. if (version_id > 5)
  14960. ret |= SSL_OP_NO_TLSv1_3;
  14961. #endif
  14962. return ret;
  14963. }
  14964. #else
  14965. static long
  14966. ssl_get_protocol(int version_id)
  14967. {
  14968. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14969. if (version_id > 0)
  14970. ret |= SSL_OP_NO_SSLv2;
  14971. if (version_id > 1)
  14972. ret |= SSL_OP_NO_SSLv3;
  14973. if (version_id > 2)
  14974. ret |= SSL_OP_NO_TLSv1;
  14975. if (version_id > 3)
  14976. ret |= SSL_OP_NO_TLSv1_1;
  14977. if (version_id > 4)
  14978. ret |= SSL_OP_NO_TLSv1_2;
  14979. #if defined(SSL_OP_NO_TLSv1_3)
  14980. if (version_id > 5)
  14981. ret |= SSL_OP_NO_TLSv1_3;
  14982. #endif
  14983. return (long)ret;
  14984. }
  14985. #endif /* OPENSSL_API_1_1 */
  14986. /* SSL callback documentation:
  14987. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14988. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14989. * https://linux.die.net/man/3/ssl_set_info_callback */
  14990. /* Note: There is no "const" for the first argument in the documentation
  14991. * examples, however some (maybe most, but not all) headers of OpenSSL
  14992. * versions / OpenSSL compatibility layers have it. Having a different
  14993. * definition will cause a warning in C and an error in C++. Use "const SSL
  14994. * *", while automatic conversion from "SSL *" works for all compilers,
  14995. * but not other way around */
  14996. static void
  14997. ssl_info_callback(const SSL *ssl, int what, int ret)
  14998. {
  14999. (void)ret;
  15000. if (what & SSL_CB_HANDSHAKE_START) {
  15001. SSL_get_app_data(ssl);
  15002. }
  15003. if (what & SSL_CB_HANDSHAKE_DONE) {
  15004. /* TODO: check for openSSL 1.1 */
  15005. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  15006. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  15007. }
  15008. }
  15009. static int
  15010. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  15011. {
  15012. #if defined(GCC_DIAGNOSTIC)
  15013. #pragma GCC diagnostic push
  15014. #pragma GCC diagnostic ignored "-Wcast-align"
  15015. #endif /* defined(GCC_DIAGNOSTIC) */
  15016. /* We used an aligned pointer in SSL_set_app_data */
  15017. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  15018. #if defined(GCC_DIAGNOSTIC)
  15019. #pragma GCC diagnostic pop
  15020. #endif /* defined(GCC_DIAGNOSTIC) */
  15021. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15022. (void)ad;
  15023. (void)arg;
  15024. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15025. DEBUG_ASSERT(0);
  15026. return SSL_TLSEXT_ERR_NOACK;
  15027. }
  15028. conn->dom_ctx = &(conn->phys_ctx->dd);
  15029. /* Old clients (Win XP) will not support SNI. Then, there
  15030. * is no server name available in the request - we can
  15031. * only work with the default certificate.
  15032. * Multiple HTTPS hosts on one IP+port are only possible
  15033. * with a certificate containing all alternative names.
  15034. */
  15035. if ((servername == NULL) || (*servername == 0)) {
  15036. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  15037. mg_lock_context(conn->phys_ctx);
  15038. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15039. mg_unlock_context(conn->phys_ctx);
  15040. return SSL_TLSEXT_ERR_NOACK;
  15041. }
  15042. DEBUG_TRACE("TLS connection to host %s", servername);
  15043. while (conn->dom_ctx) {
  15044. if (!mg_strcasecmp(servername,
  15045. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  15046. /* Found matching domain */
  15047. DEBUG_TRACE("TLS domain %s found",
  15048. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  15049. break;
  15050. }
  15051. mg_lock_context(conn->phys_ctx);
  15052. conn->dom_ctx = conn->dom_ctx->next;
  15053. mg_unlock_context(conn->phys_ctx);
  15054. }
  15055. if (conn->dom_ctx == NULL) {
  15056. /* Default domain */
  15057. DEBUG_TRACE("TLS default domain %s used",
  15058. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  15059. conn->dom_ctx = &(conn->phys_ctx->dd);
  15060. }
  15061. mg_lock_context(conn->phys_ctx);
  15062. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15063. mg_unlock_context(conn->phys_ctx);
  15064. return SSL_TLSEXT_ERR_OK;
  15065. }
  15066. #if defined(USE_ALPN)
  15067. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  15068. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  15069. alpn_proto_list + 3 + 8,
  15070. NULL};
  15071. #if defined(USE_HTTP2)
  15072. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  15073. alpn_proto_list + 3,
  15074. alpn_proto_list + 3 + 8,
  15075. NULL};
  15076. #endif
  15077. static int
  15078. alpn_select_cb(SSL *ssl,
  15079. const unsigned char **out,
  15080. unsigned char *outlen,
  15081. const unsigned char *in,
  15082. unsigned int inlen,
  15083. void *arg)
  15084. {
  15085. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15086. unsigned int i, j, enable_http2 = 0;
  15087. const char **alpn_proto_order = alpn_proto_order_http1;
  15088. struct mg_workerTLS *tls =
  15089. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  15090. (void)ssl;
  15091. if (tls == NULL) {
  15092. /* Need to store protocol in Thread Local Storage */
  15093. /* If there is no Thread Local Storage, don't use ALPN */
  15094. return SSL_TLSEXT_ERR_NOACK;
  15095. }
  15096. #if defined(USE_HTTP2)
  15097. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  15098. if (enable_http2) {
  15099. alpn_proto_order = alpn_proto_order_http2;
  15100. }
  15101. #endif
  15102. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  15103. /* check all accepted protocols in this order */
  15104. const char *alpn_proto = alpn_proto_order[j];
  15105. /* search input for matching protocol */
  15106. for (i = 0; i < inlen; i++) {
  15107. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  15108. *out = in + i + 1;
  15109. *outlen = in[i];
  15110. tls->alpn_proto = alpn_proto;
  15111. return SSL_TLSEXT_ERR_OK;
  15112. }
  15113. }
  15114. }
  15115. /* Nothing found */
  15116. return SSL_TLSEXT_ERR_NOACK;
  15117. }
  15118. static int
  15119. next_protos_advertised_cb(SSL *ssl,
  15120. const unsigned char **data,
  15121. unsigned int *len,
  15122. void *arg)
  15123. {
  15124. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15125. *data = (const unsigned char *)alpn_proto_list;
  15126. *len = (unsigned int)strlen((const char *)data);
  15127. (void)ssl;
  15128. (void)dom_ctx;
  15129. return SSL_TLSEXT_ERR_OK;
  15130. }
  15131. static int
  15132. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15133. {
  15134. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  15135. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  15136. (const unsigned char *)alpn_proto_list,
  15137. alpn_len);
  15138. if (ret != 0) {
  15139. mg_cry_ctx_internal(phys_ctx,
  15140. "SSL_CTX_set_alpn_protos error: %s",
  15141. ssl_error());
  15142. }
  15143. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  15144. alpn_select_cb,
  15145. (void *)dom_ctx);
  15146. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  15147. next_protos_advertised_cb,
  15148. (void *)dom_ctx);
  15149. return ret;
  15150. }
  15151. #endif
  15152. /* Setup SSL CTX as required by CivetWeb */
  15153. static int
  15154. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  15155. struct mg_domain_context *dom_ctx,
  15156. const char *pem,
  15157. const char *chain)
  15158. {
  15159. int callback_ret;
  15160. int should_verify_peer;
  15161. int peer_certificate_optional;
  15162. const char *ca_path;
  15163. const char *ca_file;
  15164. int use_default_verify_paths;
  15165. int verify_depth;
  15166. struct timespec now_mt;
  15167. md5_byte_t ssl_context_id[16];
  15168. md5_state_t md5state;
  15169. int protocol_ver;
  15170. int ssl_cache_timeout;
  15171. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15172. && !defined(NO_SSL_DL)
  15173. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15174. mg_cry_ctx_internal(phys_ctx,
  15175. "SSL_CTX_new (server) error: %s",
  15176. ssl_error());
  15177. return 0;
  15178. }
  15179. #else
  15180. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15181. mg_cry_ctx_internal(phys_ctx,
  15182. "SSL_CTX_new (server) error: %s",
  15183. ssl_error());
  15184. return 0;
  15185. }
  15186. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15187. #if defined(SSL_OP_NO_TLSv1_3)
  15188. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15189. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15190. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15191. | SSL_OP_NO_TLSv1_3);
  15192. #else
  15193. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15194. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15195. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15196. #endif
  15197. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15198. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15199. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15200. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15201. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15202. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15203. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15204. #if defined(SSL_OP_NO_RENEGOTIATION)
  15205. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15206. #endif
  15207. #if !defined(NO_SSL_DL)
  15208. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15209. #endif /* NO_SSL_DL */
  15210. /* In SSL documentation examples callback defined without const
  15211. * specifier 'void (*)(SSL *, int, int)' See:
  15212. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15213. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15214. * But in the source code const SSL is used:
  15215. * 'void (*)(const SSL *, int, int)' See:
  15216. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15217. * Problem about wrong documentation described, but not resolved:
  15218. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15219. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15220. * But when compiled with modern C++ compiler, correct const should be
  15221. * provided
  15222. */
  15223. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15224. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15225. ssl_servername_callback);
  15226. /* If a callback has been specified, call it. */
  15227. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15228. ? 0
  15229. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15230. phys_ctx->user_data));
  15231. /* If callback returns 0, civetweb sets up the SSL certificate.
  15232. * If it returns 1, civetweb assumes the callback already did this.
  15233. * If it returns -1, initializing ssl fails. */
  15234. if (callback_ret < 0) {
  15235. mg_cry_ctx_internal(phys_ctx,
  15236. "SSL callback returned error: %i",
  15237. callback_ret);
  15238. return 0;
  15239. }
  15240. if (callback_ret > 0) {
  15241. /* Callback did everything. */
  15242. return 1;
  15243. }
  15244. /* If a domain callback has been specified, call it. */
  15245. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15246. ? 0
  15247. : (phys_ctx->callbacks.init_ssl_domain(
  15248. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15249. dom_ctx->ssl_ctx,
  15250. phys_ctx->user_data));
  15251. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15252. * If it returns 1, civetweb assumes the callback already did this.
  15253. * If it returns -1, initializing ssl fails. */
  15254. if (callback_ret < 0) {
  15255. mg_cry_ctx_internal(phys_ctx,
  15256. "Domain SSL callback returned error: %i",
  15257. callback_ret);
  15258. return 0;
  15259. }
  15260. if (callback_ret > 0) {
  15261. /* Domain callback did everything. */
  15262. return 1;
  15263. }
  15264. /* Use some combination of start time, domain and port as a SSL
  15265. * context ID. This should be unique on the current machine. */
  15266. md5_init(&md5state);
  15267. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15268. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15269. md5_append(&md5state,
  15270. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15271. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15272. md5_append(&md5state,
  15273. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15274. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15275. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15276. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15277. md5_finish(&md5state, ssl_context_id);
  15278. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15279. (unsigned char *)ssl_context_id,
  15280. sizeof(ssl_context_id));
  15281. if (pem != NULL) {
  15282. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15283. return 0;
  15284. }
  15285. }
  15286. /* Should we support client certificates? */
  15287. /* Default is "no". */
  15288. should_verify_peer = 0;
  15289. peer_certificate_optional = 0;
  15290. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15291. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15292. /* Yes, they are mandatory */
  15293. should_verify_peer = 1;
  15294. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15295. "optional")
  15296. == 0) {
  15297. /* Yes, they are optional */
  15298. should_verify_peer = 1;
  15299. peer_certificate_optional = 1;
  15300. }
  15301. }
  15302. use_default_verify_paths =
  15303. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15304. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15305. == 0);
  15306. if (should_verify_peer) {
  15307. ca_path = dom_ctx->config[SSL_CA_PATH];
  15308. ca_file = dom_ctx->config[SSL_CA_FILE];
  15309. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15310. != 1) {
  15311. mg_cry_ctx_internal(phys_ctx,
  15312. "SSL_CTX_load_verify_locations error: %s "
  15313. "ssl_verify_peer requires setting "
  15314. "either ssl_ca_path or ssl_ca_file. "
  15315. "Is any of them present in the "
  15316. ".conf file?",
  15317. ssl_error());
  15318. return 0;
  15319. }
  15320. if (peer_certificate_optional) {
  15321. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15322. } else {
  15323. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15324. SSL_VERIFY_PEER
  15325. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15326. NULL);
  15327. }
  15328. if (use_default_verify_paths
  15329. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15330. mg_cry_ctx_internal(phys_ctx,
  15331. "SSL_CTX_set_default_verify_paths error: %s",
  15332. ssl_error());
  15333. return 0;
  15334. }
  15335. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15336. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15337. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15338. }
  15339. }
  15340. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15341. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15342. dom_ctx->config[SSL_CIPHER_LIST])
  15343. != 1) {
  15344. mg_cry_ctx_internal(phys_ctx,
  15345. "SSL_CTX_set_cipher_list error: %s",
  15346. ssl_error());
  15347. }
  15348. }
  15349. /* SSL session caching */
  15350. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15351. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15352. : 0);
  15353. if (ssl_cache_timeout > 0) {
  15354. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15355. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15356. * default */
  15357. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15358. }
  15359. #if defined(USE_ALPN)
  15360. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15361. #if !defined(NO_SSL_DL)
  15362. if (!tls_feature_missing[TLS_ALPN])
  15363. #endif
  15364. {
  15365. init_alpn(phys_ctx, dom_ctx);
  15366. }
  15367. #endif
  15368. return 1;
  15369. }
  15370. /* Check if SSL is required.
  15371. * If so, dynamically load SSL library
  15372. * and set up ctx->ssl_ctx pointer. */
  15373. static int
  15374. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15375. {
  15376. void *ssl_ctx = 0;
  15377. int callback_ret;
  15378. const char *pem;
  15379. const char *chain;
  15380. char ebuf[128];
  15381. if (!phys_ctx) {
  15382. return 0;
  15383. }
  15384. if (!dom_ctx) {
  15385. dom_ctx = &(phys_ctx->dd);
  15386. }
  15387. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15388. /* No SSL port is set. No need to setup SSL. */
  15389. return 1;
  15390. }
  15391. /* Check for external SSL_CTX */
  15392. callback_ret =
  15393. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15394. ? 0
  15395. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15396. phys_ctx->user_data));
  15397. if (callback_ret < 0) {
  15398. /* Callback exists and returns <0: Initializing failed. */
  15399. mg_cry_ctx_internal(phys_ctx,
  15400. "external_ssl_ctx callback returned error: %i",
  15401. callback_ret);
  15402. return 0;
  15403. } else if (callback_ret > 0) {
  15404. /* Callback exists and returns >0: Initializing complete,
  15405. * civetweb should not modify the SSL context. */
  15406. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15407. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15408. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15409. return 0;
  15410. }
  15411. return 1;
  15412. }
  15413. /* If the callback does not exist or return 0, civetweb must initialize
  15414. * the SSL context. Handle "domain" callback next. */
  15415. /* Check for external domain SSL_CTX callback. */
  15416. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15417. ? 0
  15418. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15419. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15420. &ssl_ctx,
  15421. phys_ctx->user_data));
  15422. if (callback_ret < 0) {
  15423. /* Callback < 0: Error. Abort init. */
  15424. mg_cry_ctx_internal(
  15425. phys_ctx,
  15426. "external_ssl_ctx_domain callback returned error: %i",
  15427. callback_ret);
  15428. return 0;
  15429. } else if (callback_ret > 0) {
  15430. /* Callback > 0: Consider init done. */
  15431. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15432. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15433. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15434. return 0;
  15435. }
  15436. return 1;
  15437. }
  15438. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15439. * 0, CivetWeb should continue initializing SSL */
  15440. /* If PEM file is not specified and the init_ssl callbacks
  15441. * are not specified, setup will fail. */
  15442. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15443. && (phys_ctx->callbacks.init_ssl == NULL)
  15444. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15445. /* No certificate and no init_ssl callbacks:
  15446. * Essential data to set up TLS is missing.
  15447. */
  15448. mg_cry_ctx_internal(phys_ctx,
  15449. "Initializing SSL failed: -%s is not set",
  15450. config_options[SSL_CERTIFICATE].name);
  15451. return 0;
  15452. }
  15453. /* If a certificate chain is configured, use it. */
  15454. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15455. if (chain == NULL) {
  15456. /* Default: certificate chain in PEM file */
  15457. chain = pem;
  15458. }
  15459. if ((chain != NULL) && (*chain == 0)) {
  15460. /* If the chain is an empty string, don't use it. */
  15461. chain = NULL;
  15462. }
  15463. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15464. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15465. return 0;
  15466. }
  15467. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15468. }
  15469. static void
  15470. uninitialize_openssl(void)
  15471. {
  15472. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15473. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15474. /* Shutdown according to
  15475. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15476. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15477. */
  15478. CONF_modules_unload(1);
  15479. #else
  15480. int i;
  15481. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15482. /* Shutdown according to
  15483. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15484. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15485. */
  15486. CRYPTO_set_locking_callback(NULL);
  15487. CRYPTO_set_id_callback(NULL);
  15488. ENGINE_cleanup();
  15489. CONF_modules_unload(1);
  15490. ERR_free_strings();
  15491. EVP_cleanup();
  15492. CRYPTO_cleanup_all_ex_data();
  15493. OPENSSL_REMOVE_THREAD_STATE();
  15494. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15495. pthread_mutex_destroy(&ssl_mutexes[i]);
  15496. }
  15497. mg_free(ssl_mutexes);
  15498. ssl_mutexes = NULL;
  15499. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15500. }
  15501. }
  15502. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15503. #if !defined(NO_FILESYSTEMS)
  15504. static int
  15505. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15506. {
  15507. if (phys_ctx) {
  15508. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15509. const char *path;
  15510. struct mg_connection fc;
  15511. if (!dom_ctx) {
  15512. dom_ctx = &(phys_ctx->dd);
  15513. }
  15514. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15515. if ((path != NULL)
  15516. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15517. mg_cry_ctx_internal(phys_ctx,
  15518. "Cannot open %s: %s",
  15519. path,
  15520. strerror(ERRNO));
  15521. return 0;
  15522. }
  15523. return 1;
  15524. }
  15525. return 0;
  15526. }
  15527. #endif /* NO_FILESYSTEMS */
  15528. static int
  15529. set_acl_option(struct mg_context *phys_ctx)
  15530. {
  15531. union usa sa;
  15532. memset(&sa, 0, sizeof(sa));
  15533. #if defined(USE_IPV6)
  15534. sa.sin6.sin6_family = AF_INET6;
  15535. #else
  15536. sa.sin.sin_family = AF_INET;
  15537. #endif
  15538. return check_acl(phys_ctx, &sa) != -1;
  15539. }
  15540. static void
  15541. reset_per_request_attributes(struct mg_connection *conn)
  15542. {
  15543. if (!conn) {
  15544. return;
  15545. }
  15546. conn->num_bytes_sent = conn->consumed_content = 0;
  15547. conn->path_info = NULL;
  15548. conn->status_code = -1;
  15549. conn->content_len = -1;
  15550. conn->is_chunked = 0;
  15551. conn->must_close = 0;
  15552. conn->request_len = 0;
  15553. conn->request_state = 0;
  15554. conn->throttle = 0;
  15555. conn->accept_gzip = 0;
  15556. conn->response_info.content_length = conn->request_info.content_length = -1;
  15557. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15558. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15559. conn->response_info.status_text = NULL;
  15560. conn->response_info.status_code = 0;
  15561. conn->request_info.remote_user = NULL;
  15562. conn->request_info.request_method = NULL;
  15563. conn->request_info.request_uri = NULL;
  15564. /* Free cleaned local URI (if any) */
  15565. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15566. mg_free((void *)conn->request_info.local_uri);
  15567. conn->request_info.local_uri = NULL;
  15568. }
  15569. conn->request_info.local_uri = NULL;
  15570. #if defined(USE_SERVER_STATS)
  15571. conn->processing_time = 0;
  15572. #endif
  15573. }
  15574. static int
  15575. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15576. {
  15577. if ((so->lsa.sa.sa_family == AF_INET)
  15578. || (so->lsa.sa.sa_family == AF_INET6)) {
  15579. /* Only for TCP sockets */
  15580. if (setsockopt(so->sock,
  15581. IPPROTO_TCP,
  15582. TCP_NODELAY,
  15583. (SOCK_OPT_TYPE)&nodelay_on,
  15584. sizeof(nodelay_on))
  15585. != 0) {
  15586. /* Error */
  15587. return 1;
  15588. }
  15589. }
  15590. /* OK */
  15591. return 0;
  15592. }
  15593. #if !defined(__ZEPHYR__)
  15594. static void
  15595. close_socket_gracefully(struct mg_connection *conn)
  15596. {
  15597. #if defined(_WIN32)
  15598. char buf[MG_BUF_LEN];
  15599. int n;
  15600. #endif
  15601. struct linger linger;
  15602. int error_code = 0;
  15603. int linger_timeout = -2;
  15604. socklen_t opt_len = sizeof(error_code);
  15605. if (!conn) {
  15606. return;
  15607. }
  15608. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15609. * "Note that enabling a nonzero timeout on a nonblocking socket
  15610. * is not recommended.", so set it to blocking now */
  15611. set_blocking_mode(conn->client.sock);
  15612. /* Send FIN to the client */
  15613. shutdown(conn->client.sock, SHUTDOWN_WR);
  15614. #if defined(_WIN32)
  15615. /* Read and discard pending incoming data. If we do not do that and
  15616. * close
  15617. * the socket, the data in the send buffer may be discarded. This
  15618. * behaviour is seen on Windows, when client keeps sending data
  15619. * when server decides to close the connection; then when client
  15620. * does recv() it gets no data back. */
  15621. do {
  15622. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15623. } while (n > 0);
  15624. #endif
  15625. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15626. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15627. }
  15628. /* Set linger option according to configuration */
  15629. if (linger_timeout >= 0) {
  15630. /* Set linger option to avoid socket hanging out after close. This
  15631. * prevent ephemeral port exhaust problem under high QPS. */
  15632. linger.l_onoff = 1;
  15633. #if defined(_MSC_VER)
  15634. #pragma warning(push)
  15635. #pragma warning(disable : 4244)
  15636. #endif
  15637. #if defined(GCC_DIAGNOSTIC)
  15638. #pragma GCC diagnostic push
  15639. #pragma GCC diagnostic ignored "-Wconversion"
  15640. #endif
  15641. /* Data type of linger structure elements may differ,
  15642. * so we don't know what cast we need here.
  15643. * Disable type conversion warnings. */
  15644. linger.l_linger = (linger_timeout + 999) / 1000;
  15645. #if defined(GCC_DIAGNOSTIC)
  15646. #pragma GCC diagnostic pop
  15647. #endif
  15648. #if defined(_MSC_VER)
  15649. #pragma warning(pop)
  15650. #endif
  15651. } else {
  15652. linger.l_onoff = 0;
  15653. linger.l_linger = 0;
  15654. }
  15655. if (linger_timeout < -1) {
  15656. /* Default: don't configure any linger */
  15657. } else if (getsockopt(conn->client.sock,
  15658. SOL_SOCKET,
  15659. SO_ERROR,
  15660. #if defined(_WIN32) /* WinSock uses different data type here */
  15661. (char *)&error_code,
  15662. #else
  15663. &error_code,
  15664. #endif
  15665. &opt_len)
  15666. != 0) {
  15667. /* Cannot determine if socket is already closed. This should
  15668. * not occur and never did in a test. Log an error message
  15669. * and continue. */
  15670. mg_cry_internal(conn,
  15671. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15672. __func__,
  15673. strerror(ERRNO));
  15674. #if defined(_WIN32)
  15675. } else if (error_code == WSAECONNRESET) {
  15676. #else
  15677. } else if (error_code == ECONNRESET) {
  15678. #endif
  15679. /* Socket already closed by client/peer, close socket without linger
  15680. */
  15681. } else {
  15682. /* Set linger timeout */
  15683. if (setsockopt(conn->client.sock,
  15684. SOL_SOCKET,
  15685. SO_LINGER,
  15686. (char *)&linger,
  15687. sizeof(linger))
  15688. != 0) {
  15689. mg_cry_internal(
  15690. conn,
  15691. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15692. __func__,
  15693. linger.l_onoff,
  15694. linger.l_linger,
  15695. strerror(ERRNO));
  15696. }
  15697. }
  15698. /* Now we know that our FIN is ACK-ed, safe to close */
  15699. closesocket(conn->client.sock);
  15700. conn->client.sock = INVALID_SOCKET;
  15701. }
  15702. #endif
  15703. static void
  15704. close_connection(struct mg_connection *conn)
  15705. {
  15706. #if defined(USE_SERVER_STATS)
  15707. conn->conn_state = 6; /* to close */
  15708. #endif
  15709. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15710. if (conn->lua_websocket_state) {
  15711. lua_websocket_close(conn, conn->lua_websocket_state);
  15712. conn->lua_websocket_state = NULL;
  15713. }
  15714. #endif
  15715. mg_lock_connection(conn);
  15716. /* Set close flag, so keep-alive loops will stop */
  15717. conn->must_close = 1;
  15718. /* call the connection_close callback if assigned */
  15719. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15720. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15721. conn->phys_ctx->callbacks.connection_close(conn);
  15722. }
  15723. }
  15724. /* Reset user data, after close callback is called.
  15725. * Do not reuse it. If the user needs a destructor,
  15726. * it must be done in the connection_close callback. */
  15727. mg_set_user_connection_data(conn, NULL);
  15728. #if defined(USE_SERVER_STATS)
  15729. conn->conn_state = 7; /* closing */
  15730. #endif
  15731. #if defined(USE_MBEDTLS)
  15732. if (conn->ssl != NULL) {
  15733. mbed_ssl_close(conn->ssl);
  15734. conn->ssl = NULL;
  15735. }
  15736. #elif !defined(NO_SSL)
  15737. if (conn->ssl != NULL) {
  15738. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15739. */
  15740. SSL_shutdown(conn->ssl);
  15741. SSL_free(conn->ssl);
  15742. OPENSSL_REMOVE_THREAD_STATE();
  15743. conn->ssl = NULL;
  15744. }
  15745. #endif
  15746. if (conn->client.sock != INVALID_SOCKET) {
  15747. #if defined(__ZEPHYR__)
  15748. closesocket(conn->client.sock);
  15749. #else
  15750. close_socket_gracefully(conn);
  15751. #endif
  15752. conn->client.sock = INVALID_SOCKET;
  15753. }
  15754. /* call the connection_closed callback if assigned */
  15755. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15756. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15757. conn->phys_ctx->callbacks.connection_closed(conn);
  15758. }
  15759. }
  15760. mg_unlock_connection(conn);
  15761. #if defined(USE_SERVER_STATS)
  15762. conn->conn_state = 8; /* closed */
  15763. #endif
  15764. }
  15765. CIVETWEB_API void
  15766. mg_close_connection(struct mg_connection *conn)
  15767. {
  15768. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15769. return;
  15770. }
  15771. #if defined(USE_WEBSOCKET)
  15772. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15773. if (conn->in_websocket_handling) {
  15774. /* Set close flag, so the server thread can exit. */
  15775. conn->must_close = 1;
  15776. return;
  15777. }
  15778. }
  15779. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15780. unsigned int i;
  15781. /* client context: loops must end */
  15782. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15783. conn->must_close = 1;
  15784. /* We need to get the client thread out of the select/recv call
  15785. * here. */
  15786. /* Since we use a sleep quantum of some seconds to check for recv
  15787. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15788. /* join worker thread */
  15789. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15790. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15791. }
  15792. }
  15793. #endif /* defined(USE_WEBSOCKET) */
  15794. close_connection(conn);
  15795. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15796. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15797. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15798. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15799. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15800. }
  15801. #endif
  15802. #if defined(USE_WEBSOCKET)
  15803. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15804. mg_free(conn->phys_ctx->worker_threadids);
  15805. (void)pthread_mutex_destroy(&conn->mutex);
  15806. mg_free(conn);
  15807. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15808. (void)pthread_mutex_destroy(&conn->mutex);
  15809. mg_free(conn);
  15810. }
  15811. #else
  15812. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15813. (void)pthread_mutex_destroy(&conn->mutex);
  15814. mg_free(conn);
  15815. }
  15816. #endif /* defined(USE_WEBSOCKET) */
  15817. }
  15818. static struct mg_connection *
  15819. mg_connect_client_impl(const struct mg_client_options *client_options,
  15820. int use_ssl,
  15821. struct mg_init_data *init,
  15822. struct mg_error_data *error)
  15823. {
  15824. struct mg_connection *conn = NULL;
  15825. SOCKET sock;
  15826. union usa sa;
  15827. struct sockaddr *psa;
  15828. socklen_t len;
  15829. unsigned max_req_size =
  15830. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15831. /* Size of structures, aligned to 8 bytes */
  15832. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15833. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15834. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15835. (void)init; /* TODO: Implement required options */
  15836. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15837. if (error != NULL) {
  15838. error->code = MG_ERROR_DATA_CODE_OK;
  15839. error->code_sub = 0;
  15840. if (error->text_buffer_size > 0) {
  15841. error->text[0] = 0;
  15842. }
  15843. }
  15844. if (conn == NULL) {
  15845. if (error != NULL) {
  15846. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15847. error->code_sub = (unsigned)alloc_size;
  15848. mg_snprintf(NULL,
  15849. NULL, /* No truncation check for ebuf */
  15850. error->text,
  15851. error->text_buffer_size,
  15852. "calloc(): %s",
  15853. strerror(ERRNO));
  15854. }
  15855. return NULL;
  15856. }
  15857. #if defined(GCC_DIAGNOSTIC)
  15858. #pragma GCC diagnostic push
  15859. #pragma GCC diagnostic ignored "-Wcast-align"
  15860. #endif /* defined(GCC_DIAGNOSTIC) */
  15861. /* conn_size is aligned to 8 bytes */
  15862. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15863. #if defined(GCC_DIAGNOSTIC)
  15864. #pragma GCC diagnostic pop
  15865. #endif /* defined(GCC_DIAGNOSTIC) */
  15866. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15867. conn->buf_size = (int)max_req_size;
  15868. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15869. conn->dom_ctx = &(conn->phys_ctx->dd);
  15870. if (!connect_socket(conn->phys_ctx,
  15871. client_options->host,
  15872. client_options->port,
  15873. use_ssl,
  15874. error,
  15875. &sock,
  15876. &sa)) {
  15877. /* "error" will be set by connect_socket. */
  15878. /* free all memory and return NULL; */
  15879. mg_free(conn);
  15880. return NULL;
  15881. }
  15882. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15883. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15884. && !defined(NO_SSL_DL)
  15885. if (use_ssl
  15886. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15887. == NULL) {
  15888. if (error != NULL) {
  15889. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15890. mg_snprintf(NULL,
  15891. NULL, /* No truncation check for ebuf */
  15892. error->text,
  15893. error->text_buffer_size,
  15894. "SSL_CTX_new error: %s",
  15895. ssl_error());
  15896. }
  15897. closesocket(sock);
  15898. mg_free(conn);
  15899. return NULL;
  15900. }
  15901. #else
  15902. if (use_ssl
  15903. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15904. == NULL) {
  15905. if (error != NULL) {
  15906. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15907. mg_snprintf(NULL,
  15908. NULL, /* No truncation check for ebuf */
  15909. error->text,
  15910. error->text_buffer_size,
  15911. "SSL_CTX_new error: %s",
  15912. ssl_error());
  15913. }
  15914. closesocket(sock);
  15915. mg_free(conn);
  15916. return NULL;
  15917. }
  15918. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15919. #endif /* NO_SSL */
  15920. #if defined(USE_IPV6)
  15921. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15922. : sizeof(conn->client.rsa.sin6);
  15923. psa = (sa.sa.sa_family == AF_INET)
  15924. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15925. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15926. #else
  15927. len = sizeof(conn->client.rsa.sin);
  15928. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15929. #endif
  15930. conn->client.sock = sock;
  15931. conn->client.lsa = sa;
  15932. if (getsockname(sock, psa, &len) != 0) {
  15933. mg_cry_internal(conn,
  15934. "%s: getsockname() failed: %s",
  15935. __func__,
  15936. strerror(ERRNO));
  15937. }
  15938. conn->client.is_ssl = use_ssl ? 1 : 0;
  15939. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15940. if (error != NULL) {
  15941. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15942. error->code_sub = (unsigned)ERRNO;
  15943. mg_snprintf(NULL,
  15944. NULL, /* No truncation check for ebuf */
  15945. error->text,
  15946. error->text_buffer_size,
  15947. "Can not create mutex");
  15948. }
  15949. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15950. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15951. #endif
  15952. closesocket(sock);
  15953. mg_free(conn);
  15954. return NULL;
  15955. }
  15956. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15957. if (use_ssl) {
  15958. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15959. * SSL_CTX_set_verify call is needed to switch off server
  15960. * certificate checking, which is off by default in OpenSSL and
  15961. * on in yaSSL. */
  15962. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15963. * SSL_VERIFY_PEER, verify_ssl_server); */
  15964. if (client_options->client_cert) {
  15965. if (!ssl_use_pem_file(conn->phys_ctx,
  15966. conn->dom_ctx,
  15967. client_options->client_cert,
  15968. NULL)) {
  15969. if (error != NULL) {
  15970. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15971. mg_snprintf(NULL,
  15972. NULL, /* No truncation check for ebuf */
  15973. error->text,
  15974. error->text_buffer_size,
  15975. "Can not use SSL client certificate");
  15976. }
  15977. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15978. closesocket(sock);
  15979. mg_free(conn);
  15980. return NULL;
  15981. }
  15982. }
  15983. if (client_options->server_cert) {
  15984. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15985. client_options->server_cert,
  15986. NULL)
  15987. != 1) {
  15988. if (error != NULL) {
  15989. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15990. mg_snprintf(NULL,
  15991. NULL, /* No truncation check for ebuf */
  15992. error->text,
  15993. error->text_buffer_size,
  15994. "SSL_CTX_load_verify_locations error: %s",
  15995. ssl_error());
  15996. }
  15997. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15998. closesocket(sock);
  15999. mg_free(conn);
  16000. return NULL;
  16001. }
  16002. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  16003. } else {
  16004. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  16005. }
  16006. if (!sslize(conn, SSL_connect, client_options)) {
  16007. if (error != NULL) {
  16008. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  16009. mg_snprintf(NULL,
  16010. NULL, /* No truncation check for ebuf */
  16011. error->text,
  16012. error->text_buffer_size,
  16013. "SSL connection error");
  16014. }
  16015. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16016. closesocket(sock);
  16017. mg_free(conn);
  16018. return NULL;
  16019. }
  16020. }
  16021. #endif
  16022. return conn;
  16023. }
  16024. CIVETWEB_API struct mg_connection *
  16025. mg_connect_client_secure(const struct mg_client_options *client_options,
  16026. char *error_buffer,
  16027. size_t error_buffer_size)
  16028. {
  16029. struct mg_init_data init;
  16030. struct mg_error_data error;
  16031. memset(&init, 0, sizeof(init));
  16032. memset(&error, 0, sizeof(error));
  16033. error.text_buffer_size = error_buffer_size;
  16034. error.text = error_buffer;
  16035. return mg_connect_client_impl(client_options, 1, &init, &error);
  16036. }
  16037. CIVETWEB_API struct mg_connection *
  16038. mg_connect_client(const char *host,
  16039. int port,
  16040. int use_ssl,
  16041. char *error_buffer,
  16042. size_t error_buffer_size)
  16043. {
  16044. struct mg_client_options opts;
  16045. struct mg_init_data init;
  16046. struct mg_error_data error;
  16047. memset(&init, 0, sizeof(init));
  16048. memset(&error, 0, sizeof(error));
  16049. error.text_buffer_size = error_buffer_size;
  16050. error.text = error_buffer;
  16051. memset(&opts, 0, sizeof(opts));
  16052. opts.host = host;
  16053. opts.port = port;
  16054. if (use_ssl) {
  16055. opts.host_name = host;
  16056. }
  16057. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  16058. }
  16059. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16060. CIVETWEB_API struct mg_connection *
  16061. mg_connect_client2(const char *host,
  16062. const char *protocol,
  16063. int port,
  16064. const char *path,
  16065. struct mg_init_data *init,
  16066. struct mg_error_data *error)
  16067. {
  16068. (void)path;
  16069. int is_ssl, is_ws;
  16070. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  16071. if (error != NULL) {
  16072. error->code = MG_ERROR_DATA_CODE_OK;
  16073. error->code_sub = 0;
  16074. if (error->text_buffer_size > 0) {
  16075. *error->text = 0;
  16076. }
  16077. }
  16078. if ((host == NULL) || (protocol == NULL)) {
  16079. if (error != NULL) {
  16080. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16081. mg_snprintf(NULL,
  16082. NULL, /* No truncation check for error buffers */
  16083. error->text,
  16084. error->text_buffer_size,
  16085. "%s",
  16086. "Invalid parameters");
  16087. }
  16088. return NULL;
  16089. }
  16090. /* check all known protocols */
  16091. if (!mg_strcasecmp(protocol, "http")) {
  16092. is_ssl = 0;
  16093. is_ws = 0;
  16094. } else if (!mg_strcasecmp(protocol, "https")) {
  16095. is_ssl = 1;
  16096. is_ws = 0;
  16097. #if defined(USE_WEBSOCKET)
  16098. } else if (!mg_strcasecmp(protocol, "ws")) {
  16099. is_ssl = 0;
  16100. is_ws = 1;
  16101. } else if (!mg_strcasecmp(protocol, "wss")) {
  16102. is_ssl = 1;
  16103. is_ws = 1;
  16104. #endif
  16105. } else {
  16106. if (error != NULL) {
  16107. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16108. mg_snprintf(NULL,
  16109. NULL, /* No truncation check for error buffers */
  16110. error->text,
  16111. error->text_buffer_size,
  16112. "Protocol %s not supported",
  16113. protocol);
  16114. }
  16115. return NULL;
  16116. }
  16117. /* TODO: The current implementation here just calls the old
  16118. * implementations, without using any new options. This is just a first
  16119. * step to test the new interfaces. */
  16120. #if defined(USE_WEBSOCKET)
  16121. if (is_ws) {
  16122. /* TODO: implement all options */
  16123. return mg_connect_websocket_client(
  16124. host,
  16125. port,
  16126. is_ssl,
  16127. ((error != NULL) ? error->text : NULL),
  16128. ((error != NULL) ? error->text_buffer_size : 0),
  16129. (path ? path : ""),
  16130. NULL /* TODO: origin */,
  16131. experimental_websocket_client_data_wrapper,
  16132. experimental_websocket_client_close_wrapper,
  16133. (void *)init->callbacks);
  16134. }
  16135. #else
  16136. (void)is_ws;
  16137. #endif
  16138. /* TODO: all additional options */
  16139. struct mg_client_options opts;
  16140. memset(&opts, 0, sizeof(opts));
  16141. opts.host = host;
  16142. opts.port = port;
  16143. return mg_connect_client_impl(&opts, is_ssl, init, error);
  16144. }
  16145. #endif
  16146. static const struct {
  16147. const char *proto;
  16148. size_t proto_len;
  16149. unsigned default_port;
  16150. } abs_uri_protocols[] = {{"http://", 7, 80},
  16151. {"https://", 8, 443},
  16152. {"ws://", 5, 80},
  16153. {"wss://", 6, 443},
  16154. {NULL, 0, 0}};
  16155. /* Check if the uri is valid.
  16156. * return 0 for invalid uri,
  16157. * return 1 for *,
  16158. * return 2 for relative uri,
  16159. * return 3 for absolute uri without port,
  16160. * return 4 for absolute uri with port */
  16161. static int
  16162. get_uri_type(const char *uri)
  16163. {
  16164. int i;
  16165. const char *hostend, *portbegin;
  16166. char *portend;
  16167. unsigned long port;
  16168. /* According to the HTTP standard
  16169. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  16170. * URI can be an asterisk (*) or should start with slash (relative uri),
  16171. * or it should start with the protocol (absolute uri). */
  16172. if ((uri[0] == '*') && (uri[1] == '\0')) {
  16173. /* asterisk */
  16174. return 1;
  16175. }
  16176. /* Valid URIs according to RFC 3986
  16177. * (https://www.ietf.org/rfc/rfc3986.txt)
  16178. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16179. * and unreserved characters A-Z a-z 0-9 and -._~
  16180. * and % encoded symbols.
  16181. */
  16182. for (i = 0; uri[i] != 0; i++) {
  16183. if ((unsigned char)uri[i] < 33) {
  16184. /* control characters and spaces are invalid */
  16185. return 0;
  16186. }
  16187. /* Allow everything else here (See #894) */
  16188. }
  16189. /* A relative uri starts with a / character */
  16190. if (uri[0] == '/') {
  16191. /* relative uri */
  16192. return 2;
  16193. }
  16194. /* It could be an absolute uri: */
  16195. /* This function only checks if the uri is valid, not if it is
  16196. * addressing the current server. So civetweb can also be used
  16197. * as a proxy server. */
  16198. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16199. if (mg_strncasecmp(uri,
  16200. abs_uri_protocols[i].proto,
  16201. abs_uri_protocols[i].proto_len)
  16202. == 0) {
  16203. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16204. if (!hostend) {
  16205. return 0;
  16206. }
  16207. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16208. if (!portbegin) {
  16209. return 3;
  16210. }
  16211. port = strtoul(portbegin + 1, &portend, 10);
  16212. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16213. return 0;
  16214. }
  16215. return 4;
  16216. }
  16217. }
  16218. return 0;
  16219. }
  16220. /* Return NULL or the relative uri at the current server */
  16221. static const char *
  16222. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16223. {
  16224. const char *server_domain;
  16225. size_t server_domain_len;
  16226. size_t request_domain_len = 0;
  16227. unsigned long port = 0;
  16228. int i, auth_domain_check_enabled;
  16229. const char *hostbegin = NULL;
  16230. const char *hostend = NULL;
  16231. const char *portbegin;
  16232. char *portend;
  16233. auth_domain_check_enabled =
  16234. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16235. /* DNS is case insensitive, so use case insensitive string compare here
  16236. */
  16237. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16238. if (mg_strncasecmp(uri,
  16239. abs_uri_protocols[i].proto,
  16240. abs_uri_protocols[i].proto_len)
  16241. == 0) {
  16242. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16243. hostend = strchr(hostbegin, '/');
  16244. if (!hostend) {
  16245. return 0;
  16246. }
  16247. portbegin = strchr(hostbegin, ':');
  16248. if ((!portbegin) || (portbegin > hostend)) {
  16249. port = abs_uri_protocols[i].default_port;
  16250. request_domain_len = (size_t)(hostend - hostbegin);
  16251. } else {
  16252. port = strtoul(portbegin + 1, &portend, 10);
  16253. if ((portend != hostend) || (port <= 0)
  16254. || !is_valid_port(port)) {
  16255. return 0;
  16256. }
  16257. request_domain_len = (size_t)(portbegin - hostbegin);
  16258. }
  16259. /* protocol found, port set */
  16260. break;
  16261. }
  16262. }
  16263. if (!port) {
  16264. /* port remains 0 if the protocol is not found */
  16265. return 0;
  16266. }
  16267. /* Check if the request is directed to a different server. */
  16268. /* First check if the port is the same. */
  16269. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16270. /* Request is directed to a different port */
  16271. return 0;
  16272. }
  16273. /* Finally check if the server corresponds to the authentication
  16274. * domain of the server (the server domain).
  16275. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16276. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16277. * but do not allow substrings (like
  16278. * http://notmydomain.com/path/file.ext
  16279. * or http://mydomain.com.fake/path/file.ext).
  16280. */
  16281. if (auth_domain_check_enabled) {
  16282. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16283. server_domain_len = strlen(server_domain);
  16284. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16285. return 0;
  16286. }
  16287. if ((request_domain_len == server_domain_len)
  16288. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16289. /* Request is directed to this server - full name match. */
  16290. } else {
  16291. if (request_domain_len < (server_domain_len + 2)) {
  16292. /* Request is directed to another server: The server name
  16293. * is longer than the request name.
  16294. * Drop this case here to avoid overflows in the
  16295. * following checks. */
  16296. return 0;
  16297. }
  16298. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16299. /* Request is directed to another server: It could be a
  16300. * substring
  16301. * like notmyserver.com */
  16302. return 0;
  16303. }
  16304. if (0
  16305. != memcmp(server_domain,
  16306. hostbegin + request_domain_len - server_domain_len,
  16307. server_domain_len)) {
  16308. /* Request is directed to another server:
  16309. * The server name is different. */
  16310. return 0;
  16311. }
  16312. }
  16313. }
  16314. return hostend;
  16315. }
  16316. static int
  16317. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16318. {
  16319. if (ebuf_len > 0) {
  16320. ebuf[0] = '\0';
  16321. }
  16322. *err = 0;
  16323. reset_per_request_attributes(conn);
  16324. if (!conn) {
  16325. mg_snprintf(conn,
  16326. NULL, /* No truncation check for ebuf */
  16327. ebuf,
  16328. ebuf_len,
  16329. "%s",
  16330. "Internal error");
  16331. *err = 500;
  16332. return 0;
  16333. }
  16334. /* Set the time the request was received. This value should be used for
  16335. * timeouts. */
  16336. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16337. conn->request_len =
  16338. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16339. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16340. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16341. mg_snprintf(conn,
  16342. NULL, /* No truncation check for ebuf */
  16343. ebuf,
  16344. ebuf_len,
  16345. "%s",
  16346. "Invalid message size");
  16347. *err = 500;
  16348. return 0;
  16349. }
  16350. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16351. mg_snprintf(conn,
  16352. NULL, /* No truncation check for ebuf */
  16353. ebuf,
  16354. ebuf_len,
  16355. "%s",
  16356. "Message too large");
  16357. *err = 413;
  16358. return 0;
  16359. }
  16360. if (conn->request_len <= 0) {
  16361. if (conn->data_len > 0) {
  16362. mg_snprintf(conn,
  16363. NULL, /* No truncation check for ebuf */
  16364. ebuf,
  16365. ebuf_len,
  16366. "%s",
  16367. conn->request_len == -3 ? "Request timeout"
  16368. : "Malformed message");
  16369. *err = 400;
  16370. } else {
  16371. /* Server did not recv anything -> just close the connection */
  16372. conn->must_close = 1;
  16373. mg_snprintf(conn,
  16374. NULL, /* No truncation check for ebuf */
  16375. ebuf,
  16376. ebuf_len,
  16377. "%s",
  16378. "No data received");
  16379. *err = 0;
  16380. }
  16381. return 0;
  16382. }
  16383. return 1;
  16384. }
  16385. static int
  16386. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16387. {
  16388. const char *cl;
  16389. conn->connection_type =
  16390. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16391. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16392. return 0;
  16393. }
  16394. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16395. <= 0) {
  16396. mg_snprintf(conn,
  16397. NULL, /* No truncation check for ebuf */
  16398. ebuf,
  16399. ebuf_len,
  16400. "%s",
  16401. "Bad request");
  16402. *err = 400;
  16403. return 0;
  16404. }
  16405. /* Message is a valid request */
  16406. if (!switch_domain_context(conn)) {
  16407. mg_snprintf(conn,
  16408. NULL, /* No truncation check for ebuf */
  16409. ebuf,
  16410. ebuf_len,
  16411. "%s",
  16412. "Bad request: Host mismatch");
  16413. *err = 400;
  16414. return 0;
  16415. }
  16416. #if USE_ZLIB
  16417. if (((cl = get_header(conn->request_info.http_headers,
  16418. conn->request_info.num_headers,
  16419. "Accept-Encoding"))
  16420. != NULL)
  16421. && strstr(cl, "gzip")) {
  16422. conn->accept_gzip = 1;
  16423. }
  16424. #endif
  16425. if (((cl = get_header(conn->request_info.http_headers,
  16426. conn->request_info.num_headers,
  16427. "Transfer-Encoding"))
  16428. != NULL)
  16429. && mg_strcasecmp(cl, "identity")) {
  16430. if (mg_strcasecmp(cl, "chunked")) {
  16431. mg_snprintf(conn,
  16432. NULL, /* No truncation check for ebuf */
  16433. ebuf,
  16434. ebuf_len,
  16435. "%s",
  16436. "Bad request");
  16437. *err = 400;
  16438. return 0;
  16439. }
  16440. conn->is_chunked = 1;
  16441. conn->content_len = 0; /* not yet read */
  16442. } else if ((cl = get_header(conn->request_info.http_headers,
  16443. conn->request_info.num_headers,
  16444. "Content-Length"))
  16445. != NULL) {
  16446. /* Request has content length set */
  16447. char *endptr = NULL;
  16448. conn->content_len = strtoll(cl, &endptr, 10);
  16449. if ((endptr == cl) || (conn->content_len < 0)) {
  16450. mg_snprintf(conn,
  16451. NULL, /* No truncation check for ebuf */
  16452. ebuf,
  16453. ebuf_len,
  16454. "%s",
  16455. "Bad request");
  16456. *err = 411;
  16457. return 0;
  16458. }
  16459. /* Publish the content length back to the request info. */
  16460. conn->request_info.content_length = conn->content_len;
  16461. } else {
  16462. /* There is no exception, see RFC7230. */
  16463. conn->content_len = 0;
  16464. }
  16465. return 1;
  16466. }
  16467. /* conn is assumed to be valid in this internal function */
  16468. static int
  16469. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16470. {
  16471. const char *cl;
  16472. conn->connection_type =
  16473. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16474. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16475. return 0;
  16476. }
  16477. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16478. <= 0) {
  16479. mg_snprintf(conn,
  16480. NULL, /* No truncation check for ebuf */
  16481. ebuf,
  16482. ebuf_len,
  16483. "%s",
  16484. "Bad response");
  16485. *err = 400;
  16486. return 0;
  16487. }
  16488. /* Message is a valid response */
  16489. if (((cl = get_header(conn->response_info.http_headers,
  16490. conn->response_info.num_headers,
  16491. "Transfer-Encoding"))
  16492. != NULL)
  16493. && mg_strcasecmp(cl, "identity")) {
  16494. if (mg_strcasecmp(cl, "chunked")) {
  16495. mg_snprintf(conn,
  16496. NULL, /* No truncation check for ebuf */
  16497. ebuf,
  16498. ebuf_len,
  16499. "%s",
  16500. "Bad request");
  16501. *err = 400;
  16502. return 0;
  16503. }
  16504. conn->is_chunked = 1;
  16505. conn->content_len = 0; /* not yet read */
  16506. } else if ((cl = get_header(conn->response_info.http_headers,
  16507. conn->response_info.num_headers,
  16508. "Content-Length"))
  16509. != NULL) {
  16510. char *endptr = NULL;
  16511. conn->content_len = strtoll(cl, &endptr, 10);
  16512. if ((endptr == cl) || (conn->content_len < 0)) {
  16513. mg_snprintf(conn,
  16514. NULL, /* No truncation check for ebuf */
  16515. ebuf,
  16516. ebuf_len,
  16517. "%s",
  16518. "Bad request");
  16519. *err = 411;
  16520. return 0;
  16521. }
  16522. /* Publish the content length back to the response info. */
  16523. conn->response_info.content_length = conn->content_len;
  16524. /* TODO: check if it is still used in response_info */
  16525. conn->request_info.content_length = conn->content_len;
  16526. /* TODO: we should also consider HEAD method */
  16527. if (conn->response_info.status_code == 304) {
  16528. conn->content_len = 0;
  16529. }
  16530. } else {
  16531. /* TODO: we should also consider HEAD method */
  16532. if (((conn->response_info.status_code >= 100)
  16533. && (conn->response_info.status_code <= 199))
  16534. || (conn->response_info.status_code == 204)
  16535. || (conn->response_info.status_code == 304)) {
  16536. conn->content_len = 0;
  16537. } else {
  16538. conn->content_len = -1; /* unknown content length */
  16539. }
  16540. }
  16541. return 1;
  16542. }
  16543. CIVETWEB_API int
  16544. mg_get_response(struct mg_connection *conn,
  16545. char *ebuf,
  16546. size_t ebuf_len,
  16547. int timeout)
  16548. {
  16549. int err, ret;
  16550. char txt[32]; /* will not overflow */
  16551. char *save_timeout;
  16552. char *new_timeout;
  16553. if (ebuf_len > 0) {
  16554. ebuf[0] = '\0';
  16555. }
  16556. if (!conn) {
  16557. mg_snprintf(conn,
  16558. NULL, /* No truncation check for ebuf */
  16559. ebuf,
  16560. ebuf_len,
  16561. "%s",
  16562. "Parameter error");
  16563. return -1;
  16564. }
  16565. /* Reset the previous responses */
  16566. conn->data_len = 0;
  16567. /* Implementation of API function for HTTP clients */
  16568. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16569. if (timeout >= 0) {
  16570. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16571. new_timeout = txt;
  16572. } else {
  16573. new_timeout = NULL;
  16574. }
  16575. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16576. ret = get_response(conn, ebuf, ebuf_len, &err);
  16577. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16578. /* TODO: here, the URI is the http response code */
  16579. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16580. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16581. /* TODO (mid): Define proper return values - maybe return length?
  16582. * For the first test use <0 for error and >0 for OK */
  16583. return (ret == 0) ? -1 : +1;
  16584. }
  16585. CIVETWEB_API struct mg_connection *
  16586. mg_download(const char *host,
  16587. int port,
  16588. int use_ssl,
  16589. char *ebuf,
  16590. size_t ebuf_len,
  16591. const char *fmt,
  16592. ...)
  16593. {
  16594. struct mg_connection *conn;
  16595. va_list ap;
  16596. int i;
  16597. int reqerr;
  16598. if (ebuf_len > 0) {
  16599. ebuf[0] = '\0';
  16600. }
  16601. va_start(ap, fmt);
  16602. /* open a connection */
  16603. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16604. if (conn != NULL) {
  16605. i = mg_vprintf(conn, fmt, ap);
  16606. if (i <= 0) {
  16607. mg_snprintf(conn,
  16608. NULL, /* No truncation check for ebuf */
  16609. ebuf,
  16610. ebuf_len,
  16611. "%s",
  16612. "Error sending request");
  16613. } else {
  16614. /* make sure the buffer is clear */
  16615. conn->data_len = 0;
  16616. get_response(conn, ebuf, ebuf_len, &reqerr);
  16617. /* TODO: here, the URI is the http response code */
  16618. conn->request_info.local_uri = conn->request_info.request_uri;
  16619. }
  16620. }
  16621. /* if an error occurred, close the connection */
  16622. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16623. mg_close_connection(conn);
  16624. conn = NULL;
  16625. }
  16626. va_end(ap);
  16627. return conn;
  16628. }
  16629. struct websocket_client_thread_data {
  16630. struct mg_connection *conn;
  16631. mg_websocket_data_handler data_handler;
  16632. mg_websocket_close_handler close_handler;
  16633. void *callback_data;
  16634. };
  16635. #if defined(USE_WEBSOCKET)
  16636. #if defined(_WIN32)
  16637. static unsigned __stdcall websocket_client_thread(void *data)
  16638. #else
  16639. static void *
  16640. websocket_client_thread(void *data)
  16641. #endif
  16642. {
  16643. struct websocket_client_thread_data *cdata =
  16644. (struct websocket_client_thread_data *)data;
  16645. void *user_thread_ptr = NULL;
  16646. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16647. struct sigaction sa;
  16648. /* Ignore SIGPIPE */
  16649. memset(&sa, 0, sizeof(sa));
  16650. sa.sa_handler = SIG_IGN;
  16651. sigaction(SIGPIPE, &sa, NULL);
  16652. #endif
  16653. mg_set_thread_name("ws-clnt");
  16654. if (cdata->conn->phys_ctx) {
  16655. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16656. /* 3 indicates a websocket client thread */
  16657. /* TODO: check if conn->phys_ctx can be set */
  16658. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16659. cdata->conn->phys_ctx, 3);
  16660. }
  16661. }
  16662. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16663. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16664. if (cdata->close_handler != NULL) {
  16665. cdata->close_handler(cdata->conn, cdata->callback_data);
  16666. }
  16667. /* The websocket_client context has only this thread. If it runs out,
  16668. set the stop_flag to 2 (= "stopped"). */
  16669. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16670. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16671. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16672. 3,
  16673. user_thread_ptr);
  16674. }
  16675. mg_free((void *)cdata);
  16676. #if defined(_WIN32)
  16677. return 0;
  16678. #else
  16679. return NULL;
  16680. #endif
  16681. }
  16682. #endif
  16683. #if defined(USE_WEBSOCKET)
  16684. static void
  16685. generate_websocket_magic(char *magic25)
  16686. {
  16687. uint64_t rnd;
  16688. unsigned char buffer[2 * sizeof(rnd)];
  16689. rnd = get_random();
  16690. memcpy(buffer, &rnd, sizeof(rnd));
  16691. rnd = get_random();
  16692. memcpy(buffer + sizeof(rnd), &rnd, sizeof(rnd));
  16693. size_t dst_len = 24 + 1;
  16694. mg_base64_encode(buffer, sizeof(buffer), magic25, &dst_len);
  16695. }
  16696. #endif
  16697. static struct mg_connection *
  16698. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16699. int use_ssl,
  16700. char *error_buffer,
  16701. size_t error_buffer_size,
  16702. const char *path,
  16703. const char *origin,
  16704. const char *extensions,
  16705. mg_websocket_data_handler data_func,
  16706. mg_websocket_close_handler close_func,
  16707. void *user_data)
  16708. {
  16709. struct mg_connection *conn = NULL;
  16710. #if defined(USE_WEBSOCKET)
  16711. struct websocket_client_thread_data *thread_data;
  16712. char magic[32];
  16713. generate_websocket_magic(magic);
  16714. const char *host = client_options->host;
  16715. int i;
  16716. struct mg_init_data init;
  16717. struct mg_error_data error;
  16718. memset(&init, 0, sizeof(init));
  16719. memset(&error, 0, sizeof(error));
  16720. error.text_buffer_size = error_buffer_size;
  16721. error.text = error_buffer;
  16722. #if defined(__clang__)
  16723. #pragma clang diagnostic push
  16724. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16725. #endif
  16726. /* Establish the client connection and request upgrade */
  16727. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16728. /* Connection object will be null if something goes wrong */
  16729. if (conn == NULL) {
  16730. /* error_buffer should be already filled ... */
  16731. if (!error_buffer[0]) {
  16732. /* ... if not add an error message */
  16733. mg_snprintf(conn,
  16734. NULL, /* No truncation check for ebuf */
  16735. error_buffer,
  16736. error_buffer_size,
  16737. "Unexpected error");
  16738. }
  16739. return NULL;
  16740. }
  16741. if (origin != NULL) {
  16742. if (extensions != NULL) {
  16743. i = mg_printf(conn,
  16744. "GET %s HTTP/1.1\r\n"
  16745. "Host: %s\r\n"
  16746. "Upgrade: websocket\r\n"
  16747. "Connection: Upgrade\r\n"
  16748. "Sec-WebSocket-Key: %s\r\n"
  16749. "Sec-WebSocket-Version: 13\r\n"
  16750. "Sec-WebSocket-Extensions: %s\r\n"
  16751. "Origin: %s\r\n"
  16752. "\r\n",
  16753. path,
  16754. host,
  16755. magic,
  16756. extensions,
  16757. origin);
  16758. } else {
  16759. i = mg_printf(conn,
  16760. "GET %s HTTP/1.1\r\n"
  16761. "Host: %s\r\n"
  16762. "Upgrade: websocket\r\n"
  16763. "Connection: Upgrade\r\n"
  16764. "Sec-WebSocket-Key: %s\r\n"
  16765. "Sec-WebSocket-Version: 13\r\n"
  16766. "Origin: %s\r\n"
  16767. "\r\n",
  16768. path,
  16769. host,
  16770. magic,
  16771. origin);
  16772. }
  16773. } else {
  16774. if (extensions != NULL) {
  16775. i = mg_printf(conn,
  16776. "GET %s HTTP/1.1\r\n"
  16777. "Host: %s\r\n"
  16778. "Upgrade: websocket\r\n"
  16779. "Connection: Upgrade\r\n"
  16780. "Sec-WebSocket-Key: %s\r\n"
  16781. "Sec-WebSocket-Version: 13\r\n"
  16782. "Sec-WebSocket-Extensions: %s\r\n"
  16783. "\r\n",
  16784. path,
  16785. host,
  16786. magic,
  16787. extensions);
  16788. } else {
  16789. i = mg_printf(conn,
  16790. "GET %s HTTP/1.1\r\n"
  16791. "Host: %s\r\n"
  16792. "Upgrade: websocket\r\n"
  16793. "Connection: Upgrade\r\n"
  16794. "Sec-WebSocket-Key: %s\r\n"
  16795. "Sec-WebSocket-Version: 13\r\n"
  16796. "\r\n",
  16797. path,
  16798. host,
  16799. magic);
  16800. }
  16801. }
  16802. if (i <= 0) {
  16803. mg_snprintf(conn,
  16804. NULL, /* No truncation check for ebuf */
  16805. error_buffer,
  16806. error_buffer_size,
  16807. "%s",
  16808. "Error sending request");
  16809. mg_close_connection(conn);
  16810. return NULL;
  16811. }
  16812. conn->data_len = 0;
  16813. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16814. mg_close_connection(conn);
  16815. return NULL;
  16816. }
  16817. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16818. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16819. #if defined(__clang__)
  16820. #pragma clang diagnostic pop
  16821. #endif
  16822. if (conn->response_info.status_code != 101) {
  16823. /* We sent an "upgrade" request. For a correct websocket
  16824. * protocol handshake, we expect a "101 Continue" response.
  16825. * Otherwise it is a protocol violation. Maybe the HTTP
  16826. * Server does not know websockets. */
  16827. if (!*error_buffer) {
  16828. /* set an error, if not yet set */
  16829. mg_snprintf(conn,
  16830. NULL, /* No truncation check for ebuf */
  16831. error_buffer,
  16832. error_buffer_size,
  16833. "Unexpected server reply");
  16834. }
  16835. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16836. mg_close_connection(conn);
  16837. return NULL;
  16838. }
  16839. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16840. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16841. if (!thread_data) {
  16842. DEBUG_TRACE("%s\r\n", "Out of memory");
  16843. mg_close_connection(conn);
  16844. return NULL;
  16845. }
  16846. thread_data->conn = conn;
  16847. thread_data->data_handler = data_func;
  16848. thread_data->close_handler = close_func;
  16849. thread_data->callback_data = user_data;
  16850. conn->phys_ctx->worker_threadids =
  16851. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16852. if (!conn->phys_ctx->worker_threadids) {
  16853. DEBUG_TRACE("%s\r\n", "Out of memory");
  16854. mg_free(thread_data);
  16855. mg_close_connection(conn);
  16856. return NULL;
  16857. }
  16858. /* Now upgrade to ws/wss client context */
  16859. conn->phys_ctx->user_data = user_data;
  16860. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16861. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  16862. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  16863. /* Start a thread to read the websocket client connection
  16864. * This thread will automatically stop when mg_disconnect is
  16865. * called on the client connection */
  16866. if (mg_start_thread_with_id(websocket_client_thread,
  16867. thread_data,
  16868. conn->phys_ctx->worker_threadids)
  16869. != 0) {
  16870. conn->phys_ctx->spawned_worker_threads = 0;
  16871. mg_free(thread_data);
  16872. mg_close_connection(conn);
  16873. conn = NULL;
  16874. DEBUG_TRACE("%s",
  16875. "Websocket client connect thread could not be started\r\n");
  16876. }
  16877. #else
  16878. /* Appease "unused parameter" warnings */
  16879. (void)client_options;
  16880. (void)use_ssl;
  16881. (void)error_buffer;
  16882. (void)error_buffer_size;
  16883. (void)path;
  16884. (void)origin;
  16885. (void)extensions;
  16886. (void)user_data;
  16887. (void)data_func;
  16888. (void)close_func;
  16889. #endif
  16890. return conn;
  16891. }
  16892. CIVETWEB_API struct mg_connection *
  16893. mg_connect_websocket_client(const char *host,
  16894. int port,
  16895. int use_ssl,
  16896. char *error_buffer,
  16897. size_t error_buffer_size,
  16898. const char *path,
  16899. const char *origin,
  16900. mg_websocket_data_handler data_func,
  16901. mg_websocket_close_handler close_func,
  16902. void *user_data)
  16903. {
  16904. struct mg_client_options client_options;
  16905. memset(&client_options, 0, sizeof(client_options));
  16906. client_options.host = host;
  16907. client_options.port = port;
  16908. return mg_connect_websocket_client_impl(&client_options,
  16909. use_ssl,
  16910. error_buffer,
  16911. error_buffer_size,
  16912. path,
  16913. origin,
  16914. NULL,
  16915. data_func,
  16916. close_func,
  16917. user_data);
  16918. }
  16919. CIVETWEB_API struct mg_connection *
  16920. mg_connect_websocket_client_secure(
  16921. const struct mg_client_options *client_options,
  16922. char *error_buffer,
  16923. size_t error_buffer_size,
  16924. const char *path,
  16925. const char *origin,
  16926. mg_websocket_data_handler data_func,
  16927. mg_websocket_close_handler close_func,
  16928. void *user_data)
  16929. {
  16930. if (!client_options) {
  16931. return NULL;
  16932. }
  16933. return mg_connect_websocket_client_impl(client_options,
  16934. 1,
  16935. error_buffer,
  16936. error_buffer_size,
  16937. path,
  16938. origin,
  16939. NULL,
  16940. data_func,
  16941. close_func,
  16942. user_data);
  16943. }
  16944. CIVETWEB_API struct mg_connection *
  16945. mg_connect_websocket_client_extensions(const char *host,
  16946. int port,
  16947. int use_ssl,
  16948. char *error_buffer,
  16949. size_t error_buffer_size,
  16950. const char *path,
  16951. const char *origin,
  16952. const char *extensions,
  16953. mg_websocket_data_handler data_func,
  16954. mg_websocket_close_handler close_func,
  16955. void *user_data)
  16956. {
  16957. struct mg_client_options client_options;
  16958. memset(&client_options, 0, sizeof(client_options));
  16959. client_options.host = host;
  16960. client_options.port = port;
  16961. return mg_connect_websocket_client_impl(&client_options,
  16962. use_ssl,
  16963. error_buffer,
  16964. error_buffer_size,
  16965. path,
  16966. origin,
  16967. extensions,
  16968. data_func,
  16969. close_func,
  16970. user_data);
  16971. }
  16972. CIVETWEB_API struct mg_connection *
  16973. mg_connect_websocket_client_secure_extensions(
  16974. const struct mg_client_options *client_options,
  16975. char *error_buffer,
  16976. size_t error_buffer_size,
  16977. const char *path,
  16978. const char *origin,
  16979. const char *extensions,
  16980. mg_websocket_data_handler data_func,
  16981. mg_websocket_close_handler close_func,
  16982. void *user_data)
  16983. {
  16984. if (!client_options) {
  16985. return NULL;
  16986. }
  16987. return mg_connect_websocket_client_impl(client_options,
  16988. 1,
  16989. error_buffer,
  16990. error_buffer_size,
  16991. path,
  16992. origin,
  16993. extensions,
  16994. data_func,
  16995. close_func,
  16996. user_data);
  16997. }
  16998. /* Prepare connection data structure */
  16999. static void
  17000. init_connection(struct mg_connection *conn)
  17001. {
  17002. /* Is keep alive allowed by the server */
  17003. int keep_alive_enabled =
  17004. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  17005. if (!keep_alive_enabled) {
  17006. conn->must_close = 1;
  17007. }
  17008. /* Important: on new connection, reset the receiving buffer. Credit
  17009. * goes to crule42. */
  17010. conn->data_len = 0;
  17011. conn->handled_requests = 0;
  17012. conn->connection_type = CONNECTION_TYPE_INVALID;
  17013. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  17014. mg_set_user_connection_data(conn, NULL);
  17015. #if defined(USE_SERVER_STATS)
  17016. conn->conn_state = 2; /* init */
  17017. #endif
  17018. /* call the init_connection callback if assigned */
  17019. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  17020. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  17021. void *conn_data = NULL;
  17022. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  17023. mg_set_user_connection_data(conn, conn_data);
  17024. }
  17025. }
  17026. }
  17027. /* Process a connection - may handle multiple requests
  17028. * using the same connection.
  17029. * Must be called with a valid connection (conn and
  17030. * conn->phys_ctx must be valid).
  17031. */
  17032. static void
  17033. process_new_connection(struct mg_connection *conn)
  17034. {
  17035. struct mg_request_info *ri = &conn->request_info;
  17036. int keep_alive, discard_len;
  17037. char ebuf[100];
  17038. const char *hostend;
  17039. int reqerr, uri_type;
  17040. #if defined(USE_SERVER_STATS)
  17041. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  17042. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  17043. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  17044. #endif
  17045. DEBUG_TRACE("Start processing connection from %s",
  17046. conn->request_info.remote_addr);
  17047. /* Loop over multiple requests sent using the same connection
  17048. * (while "keep alive"). */
  17049. do {
  17050. DEBUG_TRACE("calling get_request (%i times for this connection)",
  17051. conn->handled_requests + 1);
  17052. #if defined(USE_SERVER_STATS)
  17053. conn->conn_state = 3; /* ready */
  17054. #endif
  17055. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  17056. /* The request sent by the client could not be understood by
  17057. * the server, or it was incomplete or a timeout. Send an
  17058. * error message and close the connection. */
  17059. if (reqerr > 0) {
  17060. DEBUG_ASSERT(ebuf[0] != '\0');
  17061. mg_send_http_error(conn, reqerr, "%s", ebuf);
  17062. }
  17063. } else if (strcmp(ri->http_version, "1.0")
  17064. && strcmp(ri->http_version, "1.1")) {
  17065. /* HTTP/2 is not allowed here */
  17066. mg_snprintf(conn,
  17067. NULL, /* No truncation check for ebuf */
  17068. ebuf,
  17069. sizeof(ebuf),
  17070. "Bad HTTP version: [%s]",
  17071. ri->http_version);
  17072. mg_send_http_error(conn, 505, "%s", ebuf);
  17073. }
  17074. if (ebuf[0] == '\0') {
  17075. uri_type = get_uri_type(conn->request_info.request_uri);
  17076. switch (uri_type) {
  17077. case 1:
  17078. /* Asterisk */
  17079. conn->request_info.local_uri_raw = 0;
  17080. /* TODO: Deal with '*'. */
  17081. break;
  17082. case 2:
  17083. /* relative uri */
  17084. conn->request_info.local_uri_raw =
  17085. conn->request_info.request_uri;
  17086. break;
  17087. case 3:
  17088. case 4:
  17089. /* absolute uri (with/without port) */
  17090. hostend = get_rel_url_at_current_server(
  17091. conn->request_info.request_uri, conn);
  17092. if (hostend) {
  17093. conn->request_info.local_uri_raw = hostend;
  17094. } else {
  17095. conn->request_info.local_uri_raw = NULL;
  17096. }
  17097. break;
  17098. default:
  17099. mg_snprintf(conn,
  17100. NULL, /* No truncation check for ebuf */
  17101. ebuf,
  17102. sizeof(ebuf),
  17103. "Invalid URI");
  17104. mg_send_http_error(conn, 400, "%s", ebuf);
  17105. conn->request_info.local_uri_raw = NULL;
  17106. break;
  17107. }
  17108. conn->request_info.local_uri =
  17109. (char *)conn->request_info.local_uri_raw;
  17110. }
  17111. if (ebuf[0] != '\0') {
  17112. conn->protocol_type = -1;
  17113. } else {
  17114. /* HTTP/1 allows protocol upgrade */
  17115. conn->protocol_type = should_switch_to_protocol(conn);
  17116. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  17117. /* This will occur, if a HTTP/1.1 request should be upgraded
  17118. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  17119. * Since most (all?) major browsers only support HTTP/2 using
  17120. * ALPN, this is hard to test and very low priority.
  17121. * Deactivate it (at least for now).
  17122. */
  17123. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17124. }
  17125. }
  17126. DEBUG_TRACE("http: %s, error: %s",
  17127. (ri->http_version ? ri->http_version : "none"),
  17128. (ebuf[0] ? ebuf : "none"));
  17129. if (ebuf[0] == '\0') {
  17130. if (conn->request_info.local_uri) {
  17131. /* handle request to local server */
  17132. handle_request_stat_log(conn);
  17133. } else {
  17134. /* TODO: handle non-local request (PROXY) */
  17135. conn->must_close = 1;
  17136. }
  17137. } else {
  17138. conn->must_close = 1;
  17139. }
  17140. /* Response complete. Free header buffer */
  17141. free_buffered_response_header_list(conn);
  17142. if (ri->remote_user != NULL) {
  17143. mg_free((void *)ri->remote_user);
  17144. /* Important! When having connections with and without auth
  17145. * would cause double free and then crash */
  17146. ri->remote_user = NULL;
  17147. }
  17148. /* NOTE(lsm): order is important here. should_keep_alive() call
  17149. * is using parsed request, which will be invalid after
  17150. * memmove's below.
  17151. * Therefore, memorize should_keep_alive() result now for later
  17152. * use in loop exit condition. */
  17153. /* Enable it only if this request is completely discardable. */
  17154. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  17155. && should_keep_alive(conn) && (conn->content_len >= 0)
  17156. && (conn->request_len > 0)
  17157. && ((conn->is_chunked == 4)
  17158. || (!conn->is_chunked
  17159. && ((conn->consumed_content == conn->content_len)
  17160. || ((conn->request_len + conn->content_len)
  17161. <= conn->data_len))))
  17162. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  17163. if (keep_alive) {
  17164. /* Discard all buffered data for this request */
  17165. discard_len =
  17166. ((conn->request_len + conn->content_len) < conn->data_len)
  17167. ? (int)(conn->request_len + conn->content_len)
  17168. : conn->data_len;
  17169. conn->data_len -= discard_len;
  17170. if (conn->data_len > 0) {
  17171. DEBUG_TRACE("discard_len = %d", discard_len);
  17172. memmove(conn->buf,
  17173. conn->buf + discard_len,
  17174. (size_t)conn->data_len);
  17175. }
  17176. }
  17177. DEBUG_ASSERT(conn->data_len >= 0);
  17178. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  17179. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  17180. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  17181. (long int)conn->data_len,
  17182. (long int)conn->buf_size);
  17183. break;
  17184. }
  17185. conn->handled_requests++;
  17186. } while (keep_alive);
  17187. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  17188. conn->request_info.remote_addr,
  17189. difftime(time(NULL), conn->conn_birth_time));
  17190. close_connection(conn);
  17191. #if defined(USE_SERVER_STATS)
  17192. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17193. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17194. #endif
  17195. }
  17196. static int
  17197. mg_start_worker_thread(struct mg_context *ctx,
  17198. int only_if_no_idle_threads); /* forward declaration */
  17199. #if defined(ALTERNATIVE_QUEUE)
  17200. static void
  17201. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17202. {
  17203. unsigned int i;
  17204. (void)mg_start_worker_thread(
  17205. ctx, 1); /* will start a worker-thread only if there aren't currently
  17206. any idle worker-threads */
  17207. while (!ctx->stop_flag) {
  17208. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17209. /* find a free worker slot and signal it */
  17210. if (ctx->client_socks[i].in_use == 2) {
  17211. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17212. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17213. ctx->client_socks[i] = *sp;
  17214. ctx->client_socks[i].in_use = 1;
  17215. /* socket has been moved to the consumer */
  17216. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17217. (void)event_signal(ctx->client_wait_events[i]);
  17218. return;
  17219. }
  17220. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17221. }
  17222. }
  17223. /* queue is full */
  17224. mg_sleep(1);
  17225. }
  17226. /* must consume */
  17227. set_blocking_mode(sp->sock);
  17228. closesocket(sp->sock);
  17229. }
  17230. static int
  17231. consume_socket(struct mg_context *ctx,
  17232. struct socket *sp,
  17233. int thread_index,
  17234. int counter_was_preincremented)
  17235. {
  17236. DEBUG_TRACE("%s", "going idle");
  17237. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17238. if (counter_was_preincremented
  17239. == 0) { /* first call only: the master-thread pre-incremented this
  17240. before he spawned us */
  17241. ctx->idle_worker_thread_count++;
  17242. }
  17243. ctx->client_socks[thread_index].in_use = 2;
  17244. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17245. event_wait(ctx->client_wait_events[thread_index]);
  17246. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17247. *sp = ctx->client_socks[thread_index];
  17248. if (ctx->stop_flag) {
  17249. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17250. if (sp->in_use == 1) {
  17251. /* must consume */
  17252. set_blocking_mode(sp->sock);
  17253. closesocket(sp->sock);
  17254. }
  17255. return 0;
  17256. }
  17257. ctx->idle_worker_thread_count--;
  17258. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17259. if (sp->in_use == 1) {
  17260. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17261. return 1;
  17262. }
  17263. /* must not reach here */
  17264. DEBUG_ASSERT(0);
  17265. return 0;
  17266. }
  17267. #else /* ALTERNATIVE_QUEUE */
  17268. /* Worker threads take accepted socket from the queue */
  17269. static int
  17270. consume_socket(struct mg_context *ctx,
  17271. struct socket *sp,
  17272. int thread_index,
  17273. int counter_was_preincremented)
  17274. {
  17275. (void)thread_index;
  17276. DEBUG_TRACE("%s", "going idle");
  17277. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17278. if (counter_was_preincremented
  17279. == 0) { /* first call only: the master-thread pre-incremented this
  17280. before he spawned us */
  17281. ctx->idle_worker_thread_count++;
  17282. }
  17283. /* If the queue is empty, wait. We're idle at this point. */
  17284. while ((ctx->sq_head == ctx->sq_tail)
  17285. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17286. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17287. }
  17288. /* If we're stopping, sq_head may be equal to sq_tail. */
  17289. if (ctx->sq_head > ctx->sq_tail) {
  17290. /* Copy socket from the queue and increment tail */
  17291. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17292. ctx->sq_tail++;
  17293. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17294. /* Wrap pointers if needed */
  17295. while (ctx->sq_tail > ctx->sq_size) {
  17296. ctx->sq_tail -= ctx->sq_size;
  17297. ctx->sq_head -= ctx->sq_size;
  17298. }
  17299. }
  17300. (void)pthread_cond_signal(&ctx->sq_empty);
  17301. ctx->idle_worker_thread_count--;
  17302. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17303. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17304. }
  17305. /* Master thread adds accepted socket to a queue */
  17306. static void
  17307. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17308. {
  17309. int queue_filled;
  17310. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17311. queue_filled = ctx->sq_head - ctx->sq_tail;
  17312. /* If the queue is full, wait */
  17313. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17314. && (queue_filled >= ctx->sq_size)) {
  17315. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17316. #if defined(USE_SERVER_STATS)
  17317. if (queue_filled > ctx->sq_max_fill) {
  17318. ctx->sq_max_fill = queue_filled;
  17319. }
  17320. #endif
  17321. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17322. ctx->sq_blocked = 0; /* Not blocked now */
  17323. queue_filled = ctx->sq_head - ctx->sq_tail;
  17324. }
  17325. if (queue_filled < ctx->sq_size) {
  17326. /* Copy socket to the queue and increment head */
  17327. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17328. ctx->sq_head++;
  17329. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17330. }
  17331. queue_filled = ctx->sq_head - ctx->sq_tail;
  17332. #if defined(USE_SERVER_STATS)
  17333. if (queue_filled > ctx->sq_max_fill) {
  17334. ctx->sq_max_fill = queue_filled;
  17335. }
  17336. #endif
  17337. (void)pthread_cond_signal(&ctx->sq_full);
  17338. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17339. (void)mg_start_worker_thread(
  17340. ctx, 1); /* will start a worker-thread only if there aren't currently
  17341. any idle worker-threads */
  17342. }
  17343. #endif /* ALTERNATIVE_QUEUE */
  17344. static void
  17345. worker_thread_run(struct mg_connection *conn)
  17346. {
  17347. struct mg_context *ctx = conn->phys_ctx;
  17348. int thread_index;
  17349. struct mg_workerTLS tls;
  17350. int first_call_to_consume_socket = 1;
  17351. mg_set_thread_name("worker");
  17352. tls.is_master = 0;
  17353. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17354. #if defined(_WIN32)
  17355. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17356. #endif
  17357. /* Initialize thread local storage before calling any callback */
  17358. pthread_setspecific(sTlsKey, &tls);
  17359. /* Check if there is a user callback */
  17360. if (ctx->callbacks.init_thread) {
  17361. /* call init_thread for a worker thread (type 1), and store the
  17362. * return value */
  17363. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17364. } else {
  17365. /* No callback: set user pointer to NULL */
  17366. tls.user_ptr = NULL;
  17367. }
  17368. /* Connection structure has been pre-allocated */
  17369. thread_index = (int)(conn - ctx->worker_connections);
  17370. if ((thread_index < 0)
  17371. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17372. mg_cry_ctx_internal(ctx,
  17373. "Internal error: Invalid worker index %i",
  17374. thread_index);
  17375. return;
  17376. }
  17377. /* Request buffers are not pre-allocated. They are private to the
  17378. * request and do not contain any state information that might be
  17379. * of interest to anyone observing a server status. */
  17380. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17381. if (conn->buf == NULL) {
  17382. mg_cry_ctx_internal(
  17383. ctx,
  17384. "Out of memory: Cannot allocate buffer for worker %i",
  17385. thread_index);
  17386. return;
  17387. }
  17388. conn->buf_size = (int)ctx->max_request_size;
  17389. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17390. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17391. conn->request_info.user_data = ctx->user_data;
  17392. /* Allocate a mutex for this connection to allow communication both
  17393. * within the request handler and from elsewhere in the application
  17394. */
  17395. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17396. mg_free(conn->buf);
  17397. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17398. return;
  17399. }
  17400. #if defined(USE_SERVER_STATS)
  17401. conn->conn_state = 1; /* not consumed */
  17402. #endif
  17403. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17404. * signal sq_empty condvar to wake up the master waiting in
  17405. * produce_socket() */
  17406. while (consume_socket(
  17407. ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17408. first_call_to_consume_socket = 0;
  17409. /* New connections must start with new protocol negotiation */
  17410. tls.alpn_proto = NULL;
  17411. #if defined(USE_SERVER_STATS)
  17412. conn->conn_close_time = 0;
  17413. #endif
  17414. conn->conn_birth_time = time(NULL);
  17415. /* Fill in IP, port info early so even if SSL setup below fails,
  17416. * error handler would have the corresponding info.
  17417. * Thanks to Johannes Winkelmann for the patch.
  17418. */
  17419. conn->request_info.remote_port =
  17420. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17421. conn->request_info.server_port =
  17422. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17423. sockaddr_to_string(conn->request_info.remote_addr,
  17424. sizeof(conn->request_info.remote_addr),
  17425. &conn->client.rsa);
  17426. DEBUG_TRACE("Incoming %sconnection from %s",
  17427. (conn->client.is_ssl ? "SSL " : ""),
  17428. conn->request_info.remote_addr);
  17429. conn->request_info.is_ssl = conn->client.is_ssl;
  17430. if (conn->client.is_ssl) {
  17431. #if defined(USE_MBEDTLS)
  17432. /* HTTPS connection */
  17433. if (mbed_ssl_accept(&(conn->ssl),
  17434. conn->dom_ctx->ssl_ctx,
  17435. (int *)&(conn->client.sock),
  17436. conn->phys_ctx)
  17437. == 0) {
  17438. /* conn->dom_ctx is set in get_request */
  17439. /* process HTTPS connection */
  17440. init_connection(conn);
  17441. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17442. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17443. process_new_connection(conn);
  17444. } else {
  17445. /* make sure the connection is cleaned up on SSL failure */
  17446. close_connection(conn);
  17447. }
  17448. #elif !defined(NO_SSL)
  17449. /* HTTPS connection */
  17450. if (sslize(conn, SSL_accept, NULL)) {
  17451. /* conn->dom_ctx is set in get_request */
  17452. /* Get SSL client certificate information (if set) */
  17453. struct mg_client_cert client_cert;
  17454. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17455. conn->request_info.client_cert = &client_cert;
  17456. }
  17457. /* process HTTPS connection */
  17458. #if defined(USE_HTTP2)
  17459. if ((tls.alpn_proto != NULL)
  17460. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17461. /* process HTTPS/2 connection */
  17462. init_connection(conn);
  17463. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17464. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17465. conn->content_len =
  17466. -1; /* content length is not predefined */
  17467. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17468. process_new_http2_connection(conn);
  17469. } else
  17470. #endif
  17471. {
  17472. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17473. init_connection(conn);
  17474. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17475. /* Start with HTTP, WS will be an "upgrade" request later */
  17476. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17477. process_new_connection(conn);
  17478. }
  17479. /* Free client certificate info */
  17480. if (conn->request_info.client_cert) {
  17481. mg_free((void *)(conn->request_info.client_cert->subject));
  17482. mg_free((void *)(conn->request_info.client_cert->issuer));
  17483. mg_free((void *)(conn->request_info.client_cert->serial));
  17484. mg_free((void *)(conn->request_info.client_cert->finger));
  17485. /* Free certificate memory */
  17486. X509_free(
  17487. (X509 *)conn->request_info.client_cert->peer_cert);
  17488. conn->request_info.client_cert->peer_cert = 0;
  17489. conn->request_info.client_cert->subject = 0;
  17490. conn->request_info.client_cert->issuer = 0;
  17491. conn->request_info.client_cert->serial = 0;
  17492. conn->request_info.client_cert->finger = 0;
  17493. conn->request_info.client_cert = 0;
  17494. }
  17495. } else {
  17496. /* make sure the connection is cleaned up on SSL failure */
  17497. close_connection(conn);
  17498. }
  17499. #endif
  17500. } else {
  17501. /* process HTTP connection */
  17502. init_connection(conn);
  17503. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17504. /* Start with HTTP, WS will be an "upgrade" request later */
  17505. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17506. process_new_connection(conn);
  17507. }
  17508. DEBUG_TRACE("%s", "Connection closed");
  17509. #if defined(USE_SERVER_STATS)
  17510. conn->conn_close_time = time(NULL);
  17511. #endif
  17512. }
  17513. /* Call exit thread user callback */
  17514. if (ctx->callbacks.exit_thread) {
  17515. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17516. }
  17517. /* delete thread local storage objects */
  17518. pthread_setspecific(sTlsKey, NULL);
  17519. #if defined(_WIN32)
  17520. CloseHandle(tls.pthread_cond_helper_mutex);
  17521. #endif
  17522. pthread_mutex_destroy(&conn->mutex);
  17523. /* Free the request buffer. */
  17524. conn->buf_size = 0;
  17525. mg_free(conn->buf);
  17526. conn->buf = NULL;
  17527. /* Free cleaned URI (if any) */
  17528. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17529. mg_free((void *)conn->request_info.local_uri);
  17530. conn->request_info.local_uri = NULL;
  17531. }
  17532. #if defined(USE_SERVER_STATS)
  17533. conn->conn_state = 9; /* done */
  17534. #endif
  17535. DEBUG_TRACE("%s", "exiting");
  17536. }
  17537. /* Threads have different return types on Windows and Unix. */
  17538. #if defined(_WIN32)
  17539. static unsigned __stdcall worker_thread(void *thread_func_param)
  17540. {
  17541. worker_thread_run((struct mg_connection *)thread_func_param);
  17542. return 0;
  17543. }
  17544. #else
  17545. static void *
  17546. worker_thread(void *thread_func_param)
  17547. {
  17548. #if !defined(__ZEPHYR__)
  17549. struct sigaction sa;
  17550. /* Ignore SIGPIPE */
  17551. memset(&sa, 0, sizeof(sa));
  17552. sa.sa_handler = SIG_IGN;
  17553. sigaction(SIGPIPE, &sa, NULL);
  17554. #endif
  17555. worker_thread_run((struct mg_connection *)thread_func_param);
  17556. return NULL;
  17557. }
  17558. #endif /* _WIN32 */
  17559. /* This is an internal function, thus all arguments are expected to be
  17560. * valid - a NULL check is not required. */
  17561. static void
  17562. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17563. {
  17564. struct socket so;
  17565. char src_addr[IP_ADDR_STR_LEN];
  17566. socklen_t len = sizeof(so.rsa);
  17567. #if !defined(__ZEPHYR__)
  17568. int on = 1;
  17569. #endif
  17570. memset(&so, 0, sizeof(so));
  17571. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17572. == INVALID_SOCKET) {
  17573. } else if (check_acl(ctx, &so.rsa) != 1) {
  17574. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17575. mg_cry_ctx_internal(ctx,
  17576. "%s: %s is not allowed to connect",
  17577. __func__,
  17578. src_addr);
  17579. closesocket(so.sock);
  17580. } else {
  17581. /* Put so socket structure into the queue */
  17582. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17583. set_close_on_exec(so.sock, NULL, ctx);
  17584. so.is_ssl = listener->is_ssl;
  17585. so.ssl_redir = listener->ssl_redir;
  17586. so.is_optional = listener->is_optional;
  17587. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17588. mg_cry_ctx_internal(ctx,
  17589. "%s: getsockname() failed: %s",
  17590. __func__,
  17591. strerror(ERRNO));
  17592. }
  17593. #if !defined(__ZEPHYR__)
  17594. if ((so.lsa.sa.sa_family == AF_INET)
  17595. || (so.lsa.sa.sa_family == AF_INET6)) {
  17596. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17597. * This is needed because if HTTP-level keep-alive
  17598. * is enabled, and client resets the connection, server won't get
  17599. * TCP FIN or RST and will keep the connection open forever. With
  17600. * TCP keep-alive, next keep-alive handshake will figure out that
  17601. * the client is down and will close the server end.
  17602. * Thanks to Igor Klopov who suggested the patch. */
  17603. if (setsockopt(so.sock,
  17604. SOL_SOCKET,
  17605. SO_KEEPALIVE,
  17606. (SOCK_OPT_TYPE)&on,
  17607. sizeof(on))
  17608. != 0) {
  17609. mg_cry_ctx_internal(
  17610. ctx,
  17611. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17612. __func__,
  17613. strerror(ERRNO));
  17614. }
  17615. }
  17616. #endif
  17617. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17618. * to effectively fill up the underlying IP packet payload and
  17619. * reduce the overhead of sending lots of small buffers. However
  17620. * this hurts the server's throughput (ie. operations per second)
  17621. * when HTTP 1.1 persistent connections are used and the responses
  17622. * are relatively small (eg. less than 1400 bytes).
  17623. */
  17624. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17625. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17626. if (set_tcp_nodelay(&so, 1) != 0) {
  17627. mg_cry_ctx_internal(
  17628. ctx,
  17629. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17630. __func__,
  17631. strerror(ERRNO));
  17632. }
  17633. }
  17634. /* The "non blocking" property should already be
  17635. * inherited from the parent socket. Set it for
  17636. * non-compliant socket implementations. */
  17637. set_non_blocking_mode(so.sock);
  17638. so.in_use = 0;
  17639. produce_socket(ctx, &so);
  17640. }
  17641. }
  17642. static void
  17643. master_thread_run(struct mg_context *ctx)
  17644. {
  17645. struct mg_workerTLS tls;
  17646. struct mg_pollfd *pfd;
  17647. unsigned int i;
  17648. unsigned int workerthreadcount;
  17649. if (!ctx) {
  17650. return;
  17651. }
  17652. mg_set_thread_name("master");
  17653. /* Increase priority of the master thread */
  17654. #if defined(_WIN32)
  17655. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17656. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17657. int min_prio = sched_get_priority_min(SCHED_RR);
  17658. int max_prio = sched_get_priority_max(SCHED_RR);
  17659. if ((min_prio >= 0) && (max_prio >= 0)
  17660. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17661. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17662. struct sched_param sched_param = {0};
  17663. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17664. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17665. }
  17666. #endif
  17667. /* Initialize thread local storage */
  17668. #if defined(_WIN32)
  17669. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17670. #endif
  17671. tls.is_master = 1;
  17672. pthread_setspecific(sTlsKey, &tls);
  17673. if (ctx->callbacks.init_thread) {
  17674. /* Callback for the master thread (type 0) */
  17675. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17676. } else {
  17677. tls.user_ptr = NULL;
  17678. }
  17679. /* Lua background script "start" event */
  17680. #if defined(USE_LUA)
  17681. if (ctx->lua_background_state) {
  17682. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17683. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17684. /* call "start()" in Lua */
  17685. lua_getglobal(lstate, "start");
  17686. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17687. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17688. if (ret != 0) {
  17689. struct mg_connection fc;
  17690. lua_cry(fake_connection(&fc, ctx),
  17691. ret,
  17692. lstate,
  17693. "lua_background_script",
  17694. "start");
  17695. }
  17696. } else {
  17697. lua_pop(lstate, 1);
  17698. }
  17699. /* determine if there is a "log()" function in Lua background script */
  17700. lua_getglobal(lstate, "log");
  17701. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17702. ctx->lua_bg_log_available = 1;
  17703. }
  17704. lua_pop(lstate, 1);
  17705. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17706. }
  17707. #endif
  17708. /* Server starts *now* */
  17709. ctx->start_time = time(NULL);
  17710. /* Server accept loop */
  17711. pfd = ctx->listening_socket_fds;
  17712. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17713. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17714. pfd[i].fd = ctx->listening_sockets[i].sock;
  17715. pfd[i].events = POLLIN;
  17716. }
  17717. /* We listen on this socket just so that mg_stop() can cause mg_poll()
  17718. * to return ASAP. Don't worry, we did allocate an extra slot at the end
  17719. * of listening_socket_fds[] just to hold this
  17720. */
  17721. pfd[ctx->num_listening_sockets].fd =
  17722. ctx->thread_shutdown_notification_socket;
  17723. pfd[ctx->num_listening_sockets].events = POLLIN;
  17724. if (mg_poll(pfd,
  17725. ctx->num_listening_sockets
  17726. + 1, // +1 for the thread_shutdown_notification_socket
  17727. SOCKET_TIMEOUT_QUANTUM,
  17728. &(ctx->stop_flag))
  17729. > 0) {
  17730. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17731. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17732. * successful poll, and POLLIN is defined as
  17733. * (POLLRDNORM | POLLRDBAND)
  17734. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17735. * pfd[i].revents == POLLIN. */
  17736. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17737. && (pfd[i].revents & POLLIN)) {
  17738. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17739. }
  17740. }
  17741. }
  17742. }
  17743. /* Here stop_flag is 1 - Initiate shutdown. */
  17744. DEBUG_TRACE("%s", "stopping workers");
  17745. /* Stop signal received: somebody called mg_stop. Quit. */
  17746. close_all_listening_sockets(ctx);
  17747. /* Wakeup workers that are waiting for connections to handle. */
  17748. #if defined(ALTERNATIVE_QUEUE)
  17749. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17750. event_signal(ctx->client_wait_events[i]);
  17751. }
  17752. #else
  17753. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17754. pthread_cond_broadcast(&ctx->sq_full);
  17755. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17756. #endif
  17757. /* Join all worker threads to avoid leaking threads. */
  17758. workerthreadcount = ctx->spawned_worker_threads;
  17759. for (i = 0; i < workerthreadcount; i++) {
  17760. if (ctx->worker_threadids[i] != 0) {
  17761. mg_join_thread(ctx->worker_threadids[i]);
  17762. }
  17763. }
  17764. #if defined(USE_LUA)
  17765. /* Free Lua state of lua background task */
  17766. if (ctx->lua_background_state) {
  17767. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17768. ctx->lua_bg_log_available = 0;
  17769. /* call "stop()" in Lua */
  17770. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17771. lua_getglobal(lstate, "stop");
  17772. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17773. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17774. if (ret != 0) {
  17775. struct mg_connection fc;
  17776. lua_cry(fake_connection(&fc, ctx),
  17777. ret,
  17778. lstate,
  17779. "lua_background_script",
  17780. "stop");
  17781. }
  17782. }
  17783. DEBUG_TRACE("Close Lua background state %p", lstate);
  17784. lua_close(lstate);
  17785. ctx->lua_background_state = 0;
  17786. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17787. }
  17788. #endif
  17789. DEBUG_TRACE("%s", "exiting");
  17790. /* call exit thread callback */
  17791. if (ctx->callbacks.exit_thread) {
  17792. /* Callback for the master thread (type 0) */
  17793. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17794. }
  17795. #if defined(_WIN32)
  17796. CloseHandle(tls.pthread_cond_helper_mutex);
  17797. #endif
  17798. pthread_setspecific(sTlsKey, NULL);
  17799. /* Signal mg_stop() that we're done.
  17800. * WARNING: This must be the very last thing this
  17801. * thread does, as ctx becomes invalid after this line. */
  17802. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17803. }
  17804. /* Threads have different return types on Windows and Unix. */
  17805. #if defined(_WIN32)
  17806. static unsigned __stdcall master_thread(void *thread_func_param)
  17807. {
  17808. master_thread_run((struct mg_context *)thread_func_param);
  17809. return 0;
  17810. }
  17811. #else
  17812. static void *
  17813. master_thread(void *thread_func_param)
  17814. {
  17815. #if !defined(__ZEPHYR__)
  17816. struct sigaction sa;
  17817. /* Ignore SIGPIPE */
  17818. memset(&sa, 0, sizeof(sa));
  17819. sa.sa_handler = SIG_IGN;
  17820. sigaction(SIGPIPE, &sa, NULL);
  17821. #endif
  17822. master_thread_run((struct mg_context *)thread_func_param);
  17823. return NULL;
  17824. }
  17825. #endif /* _WIN32 */
  17826. static void
  17827. free_context(struct mg_context *ctx)
  17828. {
  17829. int i;
  17830. struct mg_handler_info *tmp_rh;
  17831. if (ctx == NULL) {
  17832. return;
  17833. }
  17834. /* Call user callback */
  17835. if (ctx->callbacks.exit_context) {
  17836. ctx->callbacks.exit_context(ctx);
  17837. }
  17838. /* All threads exited, no sync is needed. Destroy thread mutex and
  17839. * condvars
  17840. */
  17841. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17842. #if defined(ALTERNATIVE_QUEUE)
  17843. mg_free(ctx->client_socks);
  17844. if (ctx->client_wait_events != NULL) {
  17845. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  17846. event_destroy(ctx->client_wait_events[i]);
  17847. }
  17848. mg_free(ctx->client_wait_events);
  17849. }
  17850. #else
  17851. (void)pthread_cond_destroy(&ctx->sq_empty);
  17852. (void)pthread_cond_destroy(&ctx->sq_full);
  17853. mg_free(ctx->squeue);
  17854. #endif
  17855. /* Destroy other context global data structures mutex */
  17856. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17857. #if defined(USE_LUA)
  17858. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17859. #endif
  17860. /* Deallocate shutdown-triggering socket-pair */
  17861. if (ctx->user_shutdown_notification_socket >= 0) {
  17862. closesocket(ctx->user_shutdown_notification_socket);
  17863. }
  17864. if (ctx->thread_shutdown_notification_socket >= 0) {
  17865. closesocket(ctx->thread_shutdown_notification_socket);
  17866. }
  17867. /* Deallocate config parameters */
  17868. for (i = 0; i < NUM_OPTIONS; i++) {
  17869. if (ctx->dd.config[i] != NULL) {
  17870. #if defined(_MSC_VER)
  17871. #pragma warning(suppress : 6001)
  17872. #endif
  17873. mg_free(ctx->dd.config[i]);
  17874. }
  17875. }
  17876. /* Deallocate request handlers */
  17877. while (ctx->dd.handlers) {
  17878. tmp_rh = ctx->dd.handlers;
  17879. ctx->dd.handlers = tmp_rh->next;
  17880. mg_free(tmp_rh->uri);
  17881. mg_free(tmp_rh);
  17882. }
  17883. #if defined(USE_MBEDTLS)
  17884. if (ctx->dd.ssl_ctx != NULL) {
  17885. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17886. mg_free(ctx->dd.ssl_ctx);
  17887. ctx->dd.ssl_ctx = NULL;
  17888. }
  17889. #elif !defined(NO_SSL)
  17890. /* Deallocate SSL context */
  17891. if (ctx->dd.ssl_ctx != NULL) {
  17892. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17893. int callback_ret =
  17894. (ctx->callbacks.external_ssl_ctx == NULL)
  17895. ? 0
  17896. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17897. if (callback_ret == 0) {
  17898. SSL_CTX_free(ctx->dd.ssl_ctx);
  17899. }
  17900. /* else: ignore error and omit SSL_CTX_free in case
  17901. * callback_ret is 1 */
  17902. }
  17903. #endif /* !NO_SSL */
  17904. /* Deallocate worker thread ID array */
  17905. mg_free(ctx->worker_threadids);
  17906. /* Deallocate worker thread ID array */
  17907. mg_free(ctx->worker_connections);
  17908. /* deallocate system name string */
  17909. mg_free(ctx->systemName);
  17910. /* Deallocate context itself */
  17911. mg_free(ctx);
  17912. }
  17913. CIVETWEB_API void
  17914. mg_stop(struct mg_context *ctx)
  17915. {
  17916. pthread_t mt;
  17917. if (!ctx) {
  17918. return;
  17919. }
  17920. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17921. * two threads is not allowed. */
  17922. mt = ctx->masterthreadid;
  17923. if (mt == 0) {
  17924. return;
  17925. }
  17926. ctx->masterthreadid = 0;
  17927. /* Set stop flag, so all threads know they have to exit. */
  17928. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17929. /* Closing this socket will cause mg_poll() in all the I/O threads to return
  17930. * immediately */
  17931. closesocket(ctx->user_shutdown_notification_socket);
  17932. ctx->user_shutdown_notification_socket =
  17933. -1; /* to avoid calling closesocket() again in free_context() */
  17934. /* Join timer thread */
  17935. #if defined(USE_TIMERS)
  17936. timers_exit(ctx);
  17937. #endif
  17938. /* Wait until everything has stopped. */
  17939. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17940. (void)mg_sleep(10);
  17941. }
  17942. /* Wait to stop master thread */
  17943. mg_join_thread(mt);
  17944. /* Close remaining Lua states */
  17945. #if defined(USE_LUA)
  17946. lua_ctx_exit(ctx);
  17947. #endif
  17948. /* Free memory */
  17949. free_context(ctx);
  17950. }
  17951. static void
  17952. get_system_name(char **sysName)
  17953. {
  17954. #if defined(_WIN32)
  17955. char name[128];
  17956. DWORD dwVersion = 0;
  17957. DWORD dwMajorVersion = 0;
  17958. DWORD dwMinorVersion = 0;
  17959. DWORD dwBuild = 0;
  17960. BOOL wowRet, isWoW = FALSE;
  17961. #if defined(_MSC_VER)
  17962. #pragma warning(push)
  17963. /* GetVersion was declared deprecated */
  17964. #pragma warning(disable : 4996)
  17965. #endif
  17966. dwVersion = GetVersion();
  17967. #if defined(_MSC_VER)
  17968. #pragma warning(pop)
  17969. #endif
  17970. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17971. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17972. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17973. (void)dwBuild;
  17974. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17975. sprintf(name,
  17976. "Windows %u.%u%s",
  17977. (unsigned)dwMajorVersion,
  17978. (unsigned)dwMinorVersion,
  17979. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17980. *sysName = mg_strdup(name);
  17981. #elif defined(__ZEPHYR__)
  17982. *sysName = mg_strdup("Zephyr OS");
  17983. #else
  17984. struct utsname name;
  17985. memset(&name, 0, sizeof(name));
  17986. uname(&name);
  17987. *sysName = mg_strdup(name.sysname);
  17988. #endif
  17989. }
  17990. static void
  17991. legacy_init(const char **options)
  17992. {
  17993. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17994. if (options) {
  17995. const char **run_options = options;
  17996. const char *optname = config_options[LISTENING_PORTS].name;
  17997. /* Try to find the "listening_ports" option */
  17998. while (*run_options) {
  17999. if (!strcmp(*run_options, optname)) {
  18000. ports_option = run_options[1];
  18001. }
  18002. run_options += 2;
  18003. }
  18004. }
  18005. if (is_ssl_port_used(ports_option)) {
  18006. /* Initialize with SSL support */
  18007. mg_init_library(MG_FEATURES_TLS);
  18008. } else {
  18009. /* Initialize without SSL support */
  18010. mg_init_library(MG_FEATURES_DEFAULT);
  18011. }
  18012. }
  18013. /* we'll assume it's only Windows that doesn't have socketpair() available */
  18014. #if !defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  18015. #define HAVE_SOCKETPAIR 1
  18016. #endif
  18017. static int
  18018. mg_socketpair(int *sockA, int *sockB)
  18019. {
  18020. int temp[2] = {-1, -1};
  18021. int asock = -1;
  18022. /** Default to unallocated */
  18023. *sockA = -1;
  18024. *sockB = -1;
  18025. #if defined(HAVE_SOCKETPAIR)
  18026. int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, temp);
  18027. if (ret == 0) {
  18028. *sockA = temp[0];
  18029. *sockB = temp[1];
  18030. set_close_on_exec(*sockA, NULL, NULL);
  18031. set_close_on_exec(*sockB, NULL, NULL);
  18032. }
  18033. (void)asock; /* not used */
  18034. return ret;
  18035. #else
  18036. /** No socketpair() call is available, so we'll have to roll our own
  18037. * implementation */
  18038. asock = socket(PF_INET, SOCK_STREAM, 0);
  18039. if (asock >= 0) {
  18040. struct sockaddr_in addr;
  18041. struct sockaddr *pa = (struct sockaddr *)&addr;
  18042. socklen_t addrLen = sizeof(addr);
  18043. memset(&addr, 0, sizeof(addr));
  18044. addr.sin_family = AF_INET;
  18045. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18046. addr.sin_port = 0;
  18047. if ((bind(asock, pa, sizeof(addr)) == 0)
  18048. && (getsockname(asock, pa, &addrLen) == 0)
  18049. && (listen(asock, 1) == 0)) {
  18050. temp[0] = socket(PF_INET, SOCK_STREAM, 0);
  18051. if ((temp[0] >= 0) && (connect(temp[0], pa, sizeof(addr)) == 0)) {
  18052. temp[1] = accept(asock, pa, &addrLen);
  18053. if (temp[1] >= 0) {
  18054. closesocket(asock);
  18055. *sockA = temp[0];
  18056. *sockB = temp[1];
  18057. set_close_on_exec(*sockA, NULL, NULL);
  18058. set_close_on_exec(*sockB, NULL, NULL);
  18059. return 0; /* success! */
  18060. }
  18061. }
  18062. }
  18063. }
  18064. /* Cleanup */
  18065. if (asock >= 0)
  18066. closesocket(asock);
  18067. if (temp[0] >= 0)
  18068. closesocket(temp[0]);
  18069. if (temp[1] >= 0)
  18070. closesocket(temp[1]);
  18071. return -1; /* fail! */
  18072. #endif
  18073. }
  18074. static int
  18075. mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads)
  18076. {
  18077. const unsigned int i = ctx->spawned_worker_threads;
  18078. if (i >= ctx->cfg_max_worker_threads) {
  18079. return -1; /* Oops, we hit our worker-thread limit! No more worker
  18080. threads, ever! */
  18081. }
  18082. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18083. #if defined(ALTERNATIVE_QUEUE)
  18084. if ((only_if_no_idle_threads) && (ctx->idle_worker_thread_count > 0)) {
  18085. #else
  18086. if ((only_if_no_idle_threads)
  18087. && (ctx->idle_worker_thread_count
  18088. > (unsigned)(ctx->sq_head - ctx->sq_tail))) {
  18089. #endif
  18090. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18091. return -2; /* There are idle threads available, so no need to spawn a
  18092. new worker thread now */
  18093. }
  18094. ctx->idle_worker_thread_count++; /* we do this here to avoid a race
  18095. condition while the thread is starting
  18096. up */
  18097. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18098. ctx->worker_connections[i].phys_ctx = ctx;
  18099. int ret = mg_start_thread_with_id(worker_thread,
  18100. &ctx->worker_connections[i],
  18101. &ctx->worker_threadids[i]);
  18102. if (ret == 0) {
  18103. ctx->spawned_worker_threads++; /* note that we've filled another slot in
  18104. the table */
  18105. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  18106. } else {
  18107. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18108. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  18109. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18110. }
  18111. return ret;
  18112. }
  18113. CIVETWEB_API struct mg_context *
  18114. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  18115. {
  18116. struct mg_context *ctx;
  18117. const char *name, *value, *default_value;
  18118. int idx, ok, prespawnthreadcount, workerthreadcount;
  18119. unsigned int i;
  18120. int itmp;
  18121. void (*exit_callback)(const struct mg_context *ctx) = 0;
  18122. const char **options =
  18123. ((init != NULL) ? (init->configuration_options) : (NULL));
  18124. struct mg_workerTLS tls;
  18125. if (error != NULL) {
  18126. error->code = MG_ERROR_DATA_CODE_OK;
  18127. error->code_sub = 0;
  18128. if (error->text_buffer_size > 0) {
  18129. *error->text = 0;
  18130. }
  18131. }
  18132. if (mg_init_library_called == 0) {
  18133. /* Legacy INIT, if mg_start is called without mg_init_library.
  18134. * Note: This will cause a memory leak when unloading the library.
  18135. */
  18136. legacy_init(options);
  18137. }
  18138. if (mg_init_library_called == 0) {
  18139. if (error != NULL) {
  18140. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  18141. mg_snprintf(NULL,
  18142. NULL, /* No truncation check for error buffers */
  18143. error->text,
  18144. error->text_buffer_size,
  18145. "%s",
  18146. "Library uninitialized");
  18147. }
  18148. return NULL;
  18149. }
  18150. /* Allocate context and initialize reasonable general case defaults. */
  18151. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  18152. if (ctx == NULL) {
  18153. if (error != NULL) {
  18154. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18155. error->code_sub = (unsigned)sizeof(*ctx);
  18156. mg_snprintf(NULL,
  18157. NULL, /* No truncation check for error buffers */
  18158. error->text,
  18159. error->text_buffer_size,
  18160. "%s",
  18161. "Out of memory");
  18162. }
  18163. return NULL;
  18164. }
  18165. /* Random number generator will initialize at the first call */
  18166. ctx->dd.auth_nonce_mask =
  18167. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  18168. /* Save started thread index to reuse in other external API calls
  18169. * For the sake of thread synchronization all non-civetweb threads
  18170. * can be considered as single external thread */
  18171. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  18172. tls.is_master = -1; /* Thread calling mg_start */
  18173. tls.thread_idx = ctx->starter_thread_idx;
  18174. #if defined(_WIN32)
  18175. tls.pthread_cond_helper_mutex = NULL;
  18176. #endif
  18177. pthread_setspecific(sTlsKey, &tls);
  18178. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  18179. #if !defined(ALTERNATIVE_QUEUE)
  18180. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  18181. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  18182. ctx->sq_blocked = 0;
  18183. #endif
  18184. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  18185. #if defined(USE_LUA)
  18186. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  18187. #endif
  18188. /** mg_stop() will close the user_shutdown_notification_socket, and that
  18189. * will cause poll() to return immediately in the master-thread, so that
  18190. * mg_stop() can also return immediately.
  18191. */
  18192. ok &= (0
  18193. == mg_socketpair(&ctx->user_shutdown_notification_socket,
  18194. &ctx->thread_shutdown_notification_socket));
  18195. if (!ok) {
  18196. unsigned error_id = (unsigned)ERRNO;
  18197. const char *err_msg =
  18198. "Cannot initialize thread synchronization objects";
  18199. /* Fatal error - abort start. However, this situation should never
  18200. * occur in practice. */
  18201. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18202. if (error != NULL) {
  18203. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18204. error->code_sub = error_id;
  18205. mg_snprintf(NULL,
  18206. NULL, /* No truncation check for error buffers */
  18207. error->text,
  18208. error->text_buffer_size,
  18209. "%s",
  18210. err_msg);
  18211. }
  18212. mg_free(ctx);
  18213. pthread_setspecific(sTlsKey, NULL);
  18214. return NULL;
  18215. }
  18216. if ((init != NULL) && (init->callbacks != NULL)) {
  18217. /* Set all callbacks except exit_context. */
  18218. ctx->callbacks = *init->callbacks;
  18219. exit_callback = init->callbacks->exit_context;
  18220. /* The exit callback is activated once the context is successfully
  18221. * created. It should not be called, if an incomplete context object
  18222. * is deleted during a failed initialization. */
  18223. ctx->callbacks.exit_context = 0;
  18224. }
  18225. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  18226. ctx->dd.handlers = NULL;
  18227. ctx->dd.next = NULL;
  18228. #if defined(USE_LUA)
  18229. lua_ctx_init(ctx);
  18230. #endif
  18231. /* Store options */
  18232. while (options && (name = *options++) != NULL) {
  18233. idx = get_option_index(name);
  18234. if (idx == -1) {
  18235. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18236. if (error != NULL) {
  18237. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18238. error->code_sub = (unsigned)-1;
  18239. mg_snprintf(NULL,
  18240. NULL, /* No truncation check for error buffers */
  18241. error->text,
  18242. error->text_buffer_size,
  18243. "Invalid configuration option: %s",
  18244. name);
  18245. }
  18246. free_context(ctx);
  18247. pthread_setspecific(sTlsKey, NULL);
  18248. return NULL;
  18249. } else if ((value = *options++) == NULL) {
  18250. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18251. if (error != NULL) {
  18252. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18253. error->code_sub = (unsigned)idx;
  18254. mg_snprintf(NULL,
  18255. NULL, /* No truncation check for error buffers */
  18256. error->text,
  18257. error->text_buffer_size,
  18258. "Invalid configuration option value: %s",
  18259. name);
  18260. }
  18261. free_context(ctx);
  18262. pthread_setspecific(sTlsKey, NULL);
  18263. return NULL;
  18264. }
  18265. if (ctx->dd.config[idx] != NULL) {
  18266. /* A duplicate configuration option is not an error - the last
  18267. * option value will be used. */
  18268. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18269. mg_free(ctx->dd.config[idx]);
  18270. }
  18271. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  18272. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18273. }
  18274. /* Set default value if needed */
  18275. for (i = 0; config_options[i].name != NULL; i++) {
  18276. default_value = config_options[i].default_value;
  18277. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  18278. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  18279. }
  18280. }
  18281. /* Request size option */
  18282. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  18283. if (itmp < 1024) {
  18284. mg_cry_ctx_internal(ctx,
  18285. "%s too small",
  18286. config_options[MAX_REQUEST_SIZE].name);
  18287. if (error != NULL) {
  18288. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18289. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  18290. mg_snprintf(NULL,
  18291. NULL, /* No truncation check for error buffers */
  18292. error->text,
  18293. error->text_buffer_size,
  18294. "Invalid configuration option value: %s",
  18295. config_options[MAX_REQUEST_SIZE].name);
  18296. }
  18297. free_context(ctx);
  18298. pthread_setspecific(sTlsKey, NULL);
  18299. return NULL;
  18300. }
  18301. ctx->max_request_size = (unsigned)itmp;
  18302. /* Queue length */
  18303. #if !defined(ALTERNATIVE_QUEUE)
  18304. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  18305. if (itmp < 1) {
  18306. mg_cry_ctx_internal(ctx,
  18307. "%s too small",
  18308. config_options[CONNECTION_QUEUE_SIZE].name);
  18309. if (error != NULL) {
  18310. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18311. error->code_sub = CONNECTION_QUEUE_SIZE;
  18312. mg_snprintf(NULL,
  18313. NULL, /* No truncation check for error buffers */
  18314. error->text,
  18315. error->text_buffer_size,
  18316. "Invalid configuration option value: %s",
  18317. config_options[CONNECTION_QUEUE_SIZE].name);
  18318. }
  18319. free_context(ctx);
  18320. pthread_setspecific(sTlsKey, NULL);
  18321. return NULL;
  18322. }
  18323. ctx->squeue =
  18324. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  18325. if (ctx->squeue == NULL) {
  18326. mg_cry_ctx_internal(ctx,
  18327. "Out of memory: Cannot allocate %s",
  18328. config_options[CONNECTION_QUEUE_SIZE].name);
  18329. if (error != NULL) {
  18330. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18331. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  18332. mg_snprintf(NULL,
  18333. NULL, /* No truncation check for error buffers */
  18334. error->text,
  18335. error->text_buffer_size,
  18336. "Out of memory: Cannot allocate %s",
  18337. config_options[CONNECTION_QUEUE_SIZE].name);
  18338. }
  18339. free_context(ctx);
  18340. pthread_setspecific(sTlsKey, NULL);
  18341. return NULL;
  18342. }
  18343. ctx->sq_size = itmp;
  18344. #endif
  18345. /* Worker thread count option */
  18346. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18347. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18348. if ((prespawnthreadcount < 0)
  18349. || (prespawnthreadcount > workerthreadcount)) {
  18350. prespawnthreadcount =
  18351. workerthreadcount; /* can't prespawn more than all of them! */
  18352. }
  18353. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18354. if (workerthreadcount <= 0) {
  18355. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18356. } else {
  18357. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18358. }
  18359. if (error != NULL) {
  18360. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18361. error->code_sub = NUM_THREADS;
  18362. mg_snprintf(NULL,
  18363. NULL, /* No truncation check for error buffers */
  18364. error->text,
  18365. error->text_buffer_size,
  18366. "Invalid configuration option value: %s",
  18367. config_options[NUM_THREADS].name);
  18368. }
  18369. free_context(ctx);
  18370. pthread_setspecific(sTlsKey, NULL);
  18371. return NULL;
  18372. }
  18373. /* Document root */
  18374. #if defined(NO_FILES)
  18375. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18376. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18377. if (error != NULL) {
  18378. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18379. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18380. mg_snprintf(NULL,
  18381. NULL, /* No truncation check for error buffers */
  18382. error->text,
  18383. error->text_buffer_size,
  18384. "Invalid configuration option value: %s",
  18385. config_options[DOCUMENT_ROOT].name);
  18386. }
  18387. free_context(ctx);
  18388. pthread_setspecific(sTlsKey, NULL);
  18389. return NULL;
  18390. }
  18391. #endif
  18392. get_system_name(&ctx->systemName);
  18393. #if defined(USE_LUA)
  18394. /* If a Lua background script has been configured, start it. */
  18395. ctx->lua_bg_log_available = 0;
  18396. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18397. char ebuf[256];
  18398. struct vec opt_vec;
  18399. struct vec eq_vec;
  18400. const char *sparams;
  18401. memset(ebuf, 0, sizeof(ebuf));
  18402. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18403. /* Create a Lua state, load all standard libraries and the mg table */
  18404. lua_State *state = mg_lua_context_script_prepare(
  18405. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18406. if (!state) {
  18407. mg_cry_ctx_internal(ctx,
  18408. "lua_background_script load error: %s",
  18409. ebuf);
  18410. if (error != NULL) {
  18411. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18412. mg_snprintf(NULL,
  18413. NULL, /* No truncation check for error buffers */
  18414. error->text,
  18415. error->text_buffer_size,
  18416. "Error in script %s: %s",
  18417. config_options[LUA_BACKGROUND_SCRIPT].name,
  18418. ebuf);
  18419. }
  18420. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18421. free_context(ctx);
  18422. pthread_setspecific(sTlsKey, NULL);
  18423. return NULL;
  18424. }
  18425. /* Add a table with parameters into mg.params */
  18426. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18427. if (sparams && sparams[0]) {
  18428. lua_getglobal(state, "mg");
  18429. lua_pushstring(state, "params");
  18430. lua_newtable(state);
  18431. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18432. != NULL) {
  18433. reg_llstring(
  18434. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18435. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18436. break;
  18437. }
  18438. lua_rawset(state, -3);
  18439. lua_pop(state, 1);
  18440. }
  18441. /* Call script */
  18442. state = mg_lua_context_script_run(state,
  18443. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18444. ctx,
  18445. ebuf,
  18446. sizeof(ebuf));
  18447. if (!state) {
  18448. mg_cry_ctx_internal(ctx,
  18449. "lua_background_script start error: %s",
  18450. ebuf);
  18451. if (error != NULL) {
  18452. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18453. mg_snprintf(NULL,
  18454. NULL, /* No truncation check for error buffers */
  18455. error->text,
  18456. error->text_buffer_size,
  18457. "Error in script %s: %s",
  18458. config_options[DOCUMENT_ROOT].name,
  18459. ebuf);
  18460. }
  18461. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18462. free_context(ctx);
  18463. pthread_setspecific(sTlsKey, NULL);
  18464. return NULL;
  18465. }
  18466. /* state remains valid */
  18467. ctx->lua_background_state = (void *)state;
  18468. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18469. } else {
  18470. ctx->lua_background_state = 0;
  18471. }
  18472. #endif
  18473. /* Step by step initialization of ctx - depending on build options */
  18474. #if !defined(NO_FILESYSTEMS)
  18475. if (!set_gpass_option(ctx, NULL)) {
  18476. const char *err_msg = "Invalid global password file";
  18477. /* Fatal error - abort start. */
  18478. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18479. if (error != NULL) {
  18480. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18481. mg_snprintf(NULL,
  18482. NULL, /* No truncation check for error buffers */
  18483. error->text,
  18484. error->text_buffer_size,
  18485. "%s",
  18486. err_msg);
  18487. }
  18488. free_context(ctx);
  18489. pthread_setspecific(sTlsKey, NULL);
  18490. return NULL;
  18491. }
  18492. #endif
  18493. #if defined(USE_MBEDTLS)
  18494. if (!mg_sslctx_init(ctx, NULL)) {
  18495. const char *err_msg = "Error initializing SSL context";
  18496. /* Fatal error - abort start. */
  18497. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18498. if (error != NULL) {
  18499. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18500. mg_snprintf(NULL,
  18501. NULL, /* No truncation check for error buffers */
  18502. error->text,
  18503. error->text_buffer_size,
  18504. "%s",
  18505. err_msg);
  18506. }
  18507. free_context(ctx);
  18508. pthread_setspecific(sTlsKey, NULL);
  18509. return NULL;
  18510. }
  18511. #elif !defined(NO_SSL)
  18512. if (!init_ssl_ctx(ctx, NULL)) {
  18513. const char *err_msg = "Error initializing SSL context";
  18514. /* Fatal error - abort start. */
  18515. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18516. if (error != NULL) {
  18517. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18518. mg_snprintf(NULL,
  18519. NULL, /* No truncation check for error buffers */
  18520. error->text,
  18521. error->text_buffer_size,
  18522. "%s",
  18523. err_msg);
  18524. }
  18525. free_context(ctx);
  18526. pthread_setspecific(sTlsKey, NULL);
  18527. return NULL;
  18528. }
  18529. #endif
  18530. if (!set_ports_option(ctx)) {
  18531. const char *err_msg = "Failed to setup server ports";
  18532. /* Fatal error - abort start. */
  18533. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18534. if (error != NULL) {
  18535. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18536. mg_snprintf(NULL,
  18537. NULL, /* No truncation check for error buffers */
  18538. error->text,
  18539. error->text_buffer_size,
  18540. "%s",
  18541. err_msg);
  18542. }
  18543. free_context(ctx);
  18544. pthread_setspecific(sTlsKey, NULL);
  18545. return NULL;
  18546. }
  18547. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18548. if (!set_uid_option(ctx)) {
  18549. const char *err_msg = "Failed to run as configured user";
  18550. /* Fatal error - abort start. */
  18551. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18552. if (error != NULL) {
  18553. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18554. mg_snprintf(NULL,
  18555. NULL, /* No truncation check for error buffers */
  18556. error->text,
  18557. error->text_buffer_size,
  18558. "%s",
  18559. err_msg);
  18560. }
  18561. free_context(ctx);
  18562. pthread_setspecific(sTlsKey, NULL);
  18563. return NULL;
  18564. }
  18565. #endif
  18566. if (!set_acl_option(ctx)) {
  18567. const char *err_msg = "Failed to setup access control list";
  18568. /* Fatal error - abort start. */
  18569. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18570. if (error != NULL) {
  18571. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18572. mg_snprintf(NULL,
  18573. NULL, /* No truncation check for error buffers */
  18574. error->text,
  18575. error->text_buffer_size,
  18576. "%s",
  18577. err_msg);
  18578. }
  18579. free_context(ctx);
  18580. pthread_setspecific(sTlsKey, NULL);
  18581. return NULL;
  18582. }
  18583. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18584. ctx->worker_threadids =
  18585. (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18586. sizeof(pthread_t),
  18587. ctx);
  18588. if (ctx->worker_threadids == NULL) {
  18589. const char *err_msg = "Not enough memory for worker thread ID array";
  18590. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18591. if (error != NULL) {
  18592. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18593. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18594. * (unsigned)sizeof(pthread_t);
  18595. mg_snprintf(NULL,
  18596. NULL, /* No truncation check for error buffers */
  18597. error->text,
  18598. error->text_buffer_size,
  18599. "%s",
  18600. err_msg);
  18601. }
  18602. free_context(ctx);
  18603. pthread_setspecific(sTlsKey, NULL);
  18604. return NULL;
  18605. }
  18606. ctx->worker_connections =
  18607. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18608. sizeof(struct mg_connection),
  18609. ctx);
  18610. if (ctx->worker_connections == NULL) {
  18611. const char *err_msg =
  18612. "Not enough memory for worker thread connection array";
  18613. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18614. if (error != NULL) {
  18615. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18616. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18617. * (unsigned)sizeof(struct mg_connection);
  18618. mg_snprintf(NULL,
  18619. NULL, /* No truncation check for error buffers */
  18620. error->text,
  18621. error->text_buffer_size,
  18622. "%s",
  18623. err_msg);
  18624. }
  18625. free_context(ctx);
  18626. pthread_setspecific(sTlsKey, NULL);
  18627. return NULL;
  18628. }
  18629. #if defined(ALTERNATIVE_QUEUE)
  18630. ctx->client_wait_events =
  18631. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18632. sizeof(ctx->client_wait_events[0]),
  18633. ctx);
  18634. if (ctx->client_wait_events == NULL) {
  18635. const char *err_msg = "Not enough memory for worker event array";
  18636. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18637. mg_free(ctx->worker_threadids);
  18638. if (error != NULL) {
  18639. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18640. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18641. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18642. mg_snprintf(NULL,
  18643. NULL, /* No truncation check for error buffers */
  18644. error->text,
  18645. error->text_buffer_size,
  18646. "%s",
  18647. err_msg);
  18648. }
  18649. free_context(ctx);
  18650. pthread_setspecific(sTlsKey, NULL);
  18651. return NULL;
  18652. }
  18653. ctx->client_socks =
  18654. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18655. sizeof(ctx->client_socks[0]),
  18656. ctx);
  18657. if (ctx->client_socks == NULL) {
  18658. const char *err_msg = "Not enough memory for worker socket array";
  18659. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18660. mg_free(ctx->client_wait_events);
  18661. mg_free(ctx->worker_threadids);
  18662. if (error != NULL) {
  18663. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18664. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18665. * (unsigned)sizeof(ctx->client_socks[0]);
  18666. mg_snprintf(NULL,
  18667. NULL, /* No truncation check for error buffers */
  18668. error->text,
  18669. error->text_buffer_size,
  18670. "%s",
  18671. err_msg);
  18672. }
  18673. free_context(ctx);
  18674. pthread_setspecific(sTlsKey, NULL);
  18675. return NULL;
  18676. }
  18677. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18678. ctx->client_wait_events[i] = event_create();
  18679. if (ctx->client_wait_events[i] == 0) {
  18680. const char *err_msg = "Error creating worker event %i";
  18681. mg_cry_ctx_internal(ctx, err_msg, i);
  18682. while (i > 0) {
  18683. i--;
  18684. event_destroy(ctx->client_wait_events[i]);
  18685. }
  18686. mg_free(ctx->client_socks);
  18687. mg_free(ctx->client_wait_events);
  18688. mg_free(ctx->worker_threadids);
  18689. if (error != NULL) {
  18690. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18691. error->code_sub = (unsigned)ERRNO;
  18692. mg_snprintf(NULL,
  18693. NULL, /* No truncation check for error buffers */
  18694. error->text,
  18695. error->text_buffer_size,
  18696. err_msg,
  18697. i);
  18698. }
  18699. free_context(ctx);
  18700. pthread_setspecific(sTlsKey, NULL);
  18701. return NULL;
  18702. }
  18703. }
  18704. #endif
  18705. #if defined(USE_TIMERS)
  18706. if (timers_init(ctx) != 0) {
  18707. const char *err_msg = "Error creating timers";
  18708. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18709. if (error != NULL) {
  18710. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18711. error->code_sub = (unsigned)ERRNO;
  18712. mg_snprintf(NULL,
  18713. NULL, /* No truncation check for error buffers */
  18714. error->text,
  18715. error->text_buffer_size,
  18716. "%s",
  18717. err_msg);
  18718. }
  18719. free_context(ctx);
  18720. pthread_setspecific(sTlsKey, NULL);
  18721. return NULL;
  18722. }
  18723. #endif
  18724. /* Context has been created - init user libraries */
  18725. if (ctx->callbacks.init_context) {
  18726. ctx->callbacks.init_context(ctx);
  18727. }
  18728. /* From now, the context is successfully created.
  18729. * When it is destroyed, the exit callback should be called. */
  18730. ctx->callbacks.exit_context = exit_callback;
  18731. ctx->context_type = CONTEXT_SERVER; /* server context */
  18732. /* Start worker threads */
  18733. for (i = 0; (int)i < prespawnthreadcount; i++) {
  18734. /* worker_thread sets up the other fields */
  18735. if (mg_start_worker_thread(ctx, 0) != 0) {
  18736. long error_no = (long)ERRNO;
  18737. /* thread was not created */
  18738. if (ctx->spawned_worker_threads > 0) {
  18739. /* If the second, third, ... thread cannot be created, set a
  18740. * warning, but keep running. */
  18741. mg_cry_ctx_internal(ctx,
  18742. "Cannot start worker thread %i: error %ld",
  18743. ctx->spawned_worker_threads + 1,
  18744. error_no);
  18745. /* If the server initialization should stop here, all
  18746. * threads that have already been created must be stopped
  18747. * first, before any free_context(ctx) call.
  18748. */
  18749. } else {
  18750. /* If the first worker thread cannot be created, stop
  18751. * initialization and free the entire server context. */
  18752. mg_cry_ctx_internal(ctx,
  18753. "Cannot create threads: error %ld",
  18754. error_no);
  18755. if (error != NULL) {
  18756. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18757. error->code_sub = (unsigned)error_no;
  18758. mg_snprintf(
  18759. NULL,
  18760. NULL, /* No truncation check for error buffers */
  18761. error->text,
  18762. error->text_buffer_size,
  18763. "Cannot create first worker thread: error %ld",
  18764. error_no);
  18765. }
  18766. free_context(ctx);
  18767. pthread_setspecific(sTlsKey, NULL);
  18768. return NULL;
  18769. }
  18770. break;
  18771. }
  18772. }
  18773. /* Start master (listening) thread */
  18774. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18775. pthread_setspecific(sTlsKey, NULL);
  18776. return ctx;
  18777. }
  18778. CIVETWEB_API struct mg_context *
  18779. mg_start(const struct mg_callbacks *callbacks,
  18780. void *user_data,
  18781. const char **options)
  18782. {
  18783. struct mg_init_data init = {0};
  18784. init.callbacks = callbacks;
  18785. init.user_data = user_data;
  18786. init.configuration_options = options;
  18787. return mg_start2(&init, NULL);
  18788. }
  18789. /* Add an additional domain to an already running web server. */
  18790. CIVETWEB_API int
  18791. mg_start_domain2(struct mg_context *ctx,
  18792. const char **options,
  18793. struct mg_error_data *error)
  18794. {
  18795. const char *name;
  18796. const char *value;
  18797. const char *default_value;
  18798. struct mg_domain_context *new_dom;
  18799. struct mg_domain_context *dom;
  18800. int idx, i;
  18801. if (error != NULL) {
  18802. error->code = MG_ERROR_DATA_CODE_OK;
  18803. error->code_sub = 0;
  18804. if (error->text_buffer_size > 0) {
  18805. *error->text = 0;
  18806. }
  18807. }
  18808. if ((ctx == NULL) || (options == NULL)) {
  18809. if (error != NULL) {
  18810. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18811. mg_snprintf(NULL,
  18812. NULL, /* No truncation check for error buffers */
  18813. error->text,
  18814. error->text_buffer_size,
  18815. "%s",
  18816. "Invalid parameters");
  18817. }
  18818. return -1;
  18819. }
  18820. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18821. if (error != NULL) {
  18822. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18823. mg_snprintf(NULL,
  18824. NULL, /* No truncation check for error buffers */
  18825. error->text,
  18826. error->text_buffer_size,
  18827. "%s",
  18828. "Server already stopped");
  18829. }
  18830. return -7;
  18831. }
  18832. new_dom = (struct mg_domain_context *)
  18833. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18834. if (!new_dom) {
  18835. /* Out of memory */
  18836. if (error != NULL) {
  18837. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18838. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18839. mg_snprintf(NULL,
  18840. NULL, /* No truncation check for error buffers */
  18841. error->text,
  18842. error->text_buffer_size,
  18843. "%s",
  18844. "Out or memory");
  18845. }
  18846. return -6;
  18847. }
  18848. /* Store options - TODO: unite duplicate code */
  18849. while (options && (name = *options++) != NULL) {
  18850. idx = get_option_index(name);
  18851. if (idx == -1) {
  18852. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18853. if (error != NULL) {
  18854. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18855. error->code_sub = (unsigned)-1;
  18856. mg_snprintf(NULL,
  18857. NULL, /* No truncation check for error buffers */
  18858. error->text,
  18859. error->text_buffer_size,
  18860. "Invalid option: %s",
  18861. name);
  18862. }
  18863. mg_free(new_dom);
  18864. return -2;
  18865. } else if ((value = *options++) == NULL) {
  18866. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18867. if (error != NULL) {
  18868. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18869. error->code_sub = (unsigned)idx;
  18870. mg_snprintf(NULL,
  18871. NULL, /* No truncation check for error buffers */
  18872. error->text,
  18873. error->text_buffer_size,
  18874. "Invalid option value: %s",
  18875. name);
  18876. }
  18877. mg_free(new_dom);
  18878. return -2;
  18879. }
  18880. if (new_dom->config[idx] != NULL) {
  18881. /* Duplicate option: Later values overwrite earlier ones. */
  18882. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18883. mg_free(new_dom->config[idx]);
  18884. }
  18885. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18886. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18887. }
  18888. /* Authentication domain is mandatory */
  18889. /* TODO: Maybe use a new option hostname? */
  18890. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18891. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18892. if (error != NULL) {
  18893. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18894. error->code_sub = AUTHENTICATION_DOMAIN;
  18895. mg_snprintf(NULL,
  18896. NULL, /* No truncation check for error buffers */
  18897. error->text,
  18898. error->text_buffer_size,
  18899. "Mandatory option %s missing",
  18900. config_options[AUTHENTICATION_DOMAIN].name);
  18901. }
  18902. mg_free(new_dom);
  18903. return -4;
  18904. }
  18905. /* Set default value if needed. Take the config value from
  18906. * ctx as a default value. */
  18907. for (i = 0; config_options[i].name != NULL; i++) {
  18908. default_value = ctx->dd.config[i];
  18909. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18910. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18911. }
  18912. }
  18913. new_dom->handlers = NULL;
  18914. new_dom->next = NULL;
  18915. new_dom->nonce_count = 0;
  18916. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18917. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18918. new_dom->shared_lua_websockets = NULL;
  18919. #endif
  18920. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18921. if (!init_ssl_ctx(ctx, new_dom)) {
  18922. /* Init SSL failed */
  18923. if (error != NULL) {
  18924. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18925. mg_snprintf(NULL,
  18926. NULL, /* No truncation check for error buffers */
  18927. error->text,
  18928. error->text_buffer_size,
  18929. "%s",
  18930. "Initializing SSL context failed");
  18931. }
  18932. mg_free(new_dom);
  18933. return -3;
  18934. }
  18935. #endif
  18936. /* Add element to linked list. */
  18937. mg_lock_context(ctx);
  18938. idx = 0;
  18939. dom = &(ctx->dd);
  18940. for (;;) {
  18941. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18942. dom->config[AUTHENTICATION_DOMAIN])) {
  18943. /* Domain collision */
  18944. mg_cry_ctx_internal(ctx,
  18945. "domain %s already in use",
  18946. new_dom->config[AUTHENTICATION_DOMAIN]);
  18947. if (error != NULL) {
  18948. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18949. mg_snprintf(NULL,
  18950. NULL, /* No truncation check for error buffers */
  18951. error->text,
  18952. error->text_buffer_size,
  18953. "Domain %s specified by %s is already in use",
  18954. new_dom->config[AUTHENTICATION_DOMAIN],
  18955. config_options[AUTHENTICATION_DOMAIN].name);
  18956. }
  18957. mg_free(new_dom);
  18958. mg_unlock_context(ctx);
  18959. return -5;
  18960. }
  18961. /* Count number of domains */
  18962. idx++;
  18963. if (dom->next == NULL) {
  18964. dom->next = new_dom;
  18965. break;
  18966. }
  18967. dom = dom->next;
  18968. }
  18969. mg_unlock_context(ctx);
  18970. /* Return domain number */
  18971. return idx;
  18972. }
  18973. CIVETWEB_API int
  18974. mg_start_domain(struct mg_context *ctx, const char **options)
  18975. {
  18976. return mg_start_domain2(ctx, options, NULL);
  18977. }
  18978. /* Feature check API function */
  18979. CIVETWEB_API unsigned
  18980. mg_check_feature(unsigned feature)
  18981. {
  18982. static const unsigned feature_set = 0
  18983. /* Set bits for available features according to API documentation.
  18984. * This bit mask is created at compile time, according to the active
  18985. * preprocessor defines. It is a single const value at runtime. */
  18986. #if !defined(NO_FILES)
  18987. | MG_FEATURES_FILES
  18988. #endif
  18989. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18990. | MG_FEATURES_SSL
  18991. #endif
  18992. #if !defined(NO_CGI)
  18993. | MG_FEATURES_CGI
  18994. #endif
  18995. #if defined(USE_IPV6)
  18996. | MG_FEATURES_IPV6
  18997. #endif
  18998. #if defined(USE_WEBSOCKET)
  18999. | MG_FEATURES_WEBSOCKET
  19000. #endif
  19001. #if defined(USE_LUA)
  19002. | MG_FEATURES_LUA
  19003. #endif
  19004. #if defined(USE_DUKTAPE)
  19005. | MG_FEATURES_SSJS
  19006. #endif
  19007. #if !defined(NO_CACHING)
  19008. | MG_FEATURES_CACHE
  19009. #endif
  19010. #if defined(USE_SERVER_STATS)
  19011. | MG_FEATURES_STATS
  19012. #endif
  19013. #if defined(USE_ZLIB)
  19014. | MG_FEATURES_COMPRESSION
  19015. #endif
  19016. #if defined(USE_HTTP2)
  19017. | MG_FEATURES_HTTP2
  19018. #endif
  19019. #if defined(USE_X_DOM_SOCKET)
  19020. | MG_FEATURES_X_DOMAIN_SOCKET
  19021. #endif
  19022. /* Set some extra bits not defined in the API documentation.
  19023. * These bits may change without further notice. */
  19024. #if defined(MG_LEGACY_INTERFACE)
  19025. | 0x80000000u
  19026. #endif
  19027. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19028. | 0x40000000u
  19029. #endif
  19030. #if !defined(NO_RESPONSE_BUFFERING)
  19031. | 0x20000000u
  19032. #endif
  19033. #if defined(MEMORY_DEBUGGING)
  19034. | 0x10000000u
  19035. #endif
  19036. ;
  19037. return (feature & feature_set);
  19038. }
  19039. static size_t
  19040. mg_str_append(char **dst, char *end, const char *src)
  19041. {
  19042. size_t len = strlen(src);
  19043. if (*dst != end) {
  19044. /* Append src if enough space, or close dst. */
  19045. if ((size_t)(end - *dst) > len) {
  19046. strcpy(*dst, src);
  19047. *dst += len;
  19048. } else {
  19049. *dst = end;
  19050. }
  19051. }
  19052. return len;
  19053. }
  19054. /* Get system information. It can be printed or stored by the caller.
  19055. * Return the size of available information. */
  19056. CIVETWEB_API int
  19057. mg_get_system_info(char *buffer, int buflen)
  19058. {
  19059. char *end, *append_eoobj = NULL, block[256];
  19060. size_t system_info_length = 0;
  19061. #if defined(_WIN32)
  19062. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19063. #else
  19064. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19065. #endif
  19066. if ((buffer == NULL) || (buflen < 1)) {
  19067. buflen = 0;
  19068. end = buffer;
  19069. } else {
  19070. *buffer = 0;
  19071. end = buffer + buflen;
  19072. }
  19073. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19074. /* has enough space to append eoobj */
  19075. append_eoobj = buffer;
  19076. if (end) {
  19077. end -= sizeof(eoobj) - 1;
  19078. }
  19079. }
  19080. system_info_length += mg_str_append(&buffer, end, "{");
  19081. /* Server version */
  19082. {
  19083. const char *version = mg_version();
  19084. mg_snprintf(NULL,
  19085. NULL,
  19086. block,
  19087. sizeof(block),
  19088. "%s\"version\" : \"%s\"",
  19089. eol,
  19090. version);
  19091. system_info_length += mg_str_append(&buffer, end, block);
  19092. }
  19093. /* System info */
  19094. {
  19095. #if defined(_WIN32)
  19096. DWORD dwVersion = 0;
  19097. DWORD dwMajorVersion = 0;
  19098. DWORD dwMinorVersion = 0;
  19099. SYSTEM_INFO si;
  19100. GetSystemInfo(&si);
  19101. #if defined(_MSC_VER)
  19102. #pragma warning(push)
  19103. /* GetVersion was declared deprecated */
  19104. #pragma warning(disable : 4996)
  19105. #endif
  19106. dwVersion = GetVersion();
  19107. #if defined(_MSC_VER)
  19108. #pragma warning(pop)
  19109. #endif
  19110. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  19111. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  19112. mg_snprintf(NULL,
  19113. NULL,
  19114. block,
  19115. sizeof(block),
  19116. ",%s\"os\" : \"Windows %u.%u\"",
  19117. eol,
  19118. (unsigned)dwMajorVersion,
  19119. (unsigned)dwMinorVersion);
  19120. system_info_length += mg_str_append(&buffer, end, block);
  19121. mg_snprintf(NULL,
  19122. NULL,
  19123. block,
  19124. sizeof(block),
  19125. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  19126. eol,
  19127. (unsigned)si.wProcessorArchitecture,
  19128. (unsigned)si.dwNumberOfProcessors,
  19129. (unsigned)si.dwActiveProcessorMask);
  19130. system_info_length += mg_str_append(&buffer, end, block);
  19131. #elif defined(__ZEPHYR__)
  19132. mg_snprintf(NULL,
  19133. NULL,
  19134. block,
  19135. sizeof(block),
  19136. ",%s\"os\" : \"%s %s\"",
  19137. eol,
  19138. "Zephyr OS",
  19139. ZEPHYR_VERSION);
  19140. system_info_length += mg_str_append(&buffer, end, block);
  19141. #else
  19142. struct utsname name;
  19143. memset(&name, 0, sizeof(name));
  19144. uname(&name);
  19145. mg_snprintf(NULL,
  19146. NULL,
  19147. block,
  19148. sizeof(block),
  19149. ",%s\"os\" : \"%s %s (%s) - %s\"",
  19150. eol,
  19151. name.sysname,
  19152. name.version,
  19153. name.release,
  19154. name.machine);
  19155. system_info_length += mg_str_append(&buffer, end, block);
  19156. #endif
  19157. }
  19158. /* Features */
  19159. {
  19160. mg_snprintf(NULL,
  19161. NULL,
  19162. block,
  19163. sizeof(block),
  19164. ",%s\"features\" : %lu"
  19165. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  19166. eol,
  19167. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  19168. eol,
  19169. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  19170. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  19171. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  19172. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  19173. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  19174. : "",
  19175. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  19176. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  19177. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  19178. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  19179. system_info_length += mg_str_append(&buffer, end, block);
  19180. #if defined(USE_LUA)
  19181. mg_snprintf(NULL,
  19182. NULL,
  19183. block,
  19184. sizeof(block),
  19185. ",%s\"lua_version\" : \"%u (%s)\"",
  19186. eol,
  19187. (unsigned)LUA_VERSION_NUM,
  19188. LUA_RELEASE);
  19189. system_info_length += mg_str_append(&buffer, end, block);
  19190. #endif
  19191. #if defined(USE_DUKTAPE)
  19192. mg_snprintf(NULL,
  19193. NULL,
  19194. block,
  19195. sizeof(block),
  19196. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  19197. eol,
  19198. (unsigned)DUK_VERSION / 10000,
  19199. ((unsigned)DUK_VERSION / 100) % 100,
  19200. (unsigned)DUK_VERSION % 100);
  19201. system_info_length += mg_str_append(&buffer, end, block);
  19202. #endif
  19203. }
  19204. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  19205. {
  19206. #if defined(BUILD_DATE)
  19207. const char *bd = BUILD_DATE;
  19208. #else
  19209. #if defined(GCC_DIAGNOSTIC)
  19210. #if GCC_VERSION >= 40900
  19211. #pragma GCC diagnostic push
  19212. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  19213. * does not work in some versions. If "BUILD_DATE" is defined to some
  19214. * string, it is used instead of __DATE__. */
  19215. #pragma GCC diagnostic ignored "-Wdate-time"
  19216. #endif
  19217. #endif
  19218. const char *bd = __DATE__;
  19219. #if defined(GCC_DIAGNOSTIC)
  19220. #if GCC_VERSION >= 40900
  19221. #pragma GCC diagnostic pop
  19222. #endif
  19223. #endif
  19224. #endif
  19225. mg_snprintf(
  19226. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  19227. system_info_length += mg_str_append(&buffer, end, block);
  19228. }
  19229. /* Compiler information */
  19230. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  19231. {
  19232. #if defined(_MSC_VER)
  19233. mg_snprintf(NULL,
  19234. NULL,
  19235. block,
  19236. sizeof(block),
  19237. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  19238. eol,
  19239. (unsigned)_MSC_VER,
  19240. (unsigned)_MSC_FULL_VER);
  19241. system_info_length += mg_str_append(&buffer, end, block);
  19242. #elif defined(__MINGW64__)
  19243. mg_snprintf(NULL,
  19244. NULL,
  19245. block,
  19246. sizeof(block),
  19247. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  19248. eol,
  19249. (unsigned)__MINGW64_VERSION_MAJOR,
  19250. (unsigned)__MINGW64_VERSION_MINOR);
  19251. system_info_length += mg_str_append(&buffer, end, block);
  19252. mg_snprintf(NULL,
  19253. NULL,
  19254. block,
  19255. sizeof(block),
  19256. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19257. eol,
  19258. (unsigned)__MINGW32_MAJOR_VERSION,
  19259. (unsigned)__MINGW32_MINOR_VERSION);
  19260. system_info_length += mg_str_append(&buffer, end, block);
  19261. #elif defined(__MINGW32__)
  19262. mg_snprintf(NULL,
  19263. NULL,
  19264. block,
  19265. sizeof(block),
  19266. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19267. eol,
  19268. (unsigned)__MINGW32_MAJOR_VERSION,
  19269. (unsigned)__MINGW32_MINOR_VERSION);
  19270. system_info_length += mg_str_append(&buffer, end, block);
  19271. #elif defined(__clang__)
  19272. mg_snprintf(NULL,
  19273. NULL,
  19274. block,
  19275. sizeof(block),
  19276. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  19277. eol,
  19278. __clang_major__,
  19279. __clang_minor__,
  19280. __clang_patchlevel__,
  19281. __clang_version__);
  19282. system_info_length += mg_str_append(&buffer, end, block);
  19283. #elif defined(__GNUC__)
  19284. mg_snprintf(NULL,
  19285. NULL,
  19286. block,
  19287. sizeof(block),
  19288. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  19289. eol,
  19290. (unsigned)__GNUC__,
  19291. (unsigned)__GNUC_MINOR__,
  19292. (unsigned)__GNUC_PATCHLEVEL__);
  19293. system_info_length += mg_str_append(&buffer, end, block);
  19294. #elif defined(__INTEL_COMPILER)
  19295. mg_snprintf(NULL,
  19296. NULL,
  19297. block,
  19298. sizeof(block),
  19299. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  19300. eol,
  19301. (unsigned)__INTEL_COMPILER);
  19302. system_info_length += mg_str_append(&buffer, end, block);
  19303. #elif defined(__BORLANDC__)
  19304. mg_snprintf(NULL,
  19305. NULL,
  19306. block,
  19307. sizeof(block),
  19308. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  19309. eol,
  19310. (unsigned)__BORLANDC__);
  19311. system_info_length += mg_str_append(&buffer, end, block);
  19312. #elif defined(__SUNPRO_C)
  19313. mg_snprintf(NULL,
  19314. NULL,
  19315. block,
  19316. sizeof(block),
  19317. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  19318. eol,
  19319. (unsigned)__SUNPRO_C);
  19320. system_info_length += mg_str_append(&buffer, end, block);
  19321. #else
  19322. mg_snprintf(NULL,
  19323. NULL,
  19324. block,
  19325. sizeof(block),
  19326. ",%s\"compiler\" : \"other\"",
  19327. eol);
  19328. system_info_length += mg_str_append(&buffer, end, block);
  19329. #endif
  19330. }
  19331. /* Determine 32/64 bit data mode.
  19332. * see https://en.wikipedia.org/wiki/64-bit_computing */
  19333. {
  19334. mg_snprintf(NULL,
  19335. NULL,
  19336. block,
  19337. sizeof(block),
  19338. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  19339. "char:%u/%u, "
  19340. "ptr:%u, size:%u, time:%u\"",
  19341. eol,
  19342. (unsigned)sizeof(short),
  19343. (unsigned)sizeof(int),
  19344. (unsigned)sizeof(long),
  19345. (unsigned)sizeof(long long),
  19346. (unsigned)sizeof(float),
  19347. (unsigned)sizeof(double),
  19348. (unsigned)sizeof(long double),
  19349. (unsigned)sizeof(char),
  19350. (unsigned)sizeof(wchar_t),
  19351. (unsigned)sizeof(void *),
  19352. (unsigned)sizeof(size_t),
  19353. (unsigned)sizeof(time_t));
  19354. system_info_length += mg_str_append(&buffer, end, block);
  19355. }
  19356. /* Terminate string */
  19357. if (append_eoobj) {
  19358. strcat(append_eoobj, eoobj);
  19359. }
  19360. system_info_length += sizeof(eoobj) - 1;
  19361. return (int)system_info_length;
  19362. }
  19363. /* Get context information. It can be printed or stored by the caller.
  19364. * Return the size of available information. */
  19365. CIVETWEB_API int
  19366. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19367. {
  19368. #if defined(USE_SERVER_STATS)
  19369. char *end, *append_eoobj = NULL, block[256];
  19370. size_t context_info_length = 0;
  19371. #if defined(_WIN32)
  19372. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19373. #else
  19374. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19375. #endif
  19376. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19377. if ((buffer == NULL) || (buflen < 1)) {
  19378. buflen = 0;
  19379. end = buffer;
  19380. } else {
  19381. *buffer = 0;
  19382. end = buffer + buflen;
  19383. }
  19384. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19385. /* has enough space to append eoobj */
  19386. append_eoobj = buffer;
  19387. end -= sizeof(eoobj) - 1;
  19388. }
  19389. context_info_length += mg_str_append(&buffer, end, "{");
  19390. if (ms) { /* <-- should be always true */
  19391. /* Memory information */
  19392. int blockCount = (int)ms->blockCount;
  19393. int64_t totalMemUsed = ms->totalMemUsed;
  19394. int64_t maxMemUsed = ms->maxMemUsed;
  19395. if (totalMemUsed > maxMemUsed) {
  19396. maxMemUsed = totalMemUsed;
  19397. }
  19398. mg_snprintf(NULL,
  19399. NULL,
  19400. block,
  19401. sizeof(block),
  19402. "%s\"memory\" : {%s"
  19403. "\"blocks\" : %i,%s"
  19404. "\"used\" : %" INT64_FMT ",%s"
  19405. "\"maxUsed\" : %" INT64_FMT "%s"
  19406. "}",
  19407. eol,
  19408. eol,
  19409. blockCount,
  19410. eol,
  19411. totalMemUsed,
  19412. eol,
  19413. maxMemUsed,
  19414. eol);
  19415. context_info_length += mg_str_append(&buffer, end, block);
  19416. }
  19417. if (ctx) {
  19418. /* Declare all variables at begin of the block, to comply
  19419. * with old C standards. */
  19420. char start_time_str[64] = {0};
  19421. char now_str[64] = {0};
  19422. time_t start_time = ctx->start_time;
  19423. time_t now = time(NULL);
  19424. int64_t total_data_read, total_data_written;
  19425. int active_connections = (int)ctx->active_connections;
  19426. int max_active_connections = (int)ctx->max_active_connections;
  19427. int total_connections = (int)ctx->total_connections;
  19428. if (active_connections > max_active_connections) {
  19429. max_active_connections = active_connections;
  19430. }
  19431. if (active_connections > total_connections) {
  19432. total_connections = active_connections;
  19433. }
  19434. /* Connections information */
  19435. mg_snprintf(NULL,
  19436. NULL,
  19437. block,
  19438. sizeof(block),
  19439. ",%s\"connections\" : {%s"
  19440. "\"active\" : %i,%s"
  19441. "\"maxActive\" : %i,%s"
  19442. "\"total\" : %i%s"
  19443. "}",
  19444. eol,
  19445. eol,
  19446. active_connections,
  19447. eol,
  19448. max_active_connections,
  19449. eol,
  19450. total_connections,
  19451. eol);
  19452. context_info_length += mg_str_append(&buffer, end, block);
  19453. /* Queue information */
  19454. #if !defined(ALTERNATIVE_QUEUE)
  19455. mg_snprintf(NULL,
  19456. NULL,
  19457. block,
  19458. sizeof(block),
  19459. ",%s\"queue\" : {%s"
  19460. "\"length\" : %i,%s"
  19461. "\"filled\" : %i,%s"
  19462. "\"maxFilled\" : %i,%s"
  19463. "\"full\" : %s%s"
  19464. "}",
  19465. eol,
  19466. eol,
  19467. ctx->sq_size,
  19468. eol,
  19469. ctx->sq_head - ctx->sq_tail,
  19470. eol,
  19471. ctx->sq_max_fill,
  19472. eol,
  19473. (ctx->sq_blocked ? "true" : "false"),
  19474. eol);
  19475. context_info_length += mg_str_append(&buffer, end, block);
  19476. #endif
  19477. /* Requests information */
  19478. mg_snprintf(NULL,
  19479. NULL,
  19480. block,
  19481. sizeof(block),
  19482. ",%s\"requests\" : {%s"
  19483. "\"total\" : %lu%s"
  19484. "}",
  19485. eol,
  19486. eol,
  19487. (unsigned long)ctx->total_requests,
  19488. eol);
  19489. context_info_length += mg_str_append(&buffer, end, block);
  19490. /* Data information */
  19491. total_data_read =
  19492. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19493. total_data_written =
  19494. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19495. mg_snprintf(NULL,
  19496. NULL,
  19497. block,
  19498. sizeof(block),
  19499. ",%s\"data\" : {%s"
  19500. "\"read\" : %" INT64_FMT ",%s"
  19501. "\"written\" : %" INT64_FMT "%s"
  19502. "}",
  19503. eol,
  19504. eol,
  19505. total_data_read,
  19506. eol,
  19507. total_data_written,
  19508. eol);
  19509. context_info_length += mg_str_append(&buffer, end, block);
  19510. /* Execution time information */
  19511. gmt_time_string(start_time_str,
  19512. sizeof(start_time_str) - 1,
  19513. &start_time);
  19514. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19515. mg_snprintf(NULL,
  19516. NULL,
  19517. block,
  19518. sizeof(block),
  19519. ",%s\"time\" : {%s"
  19520. "\"uptime\" : %.0f,%s"
  19521. "\"start\" : \"%s\",%s"
  19522. "\"now\" : \"%s\"%s"
  19523. "}",
  19524. eol,
  19525. eol,
  19526. difftime(now, start_time),
  19527. eol,
  19528. start_time_str,
  19529. eol,
  19530. now_str,
  19531. eol);
  19532. context_info_length += mg_str_append(&buffer, end, block);
  19533. }
  19534. /* Terminate string */
  19535. if (append_eoobj) {
  19536. strcat(append_eoobj, eoobj);
  19537. }
  19538. context_info_length += sizeof(eoobj) - 1;
  19539. return (int)context_info_length;
  19540. #else
  19541. (void)ctx;
  19542. if ((buffer != NULL) && (buflen > 0)) {
  19543. *buffer = 0;
  19544. }
  19545. return 0;
  19546. #endif
  19547. }
  19548. CIVETWEB_API void
  19549. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19550. {
  19551. /* https://github.com/civetweb/civetweb/issues/727 */
  19552. if (conn != NULL) {
  19553. conn->must_close = 1;
  19554. }
  19555. }
  19556. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19557. /* Get connection information. It can be printed or stored by the caller.
  19558. * Return the size of available information. */
  19559. CIVETWEB_API int
  19560. mg_get_connection_info(const struct mg_context *ctx,
  19561. int idx,
  19562. char *buffer,
  19563. int buflen)
  19564. {
  19565. const struct mg_connection *conn;
  19566. const struct mg_request_info *ri;
  19567. char *end, *append_eoobj = NULL, block[256];
  19568. size_t connection_info_length = 0;
  19569. int state = 0;
  19570. const char *state_str = "unknown";
  19571. #if defined(_WIN32)
  19572. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19573. #else
  19574. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19575. #endif
  19576. if ((buffer == NULL) || (buflen < 1)) {
  19577. buflen = 0;
  19578. end = buffer;
  19579. } else {
  19580. *buffer = 0;
  19581. end = buffer + buflen;
  19582. }
  19583. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19584. /* has enough space to append eoobj */
  19585. append_eoobj = buffer;
  19586. end -= sizeof(eoobj) - 1;
  19587. }
  19588. if ((ctx == NULL) || (idx < 0)) {
  19589. /* Parameter error */
  19590. return 0;
  19591. }
  19592. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19593. /* Out of range */
  19594. return 0;
  19595. }
  19596. /* Take connection [idx]. This connection is not locked in
  19597. * any way, so some other thread might use it. */
  19598. conn = (ctx->worker_connections) + idx;
  19599. /* Initialize output string */
  19600. connection_info_length += mg_str_append(&buffer, end, "{");
  19601. /* Init variables */
  19602. ri = &(conn->request_info);
  19603. #if defined(USE_SERVER_STATS)
  19604. state = conn->conn_state;
  19605. /* State as string */
  19606. switch (state) {
  19607. case 0:
  19608. state_str = "undefined";
  19609. break;
  19610. case 1:
  19611. state_str = "not used";
  19612. break;
  19613. case 2:
  19614. state_str = "init";
  19615. break;
  19616. case 3:
  19617. state_str = "ready";
  19618. break;
  19619. case 4:
  19620. state_str = "processing";
  19621. break;
  19622. case 5:
  19623. state_str = "processed";
  19624. break;
  19625. case 6:
  19626. state_str = "to close";
  19627. break;
  19628. case 7:
  19629. state_str = "closing";
  19630. break;
  19631. case 8:
  19632. state_str = "closed";
  19633. break;
  19634. case 9:
  19635. state_str = "done";
  19636. break;
  19637. }
  19638. #endif
  19639. /* Connection info */
  19640. if ((state >= 3) && (state < 9)) {
  19641. mg_snprintf(NULL,
  19642. NULL,
  19643. block,
  19644. sizeof(block),
  19645. "%s\"connection\" : {%s"
  19646. "\"remote\" : {%s"
  19647. "\"protocol\" : \"%s\",%s"
  19648. "\"addr\" : \"%s\",%s"
  19649. "\"port\" : %u%s"
  19650. "},%s"
  19651. "\"handled_requests\" : %u%s"
  19652. "}",
  19653. eol,
  19654. eol,
  19655. eol,
  19656. get_proto_name(conn),
  19657. eol,
  19658. ri->remote_addr,
  19659. eol,
  19660. ri->remote_port,
  19661. eol,
  19662. eol,
  19663. conn->handled_requests,
  19664. eol);
  19665. connection_info_length += mg_str_append(&buffer, end, block);
  19666. }
  19667. /* Request info */
  19668. if ((state >= 4) && (state < 6)) {
  19669. mg_snprintf(NULL,
  19670. NULL,
  19671. block,
  19672. sizeof(block),
  19673. "%s%s\"request_info\" : {%s"
  19674. "\"method\" : \"%s\",%s"
  19675. "\"uri\" : \"%s\",%s"
  19676. "\"query\" : %s%s%s%s"
  19677. "}",
  19678. (connection_info_length > 1 ? "," : ""),
  19679. eol,
  19680. eol,
  19681. ri->request_method,
  19682. eol,
  19683. ri->request_uri,
  19684. eol,
  19685. ri->query_string ? "\"" : "",
  19686. ri->query_string ? ri->query_string : "null",
  19687. ri->query_string ? "\"" : "",
  19688. eol);
  19689. connection_info_length += mg_str_append(&buffer, end, block);
  19690. }
  19691. /* Execution time information */
  19692. if ((state >= 2) && (state < 9)) {
  19693. char start_time_str[64] = {0};
  19694. char close_time_str[64] = {0};
  19695. time_t start_time = conn->conn_birth_time;
  19696. time_t close_time = 0;
  19697. double time_diff;
  19698. gmt_time_string(start_time_str,
  19699. sizeof(start_time_str) - 1,
  19700. &start_time);
  19701. #if defined(USE_SERVER_STATS)
  19702. close_time = conn->conn_close_time;
  19703. #endif
  19704. if (close_time != 0) {
  19705. time_diff = difftime(close_time, start_time);
  19706. gmt_time_string(close_time_str,
  19707. sizeof(close_time_str) - 1,
  19708. &close_time);
  19709. } else {
  19710. time_t now = time(NULL);
  19711. time_diff = difftime(now, start_time);
  19712. close_time_str[0] = 0; /* or use "now" ? */
  19713. }
  19714. mg_snprintf(NULL,
  19715. NULL,
  19716. block,
  19717. sizeof(block),
  19718. "%s%s\"time\" : {%s"
  19719. "\"uptime\" : %.0f,%s"
  19720. "\"start\" : \"%s\",%s"
  19721. "\"closed\" : \"%s\"%s"
  19722. "}",
  19723. (connection_info_length > 1 ? "," : ""),
  19724. eol,
  19725. eol,
  19726. time_diff,
  19727. eol,
  19728. start_time_str,
  19729. eol,
  19730. close_time_str,
  19731. eol);
  19732. connection_info_length += mg_str_append(&buffer, end, block);
  19733. }
  19734. /* Remote user name */
  19735. if ((ri->remote_user) && (state < 9)) {
  19736. mg_snprintf(NULL,
  19737. NULL,
  19738. block,
  19739. sizeof(block),
  19740. "%s%s\"user\" : {%s"
  19741. "\"name\" : \"%s\",%s"
  19742. "}",
  19743. (connection_info_length > 1 ? "," : ""),
  19744. eol,
  19745. eol,
  19746. ri->remote_user,
  19747. eol);
  19748. connection_info_length += mg_str_append(&buffer, end, block);
  19749. }
  19750. /* Data block */
  19751. if (state >= 3) {
  19752. mg_snprintf(NULL,
  19753. NULL,
  19754. block,
  19755. sizeof(block),
  19756. "%s%s\"data\" : {%s"
  19757. "\"read\" : %" INT64_FMT ",%s"
  19758. "\"written\" : %" INT64_FMT "%s"
  19759. "}",
  19760. (connection_info_length > 1 ? "," : ""),
  19761. eol,
  19762. eol,
  19763. conn->consumed_content,
  19764. eol,
  19765. conn->num_bytes_sent,
  19766. eol);
  19767. connection_info_length += mg_str_append(&buffer, end, block);
  19768. }
  19769. /* State */
  19770. mg_snprintf(NULL,
  19771. NULL,
  19772. block,
  19773. sizeof(block),
  19774. "%s%s\"state\" : \"%s\"",
  19775. (connection_info_length > 1 ? "," : ""),
  19776. eol,
  19777. state_str);
  19778. connection_info_length += mg_str_append(&buffer, end, block);
  19779. /* Terminate string */
  19780. if (append_eoobj) {
  19781. strcat(append_eoobj, eoobj);
  19782. }
  19783. connection_info_length += sizeof(eoobj) - 1;
  19784. return (int)connection_info_length;
  19785. }
  19786. #if 0
  19787. /* Get handler information. Not fully implemented. Is it required? */
  19788. CIVETWEB_API int
  19789. mg_get_handler_info(struct mg_context *ctx,
  19790. char *buffer,
  19791. int buflen)
  19792. {
  19793. int handler_info_len = 0;
  19794. struct mg_handler_info *tmp_rh;
  19795. mg_lock_context(ctx);
  19796. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19797. if (buflen > handler_info_len + tmp_rh->uri_len) {
  19798. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19799. }
  19800. handler_info_len += tmp_rh->uri_len;
  19801. switch (tmp_rh->handler_type) {
  19802. case REQUEST_HANDLER:
  19803. (void)tmp_rh->handler;
  19804. break;
  19805. case WEBSOCKET_HANDLER:
  19806. (void)tmp_rh->connect_handler;
  19807. (void)tmp_rh->ready_handler;
  19808. (void)tmp_rh->data_handler;
  19809. (void)tmp_rh->close_handler;
  19810. break;
  19811. case AUTH_HANDLER:
  19812. (void)tmp_rh->auth_handler;
  19813. break;
  19814. }
  19815. (void)cbdata;
  19816. }
  19817. mg_unlock_context(ctx);
  19818. return handler_info_len;
  19819. }
  19820. #endif
  19821. #endif
  19822. /* Initialize this library. This function does not need to be thread safe.
  19823. */
  19824. CIVETWEB_API unsigned
  19825. mg_init_library(unsigned features)
  19826. {
  19827. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19828. unsigned features_inited = features_to_init;
  19829. if (mg_init_library_called <= 0) {
  19830. /* Not initialized yet */
  19831. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19832. return 0;
  19833. }
  19834. }
  19835. mg_global_lock();
  19836. if (mg_init_library_called <= 0) {
  19837. int i;
  19838. size_t len;
  19839. #if defined(_WIN32)
  19840. int file_mutex_init = 1;
  19841. int wsa = 1;
  19842. #else
  19843. int mutexattr_init = 1;
  19844. #endif
  19845. int failed = 1;
  19846. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19847. if (key_create == 0) {
  19848. #if defined(_WIN32)
  19849. file_mutex_init =
  19850. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19851. if (file_mutex_init == 0) {
  19852. /* Start WinSock */
  19853. WSADATA data;
  19854. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19855. }
  19856. #else
  19857. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19858. if (mutexattr_init == 0) {
  19859. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19860. PTHREAD_MUTEX_RECURSIVE);
  19861. }
  19862. #endif
  19863. }
  19864. if (failed) {
  19865. #if defined(_WIN32)
  19866. if (wsa == 0) {
  19867. (void)WSACleanup();
  19868. }
  19869. if (file_mutex_init == 0) {
  19870. (void)pthread_mutex_destroy(&global_log_file_lock);
  19871. }
  19872. #else
  19873. if (mutexattr_init == 0) {
  19874. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19875. }
  19876. #endif
  19877. if (key_create == 0) {
  19878. (void)pthread_key_delete(sTlsKey);
  19879. }
  19880. mg_global_unlock();
  19881. (void)pthread_mutex_destroy(&global_lock_mutex);
  19882. return 0;
  19883. }
  19884. len = 1;
  19885. for (i = 0; http_methods[i].name != NULL; i++) {
  19886. size_t sl = strlen(http_methods[i].name);
  19887. len += sl;
  19888. if (i > 0) {
  19889. len += 2;
  19890. }
  19891. }
  19892. all_methods = (char *)mg_malloc(len);
  19893. if (!all_methods) {
  19894. /* Must never happen */
  19895. mg_global_unlock();
  19896. (void)pthread_mutex_destroy(&global_lock_mutex);
  19897. return 0;
  19898. }
  19899. all_methods[0] = 0;
  19900. for (i = 0; http_methods[i].name != NULL; i++) {
  19901. if (i > 0) {
  19902. strcat(all_methods, ", ");
  19903. strcat(all_methods, http_methods[i].name);
  19904. } else {
  19905. strcpy(all_methods, http_methods[i].name);
  19906. }
  19907. }
  19908. }
  19909. #if defined(USE_LUA)
  19910. lua_init_optional_libraries();
  19911. #endif
  19912. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19913. || defined(OPENSSL_API_3_0)) \
  19914. && !defined(NO_SSL)
  19915. if (features_to_init & MG_FEATURES_SSL) {
  19916. if (!mg_openssl_initialized) {
  19917. char ebuf[128];
  19918. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19919. mg_openssl_initialized = 1;
  19920. } else {
  19921. (void)ebuf;
  19922. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19923. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19924. }
  19925. } else {
  19926. /* ssl already initialized */
  19927. }
  19928. }
  19929. #endif
  19930. if (mg_init_library_called <= 0) {
  19931. mg_init_library_called = 1;
  19932. } else {
  19933. mg_init_library_called++;
  19934. }
  19935. mg_global_unlock();
  19936. return features_inited;
  19937. }
  19938. /* Un-initialize this library. */
  19939. CIVETWEB_API unsigned
  19940. mg_exit_library(void)
  19941. {
  19942. if (mg_init_library_called <= 0) {
  19943. return 0;
  19944. }
  19945. mg_global_lock();
  19946. mg_init_library_called--;
  19947. if (mg_init_library_called == 0) {
  19948. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19949. if (mg_openssl_initialized) {
  19950. uninitialize_openssl();
  19951. mg_openssl_initialized = 0;
  19952. }
  19953. #endif
  19954. #if defined(_WIN32)
  19955. (void)WSACleanup();
  19956. (void)pthread_mutex_destroy(&global_log_file_lock);
  19957. #else
  19958. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19959. #endif
  19960. (void)pthread_key_delete(sTlsKey);
  19961. #if defined(USE_LUA)
  19962. lua_exit_optional_libraries();
  19963. #endif
  19964. mg_free(all_methods);
  19965. all_methods = NULL;
  19966. mg_global_unlock();
  19967. (void)pthread_mutex_destroy(&global_lock_mutex);
  19968. return 1;
  19969. }
  19970. mg_global_unlock();
  19971. return 1;
  19972. }
  19973. /* End of civetweb.c */