civetweb.c 583 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622
  1. /* Copyright (c) 2013-2020 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. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0502
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__) || defined(__sun)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE (1024 * 16)
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #if !defined(DEBUG_TRACE_STREAM)
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #define DEBUG_ASSERT(cond) \
  220. do { \
  221. if (!(cond)) { \
  222. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  223. exit(2); /* Exit with error */ \
  224. } \
  225. } while (0)
  226. #else
  227. #define DEBUG_ASSERT(cond)
  228. #endif /* DEBUG */
  229. #endif
  230. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  231. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  232. __attribute__((no_instrument_function));
  233. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  234. __attribute__((no_instrument_function));
  235. void
  236. __cyg_profile_func_enter(void *this_fn, void *call_site)
  237. {
  238. if ((void *)this_fn != (void *)printf) {
  239. printf("E %p %p\n", this_fn, call_site);
  240. }
  241. }
  242. void
  243. __cyg_profile_func_exit(void *this_fn, void *call_site)
  244. {
  245. if ((void *)this_fn != (void *)printf) {
  246. printf("X %p %p\n", this_fn, call_site);
  247. }
  248. }
  249. #endif
  250. #if !defined(IGNORE_UNUSED_RESULT)
  251. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  252. #endif
  253. #if defined(__GNUC__) || defined(__MINGW32__)
  254. /* GCC unused function attribute seems fundamentally broken.
  255. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  256. * OR UNUSED" for individual functions failed.
  257. * Either the compiler creates an "unused-function" warning if a
  258. * function is not marked with __attribute__((unused)).
  259. * On the other hand, if the function is marked with this attribute,
  260. * but is used, the compiler raises a completely idiotic
  261. * "used-but-marked-unused" warning - and
  262. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  263. * raises error: unknown option after "#pragma GCC diagnostic".
  264. * Disable this warning completely, until the GCC guys sober up
  265. * again.
  266. */
  267. #pragma GCC diagnostic ignored "-Wunused-function"
  268. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  269. #else
  270. #define FUNCTION_MAY_BE_UNUSED
  271. #endif
  272. /* Some ANSI #includes are not available on Windows CE */
  273. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  274. #include <errno.h>
  275. #include <fcntl.h>
  276. #include <signal.h>
  277. #include <stdlib.h>
  278. #include <sys/stat.h>
  279. #include <sys/types.h>
  280. #endif /* !_WIN32_WCE */
  281. #if defined(__clang__)
  282. /* When using -Weverything, clang does not accept it's own headers
  283. * in a release build configuration. Disable what is too much in
  284. * -Weverything. */
  285. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  286. #endif
  287. #if defined(__GNUC__) || defined(__MINGW32__)
  288. /* Who on earth came to the conclusion, using __DATE__ should rise
  289. * an "expansion of date or time macro is not reproducible"
  290. * warning. That's exactly what was intended by using this macro.
  291. * Just disable this nonsense warning. */
  292. /* And disabling them does not work either:
  293. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  294. * #pragma clang diagnostic ignored "-Wdate-time"
  295. * So we just have to disable ALL warnings for some lines
  296. * of code.
  297. * This seems to be a known GCC bug, not resolved since 2012:
  298. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  299. */
  300. #endif
  301. #if defined(__MACH__) /* Apple OSX section */
  302. #if defined(__clang__)
  303. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  304. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  305. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  306. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  307. #endif
  308. #endif
  309. #define CLOCK_MONOTONIC (1)
  310. #define CLOCK_REALTIME (2)
  311. #include <mach/clock.h>
  312. #include <mach/mach.h>
  313. #include <mach/mach_time.h>
  314. #include <sys/errno.h>
  315. #include <sys/time.h>
  316. /* clock_gettime is not implemented on OSX prior to 10.12 */
  317. static int
  318. _civet_clock_gettime(int clk_id, struct timespec *t)
  319. {
  320. memset(t, 0, sizeof(*t));
  321. if (clk_id == CLOCK_REALTIME) {
  322. struct timeval now;
  323. int rv = gettimeofday(&now, NULL);
  324. if (rv) {
  325. return rv;
  326. }
  327. t->tv_sec = now.tv_sec;
  328. t->tv_nsec = now.tv_usec * 1000;
  329. return 0;
  330. } else if (clk_id == CLOCK_MONOTONIC) {
  331. static uint64_t clock_start_time = 0;
  332. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  333. uint64_t now = mach_absolute_time();
  334. if (clock_start_time == 0) {
  335. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  336. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  337. /* appease "unused variable" warning for release builds */
  338. (void)mach_status;
  339. clock_start_time = now;
  340. }
  341. now = (uint64_t)((double)(now - clock_start_time)
  342. * (double)timebase_ifo.numer
  343. / (double)timebase_ifo.denom);
  344. t->tv_sec = now / 1000000000;
  345. t->tv_nsec = now % 1000000000;
  346. return 0;
  347. }
  348. return -1; /* EINVAL - Clock ID is unknown */
  349. }
  350. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  351. #if defined(__CLOCK_AVAILABILITY)
  352. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  353. * declared but it may be NULL at runtime. So we need to check before using
  354. * it. */
  355. static int
  356. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  357. {
  358. if (clock_gettime) {
  359. return clock_gettime(clk_id, t);
  360. }
  361. return _civet_clock_gettime(clk_id, t);
  362. }
  363. #define clock_gettime _civet_safe_clock_gettime
  364. #else
  365. #define clock_gettime _civet_clock_gettime
  366. #endif
  367. #endif
  368. #if !defined(_WIN32)
  369. /* Unix might return different error codes indicating to try again.
  370. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  371. * decades ago, but better check both and let the compile optimize it. */
  372. #define ERROR_TRY_AGAIN(err) \
  373. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  374. #endif
  375. #if defined(USE_ZLIB)
  376. #include "zconf.h"
  377. #include "zlib.h"
  378. #endif
  379. /********************************************************************/
  380. /* CivetWeb configuration defines */
  381. /********************************************************************/
  382. /* Maximum number of threads that can be configured.
  383. * The number of threads actually created depends on the "num_threads"
  384. * configuration parameter, but this is the upper limit. */
  385. #if !defined(MAX_WORKER_THREADS)
  386. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  387. #endif
  388. /* Timeout interval for select/poll calls.
  389. * The timeouts depend on "*_timeout_ms" configuration values, but long
  390. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  391. * This reduces the time required to stop the server. */
  392. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  393. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  394. #endif
  395. /* Do not try to compress files smaller than this limit. */
  396. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  397. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  398. #endif
  399. #if !defined(PASSWORDS_FILE_NAME)
  400. #define PASSWORDS_FILE_NAME ".htpasswd"
  401. #endif
  402. /* Initial buffer size for all CGI environment variables. In case there is
  403. * not enough space, another block is allocated. */
  404. #if !defined(CGI_ENVIRONMENT_SIZE)
  405. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  406. #endif
  407. /* Maximum number of environment variables. */
  408. #if !defined(MAX_CGI_ENVIR_VARS)
  409. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  410. #endif
  411. /* General purpose buffer size. */
  412. #if !defined(MG_BUF_LEN) /* in bytes */
  413. #define MG_BUF_LEN (1024 * 8)
  414. #endif
  415. /********************************************************************/
  416. /* Helper makros */
  417. #if !defined(ARRAY_SIZE)
  418. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  419. #endif
  420. #include <stdint.h>
  421. /* Standard defines */
  422. #if !defined(INT64_MAX)
  423. #define INT64_MAX (9223372036854775807)
  424. #endif
  425. #define SHUTDOWN_RD (0)
  426. #define SHUTDOWN_WR (1)
  427. #define SHUTDOWN_BOTH (2)
  428. mg_static_assert(MAX_WORKER_THREADS >= 1,
  429. "worker threads must be a positive number");
  430. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  431. "size_t data type size check");
  432. #if defined(_WIN32) /* WINDOWS include block */
  433. #include <malloc.h> /* *alloc( */
  434. #include <stdlib.h> /* *alloc( */
  435. #include <time.h> /* struct timespec */
  436. #include <windows.h>
  437. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  438. #include <ws2tcpip.h>
  439. typedef const char *SOCK_OPT_TYPE;
  440. #if defined(_WIN32)
  441. /* The Microsoft Visual Studio SDK defines MAX_PATH, but not PATH_MAX.
  442. * Linux defines PATH_MAX but not MAX_PATH. MinGW defines both.
  443. * Linux uses UTF-8 filenames, and (typically) defines PATH_MAX as 4096
  444. * (see https://eklitzke.org/path-max-is-tricky).
  445. * Windows cannot handle UTF-8 directly but uses UCS-2 (UTF-16 without checking
  446. * surrogate pairs in the file API).
  447. * CivetWeb internally uses UTF-8 on every system, thus it needs to convert
  448. * all filen ames for Windows.
  449. * Windows has an internal limit of 259 UCS-2 characters (plus termination).
  450. */
  451. /* PATH_MAX is used in CivetWeb as char[] buffer size for UTF-8 name
  452. * representations. Every character in the BMP (Basic Multilingual Plane)
  453. * encoded as UTF-8 requires 1, 2 or 3 bytes. A BMP character encoded as
  454. * UTF-16 always requires one 16-bit word. A character outside the BMP
  455. * requires 4 bytes in UTF-8 and two 16-bit words in UTF-16 (a surrogate
  456. * pair).
  457. * Thus, a 3*259+1 bytes buffer for UTF-8 encoded text will allways be
  458. * sufficent to hold a 295+1 word UTF-16 encoded text.
  459. * We do not need 4*259+1 bytes for the UTF-8 text buffer, since none BMP
  460. * characters would require two words in UTF-16 and hit the UCS-2 length
  461. * limit of the Windows file API.
  462. */
  463. /* See also https://github.com/civetweb/civetweb/issues/937 */
  464. /* W_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  465. * null termination, rounded up to the next 4 bytes boundary */
  466. #define PATH_MAX (3 * 260)
  467. /* W_PATH_MAX is the wchar_t buffer size required for 259 BMP characters
  468. * plus termination. (Note: wchar_t is 16 bit on Windows) */
  469. #define W_PATH_MAX (260)
  470. #endif
  471. mg_static_assert(PATH_MAX >= 12, "path length must be a positive number");
  472. #if !defined(_IN_PORT_T)
  473. #if !defined(in_port_t)
  474. #define in_port_t u_short
  475. #endif
  476. #endif
  477. #if !defined(_WIN32_WCE)
  478. #include <direct.h>
  479. #include <io.h>
  480. #include <process.h>
  481. #else /* _WIN32_WCE */
  482. #define NO_CGI /* WinCE has no pipes */
  483. #define NO_POPEN /* WinCE has no popen */
  484. typedef long off_t;
  485. #define errno ((int)(GetLastError()))
  486. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  487. #endif /* _WIN32_WCE */
  488. #define MAKEUQUAD(lo, hi) \
  489. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  490. #define RATE_DIFF (10000000) /* 100 nsecs */
  491. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  492. #define SYS2UNIX_TIME(lo, hi) \
  493. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  494. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  495. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  496. * Also use _strtoui64 on modern M$ compilers */
  497. #if defined(_MSC_VER)
  498. #if (_MSC_VER < 1300)
  499. #define STRX(x) #x
  500. #define STR(x) STRX(x)
  501. #define __func__ __FILE__ ":" STR(__LINE__)
  502. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  503. #define strtoll(x, y, z) (_atoi64(x))
  504. #else
  505. #define __func__ __FUNCTION__
  506. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  507. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  508. #endif
  509. #endif /* _MSC_VER */
  510. #define ERRNO ((int)(GetLastError()))
  511. #define NO_SOCKLEN_T
  512. #if defined(_WIN64) || defined(__MINGW64__)
  513. #if !defined(SSL_LIB)
  514. #if defined(OPENSSL_API_1_1)
  515. #define SSL_LIB "libssl-1_1-x64.dll"
  516. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  517. #endif /* OPENSSL_API_1_1 */
  518. #if defined(OPENSSL_API_1_0)
  519. #define SSL_LIB "ssleay64.dll"
  520. #define CRYPTO_LIB "libeay64.dll"
  521. #endif /* OPENSSL_API_1_0 */
  522. #endif
  523. #else /* defined(_WIN64) || defined(__MINGW64__) */
  524. #if !defined(SSL_LIB)
  525. #if defined(OPENSSL_API_1_1)
  526. #define SSL_LIB "libssl-1_1.dll"
  527. #define CRYPTO_LIB "libcrypto-1_1.dll"
  528. #endif /* OPENSSL_API_1_1 */
  529. #if defined(OPENSSL_API_1_0)
  530. #define SSL_LIB "ssleay32.dll"
  531. #define CRYPTO_LIB "libeay32.dll"
  532. #endif /* OPENSSL_API_1_0 */
  533. #endif /* SSL_LIB */
  534. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  535. #define O_NONBLOCK (0)
  536. #if !defined(W_OK)
  537. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  538. #endif
  539. #define _POSIX_
  540. #define INT64_FMT "I64d"
  541. #define UINT64_FMT "I64u"
  542. #define WINCDECL __cdecl
  543. #define vsnprintf_impl _vsnprintf
  544. #define access _access
  545. #define mg_sleep(x) (Sleep(x))
  546. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  547. #if !defined(popen)
  548. #define popen(x, y) (_popen(x, y))
  549. #endif
  550. #if !defined(pclose)
  551. #define pclose(x) (_pclose(x))
  552. #endif
  553. #define close(x) (_close(x))
  554. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  555. #define RTLD_LAZY (0)
  556. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  557. #define fdopen(x, y) (_fdopen((x), (y)))
  558. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  559. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  560. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  561. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  562. #define sleep(x) (Sleep((x)*1000))
  563. #define rmdir(x) (_rmdir(x))
  564. #if defined(_WIN64) || !defined(__MINGW32__)
  565. /* Only MinGW 32 bit is missing this function */
  566. #define timegm(x) (_mkgmtime(x))
  567. #else
  568. time_t timegm(struct tm *tm);
  569. #define NEED_TIMEGM
  570. #endif
  571. #if !defined(fileno)
  572. #define fileno(x) (_fileno(x))
  573. #endif /* !fileno MINGW #defines fileno */
  574. typedef struct {
  575. CRITICAL_SECTION sec; /* Immovable */
  576. } pthread_mutex_t;
  577. typedef DWORD pthread_key_t;
  578. typedef HANDLE pthread_t;
  579. typedef struct {
  580. pthread_mutex_t threadIdSec;
  581. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  582. } pthread_cond_t;
  583. #if !defined(__clockid_t_defined)
  584. typedef DWORD clockid_t;
  585. #endif
  586. #if !defined(CLOCK_MONOTONIC)
  587. #define CLOCK_MONOTONIC (1)
  588. #endif
  589. #if !defined(CLOCK_REALTIME)
  590. #define CLOCK_REALTIME (2)
  591. #endif
  592. #if !defined(CLOCK_THREAD)
  593. #define CLOCK_THREAD (3)
  594. #endif
  595. #if !defined(CLOCK_PROCESS)
  596. #define CLOCK_PROCESS (4)
  597. #endif
  598. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  599. #define _TIMESPEC_DEFINED
  600. #endif
  601. #if !defined(_TIMESPEC_DEFINED)
  602. struct timespec {
  603. time_t tv_sec; /* seconds */
  604. long tv_nsec; /* nanoseconds */
  605. };
  606. #endif
  607. #if !defined(WIN_PTHREADS_TIME_H)
  608. #define MUST_IMPLEMENT_CLOCK_GETTIME
  609. #endif
  610. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  611. #define clock_gettime mg_clock_gettime
  612. static int
  613. clock_gettime(clockid_t clk_id, struct timespec *tp)
  614. {
  615. FILETIME ft;
  616. ULARGE_INTEGER li, li2;
  617. BOOL ok = FALSE;
  618. double d;
  619. static double perfcnt_per_sec = 0.0;
  620. static BOOL initialized = FALSE;
  621. if (!initialized) {
  622. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  623. perfcnt_per_sec = 1.0 / li.QuadPart;
  624. initialized = TRUE;
  625. }
  626. if (tp) {
  627. memset(tp, 0, sizeof(*tp));
  628. if (clk_id == CLOCK_REALTIME) {
  629. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  630. GetSystemTimeAsFileTime(&ft);
  631. li.LowPart = ft.dwLowDateTime;
  632. li.HighPart = ft.dwHighDateTime;
  633. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  634. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  635. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  636. ok = TRUE;
  637. /* END: CLOCK_REALTIME */
  638. } else if (clk_id == CLOCK_MONOTONIC) {
  639. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  640. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  641. d = li.QuadPart * perfcnt_per_sec;
  642. tp->tv_sec = (time_t)d;
  643. d -= (double)tp->tv_sec;
  644. tp->tv_nsec = (long)(d * 1.0E9);
  645. ok = TRUE;
  646. /* END: CLOCK_MONOTONIC */
  647. } else if (clk_id == CLOCK_THREAD) {
  648. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  649. FILETIME t_create, t_exit, t_kernel, t_user;
  650. if (GetThreadTimes(GetCurrentThread(),
  651. &t_create,
  652. &t_exit,
  653. &t_kernel,
  654. &t_user)) {
  655. li.LowPart = t_user.dwLowDateTime;
  656. li.HighPart = t_user.dwHighDateTime;
  657. li2.LowPart = t_kernel.dwLowDateTime;
  658. li2.HighPart = t_kernel.dwHighDateTime;
  659. li.QuadPart += li2.QuadPart;
  660. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  661. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  662. ok = TRUE;
  663. }
  664. /* END: CLOCK_THREAD */
  665. } else if (clk_id == CLOCK_PROCESS) {
  666. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  667. FILETIME t_create, t_exit, t_kernel, t_user;
  668. if (GetProcessTimes(GetCurrentProcess(),
  669. &t_create,
  670. &t_exit,
  671. &t_kernel,
  672. &t_user)) {
  673. li.LowPart = t_user.dwLowDateTime;
  674. li.HighPart = t_user.dwHighDateTime;
  675. li2.LowPart = t_kernel.dwLowDateTime;
  676. li2.HighPart = t_kernel.dwHighDateTime;
  677. li.QuadPart += li2.QuadPart;
  678. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  679. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  680. ok = TRUE;
  681. }
  682. /* END: CLOCK_PROCESS */
  683. } else {
  684. /* BEGIN: unknown clock */
  685. /* ok = FALSE; already set by init */
  686. /* END: unknown clock */
  687. }
  688. }
  689. return ok ? 0 : -1;
  690. }
  691. #endif
  692. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  693. static int pthread_mutex_lock(pthread_mutex_t *);
  694. static int pthread_mutex_unlock(pthread_mutex_t *);
  695. static void path_to_unicode(const struct mg_connection *conn,
  696. const char *path,
  697. wchar_t *wbuf,
  698. size_t wbuf_len);
  699. /* All file operations need to be rewritten to solve #246. */
  700. struct mg_file;
  701. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  702. /* POSIX dirent interface */
  703. struct dirent {
  704. char d_name[PATH_MAX];
  705. };
  706. typedef struct DIR {
  707. HANDLE handle;
  708. WIN32_FIND_DATAW info;
  709. struct dirent result;
  710. } DIR;
  711. #if defined(HAVE_POLL)
  712. #define mg_pollfd pollfd
  713. #else
  714. struct mg_pollfd {
  715. SOCKET fd;
  716. short events;
  717. short revents;
  718. };
  719. #endif
  720. /* Mark required libraries */
  721. #if defined(_MSC_VER)
  722. #pragma comment(lib, "Ws2_32.lib")
  723. #endif
  724. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  725. #include <inttypes.h>
  726. typedef const void *SOCK_OPT_TYPE;
  727. #if defined(ANDROID)
  728. typedef unsigned short int in_port_t;
  729. #endif
  730. #if !defined(__ZEPHYR__)
  731. #include <arpa/inet.h>
  732. #include <ctype.h>
  733. #include <dirent.h>
  734. #include <grp.h>
  735. #include <limits.h>
  736. #include <netdb.h>
  737. #include <netinet/in.h>
  738. #include <netinet/tcp.h>
  739. #include <pthread.h>
  740. #include <pwd.h>
  741. #include <stdarg.h>
  742. #include <stddef.h>
  743. #include <stdio.h>
  744. #include <stdlib.h>
  745. #include <string.h>
  746. #include <sys/poll.h>
  747. #include <sys/socket.h>
  748. #include <sys/time.h>
  749. #include <sys/utsname.h>
  750. #include <sys/wait.h>
  751. #include <time.h>
  752. #include <unistd.h>
  753. #if defined(USE_X_DOM_SOCKET)
  754. #include <sys/un.h>
  755. #endif
  756. #endif
  757. #define vsnprintf_impl vsnprintf
  758. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  759. #include <dlfcn.h>
  760. #endif
  761. #if defined(__MACH__)
  762. #define SSL_LIB "libssl.dylib"
  763. #define CRYPTO_LIB "libcrypto.dylib"
  764. #else
  765. #if !defined(SSL_LIB)
  766. #define SSL_LIB "libssl.so"
  767. #endif
  768. #if !defined(CRYPTO_LIB)
  769. #define CRYPTO_LIB "libcrypto.so"
  770. #endif
  771. #endif
  772. #if !defined(O_BINARY)
  773. #define O_BINARY (0)
  774. #endif /* O_BINARY */
  775. #define closesocket(a) (close(a))
  776. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  777. #define mg_remove(conn, x) (remove(x))
  778. #define mg_sleep(x) (usleep((x)*1000))
  779. #define mg_opendir(conn, x) (opendir(x))
  780. #define mg_closedir(x) (closedir(x))
  781. #define mg_readdir(x) (readdir(x))
  782. #define ERRNO (errno)
  783. #define INVALID_SOCKET (-1)
  784. #define INT64_FMT PRId64
  785. #define UINT64_FMT PRIu64
  786. typedef int SOCKET;
  787. #define WINCDECL
  788. #if defined(__hpux)
  789. /* HPUX 11 does not have monotonic, fall back to realtime */
  790. #if !defined(CLOCK_MONOTONIC)
  791. #define CLOCK_MONOTONIC CLOCK_REALTIME
  792. #endif
  793. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  794. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  795. * the prototypes use int* rather than socklen_t* which matches the
  796. * actual library expectation. When called with the wrong size arg
  797. * accept() returns a zero client inet addr and check_acl() always
  798. * fails. Since socklen_t is widely used below, just force replace
  799. * their typedef with int. - DTL
  800. */
  801. #define socklen_t int
  802. #endif /* hpux */
  803. #define mg_pollfd pollfd
  804. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  805. /* In case our C library is missing "timegm", provide an implementation */
  806. #if defined(NEED_TIMEGM)
  807. static inline int
  808. is_leap(int y)
  809. {
  810. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  811. }
  812. static inline int
  813. count_leap(int y)
  814. {
  815. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  816. }
  817. time_t
  818. timegm(struct tm *tm)
  819. {
  820. static const unsigned short ydays[] = {
  821. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  822. int year = tm->tm_year + 1900;
  823. int mon = tm->tm_mon;
  824. int mday = tm->tm_mday - 1;
  825. int hour = tm->tm_hour;
  826. int min = tm->tm_min;
  827. int sec = tm->tm_sec;
  828. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  829. || (mday >= ydays[mon + 1] - ydays[mon]
  830. + (mon == 1 && is_leap(year) ? 1 : 0))
  831. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  832. return -1;
  833. time_t res = year - 1970;
  834. res *= 365;
  835. res += mday;
  836. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  837. res += count_leap(year);
  838. res *= 24;
  839. res += hour;
  840. res *= 60;
  841. res += min;
  842. res *= 60;
  843. res += sec;
  844. return res;
  845. }
  846. #endif /* NEED_TIMEGM */
  847. /* va_copy should always be a macro, C99 and C++11 - DTL */
  848. #if !defined(va_copy)
  849. #define va_copy(x, y) ((x) = (y))
  850. #endif
  851. #if defined(_WIN32)
  852. /* Create substitutes for POSIX functions in Win32. */
  853. #if defined(GCC_DIAGNOSTIC)
  854. /* Show no warning in case system functions are not used. */
  855. #pragma GCC diagnostic push
  856. #pragma GCC diagnostic ignored "-Wunused-function"
  857. #endif
  858. static pthread_mutex_t global_log_file_lock;
  859. FUNCTION_MAY_BE_UNUSED
  860. static DWORD
  861. pthread_self(void)
  862. {
  863. return GetCurrentThreadId();
  864. }
  865. FUNCTION_MAY_BE_UNUSED
  866. static int
  867. pthread_key_create(
  868. pthread_key_t *key,
  869. void (*_ignored)(void *) /* destructor not supported for Windows */
  870. )
  871. {
  872. (void)_ignored;
  873. if ((key != 0)) {
  874. *key = TlsAlloc();
  875. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  876. }
  877. return -2;
  878. }
  879. FUNCTION_MAY_BE_UNUSED
  880. static int
  881. pthread_key_delete(pthread_key_t key)
  882. {
  883. return TlsFree(key) ? 0 : 1;
  884. }
  885. FUNCTION_MAY_BE_UNUSED
  886. static int
  887. pthread_setspecific(pthread_key_t key, void *value)
  888. {
  889. return TlsSetValue(key, value) ? 0 : 1;
  890. }
  891. FUNCTION_MAY_BE_UNUSED
  892. static void *
  893. pthread_getspecific(pthread_key_t key)
  894. {
  895. return TlsGetValue(key);
  896. }
  897. #if defined(GCC_DIAGNOSTIC)
  898. /* Enable unused function warning again */
  899. #pragma GCC diagnostic pop
  900. #endif
  901. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  902. #else
  903. static pthread_mutexattr_t pthread_mutex_attr;
  904. #endif /* _WIN32 */
  905. #if defined(_WIN32_WCE)
  906. /* Create substitutes for POSIX functions in Win32. */
  907. #if defined(GCC_DIAGNOSTIC)
  908. /* Show no warning in case system functions are not used. */
  909. #pragma GCC diagnostic push
  910. #pragma GCC diagnostic ignored "-Wunused-function"
  911. #endif
  912. FUNCTION_MAY_BE_UNUSED
  913. static time_t
  914. time(time_t *ptime)
  915. {
  916. time_t t;
  917. SYSTEMTIME st;
  918. FILETIME ft;
  919. GetSystemTime(&st);
  920. SystemTimeToFileTime(&st, &ft);
  921. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  922. if (ptime != NULL) {
  923. *ptime = t;
  924. }
  925. return t;
  926. }
  927. FUNCTION_MAY_BE_UNUSED
  928. static struct tm *
  929. localtime_s(const time_t *ptime, struct tm *ptm)
  930. {
  931. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  932. FILETIME ft, lft;
  933. SYSTEMTIME st;
  934. TIME_ZONE_INFORMATION tzinfo;
  935. if (ptm == NULL) {
  936. return NULL;
  937. }
  938. *(int64_t *)&ft = t;
  939. FileTimeToLocalFileTime(&ft, &lft);
  940. FileTimeToSystemTime(&lft, &st);
  941. ptm->tm_year = st.wYear - 1900;
  942. ptm->tm_mon = st.wMonth - 1;
  943. ptm->tm_wday = st.wDayOfWeek;
  944. ptm->tm_mday = st.wDay;
  945. ptm->tm_hour = st.wHour;
  946. ptm->tm_min = st.wMinute;
  947. ptm->tm_sec = st.wSecond;
  948. ptm->tm_yday = 0; /* hope nobody uses this */
  949. ptm->tm_isdst =
  950. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  951. return ptm;
  952. }
  953. FUNCTION_MAY_BE_UNUSED
  954. static struct tm *
  955. gmtime_s(const time_t *ptime, struct tm *ptm)
  956. {
  957. /* FIXME(lsm): fix this. */
  958. return localtime_s(ptime, ptm);
  959. }
  960. static ptrdiff_t mg_atomic_inc(volatile ptrdiff_t *addr);
  961. static struct tm tm_array[MAX_WORKER_THREADS]; /* Must be 2^n */
  962. static volatile ptrdiff_t tm_index = 0;
  963. FUNCTION_MAY_BE_UNUSED
  964. static struct tm *
  965. localtime(const time_t *ptime)
  966. {
  967. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  968. return localtime_s(ptime, tm_array + i);
  969. }
  970. FUNCTION_MAY_BE_UNUSED
  971. static struct tm *
  972. gmtime(const time_t *ptime)
  973. {
  974. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  975. return gmtime_s(ptime, tm_array + i);
  976. }
  977. FUNCTION_MAY_BE_UNUSED
  978. static size_t
  979. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  980. {
  981. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  982. * for WinCE"); */
  983. return 0;
  984. }
  985. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  986. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  987. #define remove(f) mg_remove(NULL, f)
  988. FUNCTION_MAY_BE_UNUSED
  989. static int
  990. rename(const char *a, const char *b)
  991. {
  992. wchar_t wa[W_PATH_MAX];
  993. wchar_t wb[W_PATH_MAX];
  994. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  995. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  996. return MoveFileW(wa, wb) ? 0 : -1;
  997. }
  998. struct stat {
  999. int64_t st_size;
  1000. time_t st_mtime;
  1001. };
  1002. FUNCTION_MAY_BE_UNUSED
  1003. static int
  1004. stat(const char *name, struct stat *st)
  1005. {
  1006. wchar_t wbuf[W_PATH_MAX];
  1007. WIN32_FILE_ATTRIBUTE_DATA attr;
  1008. time_t creation_time, write_time;
  1009. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  1010. memset(&attr, 0, sizeof(attr));
  1011. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  1012. st->st_size =
  1013. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  1014. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  1015. attr.ftLastWriteTime.dwHighDateTime);
  1016. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  1017. attr.ftCreationTime.dwHighDateTime);
  1018. if (creation_time > write_time) {
  1019. st->st_mtime = creation_time;
  1020. } else {
  1021. st->st_mtime = write_time;
  1022. }
  1023. return 0;
  1024. }
  1025. #define access(x, a) 1 /* not required anyway */
  1026. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  1027. /* Values from errno.h in Windows SDK (Visual Studio). */
  1028. #define EEXIST 17
  1029. #define EACCES 13
  1030. #define ENOENT 2
  1031. #if defined(GCC_DIAGNOSTIC)
  1032. /* Enable unused function warning again */
  1033. #pragma GCC diagnostic pop
  1034. #endif
  1035. #endif /* defined(_WIN32_WCE) */
  1036. #if defined(GCC_DIAGNOSTIC)
  1037. /* Show no warning in case system functions are not used. */
  1038. #pragma GCC diagnostic push
  1039. #pragma GCC diagnostic ignored "-Wunused-function"
  1040. #endif /* defined(GCC_DIAGNOSTIC) */
  1041. #if defined(__clang__)
  1042. /* Show no warning in case system functions are not used. */
  1043. #pragma clang diagnostic push
  1044. #pragma clang diagnostic ignored "-Wunused-function"
  1045. #endif
  1046. static pthread_mutex_t global_lock_mutex;
  1047. FUNCTION_MAY_BE_UNUSED
  1048. static void
  1049. mg_global_lock(void)
  1050. {
  1051. (void)pthread_mutex_lock(&global_lock_mutex);
  1052. }
  1053. FUNCTION_MAY_BE_UNUSED
  1054. static void
  1055. mg_global_unlock(void)
  1056. {
  1057. (void)pthread_mutex_unlock(&global_lock_mutex);
  1058. }
  1059. #if defined(_WIN64)
  1060. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  1061. #elif defined(_WIN32)
  1062. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  1063. #endif
  1064. /* Atomic functions working on ptrdiff_t ("signed size_t").
  1065. * Operations: Increment, Decrement, Add, Maximum.
  1066. * Up to size_t, they do not an atomic "load" operation.
  1067. */
  1068. FUNCTION_MAY_BE_UNUSED
  1069. static ptrdiff_t
  1070. mg_atomic_inc(volatile ptrdiff_t *addr)
  1071. {
  1072. ptrdiff_t ret;
  1073. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1074. ret = InterlockedIncrement64(addr);
  1075. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1076. ret = InterlockedIncrement(addr);
  1077. #elif defined(__GNUC__) \
  1078. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1079. && !defined(NO_ATOMICS)
  1080. ret = __sync_add_and_fetch(addr, 1);
  1081. #else
  1082. mg_global_lock();
  1083. ret = (++(*addr));
  1084. mg_global_unlock();
  1085. #endif
  1086. return ret;
  1087. }
  1088. FUNCTION_MAY_BE_UNUSED
  1089. static ptrdiff_t
  1090. mg_atomic_dec(volatile ptrdiff_t *addr)
  1091. {
  1092. ptrdiff_t ret;
  1093. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1094. ret = InterlockedDecrement64(addr);
  1095. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1096. ret = InterlockedDecrement(addr);
  1097. #elif defined(__GNUC__) \
  1098. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1099. && !defined(NO_ATOMICS)
  1100. ret = __sync_sub_and_fetch(addr, 1);
  1101. #else
  1102. mg_global_lock();
  1103. ret = (--(*addr));
  1104. mg_global_unlock();
  1105. #endif
  1106. return ret;
  1107. }
  1108. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  1109. static ptrdiff_t
  1110. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1111. {
  1112. ptrdiff_t ret;
  1113. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1114. ret = InterlockedAdd64(addr, value);
  1115. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1116. ret = InterlockedExchangeAdd(addr, value) + value;
  1117. #elif defined(__GNUC__) \
  1118. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1119. && !defined(NO_ATOMICS)
  1120. ret = __sync_add_and_fetch(addr, value);
  1121. #else
  1122. mg_global_lock();
  1123. *addr += value;
  1124. ret = (*addr);
  1125. mg_global_unlock();
  1126. #endif
  1127. return ret;
  1128. }
  1129. FUNCTION_MAY_BE_UNUSED
  1130. static ptrdiff_t
  1131. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1132. ptrdiff_t oldval,
  1133. ptrdiff_t newval)
  1134. {
  1135. ptrdiff_t ret;
  1136. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1137. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1138. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1139. ret = InterlockedCompareExchange(addr, newval, oldval);
  1140. #elif defined(__GNUC__) \
  1141. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1142. && !defined(NO_ATOMICS)
  1143. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1144. #else
  1145. mg_global_lock();
  1146. ret = *addr;
  1147. if ((ret != newval) && (ret == oldval)) {
  1148. *addr = newval;
  1149. }
  1150. mg_global_unlock();
  1151. #endif
  1152. return ret;
  1153. }
  1154. static void
  1155. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1156. {
  1157. register ptrdiff_t tmp = *addr;
  1158. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1159. while (tmp < value) {
  1160. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1161. }
  1162. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1163. while (tmp < value) {
  1164. tmp = InterlockedCompareExchange(addr, value, tmp);
  1165. }
  1166. #elif defined(__GNUC__) \
  1167. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1168. && !defined(NO_ATOMICS)
  1169. while (tmp < value) {
  1170. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1171. }
  1172. #else
  1173. mg_global_lock();
  1174. if (*addr < value) {
  1175. *addr = value;
  1176. }
  1177. mg_global_unlock();
  1178. #endif
  1179. }
  1180. static int64_t
  1181. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1182. {
  1183. int64_t ret;
  1184. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1185. ret = InterlockedAdd64(addr, value);
  1186. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1187. ret = InterlockedExchangeAdd64(addr, value) + value;
  1188. #elif defined(__GNUC__) \
  1189. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1190. && !defined(NO_ATOMICS)
  1191. ret = __sync_add_and_fetch(addr, value);
  1192. #else
  1193. mg_global_lock();
  1194. *addr += value;
  1195. ret = (*addr);
  1196. mg_global_unlock();
  1197. #endif
  1198. return ret;
  1199. }
  1200. #endif
  1201. #if defined(GCC_DIAGNOSTIC)
  1202. /* Show no warning in case system functions are not used. */
  1203. #pragma GCC diagnostic pop
  1204. #endif /* defined(GCC_DIAGNOSTIC) */
  1205. #if defined(__clang__)
  1206. /* Show no warning in case system functions are not used. */
  1207. #pragma clang diagnostic pop
  1208. #endif
  1209. #if defined(USE_SERVER_STATS)
  1210. struct mg_memory_stat {
  1211. volatile ptrdiff_t totalMemUsed;
  1212. volatile ptrdiff_t maxMemUsed;
  1213. volatile ptrdiff_t blockCount;
  1214. };
  1215. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1216. static void *
  1217. mg_malloc_ex(size_t size,
  1218. struct mg_context *ctx,
  1219. const char *file,
  1220. unsigned line)
  1221. {
  1222. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1223. void *memory = 0;
  1224. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1225. #if defined(MEMORY_DEBUGGING)
  1226. char mallocStr[256];
  1227. #else
  1228. (void)file;
  1229. (void)line;
  1230. #endif
  1231. if (data) {
  1232. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1233. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1234. mg_atomic_inc(&mstat->blockCount);
  1235. ((uintptr_t *)data)[0] = size;
  1236. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1237. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1238. }
  1239. #if defined(MEMORY_DEBUGGING)
  1240. sprintf(mallocStr,
  1241. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1242. memory,
  1243. (unsigned long)size,
  1244. (unsigned long)mstat->totalMemUsed,
  1245. (unsigned long)mstat->blockCount,
  1246. file,
  1247. line);
  1248. DEBUG_TRACE("%s", mallocStr);
  1249. #endif
  1250. return memory;
  1251. }
  1252. static void *
  1253. mg_calloc_ex(size_t count,
  1254. size_t size,
  1255. struct mg_context *ctx,
  1256. const char *file,
  1257. unsigned line)
  1258. {
  1259. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1260. if (data) {
  1261. memset(data, 0, size * count);
  1262. }
  1263. return data;
  1264. }
  1265. static void
  1266. mg_free_ex(void *memory, const char *file, unsigned line)
  1267. {
  1268. #if defined(MEMORY_DEBUGGING)
  1269. char mallocStr[256];
  1270. #else
  1271. (void)file;
  1272. (void)line;
  1273. #endif
  1274. if (memory) {
  1275. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1276. uintptr_t size = ((uintptr_t *)data)[0];
  1277. struct mg_memory_stat *mstat =
  1278. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1279. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1280. mg_atomic_dec(&mstat->blockCount);
  1281. #if defined(MEMORY_DEBUGGING)
  1282. sprintf(mallocStr,
  1283. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1284. memory,
  1285. (unsigned long)size,
  1286. (unsigned long)mstat->totalMemUsed,
  1287. (unsigned long)mstat->blockCount,
  1288. file,
  1289. line);
  1290. DEBUG_TRACE("%s", mallocStr);
  1291. #endif
  1292. free(data);
  1293. }
  1294. }
  1295. static void *
  1296. mg_realloc_ex(void *memory,
  1297. size_t newsize,
  1298. struct mg_context *ctx,
  1299. const char *file,
  1300. unsigned line)
  1301. {
  1302. void *data;
  1303. void *_realloc;
  1304. uintptr_t oldsize;
  1305. #if defined(MEMORY_DEBUGGING)
  1306. char mallocStr[256];
  1307. #else
  1308. (void)file;
  1309. (void)line;
  1310. #endif
  1311. if (newsize) {
  1312. if (memory) {
  1313. /* Reallocate existing block */
  1314. struct mg_memory_stat *mstat;
  1315. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1316. oldsize = ((uintptr_t *)data)[0];
  1317. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1318. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1319. if (_realloc) {
  1320. data = _realloc;
  1321. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1322. #if defined(MEMORY_DEBUGGING)
  1323. sprintf(mallocStr,
  1324. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1325. memory,
  1326. (unsigned long)oldsize,
  1327. (unsigned long)mstat->totalMemUsed,
  1328. (unsigned long)mstat->blockCount,
  1329. file,
  1330. line);
  1331. DEBUG_TRACE("%s", mallocStr);
  1332. #endif
  1333. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1334. #if defined(MEMORY_DEBUGGING)
  1335. sprintf(mallocStr,
  1336. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1337. memory,
  1338. (unsigned long)newsize,
  1339. (unsigned long)mstat->totalMemUsed,
  1340. (unsigned long)mstat->blockCount,
  1341. file,
  1342. line);
  1343. DEBUG_TRACE("%s", mallocStr);
  1344. #endif
  1345. *(uintptr_t *)data = newsize;
  1346. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1347. } else {
  1348. #if defined(MEMORY_DEBUGGING)
  1349. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1350. #endif
  1351. return _realloc;
  1352. }
  1353. } else {
  1354. /* Allocate new block */
  1355. data = mg_malloc_ex(newsize, ctx, file, line);
  1356. }
  1357. } else {
  1358. /* Free existing block */
  1359. data = 0;
  1360. mg_free_ex(memory, file, line);
  1361. }
  1362. return data;
  1363. }
  1364. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1365. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1366. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1367. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1368. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1369. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1370. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1371. #else /* USE_SERVER_STATS */
  1372. static __inline void *
  1373. mg_malloc(size_t a)
  1374. {
  1375. return malloc(a);
  1376. }
  1377. static __inline void *
  1378. mg_calloc(size_t a, size_t b)
  1379. {
  1380. return calloc(a, b);
  1381. }
  1382. static __inline void *
  1383. mg_realloc(void *a, size_t b)
  1384. {
  1385. return realloc(a, b);
  1386. }
  1387. static __inline void
  1388. mg_free(void *a)
  1389. {
  1390. free(a);
  1391. }
  1392. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1393. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1394. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1395. #define mg_free_ctx(a, c) mg_free(a)
  1396. #endif /* USE_SERVER_STATS */
  1397. static void mg_vsnprintf(const struct mg_connection *conn,
  1398. int *truncated,
  1399. char *buf,
  1400. size_t buflen,
  1401. const char *fmt,
  1402. va_list ap);
  1403. static void mg_snprintf(const struct mg_connection *conn,
  1404. int *truncated,
  1405. char *buf,
  1406. size_t buflen,
  1407. PRINTF_FORMAT_STRING(const char *fmt),
  1408. ...) PRINTF_ARGS(5, 6);
  1409. /* This following lines are just meant as a reminder to use the mg-functions
  1410. * for memory management */
  1411. #if defined(malloc)
  1412. #undef malloc
  1413. #endif
  1414. #if defined(calloc)
  1415. #undef calloc
  1416. #endif
  1417. #if defined(realloc)
  1418. #undef realloc
  1419. #endif
  1420. #if defined(free)
  1421. #undef free
  1422. #endif
  1423. #if defined(snprintf)
  1424. #undef snprintf
  1425. #endif
  1426. #if defined(vsnprintf)
  1427. #undef vsnprintf
  1428. #endif
  1429. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1430. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1431. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1432. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1433. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1434. #if defined(_WIN32)
  1435. /* vsnprintf must not be used in any system,
  1436. * but this define only works well for Windows. */
  1437. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1438. #endif
  1439. /* mg_init_library counter */
  1440. static int mg_init_library_called = 0;
  1441. #if !defined(NO_SSL)
  1442. static int mg_ssl_initialized = 0;
  1443. /* TODO: Selection of SSL library and version */
  1444. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1)
  1445. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1446. #endif
  1447. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1448. #error "Multiple OPENSSL_API versions defined"
  1449. #endif
  1450. #endif /* NO_SSL */
  1451. static pthread_key_t sTlsKey; /* Thread local storage index */
  1452. static volatile ptrdiff_t thread_idx_max = 0;
  1453. #if defined(MG_LEGACY_INTERFACE)
  1454. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1455. #endif
  1456. struct mg_workerTLS {
  1457. int is_master;
  1458. unsigned long thread_idx;
  1459. void *user_ptr;
  1460. #if defined(_WIN32)
  1461. HANDLE pthread_cond_helper_mutex;
  1462. struct mg_workerTLS *next_waiting_thread;
  1463. #endif
  1464. const char *alpn_proto;
  1465. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1466. char txtbuf[4];
  1467. #endif
  1468. };
  1469. #if defined(GCC_DIAGNOSTIC)
  1470. /* Show no warning in case system functions are not used. */
  1471. #pragma GCC diagnostic push
  1472. #pragma GCC diagnostic ignored "-Wunused-function"
  1473. #endif /* defined(GCC_DIAGNOSTIC) */
  1474. #if defined(__clang__)
  1475. /* Show no warning in case system functions are not used. */
  1476. #pragma clang diagnostic push
  1477. #pragma clang diagnostic ignored "-Wunused-function"
  1478. #endif
  1479. /* Get a unique thread ID as unsigned long, independent from the data type
  1480. * of thread IDs defined by the operating system API.
  1481. * If two calls to mg_current_thread_id return the same value, they calls
  1482. * are done from the same thread. If they return different values, they are
  1483. * done from different threads. (Provided this function is used in the same
  1484. * process context and threads are not repeatedly created and deleted, but
  1485. * CivetWeb does not do that).
  1486. * This function must match the signature required for SSL id callbacks:
  1487. * CRYPTO_set_id_callback
  1488. */
  1489. FUNCTION_MAY_BE_UNUSED
  1490. static unsigned long
  1491. mg_current_thread_id(void)
  1492. {
  1493. #if defined(_WIN32)
  1494. return GetCurrentThreadId();
  1495. #else
  1496. #if defined(__clang__)
  1497. #pragma clang diagnostic push
  1498. #pragma clang diagnostic ignored "-Wunreachable-code"
  1499. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1500. * or not, so one of the two conditions will be unreachable by construction.
  1501. * Unfortunately the C standard does not define a way to check this at
  1502. * compile time, since the #if preprocessor conditions can not use the sizeof
  1503. * operator as an argument. */
  1504. #endif
  1505. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1506. /* This is the problematic case for CRYPTO_set_id_callback:
  1507. * The OS pthread_t can not be cast to unsigned long. */
  1508. struct mg_workerTLS *tls =
  1509. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1510. if (tls == NULL) {
  1511. /* SSL called from an unknown thread: Create some thread index.
  1512. */
  1513. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1514. tls->is_master = -2; /* -2 means "3rd party thread" */
  1515. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1516. pthread_setspecific(sTlsKey, tls);
  1517. }
  1518. return tls->thread_idx;
  1519. } else {
  1520. /* pthread_t may be any data type, so a simple cast to unsigned long
  1521. * can rise a warning/error, depending on the platform.
  1522. * Here memcpy is used as an anything-to-anything cast. */
  1523. unsigned long ret = 0;
  1524. pthread_t t = pthread_self();
  1525. memcpy(&ret, &t, sizeof(pthread_t));
  1526. return ret;
  1527. }
  1528. #if defined(__clang__)
  1529. #pragma clang diagnostic pop
  1530. #endif
  1531. #endif
  1532. }
  1533. FUNCTION_MAY_BE_UNUSED
  1534. static uint64_t
  1535. mg_get_current_time_ns(void)
  1536. {
  1537. struct timespec tsnow;
  1538. clock_gettime(CLOCK_REALTIME, &tsnow);
  1539. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1540. }
  1541. #if defined(GCC_DIAGNOSTIC)
  1542. /* Show no warning in case system functions are not used. */
  1543. #pragma GCC diagnostic pop
  1544. #endif /* defined(GCC_DIAGNOSTIC) */
  1545. #if defined(__clang__)
  1546. /* Show no warning in case system functions are not used. */
  1547. #pragma clang diagnostic pop
  1548. #endif
  1549. #if defined(NEED_DEBUG_TRACE_FUNC)
  1550. static void
  1551. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1552. {
  1553. va_list args;
  1554. struct timespec tsnow;
  1555. /* Get some operating system independent thread id */
  1556. unsigned long thread_id = mg_current_thread_id();
  1557. clock_gettime(CLOCK_REALTIME, &tsnow);
  1558. flockfile(DEBUG_TRACE_STREAM);
  1559. fprintf(DEBUG_TRACE_STREAM,
  1560. "*** %lu.%09lu %lu %s:%u: ",
  1561. (unsigned long)tsnow.tv_sec,
  1562. (unsigned long)tsnow.tv_nsec,
  1563. thread_id,
  1564. func,
  1565. line);
  1566. va_start(args, fmt);
  1567. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1568. va_end(args);
  1569. putc('\n', DEBUG_TRACE_STREAM);
  1570. fflush(DEBUG_TRACE_STREAM);
  1571. funlockfile(DEBUG_TRACE_STREAM);
  1572. }
  1573. #endif /* NEED_DEBUG_TRACE_FUNC */
  1574. #define MD5_STATIC static
  1575. #include "md5.inl"
  1576. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1577. #if defined(NO_SOCKLEN_T)
  1578. typedef int socklen_t;
  1579. #endif /* NO_SOCKLEN_T */
  1580. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1581. #if !defined(MSG_NOSIGNAL)
  1582. #define MSG_NOSIGNAL (0)
  1583. #endif
  1584. #if defined(NO_SSL)
  1585. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1586. typedef struct SSL_CTX SSL_CTX;
  1587. #else
  1588. #if defined(NO_SSL_DL)
  1589. #include <openssl/bn.h>
  1590. #include <openssl/conf.h>
  1591. #include <openssl/crypto.h>
  1592. #include <openssl/dh.h>
  1593. #include <openssl/engine.h>
  1594. #include <openssl/err.h>
  1595. #include <openssl/opensslv.h>
  1596. #include <openssl/pem.h>
  1597. #include <openssl/ssl.h>
  1598. #include <openssl/tls1.h>
  1599. #include <openssl/x509.h>
  1600. #if defined(WOLFSSL_VERSION)
  1601. /* Additional defines for WolfSSL, see
  1602. * https://github.com/civetweb/civetweb/issues/583 */
  1603. #include "wolfssl_extras.inl"
  1604. #endif
  1605. #if defined(OPENSSL_IS_BORINGSSL)
  1606. /* From boringssl/src/include/openssl/mem.h:
  1607. *
  1608. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1609. * However, that was written in a time before Valgrind and ASAN. Since we now
  1610. * have those tools, the OpenSSL allocation functions are simply macros around
  1611. * the standard memory functions.
  1612. *
  1613. * #define OPENSSL_free free */
  1614. #define free free
  1615. // disable for boringssl
  1616. #define CONF_modules_unload(a) ((void)0)
  1617. #define ENGINE_cleanup() ((void)0)
  1618. #endif
  1619. /* If OpenSSL headers are included, automatically select the API version */
  1620. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1621. #if !defined(OPENSSL_API_1_1)
  1622. #define OPENSSL_API_1_1
  1623. #endif
  1624. #define OPENSSL_REMOVE_THREAD_STATE()
  1625. #else
  1626. #if !defined(OPENSSL_API_1_0)
  1627. #define OPENSSL_API_1_0
  1628. #endif
  1629. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1630. #endif
  1631. #else
  1632. /* SSL loaded dynamically from DLL.
  1633. * I put the prototypes here to be independent from OpenSSL source
  1634. * installation. */
  1635. typedef struct ssl_st SSL;
  1636. typedef struct ssl_method_st SSL_METHOD;
  1637. typedef struct ssl_ctx_st SSL_CTX;
  1638. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1639. typedef struct x509_name X509_NAME;
  1640. typedef struct asn1_integer ASN1_INTEGER;
  1641. typedef struct bignum BIGNUM;
  1642. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1643. typedef struct evp_md EVP_MD;
  1644. typedef struct x509 X509;
  1645. #define SSL_CTRL_OPTIONS (32)
  1646. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1647. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1648. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1649. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1650. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1651. #define SSL_VERIFY_NONE (0)
  1652. #define SSL_VERIFY_PEER (1)
  1653. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1654. #define SSL_VERIFY_CLIENT_ONCE (4)
  1655. #define SSL_OP_ALL (0x80000BFFul)
  1656. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1657. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1658. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1659. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1660. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1661. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1662. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1663. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1664. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1665. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1666. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1667. #define SSL_CB_HANDSHAKE_START (0x10)
  1668. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1669. #define SSL_ERROR_NONE (0)
  1670. #define SSL_ERROR_SSL (1)
  1671. #define SSL_ERROR_WANT_READ (2)
  1672. #define SSL_ERROR_WANT_WRITE (3)
  1673. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1674. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1675. #define SSL_ERROR_ZERO_RETURN (6)
  1676. #define SSL_ERROR_WANT_CONNECT (7)
  1677. #define SSL_ERROR_WANT_ACCEPT (8)
  1678. #define TLSEXT_TYPE_server_name (0)
  1679. #define TLSEXT_NAMETYPE_host_name (0)
  1680. #define SSL_TLSEXT_ERR_OK (0)
  1681. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1682. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1683. #define SSL_TLSEXT_ERR_NOACK (3)
  1684. #define SSL_SESS_CACHE_BOTH (3)
  1685. enum ssl_func_category {
  1686. TLS_Mandatory, /* required for HTTPS */
  1687. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1688. TLS_END_OF_LIST
  1689. };
  1690. /* Check if all TLS functions/features are available */
  1691. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1692. struct ssl_func {
  1693. const char *name; /* SSL function name */
  1694. enum ssl_func_category required; /* Mandatory or optional */
  1695. void (*ptr)(void); /* Function pointer */
  1696. };
  1697. #if defined(OPENSSL_API_1_1)
  1698. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1699. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1700. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1701. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1702. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1703. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1704. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1705. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1706. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1707. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1708. #define OPENSSL_init_ssl \
  1709. (*(int (*)(uint64_t opts, \
  1710. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1711. .ptr)
  1712. #define SSL_CTX_use_PrivateKey_file \
  1713. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1714. #define SSL_CTX_use_certificate_file \
  1715. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1716. #define SSL_CTX_set_default_passwd_cb \
  1717. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1718. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1719. #define SSL_CTX_use_certificate_chain_file \
  1720. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1721. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1722. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1723. #define SSL_CTX_set_verify \
  1724. (*(void (*)(SSL_CTX *, \
  1725. int, \
  1726. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1727. .ptr)
  1728. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1729. #define SSL_CTX_load_verify_locations \
  1730. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1731. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1732. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1733. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1734. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1735. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1736. #define SSL_CIPHER_get_name \
  1737. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1738. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1739. #define SSL_CTX_set_session_id_context \
  1740. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1741. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1742. #define SSL_CTX_set_cipher_list \
  1743. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1744. #define SSL_CTX_set_options \
  1745. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1746. #define SSL_CTX_set_info_callback \
  1747. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1748. ssl_sw[32] \
  1749. .ptr)
  1750. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1751. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1752. #define SSL_CTX_callback_ctrl \
  1753. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1754. #define SSL_get_servername \
  1755. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1756. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1757. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1758. #define SSL_CTX_set_alpn_protos \
  1759. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1760. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1761. const unsigned char **out,
  1762. unsigned char *outlen,
  1763. const unsigned char *in,
  1764. unsigned int inlen,
  1765. void *arg);
  1766. #define SSL_CTX_set_alpn_select_cb \
  1767. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1768. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1769. const unsigned char **out,
  1770. unsigned int *outlen,
  1771. void *arg);
  1772. #define SSL_CTX_set_next_protos_advertised_cb \
  1773. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1774. .ptr)
  1775. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1776. #define SSL_CTX_clear_options(ctx, op) \
  1777. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1778. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1779. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1780. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1781. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1782. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1783. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1784. SSL_CTX_callback_ctrl(ctx, \
  1785. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1786. (void (*)(void))cb)
  1787. #define SSL_set_tlsext_host_name(ctx, arg) \
  1788. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1789. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1790. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1791. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1792. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1793. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1794. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1795. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1796. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1797. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1798. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1799. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1800. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1801. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1802. #define X509_NAME_oneline \
  1803. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1804. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1805. #define EVP_get_digestbyname \
  1806. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1807. #define EVP_Digest \
  1808. (*(int (*)( \
  1809. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1810. crypto_sw[9] \
  1811. .ptr)
  1812. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1813. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1814. #define ASN1_INTEGER_to_BN \
  1815. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1816. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1817. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1818. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1819. #define OPENSSL_free(a) CRYPTO_free(a)
  1820. #define OPENSSL_REMOVE_THREAD_STATE()
  1821. /* init_ssl_ctx() function updates this array.
  1822. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1823. * of respective functions. The macros above (like SSL_connect()) are really
  1824. * just calling these functions indirectly via the pointer. */
  1825. static struct ssl_func ssl_sw[] = {
  1826. {"SSL_free", TLS_Mandatory, NULL},
  1827. {"SSL_accept", TLS_Mandatory, NULL},
  1828. {"SSL_connect", TLS_Mandatory, NULL},
  1829. {"SSL_read", TLS_Mandatory, NULL},
  1830. {"SSL_write", TLS_Mandatory, NULL},
  1831. {"SSL_get_error", TLS_Mandatory, NULL},
  1832. {"SSL_set_fd", TLS_Mandatory, NULL},
  1833. {"SSL_new", TLS_Mandatory, NULL},
  1834. {"SSL_CTX_new", TLS_Mandatory, NULL},
  1835. {"TLS_server_method", TLS_Mandatory, NULL},
  1836. {"OPENSSL_init_ssl", TLS_Mandatory, NULL},
  1837. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  1838. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  1839. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  1840. {"SSL_CTX_free", TLS_Mandatory, NULL},
  1841. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  1842. {"TLS_client_method", TLS_Mandatory, NULL},
  1843. {"SSL_pending", TLS_Mandatory, NULL},
  1844. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  1845. {"SSL_shutdown", TLS_Mandatory, NULL},
  1846. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  1847. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  1848. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  1849. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  1850. {"SSL_get_version", TLS_Mandatory, NULL},
  1851. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  1852. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  1853. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  1854. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  1855. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  1856. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  1857. {"SSL_CTX_set_options", TLS_Mandatory, NULL},
  1858. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  1859. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  1860. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  1861. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  1862. {"SSL_get_servername", TLS_Mandatory, NULL},
  1863. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  1864. {"SSL_ctrl", TLS_Mandatory, NULL},
  1865. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  1866. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  1867. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  1868. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  1869. {NULL, TLS_END_OF_LIST, NULL}};
  1870. /* Similar array as ssl_sw. These functions could be located in different
  1871. * lib. */
  1872. static struct ssl_func crypto_sw[] = {
  1873. {"ERR_get_error", TLS_Mandatory, NULL},
  1874. {"ERR_error_string", TLS_Mandatory, NULL},
  1875. {"CONF_modules_unload", TLS_Mandatory, NULL},
  1876. {"X509_free", TLS_Mandatory, NULL},
  1877. {"X509_get_subject_name", TLS_Mandatory, NULL},
  1878. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  1879. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  1880. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  1881. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  1882. {"EVP_Digest", TLS_Mandatory, NULL},
  1883. {"i2d_X509", TLS_Mandatory, NULL},
  1884. {"BN_bn2hex", TLS_Mandatory, NULL},
  1885. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  1886. {"BN_free", TLS_Mandatory, NULL},
  1887. {"CRYPTO_free", TLS_Mandatory, NULL},
  1888. {"ERR_clear_error", TLS_Mandatory, NULL},
  1889. {NULL, TLS_END_OF_LIST, NULL}};
  1890. #else
  1891. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1892. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1893. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1894. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1895. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1896. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1897. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1898. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1899. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1900. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1901. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1902. #define SSL_CTX_use_PrivateKey_file \
  1903. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1904. #define SSL_CTX_use_certificate_file \
  1905. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1906. #define SSL_CTX_set_default_passwd_cb \
  1907. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1908. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1909. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1910. #define SSL_CTX_use_certificate_chain_file \
  1911. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1912. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1913. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1914. #define SSL_CTX_set_verify \
  1915. (*(void (*)(SSL_CTX *, \
  1916. int, \
  1917. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1918. .ptr)
  1919. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1920. #define SSL_CTX_load_verify_locations \
  1921. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1922. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1923. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1924. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1925. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1926. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1927. #define SSL_CIPHER_get_name \
  1928. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1929. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1930. #define SSL_CTX_set_session_id_context \
  1931. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1932. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1933. #define SSL_CTX_set_cipher_list \
  1934. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1935. #define SSL_CTX_set_info_callback \
  1936. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1937. .ptr)
  1938. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1939. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1940. #define SSL_CTX_callback_ctrl \
  1941. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1942. #define SSL_get_servername \
  1943. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1944. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1945. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1946. #define SSL_CTX_set_alpn_protos \
  1947. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1948. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1949. const unsigned char **out,
  1950. unsigned char *outlen,
  1951. const unsigned char *in,
  1952. unsigned int inlen,
  1953. void *arg);
  1954. #define SSL_CTX_set_alpn_select_cb \
  1955. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1956. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1957. const unsigned char **out,
  1958. unsigned int *outlen,
  1959. void *arg);
  1960. #define SSL_CTX_set_next_protos_advertised_cb \
  1961. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1962. .ptr)
  1963. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1964. #define SSL_CTX_set_options(ctx, op) \
  1965. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1966. #define SSL_CTX_clear_options(ctx, op) \
  1967. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1968. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1969. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1970. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1971. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1972. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1973. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1974. SSL_CTX_callback_ctrl(ctx, \
  1975. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1976. (void (*)(void))cb)
  1977. #define SSL_set_tlsext_host_name(ctx, arg) \
  1978. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1979. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1980. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1981. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1982. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1983. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1984. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1985. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1986. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1987. #define CRYPTO_set_locking_callback \
  1988. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1989. #define CRYPTO_set_id_callback \
  1990. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1991. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1992. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1993. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1994. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1995. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1996. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1997. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1998. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1999. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  2000. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  2001. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  2002. #define X509_NAME_oneline \
  2003. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  2004. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  2005. #define i2c_ASN1_INTEGER \
  2006. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  2007. #define EVP_get_digestbyname \
  2008. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  2009. #define EVP_Digest \
  2010. (*(int (*)( \
  2011. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  2012. crypto_sw[18] \
  2013. .ptr)
  2014. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  2015. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  2016. #define ASN1_INTEGER_to_BN \
  2017. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  2018. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  2019. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  2020. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  2021. #define OPENSSL_free(a) CRYPTO_free(a)
  2022. /* use here ERR_remove_state,
  2023. * while on some platforms function is not included into library due to
  2024. * deprication */
  2025. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  2026. /* init_ssl_ctx() function updates this array.
  2027. * It loads SSL library dynamically and changes NULLs to the actual addresses
  2028. * of respective functions. The macros above (like SSL_connect()) are really
  2029. * just calling these functions indirectly via the pointer. */
  2030. static struct ssl_func ssl_sw[] = {
  2031. {"SSL_free", TLS_Mandatory, NULL},
  2032. {"SSL_accept", TLS_Mandatory, NULL},
  2033. {"SSL_connect", TLS_Mandatory, NULL},
  2034. {"SSL_read", TLS_Mandatory, NULL},
  2035. {"SSL_write", TLS_Mandatory, NULL},
  2036. {"SSL_get_error", TLS_Mandatory, NULL},
  2037. {"SSL_set_fd", TLS_Mandatory, NULL},
  2038. {"SSL_new", TLS_Mandatory, NULL},
  2039. {"SSL_CTX_new", TLS_Mandatory, NULL},
  2040. {"SSLv23_server_method", TLS_Mandatory, NULL},
  2041. {"SSL_library_init", TLS_Mandatory, NULL},
  2042. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  2043. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  2044. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  2045. {"SSL_CTX_free", TLS_Mandatory, NULL},
  2046. {"SSL_load_error_strings", TLS_Mandatory, NULL},
  2047. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  2048. {"SSLv23_client_method", TLS_Mandatory, NULL},
  2049. {"SSL_pending", TLS_Mandatory, NULL},
  2050. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  2051. {"SSL_shutdown", TLS_Mandatory, NULL},
  2052. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  2053. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  2054. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  2055. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  2056. {"SSL_get_version", TLS_Mandatory, NULL},
  2057. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  2058. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  2059. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  2060. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  2061. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  2062. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  2063. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  2064. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  2065. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  2066. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  2067. {"SSL_get_servername", TLS_Mandatory, NULL},
  2068. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  2069. {"SSL_ctrl", TLS_Mandatory, NULL},
  2070. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  2071. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  2072. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  2073. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  2074. {NULL, TLS_END_OF_LIST, NULL}};
  2075. /* Similar array as ssl_sw. These functions could be located in different
  2076. * lib. */
  2077. static struct ssl_func crypto_sw[] = {
  2078. {"CRYPTO_num_locks", TLS_Mandatory, NULL},
  2079. {"CRYPTO_set_locking_callback", TLS_Mandatory, NULL},
  2080. {"CRYPTO_set_id_callback", TLS_Mandatory, NULL},
  2081. {"ERR_get_error", TLS_Mandatory, NULL},
  2082. {"ERR_error_string", TLS_Mandatory, NULL},
  2083. {"ERR_remove_state", TLS_Mandatory, NULL},
  2084. {"ERR_free_strings", TLS_Mandatory, NULL},
  2085. {"ENGINE_cleanup", TLS_Mandatory, NULL},
  2086. {"CONF_modules_unload", TLS_Mandatory, NULL},
  2087. {"CRYPTO_cleanup_all_ex_data", TLS_Mandatory, NULL},
  2088. {"EVP_cleanup", TLS_Mandatory, NULL},
  2089. {"X509_free", TLS_Mandatory, NULL},
  2090. {"X509_get_subject_name", TLS_Mandatory, NULL},
  2091. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  2092. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  2093. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  2094. {"i2c_ASN1_INTEGER", TLS_Mandatory, NULL},
  2095. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  2096. {"EVP_Digest", TLS_Mandatory, NULL},
  2097. {"i2d_X509", TLS_Mandatory, NULL},
  2098. {"BN_bn2hex", TLS_Mandatory, NULL},
  2099. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  2100. {"BN_free", TLS_Mandatory, NULL},
  2101. {"CRYPTO_free", TLS_Mandatory, NULL},
  2102. {"ERR_clear_error", TLS_Mandatory, NULL},
  2103. {NULL, TLS_END_OF_LIST, NULL}};
  2104. #endif /* OPENSSL_API_1_1 */
  2105. #endif /* NO_SSL_DL */
  2106. #endif /* NO_SSL */
  2107. #if !defined(NO_CACHING)
  2108. static const char month_names[][4] = {"Jan",
  2109. "Feb",
  2110. "Mar",
  2111. "Apr",
  2112. "May",
  2113. "Jun",
  2114. "Jul",
  2115. "Aug",
  2116. "Sep",
  2117. "Oct",
  2118. "Nov",
  2119. "Dec"};
  2120. #endif /* !NO_CACHING */
  2121. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2122. * the union u. */
  2123. union usa {
  2124. struct sockaddr sa;
  2125. struct sockaddr_in sin;
  2126. #if defined(USE_IPV6)
  2127. struct sockaddr_in6 sin6;
  2128. #endif
  2129. #if defined(USE_X_DOM_SOCKET)
  2130. struct sockaddr_un sun;
  2131. #endif
  2132. };
  2133. #if defined(USE_X_DOM_SOCKET)
  2134. static unsigned short
  2135. USA_IN_PORT_UNSAFE(union usa *s)
  2136. {
  2137. if (s->sa.sa_family == AF_INET)
  2138. return s->sin.sin_port;
  2139. #if defined(USE_IPV6)
  2140. if (s->sa.sa_family == AF_INET6)
  2141. return s->sin6.sin6_port;
  2142. #endif
  2143. return 0;
  2144. }
  2145. #endif
  2146. #if defined(USE_IPV6)
  2147. #define USA_IN_PORT_UNSAFE(s) \
  2148. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  2149. #else
  2150. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  2151. #endif
  2152. /* Describes a string (chunk of memory). */
  2153. struct vec {
  2154. const char *ptr;
  2155. size_t len;
  2156. };
  2157. struct mg_file_stat {
  2158. /* File properties filled by mg_stat: */
  2159. uint64_t size;
  2160. time_t last_modified;
  2161. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2162. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2163. * case we need a "Content-Eencoding: gzip" header */
  2164. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2165. };
  2166. struct mg_file_access {
  2167. /* File properties filled by mg_fopen: */
  2168. FILE *fp;
  2169. };
  2170. struct mg_file {
  2171. struct mg_file_stat stat;
  2172. struct mg_file_access access;
  2173. };
  2174. #define STRUCT_FILE_INITIALIZER \
  2175. { \
  2176. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2177. { \
  2178. (FILE *)NULL \
  2179. } \
  2180. }
  2181. /* Describes listening socket, or socket which was accept()-ed by the master
  2182. * thread and queued for future handling by the worker thread. */
  2183. struct socket {
  2184. SOCKET sock; /* Listening socket */
  2185. union usa lsa; /* Local socket address */
  2186. union usa rsa; /* Remote socket address */
  2187. unsigned char is_ssl; /* Is port SSL-ed */
  2188. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2189. * port */
  2190. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2191. };
  2192. /* Enum const for all options must be in sync with
  2193. * static struct mg_option config_options[]
  2194. * This is tested in the unit test (test/private.c)
  2195. * "Private Config Options"
  2196. */
  2197. enum {
  2198. /* Once for each server */
  2199. LISTENING_PORTS,
  2200. NUM_THREADS,
  2201. RUN_AS_USER,
  2202. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2203. * socket option typedef TCP_NODELAY. */
  2204. MAX_REQUEST_SIZE,
  2205. LINGER_TIMEOUT,
  2206. CONNECTION_QUEUE_SIZE,
  2207. LISTEN_BACKLOG_SIZE,
  2208. #if defined(__linux__)
  2209. ALLOW_SENDFILE_CALL,
  2210. #endif
  2211. #if defined(_WIN32)
  2212. CASE_SENSITIVE_FILES,
  2213. #endif
  2214. THROTTLE,
  2215. ACCESS_LOG_FILE,
  2216. ERROR_LOG_FILE,
  2217. ENABLE_KEEP_ALIVE,
  2218. REQUEST_TIMEOUT,
  2219. KEEP_ALIVE_TIMEOUT,
  2220. #if defined(USE_WEBSOCKET)
  2221. WEBSOCKET_TIMEOUT,
  2222. ENABLE_WEBSOCKET_PING_PONG,
  2223. #endif
  2224. DECODE_URL,
  2225. #if defined(USE_LUA)
  2226. LUA_BACKGROUND_SCRIPT,
  2227. LUA_BACKGROUND_SCRIPT_PARAMS,
  2228. #endif
  2229. #if defined(USE_HTTP2)
  2230. ENABLE_HTTP2,
  2231. #endif
  2232. /* Once for each domain */
  2233. DOCUMENT_ROOT,
  2234. CGI_EXTENSIONS,
  2235. CGI2_EXTENSIONS,
  2236. CGI_ENVIRONMENT,
  2237. CGI2_ENVIRONMENT,
  2238. CGI_INTERPRETER,
  2239. CGI2_INTERPRETER,
  2240. CGI_INTERPRETER_ARGS,
  2241. CGI2_INTERPRETER_ARGS,
  2242. #if defined(USE_TIMERS)
  2243. CGI_TIMEOUT,
  2244. CGI2_TIMEOUT,
  2245. #endif
  2246. PUT_DELETE_PASSWORDS_FILE,
  2247. PROTECT_URI,
  2248. AUTHENTICATION_DOMAIN,
  2249. ENABLE_AUTH_DOMAIN_CHECK,
  2250. SSI_EXTENSIONS,
  2251. ENABLE_DIRECTORY_LISTING,
  2252. GLOBAL_PASSWORDS_FILE,
  2253. INDEX_FILES,
  2254. ACCESS_CONTROL_LIST,
  2255. EXTRA_MIME_TYPES,
  2256. SSL_CERTIFICATE,
  2257. SSL_CERTIFICATE_CHAIN,
  2258. URL_REWRITE_PATTERN,
  2259. HIDE_FILES,
  2260. SSL_DO_VERIFY_PEER,
  2261. SSL_CACHE_TIMEOUT,
  2262. SSL_CA_PATH,
  2263. SSL_CA_FILE,
  2264. SSL_VERIFY_DEPTH,
  2265. SSL_DEFAULT_VERIFY_PATHS,
  2266. SSL_CIPHER_LIST,
  2267. SSL_PROTOCOL_VERSION,
  2268. SSL_SHORT_TRUST,
  2269. #if defined(USE_LUA)
  2270. LUA_PRELOAD_FILE,
  2271. LUA_SCRIPT_EXTENSIONS,
  2272. LUA_SERVER_PAGE_EXTENSIONS,
  2273. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2274. LUA_DEBUG_PARAMS,
  2275. #endif
  2276. #endif
  2277. #if defined(USE_DUKTAPE)
  2278. DUKTAPE_SCRIPT_EXTENSIONS,
  2279. #endif
  2280. #if defined(USE_WEBSOCKET)
  2281. WEBSOCKET_ROOT,
  2282. #endif
  2283. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2284. LUA_WEBSOCKET_EXTENSIONS,
  2285. #endif
  2286. ACCESS_CONTROL_ALLOW_ORIGIN,
  2287. ACCESS_CONTROL_ALLOW_METHODS,
  2288. ACCESS_CONTROL_ALLOW_HEADERS,
  2289. ERROR_PAGES,
  2290. #if !defined(NO_CACHING)
  2291. STATIC_FILE_MAX_AGE,
  2292. STATIC_FILE_CACHE_CONTROL,
  2293. #endif
  2294. #if !defined(NO_SSL)
  2295. STRICT_HTTPS_MAX_AGE,
  2296. #endif
  2297. ADDITIONAL_HEADER,
  2298. ALLOW_INDEX_SCRIPT_SUB_RES,
  2299. #if defined(DAEMONIZE)
  2300. ENABLE_DAEMONIZE,
  2301. #endif
  2302. NUM_OPTIONS
  2303. };
  2304. /* Config option name, config types, default value.
  2305. * Must be in the same order as the enum const above.
  2306. */
  2307. static const struct mg_option config_options[] = {
  2308. /* Once for each server */
  2309. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2310. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2311. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2312. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2313. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2314. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2315. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2316. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2317. #if defined(__linux__)
  2318. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2319. #endif
  2320. #if defined(_WIN32)
  2321. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2322. #endif
  2323. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2324. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2325. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2326. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2327. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2328. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2329. #if defined(USE_WEBSOCKET)
  2330. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2331. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2332. #endif
  2333. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2334. #if defined(USE_LUA)
  2335. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2336. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2337. #endif
  2338. #if defined(USE_HTTP2)
  2339. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2340. #endif
  2341. /* Once for each domain */
  2342. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2343. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2344. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2345. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2346. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2347. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2348. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2349. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2350. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2351. #if defined(USE_TIMERS)
  2352. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2353. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2354. #endif
  2355. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2356. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2357. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2358. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2359. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2360. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2361. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2362. {"index_files",
  2363. MG_CONFIG_TYPE_STRING_LIST,
  2364. #if defined(USE_LUA)
  2365. "index.xhtml,index.html,index.htm,"
  2366. "index.lp,index.lsp,index.lua,index.cgi,"
  2367. "index.shtml,index.php"},
  2368. #else
  2369. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2370. #endif
  2371. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2372. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2373. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2374. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2375. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2376. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2377. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2378. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  2379. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2380. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2381. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2382. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2383. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2384. #if defined(USE_HTTP2)
  2385. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  2386. * as a minimum in 2020 */
  2387. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  2388. #else
  2389. /* Keep the default (compatibility) */
  2390. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2391. #endif /* defined(USE_HTTP2) */
  2392. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2393. #if defined(USE_LUA)
  2394. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2395. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2396. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2397. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2398. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2399. #endif
  2400. #endif
  2401. #if defined(USE_DUKTAPE)
  2402. /* The support for duktape is still in alpha version state.
  2403. * The name of this config option might change. */
  2404. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2405. #endif
  2406. #if defined(USE_WEBSOCKET)
  2407. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2408. #endif
  2409. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2410. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2411. #endif
  2412. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2413. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2414. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2415. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2416. #if !defined(NO_CACHING)
  2417. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2418. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2419. #endif
  2420. #if !defined(NO_SSL)
  2421. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2422. #endif
  2423. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2424. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2425. #if defined(DAEMONIZE)
  2426. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2427. #endif
  2428. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2429. /* Check if the config_options and the corresponding enum have compatible
  2430. * sizes. */
  2431. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2432. == (NUM_OPTIONS + 1),
  2433. "config_options and enum not sync");
  2434. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2435. struct mg_handler_info {
  2436. /* Name/Pattern of the URI. */
  2437. char *uri;
  2438. size_t uri_len;
  2439. /* handler type */
  2440. int handler_type;
  2441. /* Handler for http/https or authorization requests. */
  2442. mg_request_handler handler;
  2443. unsigned int refcount;
  2444. int removing;
  2445. /* Handler for ws/wss (websocket) requests. */
  2446. mg_websocket_connect_handler connect_handler;
  2447. mg_websocket_ready_handler ready_handler;
  2448. mg_websocket_data_handler data_handler;
  2449. mg_websocket_close_handler close_handler;
  2450. /* accepted subprotocols for ws/wss requests. */
  2451. struct mg_websocket_subprotocols *subprotocols;
  2452. /* Handler for authorization requests */
  2453. mg_authorization_handler auth_handler;
  2454. /* User supplied argument for the handler function. */
  2455. void *cbdata;
  2456. /* next handler in a linked list */
  2457. struct mg_handler_info *next;
  2458. };
  2459. enum {
  2460. CONTEXT_INVALID,
  2461. CONTEXT_SERVER,
  2462. CONTEXT_HTTP_CLIENT,
  2463. CONTEXT_WS_CLIENT
  2464. };
  2465. struct mg_domain_context {
  2466. SSL_CTX *ssl_ctx; /* SSL context */
  2467. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2468. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2469. int64_t ssl_cert_last_mtime;
  2470. /* Server nonce */
  2471. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2472. unsigned long nonce_count; /* Used nonces, used for authentication */
  2473. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2474. /* linked list of shared lua websockets */
  2475. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2476. #endif
  2477. /* Linked list of domains */
  2478. struct mg_domain_context *next;
  2479. };
  2480. /* Stop flag can be "volatile" or require a lock.
  2481. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  2482. * states a read operation for int is always atomic. */
  2483. #if defined(STOP_FLAG_NEEDS_LOCK)
  2484. typedef ptrdiff_t volatile stop_flag_t;
  2485. static int
  2486. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2487. {
  2488. stop_flag_t sf = mg_atomic_add(f, 0);
  2489. return (sf == 0);
  2490. }
  2491. static int
  2492. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2493. {
  2494. stop_flag_t sf = mg_atomic_add(f, 0);
  2495. return (sf == 2);
  2496. }
  2497. static void
  2498. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2499. {
  2500. stop_flag_t sf;
  2501. do {
  2502. sf = mg_atomic_compare_and_swap(f, *f, v);
  2503. } while (sf != v);
  2504. }
  2505. #else /* STOP_FLAG_NEEDS_LOCK */
  2506. typedef int volatile stop_flag_t;
  2507. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2508. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2509. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2510. #endif /* STOP_FLAG_NEEDS_LOCK */
  2511. struct mg_context {
  2512. /* Part 1 - Physical context:
  2513. * This holds threads, ports, timeouts, ...
  2514. * set for the entire server, independent from the
  2515. * addressed hostname.
  2516. */
  2517. /* Connection related */
  2518. int context_type; /* See CONTEXT_* above */
  2519. struct socket *listening_sockets;
  2520. struct mg_pollfd *listening_socket_fds;
  2521. unsigned int num_listening_sockets;
  2522. struct mg_connection *worker_connections; /* The connection struct, pre-
  2523. * allocated for each worker */
  2524. #if defined(USE_SERVER_STATS)
  2525. volatile ptrdiff_t active_connections;
  2526. volatile ptrdiff_t max_active_connections;
  2527. volatile ptrdiff_t total_connections;
  2528. volatile ptrdiff_t total_requests;
  2529. volatile int64_t total_data_read;
  2530. volatile int64_t total_data_written;
  2531. #endif
  2532. /* Thread related */
  2533. stop_flag_t stop_flag; /* Should we stop event loop */
  2534. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2535. pthread_t masterthreadid; /* The master thread ID */
  2536. unsigned int
  2537. cfg_worker_threads; /* The number of configured worker threads. */
  2538. pthread_t *worker_threadids; /* The worker thread IDs */
  2539. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2540. /* Connection to thread dispatching */
  2541. #if defined(ALTERNATIVE_QUEUE)
  2542. struct socket *client_socks;
  2543. void **client_wait_events;
  2544. #else
  2545. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2546. worker thread */
  2547. volatile int sq_head; /* Head of the socket queue */
  2548. volatile int sq_tail; /* Tail of the socket queue */
  2549. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2550. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2551. volatile int sq_blocked; /* Status information: sq is full */
  2552. int sq_size; /* No of elements in socket queue */
  2553. #if defined(USE_SERVER_STATS)
  2554. int sq_max_fill;
  2555. #endif /* USE_SERVER_STATS */
  2556. #endif /* ALTERNATIVE_QUEUE */
  2557. /* Memory related */
  2558. unsigned int max_request_size; /* The max request size */
  2559. #if defined(USE_SERVER_STATS)
  2560. struct mg_memory_stat ctx_memory;
  2561. #endif
  2562. /* Operating system related */
  2563. char *systemName; /* What operating system is running */
  2564. time_t start_time; /* Server start time, used for authentication
  2565. * and for diagnstics. */
  2566. #if defined(USE_TIMERS)
  2567. struct ttimers *timers;
  2568. #endif
  2569. /* Lua specific: Background operations and shared websockets */
  2570. #if defined(USE_LUA)
  2571. void *lua_background_state;
  2572. #endif
  2573. /* Server nonce */
  2574. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2575. * ssl_cert_last_mtime, nonce_count, and
  2576. * next (linked list) */
  2577. /* Server callbacks */
  2578. struct mg_callbacks callbacks; /* User-defined callback function */
  2579. void *user_data; /* User-defined data */
  2580. /* Part 2 - Logical domain:
  2581. * This holds hostname, TLS certificate, document root, ...
  2582. * set for a domain hosted at the server.
  2583. * There may be multiple domains hosted at one physical server.
  2584. * The default domain "dd" is the first element of a list of
  2585. * domains.
  2586. */
  2587. struct mg_domain_context dd; /* default domain */
  2588. };
  2589. #if defined(USE_SERVER_STATS)
  2590. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2591. static struct mg_memory_stat *
  2592. get_memory_stat(struct mg_context *ctx)
  2593. {
  2594. if (ctx) {
  2595. return &(ctx->ctx_memory);
  2596. }
  2597. return &mg_common_memory;
  2598. }
  2599. #endif
  2600. enum {
  2601. CONNECTION_TYPE_INVALID = 0,
  2602. CONNECTION_TYPE_REQUEST = 1,
  2603. CONNECTION_TYPE_RESPONSE = 2
  2604. };
  2605. enum {
  2606. PROTOCOL_TYPE_HTTP1 = 0,
  2607. PROTOCOL_TYPE_WEBSOCKET = 1,
  2608. PROTOCOL_TYPE_HTTP2 = 2
  2609. };
  2610. #if defined(USE_HTTP2)
  2611. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2612. #define HTTP2_DYN_TABLE_SIZE (256)
  2613. #endif
  2614. struct mg_http2_connection {
  2615. uint32_t stream_id;
  2616. uint32_t dyn_table_size;
  2617. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2618. };
  2619. #endif
  2620. struct mg_connection {
  2621. int connection_type; /* see CONNECTION_TYPE_* above */
  2622. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2623. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2624. fully sent */
  2625. #if defined(USE_HTTP2)
  2626. struct mg_http2_connection http2;
  2627. #endif
  2628. struct mg_request_info request_info;
  2629. struct mg_response_info response_info;
  2630. struct mg_context *phys_ctx;
  2631. struct mg_domain_context *dom_ctx;
  2632. #if defined(USE_SERVER_STATS)
  2633. int conn_state; /* 0 = undef, numerical value may change in different
  2634. * versions. For the current definition, see
  2635. * mg_get_connection_info_impl */
  2636. #endif
  2637. SSL *ssl; /* SSL descriptor */
  2638. struct socket client; /* Connected client */
  2639. time_t conn_birth_time; /* Time (wall clock) when connection was
  2640. * established */
  2641. #if defined(USE_SERVER_STATS)
  2642. time_t conn_close_time; /* Time (wall clock) when connection was
  2643. * closed (or 0 if still open) */
  2644. #endif
  2645. struct timespec req_time; /* Time (since system start) when the request
  2646. * was received */
  2647. int64_t num_bytes_sent; /* Total bytes sent to client */
  2648. int64_t content_len; /* How many bytes of content can be read
  2649. * !is_chunked: Content-Length header value
  2650. * or -1 (until connection closed,
  2651. * not allowed for a request)
  2652. * is_chunked: >= 0, appended gradually
  2653. */
  2654. int64_t consumed_content; /* How many bytes of content have been read */
  2655. int is_chunked; /* Transfer-Encoding is chunked:
  2656. * 0 = not chunked,
  2657. * 1 = chunked, not yet, or some data read,
  2658. * 2 = chunked, has error,
  2659. * 3 = chunked, all data read except trailer,
  2660. * 4 = chunked, all data read
  2661. */
  2662. char *buf; /* Buffer for received data */
  2663. char *path_info; /* PATH_INFO part of the URL */
  2664. int must_close; /* 1 if connection must be closed */
  2665. int accept_gzip; /* 1 if gzip encoding is accepted */
  2666. int in_error_handler; /* 1 if in handler for user defined error
  2667. * pages */
  2668. #if defined(USE_WEBSOCKET)
  2669. int in_websocket_handling; /* 1 if in read_websocket */
  2670. #endif
  2671. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2672. && defined(MG_EXPERIMENTAL_INTERFACES)
  2673. /* Parameters for websocket data compression according to rfc7692 */
  2674. int websocket_deflate_server_max_windows_bits;
  2675. int websocket_deflate_client_max_windows_bits;
  2676. int websocket_deflate_server_no_context_takeover;
  2677. int websocket_deflate_client_no_context_takeover;
  2678. int websocket_deflate_initialized;
  2679. int websocket_deflate_flush;
  2680. z_stream websocket_deflate_state;
  2681. z_stream websocket_inflate_state;
  2682. #endif
  2683. int handled_requests; /* Number of requests handled by this connection
  2684. */
  2685. int buf_size; /* Buffer size */
  2686. int request_len; /* Size of the request + headers in a buffer */
  2687. int data_len; /* Total size of data in a buffer */
  2688. int status_code; /* HTTP reply status code, e.g. 200 */
  2689. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2690. * throttle */
  2691. time_t last_throttle_time; /* Last time throttled data was sent */
  2692. int last_throttle_bytes; /* Bytes sent this second */
  2693. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2694. * atomic transmissions for websockets */
  2695. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2696. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2697. #endif
  2698. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2699. * for quick access */
  2700. };
  2701. /* Directory entry */
  2702. struct de {
  2703. struct mg_connection *conn;
  2704. char *file_name;
  2705. struct mg_file_stat file;
  2706. };
  2707. #define mg_cry_internal(conn, fmt, ...) \
  2708. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2709. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2710. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2711. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2712. struct mg_context *ctx,
  2713. const char *func,
  2714. unsigned line,
  2715. const char *fmt,
  2716. ...) PRINTF_ARGS(5, 6);
  2717. #if !defined(NO_THREAD_NAME)
  2718. #if defined(_WIN32) && defined(_MSC_VER)
  2719. /* Set the thread name for debugging purposes in Visual Studio
  2720. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2721. */
  2722. #pragma pack(push, 8)
  2723. typedef struct tagTHREADNAME_INFO {
  2724. DWORD dwType; /* Must be 0x1000. */
  2725. LPCSTR szName; /* Pointer to name (in user addr space). */
  2726. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2727. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2728. } THREADNAME_INFO;
  2729. #pragma pack(pop)
  2730. #elif defined(__linux__)
  2731. #include <sys/prctl.h>
  2732. #include <sys/sendfile.h>
  2733. #if defined(ALTERNATIVE_QUEUE)
  2734. #include <sys/eventfd.h>
  2735. #endif /* ALTERNATIVE_QUEUE */
  2736. #if defined(ALTERNATIVE_QUEUE)
  2737. static void *
  2738. event_create(void)
  2739. {
  2740. int evhdl = eventfd(0, EFD_CLOEXEC);
  2741. int *ret;
  2742. if (evhdl == -1) {
  2743. /* Linux uses -1 on error, Windows NULL. */
  2744. /* However, Linux does not return 0 on success either. */
  2745. return 0;
  2746. }
  2747. ret = (int *)mg_malloc(sizeof(int));
  2748. if (ret) {
  2749. *ret = evhdl;
  2750. } else {
  2751. (void)close(evhdl);
  2752. }
  2753. return (void *)ret;
  2754. }
  2755. static int
  2756. event_wait(void *eventhdl)
  2757. {
  2758. uint64_t u;
  2759. int evhdl, s;
  2760. if (!eventhdl) {
  2761. /* error */
  2762. return 0;
  2763. }
  2764. evhdl = *(int *)eventhdl;
  2765. s = (int)read(evhdl, &u, sizeof(u));
  2766. if (s != sizeof(u)) {
  2767. /* error */
  2768. return 0;
  2769. }
  2770. (void)u; /* the value is not required */
  2771. return 1;
  2772. }
  2773. static int
  2774. event_signal(void *eventhdl)
  2775. {
  2776. uint64_t u = 1;
  2777. int evhdl, s;
  2778. if (!eventhdl) {
  2779. /* error */
  2780. return 0;
  2781. }
  2782. evhdl = *(int *)eventhdl;
  2783. s = (int)write(evhdl, &u, sizeof(u));
  2784. if (s != sizeof(u)) {
  2785. /* error */
  2786. return 0;
  2787. }
  2788. return 1;
  2789. }
  2790. static void
  2791. event_destroy(void *eventhdl)
  2792. {
  2793. int evhdl;
  2794. if (!eventhdl) {
  2795. /* error */
  2796. return;
  2797. }
  2798. evhdl = *(int *)eventhdl;
  2799. close(evhdl);
  2800. mg_free(eventhdl);
  2801. }
  2802. #endif
  2803. #endif
  2804. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2805. struct posix_event {
  2806. pthread_mutex_t mutex;
  2807. pthread_cond_t cond;
  2808. int signaled;
  2809. };
  2810. static void *
  2811. event_create(void)
  2812. {
  2813. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2814. if (ret == 0) {
  2815. /* out of memory */
  2816. return 0;
  2817. }
  2818. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2819. /* pthread mutex not available */
  2820. mg_free(ret);
  2821. return 0;
  2822. }
  2823. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2824. /* pthread cond not available */
  2825. pthread_mutex_destroy(&(ret->mutex));
  2826. mg_free(ret);
  2827. return 0;
  2828. }
  2829. ret->signaled = 0;
  2830. return (void *)ret;
  2831. }
  2832. static int
  2833. event_wait(void *eventhdl)
  2834. {
  2835. struct posix_event *ev = (struct posix_event *)eventhdl;
  2836. pthread_mutex_lock(&(ev->mutex));
  2837. while (!ev->signaled) {
  2838. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2839. }
  2840. ev->signaled = 0;
  2841. pthread_mutex_unlock(&(ev->mutex));
  2842. return 1;
  2843. }
  2844. static int
  2845. event_signal(void *eventhdl)
  2846. {
  2847. struct posix_event *ev = (struct posix_event *)eventhdl;
  2848. pthread_mutex_lock(&(ev->mutex));
  2849. pthread_cond_signal(&(ev->cond));
  2850. ev->signaled = 1;
  2851. pthread_mutex_unlock(&(ev->mutex));
  2852. return 1;
  2853. }
  2854. static void
  2855. event_destroy(void *eventhdl)
  2856. {
  2857. struct posix_event *ev = (struct posix_event *)eventhdl;
  2858. pthread_cond_destroy(&(ev->cond));
  2859. pthread_mutex_destroy(&(ev->mutex));
  2860. mg_free(ev);
  2861. }
  2862. #endif
  2863. static void
  2864. mg_set_thread_name(const char *name)
  2865. {
  2866. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2867. mg_snprintf(
  2868. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2869. #if defined(_WIN32)
  2870. #if defined(_MSC_VER)
  2871. /* Windows and Visual Studio Compiler */
  2872. __try {
  2873. THREADNAME_INFO info;
  2874. info.dwType = 0x1000;
  2875. info.szName = threadName;
  2876. info.dwThreadID = ~0U;
  2877. info.dwFlags = 0;
  2878. RaiseException(0x406D1388,
  2879. 0,
  2880. sizeof(info) / sizeof(ULONG_PTR),
  2881. (ULONG_PTR *)&info);
  2882. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2883. }
  2884. #elif defined(__MINGW32__)
  2885. /* No option known to set thread name for MinGW known */
  2886. #endif
  2887. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2888. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2889. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2890. #if defined(__MACH__)
  2891. /* OS X only current thread name can be changed */
  2892. (void)pthread_setname_np(threadName);
  2893. #else
  2894. (void)pthread_setname_np(pthread_self(), threadName);
  2895. #endif
  2896. #elif defined(__linux__)
  2897. /* On Linux we can use the prctl function.
  2898. * When building for Linux Standard Base (LSB) use
  2899. * NO_THREAD_NAME. However, thread names are a big
  2900. * help for debugging, so the stadard is to set them.
  2901. */
  2902. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2903. #endif
  2904. }
  2905. #else /* !defined(NO_THREAD_NAME) */
  2906. void
  2907. mg_set_thread_name(const char *threadName)
  2908. {
  2909. }
  2910. #endif
  2911. const struct mg_option *
  2912. mg_get_valid_options(void)
  2913. {
  2914. return config_options;
  2915. }
  2916. /* Do not open file (unused) */
  2917. #define MG_FOPEN_MODE_NONE (0)
  2918. /* Open file for read only access */
  2919. #define MG_FOPEN_MODE_READ (1)
  2920. /* Open file for writing, create and overwrite */
  2921. #define MG_FOPEN_MODE_WRITE (2)
  2922. /* Open file for writing, create and append */
  2923. #define MG_FOPEN_MODE_APPEND (4)
  2924. static int
  2925. is_file_opened(const struct mg_file_access *fileacc)
  2926. {
  2927. if (!fileacc) {
  2928. return 0;
  2929. }
  2930. return (fileacc->fp != NULL);
  2931. }
  2932. #if !defined(NO_FILESYSTEMS)
  2933. static int mg_stat(const struct mg_connection *conn,
  2934. const char *path,
  2935. struct mg_file_stat *filep);
  2936. /* Reject files with special characters */
  2937. static int
  2938. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2939. {
  2940. const uint8_t *c = (const uint8_t *)path;
  2941. (void)conn; /* not used */
  2942. if ((c == NULL) || (c[0] == 0)) {
  2943. /* Null pointer or empty path --> suspicious */
  2944. return 1;
  2945. }
  2946. while (*c) {
  2947. if (*c <= 32) {
  2948. /* Control character or space */
  2949. return 0;
  2950. }
  2951. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2952. /* stdin/stdout redirection character */
  2953. return 0;
  2954. }
  2955. #if defined(_WIN32)
  2956. if (*c == '\\') {
  2957. /* Windows backslash */
  2958. return 0;
  2959. }
  2960. #else
  2961. if (*c == '&') {
  2962. /* Linux ampersand */
  2963. return 0;
  2964. }
  2965. #endif
  2966. c++;
  2967. }
  2968. /* Nothing suspicious found */
  2969. return 0;
  2970. }
  2971. /* mg_fopen will open a file either in memory or on the disk.
  2972. * The input parameter path is a string in UTF-8 encoding.
  2973. * The input parameter mode is MG_FOPEN_MODE_*
  2974. * On success, fp will be set in the output struct mg_file.
  2975. * All status members will also be set.
  2976. * The function returns 1 on success, 0 on error. */
  2977. static int
  2978. mg_fopen(const struct mg_connection *conn,
  2979. const char *path,
  2980. int mode,
  2981. struct mg_file *filep)
  2982. {
  2983. int found;
  2984. if (!filep) {
  2985. return 0;
  2986. }
  2987. filep->access.fp = NULL;
  2988. if (mg_path_suspicious(conn, path)) {
  2989. return 0;
  2990. }
  2991. /* filep is initialized in mg_stat: all fields with memset to,
  2992. * some fields like size and modification date with values */
  2993. found = mg_stat(conn, path, &(filep->stat));
  2994. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2995. /* file does not exist and will not be created */
  2996. return 0;
  2997. }
  2998. #if defined(_WIN32)
  2999. {
  3000. wchar_t wbuf[W_PATH_MAX];
  3001. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3002. switch (mode) {
  3003. case MG_FOPEN_MODE_READ:
  3004. filep->access.fp = _wfopen(wbuf, L"rb");
  3005. break;
  3006. case MG_FOPEN_MODE_WRITE:
  3007. filep->access.fp = _wfopen(wbuf, L"wb");
  3008. break;
  3009. case MG_FOPEN_MODE_APPEND:
  3010. filep->access.fp = _wfopen(wbuf, L"ab");
  3011. break;
  3012. }
  3013. }
  3014. #else
  3015. /* Linux et al already use unicode. No need to convert. */
  3016. switch (mode) {
  3017. case MG_FOPEN_MODE_READ:
  3018. filep->access.fp = fopen(path, "r");
  3019. break;
  3020. case MG_FOPEN_MODE_WRITE:
  3021. filep->access.fp = fopen(path, "w");
  3022. break;
  3023. case MG_FOPEN_MODE_APPEND:
  3024. filep->access.fp = fopen(path, "a");
  3025. break;
  3026. }
  3027. #endif
  3028. if (!found) {
  3029. /* File did not exist before fopen was called.
  3030. * Maybe it has been created now. Get stat info
  3031. * like creation time now. */
  3032. found = mg_stat(conn, path, &(filep->stat));
  3033. (void)found;
  3034. }
  3035. /* return OK if file is opened */
  3036. return (filep->access.fp != NULL);
  3037. }
  3038. /* return 0 on success, just like fclose */
  3039. static int
  3040. mg_fclose(struct mg_file_access *fileacc)
  3041. {
  3042. int ret = -1;
  3043. if (fileacc != NULL) {
  3044. if (fileacc->fp != NULL) {
  3045. ret = fclose(fileacc->fp);
  3046. }
  3047. /* reset all members of fileacc */
  3048. memset(fileacc, 0, sizeof(*fileacc));
  3049. }
  3050. return ret;
  3051. }
  3052. #endif /* NO_FILESYSTEMS */
  3053. static void
  3054. mg_strlcpy(register char *dst, register const char *src, size_t n)
  3055. {
  3056. for (; *src != '\0' && n > 1; n--) {
  3057. *dst++ = *src++;
  3058. }
  3059. *dst = '\0';
  3060. }
  3061. static int
  3062. lowercase(const char *s)
  3063. {
  3064. return tolower((unsigned char)*s);
  3065. }
  3066. int
  3067. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  3068. {
  3069. int diff = 0;
  3070. if (len > 0) {
  3071. do {
  3072. diff = lowercase(s1++) - lowercase(s2++);
  3073. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  3074. }
  3075. return diff;
  3076. }
  3077. int
  3078. mg_strcasecmp(const char *s1, const char *s2)
  3079. {
  3080. int diff;
  3081. do {
  3082. diff = lowercase(s1++) - lowercase(s2++);
  3083. } while (diff == 0 && s1[-1] != '\0');
  3084. return diff;
  3085. }
  3086. static char *
  3087. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3088. {
  3089. char *p;
  3090. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3091. * defined */
  3092. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3093. mg_strlcpy(p, ptr, len + 1);
  3094. }
  3095. return p;
  3096. }
  3097. static char *
  3098. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3099. {
  3100. return mg_strndup_ctx(str, strlen(str), ctx);
  3101. }
  3102. static char *
  3103. mg_strdup(const char *str)
  3104. {
  3105. return mg_strndup_ctx(str, strlen(str), NULL);
  3106. }
  3107. static const char *
  3108. mg_strcasestr(const char *big_str, const char *small_str)
  3109. {
  3110. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3111. if (big_len >= small_len) {
  3112. for (i = 0; i <= (big_len - small_len); i++) {
  3113. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3114. return big_str + i;
  3115. }
  3116. }
  3117. }
  3118. return NULL;
  3119. }
  3120. /* Return null terminated string of given maximum length.
  3121. * Report errors if length is exceeded. */
  3122. static void
  3123. mg_vsnprintf(const struct mg_connection *conn,
  3124. int *truncated,
  3125. char *buf,
  3126. size_t buflen,
  3127. const char *fmt,
  3128. va_list ap)
  3129. {
  3130. int n, ok;
  3131. if (buflen == 0) {
  3132. if (truncated) {
  3133. *truncated = 1;
  3134. }
  3135. return;
  3136. }
  3137. #if defined(__clang__)
  3138. #pragma clang diagnostic push
  3139. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3140. /* Using fmt as a non-literal is intended here, since it is mostly called
  3141. * indirectly by mg_snprintf */
  3142. #endif
  3143. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3144. ok = (n >= 0) && ((size_t)n < buflen);
  3145. #if defined(__clang__)
  3146. #pragma clang diagnostic pop
  3147. #endif
  3148. if (ok) {
  3149. if (truncated) {
  3150. *truncated = 0;
  3151. }
  3152. } else {
  3153. if (truncated) {
  3154. *truncated = 1;
  3155. }
  3156. mg_cry_internal(conn,
  3157. "truncating vsnprintf buffer: [%.*s]",
  3158. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3159. buf);
  3160. n = (int)buflen - 1;
  3161. }
  3162. buf[n] = '\0';
  3163. }
  3164. static void
  3165. mg_snprintf(const struct mg_connection *conn,
  3166. int *truncated,
  3167. char *buf,
  3168. size_t buflen,
  3169. const char *fmt,
  3170. ...)
  3171. {
  3172. va_list ap;
  3173. va_start(ap, fmt);
  3174. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3175. va_end(ap);
  3176. }
  3177. static int
  3178. get_option_index(const char *name)
  3179. {
  3180. int i;
  3181. for (i = 0; config_options[i].name != NULL; i++) {
  3182. if (strcmp(config_options[i].name, name) == 0) {
  3183. return i;
  3184. }
  3185. }
  3186. return -1;
  3187. }
  3188. const char *
  3189. mg_get_option(const struct mg_context *ctx, const char *name)
  3190. {
  3191. int i;
  3192. if ((i = get_option_index(name)) == -1) {
  3193. return NULL;
  3194. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3195. return "";
  3196. } else {
  3197. return ctx->dd.config[i];
  3198. }
  3199. }
  3200. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3201. struct mg_context *
  3202. mg_get_context(const struct mg_connection *conn)
  3203. {
  3204. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3205. }
  3206. void *
  3207. mg_get_user_data(const struct mg_context *ctx)
  3208. {
  3209. return (ctx == NULL) ? NULL : ctx->user_data;
  3210. }
  3211. void *
  3212. mg_get_user_context_data(const struct mg_connection *conn)
  3213. {
  3214. return mg_get_user_data(mg_get_context(conn));
  3215. }
  3216. void *
  3217. mg_get_thread_pointer(const struct mg_connection *conn)
  3218. {
  3219. /* both methods should return the same pointer */
  3220. if (conn) {
  3221. /* quick access, in case conn is known */
  3222. return conn->tls_user_ptr;
  3223. } else {
  3224. /* otherwise get pointer from thread local storage (TLS) */
  3225. struct mg_workerTLS *tls =
  3226. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3227. return tls->user_ptr;
  3228. }
  3229. }
  3230. void
  3231. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  3232. {
  3233. if (const_conn != NULL) {
  3234. /* Const cast, since "const struct mg_connection *" does not mean
  3235. * the connection object is not modified. Here "const" is used,
  3236. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  3237. struct mg_connection *conn = (struct mg_connection *)const_conn;
  3238. conn->request_info.conn_data = data;
  3239. }
  3240. }
  3241. void *
  3242. mg_get_user_connection_data(const struct mg_connection *conn)
  3243. {
  3244. if (conn != NULL) {
  3245. return conn->request_info.conn_data;
  3246. }
  3247. return NULL;
  3248. }
  3249. #if defined(MG_LEGACY_INTERFACE)
  3250. /* Deprecated: Use mg_get_server_ports instead. */
  3251. size_t
  3252. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3253. {
  3254. size_t i;
  3255. if (!ctx) {
  3256. return 0;
  3257. }
  3258. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3259. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3260. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3261. }
  3262. return i;
  3263. }
  3264. #endif
  3265. int
  3266. mg_get_server_ports(const struct mg_context *ctx,
  3267. int size,
  3268. struct mg_server_port *ports)
  3269. {
  3270. int i, cnt = 0;
  3271. if (size <= 0) {
  3272. return -1;
  3273. }
  3274. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3275. if (!ctx) {
  3276. return -1;
  3277. }
  3278. if (!ctx->listening_sockets) {
  3279. return -1;
  3280. }
  3281. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3282. ports[cnt].port =
  3283. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3284. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3285. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3286. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3287. /* IPv4 */
  3288. ports[cnt].protocol = 1;
  3289. cnt++;
  3290. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3291. /* IPv6 */
  3292. ports[cnt].protocol = 3;
  3293. cnt++;
  3294. }
  3295. }
  3296. return cnt;
  3297. }
  3298. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  3299. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  3300. #endif
  3301. static void
  3302. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3303. {
  3304. buf[0] = '\0';
  3305. if (!usa) {
  3306. return;
  3307. }
  3308. if (usa->sa.sa_family == AF_INET) {
  3309. getnameinfo(&usa->sa,
  3310. sizeof(usa->sin),
  3311. buf,
  3312. (unsigned)len,
  3313. NULL,
  3314. 0,
  3315. NI_NUMERICHOST);
  3316. }
  3317. #if defined(USE_IPV6)
  3318. else if (usa->sa.sa_family == AF_INET6) {
  3319. getnameinfo(&usa->sa,
  3320. sizeof(usa->sin6),
  3321. buf,
  3322. (unsigned)len,
  3323. NULL,
  3324. 0,
  3325. NI_NUMERICHOST);
  3326. }
  3327. #endif
  3328. #if defined(USE_X_DOM_SOCKET)
  3329. else if (usa->sa.sa_family == AF_UNIX) {
  3330. /* TODO: Define a remote address for unix domain sockets.
  3331. * This code will always return "localhost", identical to http+tcp:
  3332. getnameinfo(&usa->sa,
  3333. sizeof(usa->sun),
  3334. buf,
  3335. (unsigned)len,
  3336. NULL,
  3337. 0,
  3338. NI_NUMERICHOST);
  3339. */
  3340. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  3341. buf[len] = 0;
  3342. }
  3343. #endif
  3344. }
  3345. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3346. * included in all responses other than 100, 101, 5xx. */
  3347. static void
  3348. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3349. {
  3350. #if !defined(REENTRANT_TIME)
  3351. struct tm *tm;
  3352. tm = ((t != NULL) ? gmtime(t) : NULL);
  3353. if (tm != NULL) {
  3354. #else
  3355. struct tm _tm;
  3356. struct tm *tm = &_tm;
  3357. if (t != NULL) {
  3358. gmtime_r(t, tm);
  3359. #endif
  3360. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3361. } else {
  3362. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3363. buf[buf_len - 1] = '\0';
  3364. }
  3365. }
  3366. /* difftime for struct timespec. Return value is in seconds. */
  3367. static double
  3368. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3369. {
  3370. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3371. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3372. }
  3373. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3374. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3375. const char *func,
  3376. unsigned line,
  3377. const char *fmt,
  3378. va_list ap);
  3379. #include "external_mg_cry_internal_impl.inl"
  3380. #elif !defined(NO_FILESYSTEMS)
  3381. /* Print error message to the opened error log stream. */
  3382. static void
  3383. mg_cry_internal_impl(const struct mg_connection *conn,
  3384. const char *func,
  3385. unsigned line,
  3386. const char *fmt,
  3387. va_list ap)
  3388. {
  3389. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3390. struct mg_file fi;
  3391. time_t timestamp;
  3392. /* Unused, in the RELEASE build */
  3393. (void)func;
  3394. (void)line;
  3395. #if defined(GCC_DIAGNOSTIC)
  3396. #pragma GCC diagnostic push
  3397. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3398. #endif
  3399. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3400. #if defined(GCC_DIAGNOSTIC)
  3401. #pragma GCC diagnostic pop
  3402. #endif
  3403. buf[sizeof(buf) - 1] = 0;
  3404. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3405. if (!conn) {
  3406. puts(buf);
  3407. return;
  3408. }
  3409. /* Do not lock when getting the callback value, here and below.
  3410. * I suppose this is fine, since function cannot disappear in the
  3411. * same way string option can. */
  3412. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3413. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3414. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3415. if (mg_fopen(conn,
  3416. conn->dom_ctx->config[ERROR_LOG_FILE],
  3417. MG_FOPEN_MODE_APPEND,
  3418. &fi)
  3419. == 0) {
  3420. fi.access.fp = NULL;
  3421. }
  3422. } else {
  3423. fi.access.fp = NULL;
  3424. }
  3425. if (fi.access.fp != NULL) {
  3426. flockfile(fi.access.fp);
  3427. timestamp = time(NULL);
  3428. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3429. fprintf(fi.access.fp,
  3430. "[%010lu] [error] [client %s] ",
  3431. (unsigned long)timestamp,
  3432. src_addr);
  3433. if (conn->request_info.request_method != NULL) {
  3434. fprintf(fi.access.fp,
  3435. "%s %s: ",
  3436. conn->request_info.request_method,
  3437. conn->request_info.request_uri
  3438. ? conn->request_info.request_uri
  3439. : "");
  3440. }
  3441. fprintf(fi.access.fp, "%s", buf);
  3442. fputc('\n', fi.access.fp);
  3443. fflush(fi.access.fp);
  3444. funlockfile(fi.access.fp);
  3445. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3446. * mg_cry here anyway ;-) */
  3447. }
  3448. }
  3449. }
  3450. #else
  3451. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3452. #endif /* Externally provided function */
  3453. /* Construct fake connection structure. Used for logging, if connection
  3454. * is not applicable at the moment of logging. */
  3455. static struct mg_connection *
  3456. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3457. {
  3458. static const struct mg_connection conn_zero = {0};
  3459. *fc = conn_zero;
  3460. fc->phys_ctx = ctx;
  3461. fc->dom_ctx = &(ctx->dd);
  3462. return fc;
  3463. }
  3464. static void
  3465. mg_cry_internal_wrap(const struct mg_connection *conn,
  3466. struct mg_context *ctx,
  3467. const char *func,
  3468. unsigned line,
  3469. const char *fmt,
  3470. ...)
  3471. {
  3472. va_list ap;
  3473. va_start(ap, fmt);
  3474. if (!conn && ctx) {
  3475. struct mg_connection fc;
  3476. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3477. } else {
  3478. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3479. }
  3480. va_end(ap);
  3481. }
  3482. void
  3483. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3484. {
  3485. va_list ap;
  3486. va_start(ap, fmt);
  3487. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3488. va_end(ap);
  3489. }
  3490. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3491. const char *
  3492. mg_version(void)
  3493. {
  3494. return CIVETWEB_VERSION;
  3495. }
  3496. const struct mg_request_info *
  3497. mg_get_request_info(const struct mg_connection *conn)
  3498. {
  3499. if (!conn) {
  3500. return NULL;
  3501. }
  3502. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3503. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3504. char txt[16];
  3505. struct mg_workerTLS *tls =
  3506. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3507. sprintf(txt, "%03i", conn->response_info.status_code);
  3508. if (strlen(txt) == 3) {
  3509. memcpy(tls->txtbuf, txt, 4);
  3510. } else {
  3511. strcpy(tls->txtbuf, "ERR");
  3512. }
  3513. ((struct mg_connection *)conn)->request_info.local_uri =
  3514. ((struct mg_connection *)conn)->request_info.request_uri =
  3515. tls->txtbuf; /* use thread safe buffer */
  3516. ((struct mg_connection *)conn)->request_info.num_headers =
  3517. conn->response_info.num_headers;
  3518. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3519. conn->response_info.http_headers,
  3520. sizeof(conn->response_info.http_headers));
  3521. } else
  3522. #endif
  3523. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3524. return NULL;
  3525. }
  3526. return &conn->request_info;
  3527. }
  3528. const struct mg_response_info *
  3529. mg_get_response_info(const struct mg_connection *conn)
  3530. {
  3531. if (!conn) {
  3532. return NULL;
  3533. }
  3534. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3535. return NULL;
  3536. }
  3537. return &conn->response_info;
  3538. }
  3539. static const char *
  3540. get_proto_name(const struct mg_connection *conn)
  3541. {
  3542. #if defined(__clang__)
  3543. #pragma clang diagnostic push
  3544. #pragma clang diagnostic ignored "-Wunreachable-code"
  3545. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3546. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3547. * unreachable, but splitting into four different #ifdef clauses here is more
  3548. * complicated.
  3549. */
  3550. #endif
  3551. const struct mg_request_info *ri = &conn->request_info;
  3552. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3553. ? (ri->is_ssl ? "wss" : "ws")
  3554. : (ri->is_ssl ? "https" : "http"));
  3555. return proto;
  3556. #if defined(__clang__)
  3557. #pragma clang diagnostic pop
  3558. #endif
  3559. }
  3560. static int
  3561. mg_construct_local_link(const struct mg_connection *conn,
  3562. char *buf,
  3563. size_t buflen,
  3564. const char *define_proto,
  3565. int define_port,
  3566. const char *define_uri)
  3567. {
  3568. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3569. return -1;
  3570. } else {
  3571. int truncated = 0;
  3572. const struct mg_request_info *ri = &conn->request_info;
  3573. const char *proto =
  3574. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3575. const char *uri =
  3576. (define_uri != NULL)
  3577. ? define_uri
  3578. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3579. int port = (define_port > 0) ? define_port : ri->server_port;
  3580. int default_port = 80;
  3581. if (uri == NULL) {
  3582. return -1;
  3583. }
  3584. #if defined(USE_X_DOM_SOCKET)
  3585. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3586. /* TODO: Define and document a link for UNIX domain sockets. */
  3587. /* There seems to be no official standard for this.
  3588. * Common uses seem to be "httpunix://", "http.unix://" or
  3589. * "http+unix://" as a protocol definition string, followed by
  3590. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3591. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3592. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3593. * "" (completely skipping the server name part). In any case, the
  3594. * last part is the server local path. */
  3595. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3596. mg_snprintf(conn,
  3597. &truncated,
  3598. buf,
  3599. buflen,
  3600. "%s.unix://%s%s",
  3601. proto,
  3602. server_name,
  3603. ri->local_uri);
  3604. default_port = 0;
  3605. return 0;
  3606. }
  3607. #endif
  3608. if (define_proto) {
  3609. /* If we got a protocol name, use the default port accordingly. */
  3610. if ((0 == strcmp(define_proto, "https"))
  3611. || (0 == strcmp(define_proto, "wss"))) {
  3612. default_port = 443;
  3613. }
  3614. } else if (ri->is_ssl) {
  3615. /* If we did not get a protocol name, use TLS as default if it is
  3616. * already used. */
  3617. default_port = 443;
  3618. }
  3619. {
  3620. #if defined(USE_IPV6)
  3621. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3622. #endif
  3623. int auth_domain_check_enabled =
  3624. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3625. && (!mg_strcasecmp(
  3626. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3627. const char *server_domain =
  3628. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3629. char portstr[16];
  3630. char server_ip[48];
  3631. if (port != default_port) {
  3632. sprintf(portstr, ":%u", (unsigned)port);
  3633. } else {
  3634. portstr[0] = 0;
  3635. }
  3636. if (!auth_domain_check_enabled || !server_domain) {
  3637. sockaddr_to_string(server_ip,
  3638. sizeof(server_ip),
  3639. &conn->client.lsa);
  3640. server_domain = server_ip;
  3641. }
  3642. mg_snprintf(conn,
  3643. &truncated,
  3644. buf,
  3645. buflen,
  3646. #if defined(USE_IPV6)
  3647. "%s://%s%s%s%s%s",
  3648. proto,
  3649. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3650. server_domain,
  3651. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3652. #else
  3653. "%s://%s%s%s",
  3654. proto,
  3655. server_domain,
  3656. #endif
  3657. portstr,
  3658. ri->local_uri);
  3659. if (truncated) {
  3660. return -1;
  3661. }
  3662. return 0;
  3663. }
  3664. }
  3665. }
  3666. int
  3667. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3668. {
  3669. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3670. }
  3671. /* Skip the characters until one of the delimiters characters found.
  3672. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3673. * Advance pointer to buffer to the next word. Return found 0-terminated
  3674. * word.
  3675. * Delimiters can be quoted with quotechar. */
  3676. static char *
  3677. skip_quoted(char **buf,
  3678. const char *delimiters,
  3679. const char *whitespace,
  3680. char quotechar)
  3681. {
  3682. char *p, *begin_word, *end_word, *end_whitespace;
  3683. begin_word = *buf;
  3684. end_word = begin_word + strcspn(begin_word, delimiters);
  3685. /* Check for quotechar */
  3686. if (end_word > begin_word) {
  3687. p = end_word - 1;
  3688. while (*p == quotechar) {
  3689. /* While the delimiter is quoted, look for the next delimiter.
  3690. */
  3691. /* This happens, e.g., in calls from parse_auth_header,
  3692. * if the user name contains a " character. */
  3693. /* If there is anything beyond end_word, copy it. */
  3694. if (*end_word != '\0') {
  3695. size_t end_off = strcspn(end_word + 1, delimiters);
  3696. memmove(p, end_word, end_off + 1);
  3697. p += end_off; /* p must correspond to end_word - 1 */
  3698. end_word += end_off + 1;
  3699. } else {
  3700. *p = '\0';
  3701. break;
  3702. }
  3703. }
  3704. for (p++; p < end_word; p++) {
  3705. *p = '\0';
  3706. }
  3707. }
  3708. if (*end_word == '\0') {
  3709. *buf = end_word;
  3710. } else {
  3711. #if defined(GCC_DIAGNOSTIC)
  3712. /* Disable spurious conversion warning for GCC */
  3713. #pragma GCC diagnostic push
  3714. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3715. #endif /* defined(GCC_DIAGNOSTIC) */
  3716. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3717. #if defined(GCC_DIAGNOSTIC)
  3718. #pragma GCC diagnostic pop
  3719. #endif /* defined(GCC_DIAGNOSTIC) */
  3720. for (p = end_word; p < end_whitespace; p++) {
  3721. *p = '\0';
  3722. }
  3723. *buf = end_whitespace;
  3724. }
  3725. return begin_word;
  3726. }
  3727. /* Return HTTP header value, or NULL if not found. */
  3728. static const char *
  3729. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3730. {
  3731. int i;
  3732. for (i = 0; i < num_hdr; i++) {
  3733. if (!mg_strcasecmp(name, hdr[i].name)) {
  3734. return hdr[i].value;
  3735. }
  3736. }
  3737. return NULL;
  3738. }
  3739. #if defined(USE_WEBSOCKET)
  3740. /* Retrieve requested HTTP header multiple values, and return the number of
  3741. * found occurrences */
  3742. static int
  3743. get_req_headers(const struct mg_request_info *ri,
  3744. const char *name,
  3745. const char **output,
  3746. int output_max_size)
  3747. {
  3748. int i;
  3749. int cnt = 0;
  3750. if (ri) {
  3751. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3752. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3753. output[cnt++] = ri->http_headers[i].value;
  3754. }
  3755. }
  3756. }
  3757. return cnt;
  3758. }
  3759. #endif
  3760. const char *
  3761. mg_get_header(const struct mg_connection *conn, const char *name)
  3762. {
  3763. if (!conn) {
  3764. return NULL;
  3765. }
  3766. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3767. return get_header(conn->request_info.http_headers,
  3768. conn->request_info.num_headers,
  3769. name);
  3770. }
  3771. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3772. return get_header(conn->response_info.http_headers,
  3773. conn->response_info.num_headers,
  3774. name);
  3775. }
  3776. return NULL;
  3777. }
  3778. static const char *
  3779. get_http_version(const struct mg_connection *conn)
  3780. {
  3781. if (!conn) {
  3782. return NULL;
  3783. }
  3784. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3785. return conn->request_info.http_version;
  3786. }
  3787. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3788. return conn->response_info.http_version;
  3789. }
  3790. return NULL;
  3791. }
  3792. /* A helper function for traversing a comma separated list of values.
  3793. * It returns a list pointer shifted to the next value, or NULL if the end
  3794. * of the list found.
  3795. * Value is stored in val vector. If value has form "x=y", then eq_val
  3796. * vector is initialized to point to the "y" part, and val vector length
  3797. * is adjusted to point only to "x". */
  3798. static const char *
  3799. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3800. {
  3801. int end;
  3802. reparse:
  3803. if (val == NULL || list == NULL || *list == '\0') {
  3804. /* End of the list */
  3805. return NULL;
  3806. }
  3807. /* Skip over leading LWS */
  3808. while (*list == ' ' || *list == '\t')
  3809. list++;
  3810. val->ptr = list;
  3811. if ((list = strchr(val->ptr, ',')) != NULL) {
  3812. /* Comma found. Store length and shift the list ptr */
  3813. val->len = ((size_t)(list - val->ptr));
  3814. list++;
  3815. } else {
  3816. /* This value is the last one */
  3817. list = val->ptr + strlen(val->ptr);
  3818. val->len = ((size_t)(list - val->ptr));
  3819. }
  3820. /* Adjust length for trailing LWS */
  3821. end = (int)val->len - 1;
  3822. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3823. end--;
  3824. val->len = (size_t)(end) + (size_t)(1);
  3825. if (val->len == 0) {
  3826. /* Ignore any empty entries. */
  3827. goto reparse;
  3828. }
  3829. if (eq_val != NULL) {
  3830. /* Value has form "x=y", adjust pointers and lengths
  3831. * so that val points to "x", and eq_val points to "y". */
  3832. eq_val->len = 0;
  3833. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3834. if (eq_val->ptr != NULL) {
  3835. eq_val->ptr++; /* Skip over '=' character */
  3836. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3837. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3838. }
  3839. }
  3840. return list;
  3841. }
  3842. /* A helper function for checking if a comma separated list of values
  3843. * contains
  3844. * the given option (case insensitvely).
  3845. * 'header' can be NULL, in which case false is returned. */
  3846. static int
  3847. header_has_option(const char *header, const char *option)
  3848. {
  3849. struct vec opt_vec;
  3850. struct vec eq_vec;
  3851. DEBUG_ASSERT(option != NULL);
  3852. DEBUG_ASSERT(option[0] != '\0');
  3853. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3854. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3855. return 1;
  3856. }
  3857. return 0;
  3858. }
  3859. /* Perform case-insensitive match of string against pattern */
  3860. static ptrdiff_t
  3861. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3862. {
  3863. const char *or_str;
  3864. ptrdiff_t i, j, len, res;
  3865. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3866. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3867. return (res > 0) ? res
  3868. : match_prefix(or_str + 1,
  3869. (size_t)((pattern + pattern_len)
  3870. - (or_str + 1)),
  3871. str);
  3872. }
  3873. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3874. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3875. continue;
  3876. } else if (pattern[i] == '$') {
  3877. return (str[j] == '\0') ? j : -1;
  3878. } else if (pattern[i] == '*') {
  3879. i++;
  3880. if (pattern[i] == '*') {
  3881. i++;
  3882. len = (ptrdiff_t)strlen(str + j);
  3883. } else {
  3884. len = (ptrdiff_t)strcspn(str + j, "/");
  3885. }
  3886. if (i == (ptrdiff_t)pattern_len) {
  3887. return j + len;
  3888. }
  3889. do {
  3890. res = match_prefix(pattern + i,
  3891. (pattern_len - (size_t)i),
  3892. str + j + len);
  3893. } while (res == -1 && len-- > 0);
  3894. return (res == -1) ? -1 : j + res + len;
  3895. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3896. return -1;
  3897. }
  3898. }
  3899. return (ptrdiff_t)j;
  3900. }
  3901. static ptrdiff_t
  3902. match_prefix_strlen(const char *pattern, const char *str)
  3903. {
  3904. if (pattern == NULL) {
  3905. return -1;
  3906. }
  3907. return match_prefix(pattern, strlen(pattern), str);
  3908. }
  3909. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3910. * This function must tolerate situations when connection info is not
  3911. * set up, for example if request parsing failed. */
  3912. static int
  3913. should_keep_alive(const struct mg_connection *conn)
  3914. {
  3915. const char *http_version;
  3916. const char *header;
  3917. /* First satisfy needs of the server */
  3918. if ((conn == NULL) || conn->must_close) {
  3919. /* Close, if civetweb framework needs to close */
  3920. return 0;
  3921. }
  3922. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3923. /* Close, if keep alive is not enabled */
  3924. return 0;
  3925. }
  3926. /* Check explicit wish of the client */
  3927. header = mg_get_header(conn, "Connection");
  3928. if (header) {
  3929. /* If there is a connection header from the client, obey */
  3930. if (header_has_option(header, "keep-alive")) {
  3931. return 1;
  3932. }
  3933. return 0;
  3934. }
  3935. /* Use default of the standard */
  3936. http_version = get_http_version(conn);
  3937. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3938. /* HTTP 1.1 default is keep alive */
  3939. return 1;
  3940. }
  3941. /* HTTP 1.0 (and earlier) default is to close the connection */
  3942. return 0;
  3943. }
  3944. static int
  3945. should_decode_url(const struct mg_connection *conn)
  3946. {
  3947. if (!conn || !conn->dom_ctx) {
  3948. return 0;
  3949. }
  3950. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3951. }
  3952. static const char *
  3953. suggest_connection_header(const struct mg_connection *conn)
  3954. {
  3955. return should_keep_alive(conn) ? "keep-alive" : "close";
  3956. }
  3957. #include "response.inl"
  3958. static void
  3959. send_no_cache_header(struct mg_connection *conn)
  3960. {
  3961. /* Send all current and obsolete cache opt-out directives. */
  3962. mg_response_header_add(conn,
  3963. "Cache-Control",
  3964. "no-cache, no-store, "
  3965. "must-revalidate, private, max-age=0",
  3966. -1);
  3967. mg_response_header_add(conn, "Expires", "0", -1);
  3968. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3969. /* Obsolete, but still send it for HTTP/1.0 */
  3970. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3971. }
  3972. }
  3973. static void
  3974. send_static_cache_header(struct mg_connection *conn)
  3975. {
  3976. #if !defined(NO_CACHING)
  3977. int max_age;
  3978. char val[64];
  3979. const char *cache_control =
  3980. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3981. /* If there is a full cache-control option configured,0 use it */
  3982. if (cache_control != NULL) {
  3983. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3984. return;
  3985. }
  3986. /* Read the server config to check how long a file may be cached.
  3987. * The configuration is in seconds. */
  3988. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3989. if (max_age <= 0) {
  3990. /* 0 means "do not cache". All values <0 are reserved
  3991. * and may be used differently in the future. */
  3992. /* If a file should not be cached, do not only send
  3993. * max-age=0, but also pragmas and Expires headers. */
  3994. send_no_cache_header(conn);
  3995. return;
  3996. }
  3997. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3998. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3999. /* See also https://www.mnot.net/cache_docs/ */
  4000. /* According to RFC 2616, Section 14.21, caching times should not exceed
  4001. * one year. A year with 365 days corresponds to 31536000 seconds, a
  4002. * leap
  4003. * year to 31622400 seconds. For the moment, we just send whatever has
  4004. * been configured, still the behavior for >1 year should be considered
  4005. * as undefined. */
  4006. mg_snprintf(
  4007. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  4008. mg_response_header_add(conn, "Cache-Control", val, -1);
  4009. #else /* NO_CACHING */
  4010. send_no_cache_header(conn);
  4011. #endif /* !NO_CACHING */
  4012. }
  4013. static void
  4014. send_additional_header(struct mg_connection *conn)
  4015. {
  4016. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  4017. #if !defined(NO_SSL)
  4018. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  4019. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  4020. if (max_age >= 0) {
  4021. char val[64];
  4022. mg_snprintf(conn,
  4023. NULL,
  4024. val,
  4025. sizeof(val),
  4026. "max-age=%lu",
  4027. (unsigned long)max_age);
  4028. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  4029. }
  4030. }
  4031. #endif
  4032. if (header && header[0]) {
  4033. mg_response_header_add_lines(conn, header);
  4034. }
  4035. }
  4036. #if !defined(NO_FILESYSTEMS)
  4037. static void handle_file_based_request(struct mg_connection *conn,
  4038. const char *path,
  4039. struct mg_file *filep);
  4040. #endif /* NO_FILESYSTEMS */
  4041. const char *
  4042. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  4043. {
  4044. /* See IANA HTTP status code assignment:
  4045. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  4046. */
  4047. switch (response_code) {
  4048. /* RFC2616 Section 10.1 - Informational 1xx */
  4049. case 100:
  4050. return "Continue"; /* RFC2616 Section 10.1.1 */
  4051. case 101:
  4052. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  4053. case 102:
  4054. return "Processing"; /* RFC2518 Section 10.1 */
  4055. /* RFC2616 Section 10.2 - Successful 2xx */
  4056. case 200:
  4057. return "OK"; /* RFC2616 Section 10.2.1 */
  4058. case 201:
  4059. return "Created"; /* RFC2616 Section 10.2.2 */
  4060. case 202:
  4061. return "Accepted"; /* RFC2616 Section 10.2.3 */
  4062. case 203:
  4063. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  4064. case 204:
  4065. return "No Content"; /* RFC2616 Section 10.2.5 */
  4066. case 205:
  4067. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  4068. case 206:
  4069. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  4070. case 207:
  4071. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  4072. */
  4073. case 208:
  4074. return "Already Reported"; /* RFC5842 Section 7.1 */
  4075. case 226:
  4076. return "IM used"; /* RFC3229 Section 10.4.1 */
  4077. /* RFC2616 Section 10.3 - Redirection 3xx */
  4078. case 300:
  4079. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  4080. case 301:
  4081. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  4082. case 302:
  4083. return "Found"; /* RFC2616 Section 10.3.3 */
  4084. case 303:
  4085. return "See Other"; /* RFC2616 Section 10.3.4 */
  4086. case 304:
  4087. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  4088. case 305:
  4089. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  4090. case 307:
  4091. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  4092. case 308:
  4093. return "Permanent Redirect"; /* RFC7238 Section 3 */
  4094. /* RFC2616 Section 10.4 - Client Error 4xx */
  4095. case 400:
  4096. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  4097. case 401:
  4098. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  4099. case 402:
  4100. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  4101. case 403:
  4102. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  4103. case 404:
  4104. return "Not Found"; /* RFC2616 Section 10.4.5 */
  4105. case 405:
  4106. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  4107. case 406:
  4108. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  4109. case 407:
  4110. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  4111. case 408:
  4112. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  4113. case 409:
  4114. return "Conflict"; /* RFC2616 Section 10.4.10 */
  4115. case 410:
  4116. return "Gone"; /* RFC2616 Section 10.4.11 */
  4117. case 411:
  4118. return "Length Required"; /* RFC2616 Section 10.4.12 */
  4119. case 412:
  4120. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  4121. case 413:
  4122. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  4123. case 414:
  4124. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  4125. case 415:
  4126. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  4127. case 416:
  4128. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  4129. */
  4130. case 417:
  4131. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  4132. case 421:
  4133. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  4134. case 422:
  4135. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  4136. * Section 11.2 */
  4137. case 423:
  4138. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  4139. case 424:
  4140. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  4141. * Section 11.4 */
  4142. case 426:
  4143. return "Upgrade Required"; /* RFC 2817 Section 4 */
  4144. case 428:
  4145. return "Precondition Required"; /* RFC 6585, Section 3 */
  4146. case 429:
  4147. return "Too Many Requests"; /* RFC 6585, Section 4 */
  4148. case 431:
  4149. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  4150. case 451:
  4151. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  4152. * Section 3 */
  4153. /* RFC2616 Section 10.5 - Server Error 5xx */
  4154. case 500:
  4155. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  4156. case 501:
  4157. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  4158. case 502:
  4159. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4160. case 503:
  4161. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4162. case 504:
  4163. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4164. case 505:
  4165. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4166. case 506:
  4167. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4168. case 507:
  4169. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4170. * Section 11.5 */
  4171. case 508:
  4172. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4173. case 510:
  4174. return "Not Extended"; /* RFC 2774, Section 7 */
  4175. case 511:
  4176. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4177. /* Other status codes, not shown in the IANA HTTP status code
  4178. * assignment.
  4179. * E.g., "de facto" standards due to common use, ... */
  4180. case 418:
  4181. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4182. case 419:
  4183. return "Authentication Timeout"; /* common use */
  4184. case 420:
  4185. return "Enhance Your Calm"; /* common use */
  4186. case 440:
  4187. return "Login Timeout"; /* common use */
  4188. case 509:
  4189. return "Bandwidth Limit Exceeded"; /* common use */
  4190. default:
  4191. /* This error code is unknown. This should not happen. */
  4192. if (conn) {
  4193. mg_cry_internal(conn,
  4194. "Unknown HTTP response code: %u",
  4195. response_code);
  4196. }
  4197. /* Return at least a category according to RFC 2616 Section 10. */
  4198. if (response_code >= 100 && response_code < 200) {
  4199. /* Unknown informational status code */
  4200. return "Information";
  4201. }
  4202. if (response_code >= 200 && response_code < 300) {
  4203. /* Unknown success code */
  4204. return "Success";
  4205. }
  4206. if (response_code >= 300 && response_code < 400) {
  4207. /* Unknown redirection code */
  4208. return "Redirection";
  4209. }
  4210. if (response_code >= 400 && response_code < 500) {
  4211. /* Unknown request error code */
  4212. return "Client Error";
  4213. }
  4214. if (response_code >= 500 && response_code < 600) {
  4215. /* Unknown server error code */
  4216. return "Server Error";
  4217. }
  4218. /* Response code not even within reasonable range */
  4219. return "";
  4220. }
  4221. }
  4222. static int
  4223. mg_send_http_error_impl(struct mg_connection *conn,
  4224. int status,
  4225. const char *fmt,
  4226. va_list args)
  4227. {
  4228. char errmsg_buf[MG_BUF_LEN];
  4229. va_list ap;
  4230. int has_body;
  4231. #if !defined(NO_FILESYSTEMS)
  4232. char path_buf[PATH_MAX];
  4233. int len, i, page_handler_found, scope, truncated;
  4234. const char *error_handler = NULL;
  4235. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4236. const char *error_page_file_ext, *tstr;
  4237. #endif /* NO_FILESYSTEMS */
  4238. int handled_by_callback = 0;
  4239. if ((conn == NULL) || (fmt == NULL)) {
  4240. return -2;
  4241. }
  4242. /* Set status (for log) */
  4243. conn->status_code = status;
  4244. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4245. has_body = ((status > 199) && (status != 204) && (status != 304));
  4246. /* Prepare message in buf, if required */
  4247. if (has_body
  4248. || (!conn->in_error_handler
  4249. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4250. /* Store error message in errmsg_buf */
  4251. va_copy(ap, args);
  4252. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4253. va_end(ap);
  4254. /* In a debug build, print all html errors */
  4255. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4256. }
  4257. /* If there is a http_error callback, call it.
  4258. * But don't do it recursively, if callback calls mg_send_http_error again.
  4259. */
  4260. if (!conn->in_error_handler
  4261. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4262. /* Mark in_error_handler to avoid recursion and call user callback. */
  4263. conn->in_error_handler = 1;
  4264. handled_by_callback =
  4265. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4266. == 0);
  4267. conn->in_error_handler = 0;
  4268. }
  4269. if (!handled_by_callback) {
  4270. /* Check for recursion */
  4271. if (conn->in_error_handler) {
  4272. DEBUG_TRACE(
  4273. "Recursion when handling error %u - fall back to default",
  4274. status);
  4275. #if !defined(NO_FILESYSTEMS)
  4276. } else {
  4277. /* Send user defined error pages, if defined */
  4278. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4279. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4280. page_handler_found = 0;
  4281. if (error_handler != NULL) {
  4282. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4283. switch (scope) {
  4284. case 1: /* Handler for specific error, e.g. 404 error */
  4285. mg_snprintf(conn,
  4286. &truncated,
  4287. path_buf,
  4288. sizeof(path_buf) - 32,
  4289. "%serror%03u.",
  4290. error_handler,
  4291. status);
  4292. break;
  4293. case 2: /* Handler for error group, e.g., 5xx error
  4294. * handler
  4295. * for all server errors (500-599) */
  4296. mg_snprintf(conn,
  4297. &truncated,
  4298. path_buf,
  4299. sizeof(path_buf) - 32,
  4300. "%serror%01uxx.",
  4301. error_handler,
  4302. status / 100);
  4303. break;
  4304. default: /* Handler for all errors */
  4305. mg_snprintf(conn,
  4306. &truncated,
  4307. path_buf,
  4308. sizeof(path_buf) - 32,
  4309. "%serror.",
  4310. error_handler);
  4311. break;
  4312. }
  4313. /* String truncation in buf may only occur if
  4314. * error_handler is too long. This string is
  4315. * from the config, not from a client. */
  4316. (void)truncated;
  4317. /* The following code is redundant, but it should avoid
  4318. * false positives in static source code analyzers and
  4319. * vulnerability scanners.
  4320. */
  4321. path_buf[sizeof(path_buf) - 32] = 0;
  4322. len = (int)strlen(path_buf);
  4323. if (len > (int)sizeof(path_buf) - 32) {
  4324. len = (int)sizeof(path_buf) - 32;
  4325. }
  4326. /* Start with the file extenstion from the configuration. */
  4327. tstr = strchr(error_page_file_ext, '.');
  4328. while (tstr) {
  4329. for (i = 1;
  4330. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4331. i++) {
  4332. /* buffer overrun is not possible here, since
  4333. * (i < 32) && (len < sizeof(path_buf) - 32)
  4334. * ==> (i + len) < sizeof(path_buf) */
  4335. path_buf[len + i - 1] = tstr[i];
  4336. }
  4337. /* buffer overrun is not possible here, since
  4338. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4339. * ==> (i + len) <= sizeof(path_buf) */
  4340. path_buf[len + i - 1] = 0;
  4341. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4342. DEBUG_TRACE("Check error page %s - found",
  4343. path_buf);
  4344. page_handler_found = 1;
  4345. break;
  4346. }
  4347. DEBUG_TRACE("Check error page %s - not found",
  4348. path_buf);
  4349. /* Continue with the next file extenstion from the
  4350. * configuration (if there is a next one). */
  4351. tstr = strchr(tstr + i, '.');
  4352. }
  4353. }
  4354. }
  4355. if (page_handler_found) {
  4356. conn->in_error_handler = 1;
  4357. handle_file_based_request(conn, path_buf, &error_page_file);
  4358. conn->in_error_handler = 0;
  4359. return 0;
  4360. }
  4361. #endif /* NO_FILESYSTEMS */
  4362. }
  4363. /* No custom error page. Send default error page. */
  4364. conn->must_close = 1;
  4365. mg_response_header_start(conn, status);
  4366. send_no_cache_header(conn);
  4367. send_additional_header(conn);
  4368. if (has_body) {
  4369. mg_response_header_add(conn,
  4370. "Content-Type",
  4371. "text/plain; charset=utf-8",
  4372. -1);
  4373. }
  4374. mg_response_header_send(conn);
  4375. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4376. if (has_body) {
  4377. /* For other errors, send a generic error message. */
  4378. const char *status_text = mg_get_response_code_text(conn, status);
  4379. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4380. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4381. } else {
  4382. /* No body allowed. Close the connection. */
  4383. DEBUG_TRACE("Error %i", status);
  4384. }
  4385. }
  4386. return 0;
  4387. }
  4388. int
  4389. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4390. {
  4391. va_list ap;
  4392. int ret;
  4393. va_start(ap, fmt);
  4394. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4395. va_end(ap);
  4396. return ret;
  4397. }
  4398. int
  4399. mg_send_http_ok(struct mg_connection *conn,
  4400. const char *mime_type,
  4401. long long content_length)
  4402. {
  4403. if ((mime_type == NULL) || (*mime_type == 0)) {
  4404. /* No content type defined: default to text/html */
  4405. mime_type = "text/html";
  4406. }
  4407. mg_response_header_start(conn, 200);
  4408. send_no_cache_header(conn);
  4409. send_additional_header(conn);
  4410. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  4411. if (content_length < 0) {
  4412. /* Size not known. Use chunked encoding (HTTP/1.x) */
  4413. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  4414. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  4415. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  4416. }
  4417. } else {
  4418. char len[32];
  4419. int trunc = 0;
  4420. mg_snprintf(conn,
  4421. &trunc,
  4422. len,
  4423. sizeof(len),
  4424. "%" UINT64_FMT,
  4425. (uint64_t)content_length);
  4426. if (!trunc) {
  4427. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  4428. * !trunc is always true */
  4429. mg_response_header_add(conn, "Content-Length", len, -1);
  4430. }
  4431. }
  4432. mg_response_header_send(conn);
  4433. return 0;
  4434. }
  4435. int
  4436. mg_send_http_redirect(struct mg_connection *conn,
  4437. const char *target_url,
  4438. int redirect_code)
  4439. {
  4440. /* Send a 30x redirect response.
  4441. *
  4442. * Redirect types (status codes):
  4443. *
  4444. * Status | Perm/Temp | Method | Version
  4445. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4446. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4447. * 303 | temporary | always use GET | HTTP/1.1
  4448. * 307 | temporary | always keep method | HTTP/1.1
  4449. * 308 | permanent | always keep method | HTTP/1.1
  4450. */
  4451. const char *redirect_text;
  4452. int ret;
  4453. size_t content_len = 0;
  4454. #if defined(MG_SEND_REDIRECT_BODY)
  4455. char reply[MG_BUF_LEN];
  4456. #endif
  4457. /* In case redirect_code=0, use 307. */
  4458. if (redirect_code == 0) {
  4459. redirect_code = 307;
  4460. }
  4461. /* In case redirect_code is none of the above, return error. */
  4462. if ((redirect_code != 301) && (redirect_code != 302)
  4463. && (redirect_code != 303) && (redirect_code != 307)
  4464. && (redirect_code != 308)) {
  4465. /* Parameter error */
  4466. return -2;
  4467. }
  4468. /* Get proper text for response code */
  4469. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4470. /* If target_url is not defined, redirect to "/". */
  4471. if ((target_url == NULL) || (*target_url == 0)) {
  4472. target_url = "/";
  4473. }
  4474. #if defined(MG_SEND_REDIRECT_BODY)
  4475. /* TODO: condition name? */
  4476. /* Prepare a response body with a hyperlink.
  4477. *
  4478. * According to RFC2616 (and RFC1945 before):
  4479. * Unless the request method was HEAD, the entity of the
  4480. * response SHOULD contain a short hypertext note with a hyperlink to
  4481. * the new URI(s).
  4482. *
  4483. * However, this response body is not useful in M2M communication.
  4484. * Probably the original reason in the RFC was, clients not supporting
  4485. * a 30x HTTP redirect could still show the HTML page and let the user
  4486. * press the link. Since current browsers support 30x HTTP, the additional
  4487. * HTML body does not seem to make sense anymore.
  4488. *
  4489. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4490. * but it only notes:
  4491. * The server's response payload usually contains a short
  4492. * hypertext note with a hyperlink to the new URI(s).
  4493. *
  4494. * Deactivated by default. If you need the 30x body, set the define.
  4495. */
  4496. mg_snprintf(
  4497. conn,
  4498. NULL /* ignore truncation */,
  4499. reply,
  4500. sizeof(reply),
  4501. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4502. redirect_text,
  4503. target_url,
  4504. target_url);
  4505. content_len = strlen(reply);
  4506. #endif
  4507. /* Do not send any additional header. For all other options,
  4508. * including caching, there are suitable defaults. */
  4509. ret = mg_printf(conn,
  4510. "HTTP/1.1 %i %s\r\n"
  4511. "Location: %s\r\n"
  4512. "Content-Length: %u\r\n"
  4513. "Connection: %s\r\n\r\n",
  4514. redirect_code,
  4515. redirect_text,
  4516. target_url,
  4517. (unsigned int)content_len,
  4518. suggest_connection_header(conn));
  4519. #if defined(MG_SEND_REDIRECT_BODY)
  4520. /* Send response body */
  4521. if (ret > 0) {
  4522. /* ... unless it is a HEAD request */
  4523. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4524. ret = mg_write(conn, reply, content_len);
  4525. }
  4526. }
  4527. #endif
  4528. return (ret > 0) ? ret : -1;
  4529. }
  4530. #if defined(_WIN32)
  4531. /* Create substitutes for POSIX functions in Win32. */
  4532. #if defined(GCC_DIAGNOSTIC)
  4533. /* Show no warning in case system functions are not used. */
  4534. #pragma GCC diagnostic push
  4535. #pragma GCC diagnostic ignored "-Wunused-function"
  4536. #endif
  4537. static int
  4538. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4539. {
  4540. (void)unused;
  4541. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4542. InitializeCriticalSection(&mutex->sec);
  4543. return 0;
  4544. }
  4545. static int
  4546. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4547. {
  4548. DeleteCriticalSection(&mutex->sec);
  4549. return 0;
  4550. }
  4551. static int
  4552. pthread_mutex_lock(pthread_mutex_t *mutex)
  4553. {
  4554. EnterCriticalSection(&mutex->sec);
  4555. return 0;
  4556. }
  4557. static int
  4558. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4559. {
  4560. LeaveCriticalSection(&mutex->sec);
  4561. return 0;
  4562. }
  4563. FUNCTION_MAY_BE_UNUSED
  4564. static int
  4565. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4566. {
  4567. (void)unused;
  4568. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4569. cv->waiting_thread = NULL;
  4570. return 0;
  4571. }
  4572. FUNCTION_MAY_BE_UNUSED
  4573. static int
  4574. pthread_cond_timedwait(pthread_cond_t *cv,
  4575. pthread_mutex_t *mutex,
  4576. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4577. {
  4578. struct mg_workerTLS **ptls,
  4579. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4580. int ok;
  4581. int64_t nsnow, nswaitabs, nswaitrel;
  4582. DWORD mswaitrel;
  4583. pthread_mutex_lock(&cv->threadIdSec);
  4584. /* Add this thread to cv's waiting list */
  4585. ptls = &cv->waiting_thread;
  4586. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4587. ;
  4588. tls->next_waiting_thread = NULL;
  4589. *ptls = tls;
  4590. pthread_mutex_unlock(&cv->threadIdSec);
  4591. if (abstime) {
  4592. nsnow = mg_get_current_time_ns();
  4593. nswaitabs =
  4594. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4595. nswaitrel = nswaitabs - nsnow;
  4596. if (nswaitrel < 0) {
  4597. nswaitrel = 0;
  4598. }
  4599. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4600. } else {
  4601. mswaitrel = (DWORD)INFINITE;
  4602. }
  4603. pthread_mutex_unlock(mutex);
  4604. ok = (WAIT_OBJECT_0
  4605. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4606. if (!ok) {
  4607. ok = 1;
  4608. pthread_mutex_lock(&cv->threadIdSec);
  4609. ptls = &cv->waiting_thread;
  4610. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4611. if (*ptls == tls) {
  4612. *ptls = tls->next_waiting_thread;
  4613. ok = 0;
  4614. break;
  4615. }
  4616. }
  4617. pthread_mutex_unlock(&cv->threadIdSec);
  4618. if (ok) {
  4619. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4620. (DWORD)INFINITE);
  4621. }
  4622. }
  4623. /* This thread has been removed from cv's waiting list */
  4624. pthread_mutex_lock(mutex);
  4625. return ok ? 0 : -1;
  4626. }
  4627. FUNCTION_MAY_BE_UNUSED
  4628. static int
  4629. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4630. {
  4631. return pthread_cond_timedwait(cv, mutex, NULL);
  4632. }
  4633. FUNCTION_MAY_BE_UNUSED
  4634. static int
  4635. pthread_cond_signal(pthread_cond_t *cv)
  4636. {
  4637. HANDLE wkup = NULL;
  4638. BOOL ok = FALSE;
  4639. pthread_mutex_lock(&cv->threadIdSec);
  4640. if (cv->waiting_thread) {
  4641. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4642. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4643. ok = SetEvent(wkup);
  4644. DEBUG_ASSERT(ok);
  4645. }
  4646. pthread_mutex_unlock(&cv->threadIdSec);
  4647. return ok ? 0 : 1;
  4648. }
  4649. FUNCTION_MAY_BE_UNUSED
  4650. static int
  4651. pthread_cond_broadcast(pthread_cond_t *cv)
  4652. {
  4653. pthread_mutex_lock(&cv->threadIdSec);
  4654. while (cv->waiting_thread) {
  4655. pthread_cond_signal(cv);
  4656. }
  4657. pthread_mutex_unlock(&cv->threadIdSec);
  4658. return 0;
  4659. }
  4660. FUNCTION_MAY_BE_UNUSED
  4661. static int
  4662. pthread_cond_destroy(pthread_cond_t *cv)
  4663. {
  4664. pthread_mutex_lock(&cv->threadIdSec);
  4665. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4666. pthread_mutex_unlock(&cv->threadIdSec);
  4667. pthread_mutex_destroy(&cv->threadIdSec);
  4668. return 0;
  4669. }
  4670. #if defined(ALTERNATIVE_QUEUE)
  4671. FUNCTION_MAY_BE_UNUSED
  4672. static void *
  4673. event_create(void)
  4674. {
  4675. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4676. }
  4677. FUNCTION_MAY_BE_UNUSED
  4678. static int
  4679. event_wait(void *eventhdl)
  4680. {
  4681. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4682. return (res == WAIT_OBJECT_0);
  4683. }
  4684. FUNCTION_MAY_BE_UNUSED
  4685. static int
  4686. event_signal(void *eventhdl)
  4687. {
  4688. return (int)SetEvent((HANDLE)eventhdl);
  4689. }
  4690. FUNCTION_MAY_BE_UNUSED
  4691. static void
  4692. event_destroy(void *eventhdl)
  4693. {
  4694. CloseHandle((HANDLE)eventhdl);
  4695. }
  4696. #endif
  4697. #if defined(GCC_DIAGNOSTIC)
  4698. /* Enable unused function warning again */
  4699. #pragma GCC diagnostic pop
  4700. #endif
  4701. /* For Windows, change all slashes to backslashes in path names. */
  4702. static void
  4703. change_slashes_to_backslashes(char *path)
  4704. {
  4705. int i;
  4706. for (i = 0; path[i] != '\0'; i++) {
  4707. if (path[i] == '/') {
  4708. path[i] = '\\';
  4709. }
  4710. /* remove double backslash (check i > 0 to preserve UNC paths,
  4711. * like \\server\file.txt) */
  4712. if ((i > 0) && (path[i] == '\\')) {
  4713. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4714. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4715. }
  4716. }
  4717. }
  4718. }
  4719. static int
  4720. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4721. {
  4722. int diff;
  4723. do {
  4724. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4725. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4726. s1++;
  4727. s2++;
  4728. } while ((diff == 0) && (s1[-1] != L'\0'));
  4729. return diff;
  4730. }
  4731. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4732. * wbuf and wbuf_len is a target buffer and its length. */
  4733. static void
  4734. path_to_unicode(const struct mg_connection *conn,
  4735. const char *path,
  4736. wchar_t *wbuf,
  4737. size_t wbuf_len)
  4738. {
  4739. char buf[PATH_MAX], buf2[PATH_MAX];
  4740. wchar_t wbuf2[W_PATH_MAX + 1];
  4741. DWORD long_len, err;
  4742. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4743. mg_strlcpy(buf, path, sizeof(buf));
  4744. change_slashes_to_backslashes(buf);
  4745. /* Convert to Unicode and back. If doubly-converted string does not
  4746. * match the original, something is fishy, reject. */
  4747. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4748. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4749. WideCharToMultiByte(
  4750. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4751. if (strcmp(buf, buf2) != 0) {
  4752. wbuf[0] = L'\0';
  4753. }
  4754. /* Windows file systems are not case sensitive, but you can still use
  4755. * uppercase and lowercase letters (on all modern file systems).
  4756. * The server can check if the URI uses the same upper/lowercase
  4757. * letters an the file system, effectively making Windows servers
  4758. * case sensitive (like Linux servers are). It is still not possible
  4759. * to use two files with the same name in different cases on Windows
  4760. * (like /a and /A) - this would be possible in Linux.
  4761. * As a default, Windows is not case sensitive, but the case sensitive
  4762. * file name check can be activated by an additional configuration. */
  4763. if (conn) {
  4764. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4765. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4766. "yes")) {
  4767. /* Use case sensitive compare function */
  4768. fcompare = wcscmp;
  4769. }
  4770. }
  4771. (void)conn; /* conn is currently unused */
  4772. #if !defined(_WIN32_WCE)
  4773. /* Only accept a full file path, not a Windows short (8.3) path. */
  4774. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4775. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4776. if (long_len == 0) {
  4777. err = GetLastError();
  4778. if (err == ERROR_FILE_NOT_FOUND) {
  4779. /* File does not exist. This is not always a problem here. */
  4780. return;
  4781. }
  4782. }
  4783. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4784. /* Short name is used. */
  4785. wbuf[0] = L'\0';
  4786. }
  4787. #else
  4788. (void)long_len;
  4789. (void)wbuf2;
  4790. (void)err;
  4791. if (strchr(path, '~')) {
  4792. wbuf[0] = L'\0';
  4793. }
  4794. #endif
  4795. }
  4796. #if !defined(NO_FILESYSTEMS)
  4797. /* Get file information, return 1 if file exists, 0 if not */
  4798. static int
  4799. mg_stat(const struct mg_connection *conn,
  4800. const char *path,
  4801. struct mg_file_stat *filep)
  4802. {
  4803. wchar_t wbuf[W_PATH_MAX];
  4804. WIN32_FILE_ATTRIBUTE_DATA info;
  4805. time_t creation_time;
  4806. size_t len;
  4807. if (!filep) {
  4808. return 0;
  4809. }
  4810. memset(filep, 0, sizeof(*filep));
  4811. if (mg_path_suspicious(conn, path)) {
  4812. return 0;
  4813. }
  4814. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4815. /* Windows happily opens files with some garbage at the end of file name.
  4816. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4817. * "a.cgi", despite one would expect an error back. */
  4818. len = strlen(path);
  4819. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4820. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4821. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4822. filep->last_modified =
  4823. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4824. info.ftLastWriteTime.dwHighDateTime);
  4825. /* On Windows, the file creation time can be higher than the
  4826. * modification time, e.g. when a file is copied.
  4827. * Since the Last-Modified timestamp is used for caching
  4828. * it should be based on the most recent timestamp. */
  4829. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4830. info.ftCreationTime.dwHighDateTime);
  4831. if (creation_time > filep->last_modified) {
  4832. filep->last_modified = creation_time;
  4833. }
  4834. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4835. return 1;
  4836. }
  4837. return 0;
  4838. }
  4839. #endif
  4840. static int
  4841. mg_remove(const struct mg_connection *conn, const char *path)
  4842. {
  4843. wchar_t wbuf[W_PATH_MAX];
  4844. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4845. return DeleteFileW(wbuf) ? 0 : -1;
  4846. }
  4847. static int
  4848. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4849. {
  4850. wchar_t wbuf[W_PATH_MAX];
  4851. (void)mode;
  4852. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4853. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4854. }
  4855. /* Create substitutes for POSIX functions in Win32. */
  4856. #if defined(GCC_DIAGNOSTIC)
  4857. /* Show no warning in case system functions are not used. */
  4858. #pragma GCC diagnostic push
  4859. #pragma GCC diagnostic ignored "-Wunused-function"
  4860. #endif
  4861. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4862. FUNCTION_MAY_BE_UNUSED
  4863. static DIR *
  4864. mg_opendir(const struct mg_connection *conn, const char *name)
  4865. {
  4866. DIR *dir = NULL;
  4867. wchar_t wpath[W_PATH_MAX];
  4868. DWORD attrs;
  4869. if (name == NULL) {
  4870. SetLastError(ERROR_BAD_ARGUMENTS);
  4871. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4872. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4873. } else {
  4874. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4875. attrs = GetFileAttributesW(wpath);
  4876. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4877. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4878. (void)wcscat(wpath, L"\\*");
  4879. dir->handle = FindFirstFileW(wpath, &dir->info);
  4880. dir->result.d_name[0] = '\0';
  4881. } else {
  4882. mg_free(dir);
  4883. dir = NULL;
  4884. }
  4885. }
  4886. return dir;
  4887. }
  4888. FUNCTION_MAY_BE_UNUSED
  4889. static int
  4890. mg_closedir(DIR *dir)
  4891. {
  4892. int result = 0;
  4893. if (dir != NULL) {
  4894. if (dir->handle != INVALID_HANDLE_VALUE)
  4895. result = FindClose(dir->handle) ? 0 : -1;
  4896. mg_free(dir);
  4897. } else {
  4898. result = -1;
  4899. SetLastError(ERROR_BAD_ARGUMENTS);
  4900. }
  4901. return result;
  4902. }
  4903. FUNCTION_MAY_BE_UNUSED
  4904. static struct dirent *
  4905. mg_readdir(DIR *dir)
  4906. {
  4907. struct dirent *result = 0;
  4908. if (dir) {
  4909. if (dir->handle != INVALID_HANDLE_VALUE) {
  4910. result = &dir->result;
  4911. (void)WideCharToMultiByte(CP_UTF8,
  4912. 0,
  4913. dir->info.cFileName,
  4914. -1,
  4915. result->d_name,
  4916. sizeof(result->d_name),
  4917. NULL,
  4918. NULL);
  4919. if (!FindNextFileW(dir->handle, &dir->info)) {
  4920. (void)FindClose(dir->handle);
  4921. dir->handle = INVALID_HANDLE_VALUE;
  4922. }
  4923. } else {
  4924. SetLastError(ERROR_FILE_NOT_FOUND);
  4925. }
  4926. } else {
  4927. SetLastError(ERROR_BAD_ARGUMENTS);
  4928. }
  4929. return result;
  4930. }
  4931. #if !defined(HAVE_POLL)
  4932. #undef POLLIN
  4933. #undef POLLPRI
  4934. #undef POLLOUT
  4935. #define POLLIN (1) /* Data ready - read will not block. */
  4936. #define POLLPRI (2) /* Priority data ready. */
  4937. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4938. FUNCTION_MAY_BE_UNUSED
  4939. static int
  4940. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4941. {
  4942. struct timeval tv;
  4943. fd_set rset;
  4944. fd_set wset;
  4945. unsigned int i;
  4946. int result;
  4947. SOCKET maxfd = 0;
  4948. memset(&tv, 0, sizeof(tv));
  4949. tv.tv_sec = milliseconds / 1000;
  4950. tv.tv_usec = (milliseconds % 1000) * 1000;
  4951. FD_ZERO(&rset);
  4952. FD_ZERO(&wset);
  4953. for (i = 0; i < n; i++) {
  4954. if (pfd[i].events & POLLIN) {
  4955. FD_SET(pfd[i].fd, &rset);
  4956. }
  4957. if (pfd[i].events & POLLOUT) {
  4958. FD_SET(pfd[i].fd, &wset);
  4959. }
  4960. pfd[i].revents = 0;
  4961. if (pfd[i].fd > maxfd) {
  4962. maxfd = pfd[i].fd;
  4963. }
  4964. }
  4965. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4966. for (i = 0; i < n; i++) {
  4967. if (FD_ISSET(pfd[i].fd, &rset)) {
  4968. pfd[i].revents |= POLLIN;
  4969. }
  4970. if (FD_ISSET(pfd[i].fd, &wset)) {
  4971. pfd[i].revents |= POLLOUT;
  4972. }
  4973. }
  4974. }
  4975. /* We should subtract the time used in select from remaining
  4976. * "milliseconds", in particular if called from mg_poll with a
  4977. * timeout quantum.
  4978. * Unfortunately, the remaining time is not stored in "tv" in all
  4979. * implementations, so the result in "tv" must be considered undefined.
  4980. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4981. return result;
  4982. }
  4983. #endif /* HAVE_POLL */
  4984. #if defined(GCC_DIAGNOSTIC)
  4985. /* Enable unused function warning again */
  4986. #pragma GCC diagnostic pop
  4987. #endif
  4988. static void
  4989. set_close_on_exec(SOCKET sock,
  4990. const struct mg_connection *conn /* may be null */,
  4991. struct mg_context *ctx /* may be null */)
  4992. {
  4993. (void)conn; /* Unused. */
  4994. (void)ctx;
  4995. #if defined(_WIN32_WCE)
  4996. (void)sock;
  4997. #else
  4998. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4999. #endif
  5000. }
  5001. int
  5002. mg_start_thread(mg_thread_func_t f, void *p)
  5003. {
  5004. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5005. /* Compile-time option to control stack size, e.g.
  5006. * -DUSE_STACK_SIZE=16384
  5007. */
  5008. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  5009. == ((uintptr_t)(-1L)))
  5010. ? -1
  5011. : 0);
  5012. #else
  5013. return (
  5014. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  5015. ? -1
  5016. : 0);
  5017. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5018. }
  5019. /* Start a thread storing the thread context. */
  5020. static int
  5021. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  5022. void *p,
  5023. pthread_t *threadidptr)
  5024. {
  5025. uintptr_t uip;
  5026. HANDLE threadhandle;
  5027. int result = -1;
  5028. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  5029. threadhandle = (HANDLE)uip;
  5030. if ((uip != 0) && (threadidptr != NULL)) {
  5031. *threadidptr = threadhandle;
  5032. result = 0;
  5033. }
  5034. return result;
  5035. }
  5036. /* Wait for a thread to finish. */
  5037. static int
  5038. mg_join_thread(pthread_t threadid)
  5039. {
  5040. int result;
  5041. DWORD dwevent;
  5042. result = -1;
  5043. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  5044. if (dwevent == WAIT_FAILED) {
  5045. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  5046. } else {
  5047. if (dwevent == WAIT_OBJECT_0) {
  5048. CloseHandle(threadid);
  5049. result = 0;
  5050. }
  5051. }
  5052. return result;
  5053. }
  5054. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  5055. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  5056. /* Create substitutes for POSIX functions in Win32. */
  5057. #if defined(GCC_DIAGNOSTIC)
  5058. /* Show no warning in case system functions are not used. */
  5059. #pragma GCC diagnostic push
  5060. #pragma GCC diagnostic ignored "-Wunused-function"
  5061. #endif
  5062. FUNCTION_MAY_BE_UNUSED
  5063. static HANDLE
  5064. dlopen(const char *dll_name, int flags)
  5065. {
  5066. wchar_t wbuf[W_PATH_MAX];
  5067. (void)flags;
  5068. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  5069. return LoadLibraryW(wbuf);
  5070. }
  5071. FUNCTION_MAY_BE_UNUSED
  5072. static int
  5073. dlclose(void *handle)
  5074. {
  5075. int result;
  5076. if (FreeLibrary((HMODULE)handle) != 0) {
  5077. result = 0;
  5078. } else {
  5079. result = -1;
  5080. }
  5081. return result;
  5082. }
  5083. #if defined(GCC_DIAGNOSTIC)
  5084. /* Enable unused function warning again */
  5085. #pragma GCC diagnostic pop
  5086. #endif
  5087. #endif
  5088. #if !defined(NO_CGI)
  5089. #define SIGKILL (0)
  5090. static int
  5091. kill(pid_t pid, int sig_num)
  5092. {
  5093. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  5094. (void)CloseHandle((HANDLE)pid);
  5095. return 0;
  5096. }
  5097. #if !defined(WNOHANG)
  5098. #define WNOHANG (1)
  5099. #endif
  5100. static pid_t
  5101. waitpid(pid_t pid, int *status, int flags)
  5102. {
  5103. DWORD timeout = INFINITE;
  5104. DWORD waitres;
  5105. (void)status; /* Currently not used by any client here */
  5106. if ((flags | WNOHANG) == WNOHANG) {
  5107. timeout = 0;
  5108. }
  5109. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  5110. if (waitres == WAIT_OBJECT_0) {
  5111. return pid;
  5112. }
  5113. if (waitres == WAIT_TIMEOUT) {
  5114. return 0;
  5115. }
  5116. return (pid_t)-1;
  5117. }
  5118. static void
  5119. trim_trailing_whitespaces(char *s)
  5120. {
  5121. char *e = s + strlen(s);
  5122. while ((e > s) && isspace((unsigned char)e[-1])) {
  5123. *(--e) = '\0';
  5124. }
  5125. }
  5126. static pid_t
  5127. spawn_process(struct mg_connection *conn,
  5128. const char *prog,
  5129. char *envblk,
  5130. char *envp[],
  5131. int fdin[2],
  5132. int fdout[2],
  5133. int fderr[2],
  5134. const char *dir)
  5135. {
  5136. HANDLE me;
  5137. char *interp;
  5138. char *interp_arg = 0;
  5139. char full_dir[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX];
  5140. int truncated;
  5141. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5142. STARTUPINFOA si;
  5143. PROCESS_INFORMATION pi = {0};
  5144. (void)envp;
  5145. memset(&si, 0, sizeof(si));
  5146. si.cb = sizeof(si);
  5147. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5148. si.wShowWindow = SW_HIDE;
  5149. me = GetCurrentProcess();
  5150. DuplicateHandle(me,
  5151. (HANDLE)_get_osfhandle(fdin[0]),
  5152. me,
  5153. &si.hStdInput,
  5154. 0,
  5155. TRUE,
  5156. DUPLICATE_SAME_ACCESS);
  5157. DuplicateHandle(me,
  5158. (HANDLE)_get_osfhandle(fdout[1]),
  5159. me,
  5160. &si.hStdOutput,
  5161. 0,
  5162. TRUE,
  5163. DUPLICATE_SAME_ACCESS);
  5164. DuplicateHandle(me,
  5165. (HANDLE)_get_osfhandle(fderr[1]),
  5166. me,
  5167. &si.hStdError,
  5168. 0,
  5169. TRUE,
  5170. DUPLICATE_SAME_ACCESS);
  5171. /* Mark handles that should not be inherited. See
  5172. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5173. */
  5174. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5175. HANDLE_FLAG_INHERIT,
  5176. 0);
  5177. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5178. HANDLE_FLAG_INHERIT,
  5179. 0);
  5180. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5181. HANDLE_FLAG_INHERIT,
  5182. 0);
  5183. /* First check, if there is a CGI interpreter configured for all CGI
  5184. * scripts. */
  5185. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5186. if (interp != NULL) {
  5187. /* If there is a configured interpreter, check for additional arguments
  5188. */
  5189. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5190. } else {
  5191. /* Otherwise, the interpreter must be stated in the first line of the
  5192. * CGI script file, after a #! (shebang) mark. */
  5193. buf[0] = buf[1] = '\0';
  5194. /* Get the full script path */
  5195. mg_snprintf(
  5196. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5197. if (truncated) {
  5198. pi.hProcess = (pid_t)-1;
  5199. goto spawn_cleanup;
  5200. }
  5201. /* Open the script file, to read the first line */
  5202. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5203. /* Read the first line of the script into the buffer */
  5204. mg_fgets(buf, sizeof(buf), &file);
  5205. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5206. buf[sizeof(buf) - 1] = '\0';
  5207. }
  5208. if ((buf[0] == '#') && (buf[1] == '!')) {
  5209. trim_trailing_whitespaces(buf + 2);
  5210. } else {
  5211. buf[2] = '\0';
  5212. }
  5213. interp = buf + 2;
  5214. }
  5215. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5216. if (interp[0] != '\0') {
  5217. /* This is an interpreted script file. We must call the interpreter. */
  5218. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5219. mg_snprintf(conn,
  5220. &truncated,
  5221. cmdline,
  5222. sizeof(cmdline),
  5223. "\"%s\" %s \"%s\\%s\"",
  5224. interp,
  5225. interp_arg,
  5226. full_dir,
  5227. prog);
  5228. } else {
  5229. mg_snprintf(conn,
  5230. &truncated,
  5231. cmdline,
  5232. sizeof(cmdline),
  5233. "\"%s\" \"%s\\%s\"",
  5234. interp,
  5235. full_dir,
  5236. prog);
  5237. }
  5238. } else {
  5239. /* This is (probably) a compiled program. We call it directly. */
  5240. mg_snprintf(conn,
  5241. &truncated,
  5242. cmdline,
  5243. sizeof(cmdline),
  5244. "\"%s\\%s\"",
  5245. full_dir,
  5246. prog);
  5247. }
  5248. if (truncated) {
  5249. pi.hProcess = (pid_t)-1;
  5250. goto spawn_cleanup;
  5251. }
  5252. DEBUG_TRACE("Running [%s]", cmdline);
  5253. if (CreateProcessA(NULL,
  5254. cmdline,
  5255. NULL,
  5256. NULL,
  5257. TRUE,
  5258. CREATE_NEW_PROCESS_GROUP,
  5259. envblk,
  5260. NULL,
  5261. &si,
  5262. &pi)
  5263. == 0) {
  5264. mg_cry_internal(
  5265. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5266. pi.hProcess = (pid_t)-1;
  5267. /* goto spawn_cleanup; */
  5268. }
  5269. spawn_cleanup:
  5270. (void)CloseHandle(si.hStdOutput);
  5271. (void)CloseHandle(si.hStdError);
  5272. (void)CloseHandle(si.hStdInput);
  5273. if (pi.hThread != NULL) {
  5274. (void)CloseHandle(pi.hThread);
  5275. }
  5276. return (pid_t)pi.hProcess;
  5277. }
  5278. #endif /* !NO_CGI */
  5279. static int
  5280. set_blocking_mode(SOCKET sock)
  5281. {
  5282. unsigned long non_blocking = 0;
  5283. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5284. }
  5285. static int
  5286. set_non_blocking_mode(SOCKET sock)
  5287. {
  5288. unsigned long non_blocking = 1;
  5289. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5290. }
  5291. #else
  5292. #if !defined(NO_FILESYSTEMS)
  5293. static int
  5294. mg_stat(const struct mg_connection *conn,
  5295. const char *path,
  5296. struct mg_file_stat *filep)
  5297. {
  5298. struct stat st;
  5299. if (!filep) {
  5300. return 0;
  5301. }
  5302. memset(filep, 0, sizeof(*filep));
  5303. if (mg_path_suspicious(conn, path)) {
  5304. return 0;
  5305. }
  5306. if (0 == stat(path, &st)) {
  5307. filep->size = (uint64_t)(st.st_size);
  5308. filep->last_modified = st.st_mtime;
  5309. filep->is_directory = S_ISDIR(st.st_mode);
  5310. return 1;
  5311. }
  5312. return 0;
  5313. }
  5314. #endif /* NO_FILESYSTEMS */
  5315. static void
  5316. set_close_on_exec(int fd,
  5317. const struct mg_connection *conn /* may be null */,
  5318. struct mg_context *ctx /* may be null */)
  5319. {
  5320. #if defined(__ZEPHYR__)
  5321. (void)fd;
  5322. (void)conn;
  5323. (void)ctx;
  5324. #else
  5325. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5326. if (conn || ctx) {
  5327. struct mg_connection fc;
  5328. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5329. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5330. __func__,
  5331. strerror(ERRNO));
  5332. }
  5333. }
  5334. #endif
  5335. }
  5336. int
  5337. mg_start_thread(mg_thread_func_t func, void *param)
  5338. {
  5339. pthread_t thread_id;
  5340. pthread_attr_t attr;
  5341. int result;
  5342. (void)pthread_attr_init(&attr);
  5343. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5344. #if defined(__ZEPHYR__)
  5345. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5346. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5347. /* Compile-time option to control stack size,
  5348. * e.g. -DUSE_STACK_SIZE=16384 */
  5349. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5350. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5351. result = pthread_create(&thread_id, &attr, func, param);
  5352. pthread_attr_destroy(&attr);
  5353. return result;
  5354. }
  5355. /* Start a thread storing the thread context. */
  5356. static int
  5357. mg_start_thread_with_id(mg_thread_func_t func,
  5358. void *param,
  5359. pthread_t *threadidptr)
  5360. {
  5361. pthread_t thread_id;
  5362. pthread_attr_t attr;
  5363. int result;
  5364. (void)pthread_attr_init(&attr);
  5365. #if defined(__ZEPHYR__)
  5366. pthread_attr_setstack(&attr,
  5367. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5368. ZEPHYR_STACK_SIZE);
  5369. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5370. /* Compile-time option to control stack size,
  5371. * e.g. -DUSE_STACK_SIZE=16384 */
  5372. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5373. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5374. result = pthread_create(&thread_id, &attr, func, param);
  5375. pthread_attr_destroy(&attr);
  5376. if ((result == 0) && (threadidptr != NULL)) {
  5377. *threadidptr = thread_id;
  5378. }
  5379. return result;
  5380. }
  5381. /* Wait for a thread to finish. */
  5382. static int
  5383. mg_join_thread(pthread_t threadid)
  5384. {
  5385. int result;
  5386. result = pthread_join(threadid, NULL);
  5387. return result;
  5388. }
  5389. #if !defined(NO_CGI)
  5390. static pid_t
  5391. spawn_process(struct mg_connection *conn,
  5392. const char *prog,
  5393. char *envblk,
  5394. char *envp[],
  5395. int fdin[2],
  5396. int fdout[2],
  5397. int fderr[2],
  5398. const char *dir)
  5399. {
  5400. pid_t pid;
  5401. const char *interp;
  5402. (void)envblk;
  5403. if ((pid = fork()) == -1) {
  5404. /* Parent */
  5405. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5406. } else if (pid != 0) {
  5407. /* Make sure children close parent-side descriptors.
  5408. * The caller will close the child-side immediately. */
  5409. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5410. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5411. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5412. } else {
  5413. /* Child */
  5414. if (chdir(dir) != 0) {
  5415. mg_cry_internal(
  5416. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5417. } else if (dup2(fdin[0], 0) == -1) {
  5418. mg_cry_internal(conn,
  5419. "%s: dup2(%d, 0): %s",
  5420. __func__,
  5421. fdin[0],
  5422. strerror(ERRNO));
  5423. } else if (dup2(fdout[1], 1) == -1) {
  5424. mg_cry_internal(conn,
  5425. "%s: dup2(%d, 1): %s",
  5426. __func__,
  5427. fdout[1],
  5428. strerror(ERRNO));
  5429. } else if (dup2(fderr[1], 2) == -1) {
  5430. mg_cry_internal(conn,
  5431. "%s: dup2(%d, 2): %s",
  5432. __func__,
  5433. fderr[1],
  5434. strerror(ERRNO));
  5435. } else {
  5436. struct sigaction sa;
  5437. /* Keep stderr and stdout in two different pipes.
  5438. * Stdout will be sent back to the client,
  5439. * stderr should go into a server error log. */
  5440. (void)close(fdin[0]);
  5441. (void)close(fdout[1]);
  5442. (void)close(fderr[1]);
  5443. /* Close write end fdin and read end fdout and fderr */
  5444. (void)close(fdin[1]);
  5445. (void)close(fdout[0]);
  5446. (void)close(fderr[0]);
  5447. /* After exec, all signal handlers are restored to their default
  5448. * values, with one exception of SIGCHLD. According to
  5449. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5450. * will leave unchanged after exec if it was set to be ignored.
  5451. * Restore it to default action. */
  5452. memset(&sa, 0, sizeof(sa));
  5453. sa.sa_handler = SIG_DFL;
  5454. sigaction(SIGCHLD, &sa, NULL);
  5455. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5456. if (interp == NULL) {
  5457. /* no interpreter configured, call the programm directly */
  5458. (void)execle(prog, prog, NULL, envp);
  5459. mg_cry_internal(conn,
  5460. "%s: execle(%s): %s",
  5461. __func__,
  5462. prog,
  5463. strerror(ERRNO));
  5464. } else {
  5465. /* call the configured interpreter */
  5466. const char *interp_args =
  5467. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5468. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5469. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5470. } else {
  5471. (void)execle(interp, interp, prog, NULL, envp);
  5472. }
  5473. mg_cry_internal(conn,
  5474. "%s: execle(%s %s): %s",
  5475. __func__,
  5476. interp,
  5477. prog,
  5478. strerror(ERRNO));
  5479. }
  5480. }
  5481. exit(EXIT_FAILURE);
  5482. }
  5483. return pid;
  5484. }
  5485. #endif /* !NO_CGI */
  5486. static int
  5487. set_non_blocking_mode(SOCKET sock)
  5488. {
  5489. int flags = fcntl(sock, F_GETFL, 0);
  5490. if (flags < 0) {
  5491. return -1;
  5492. }
  5493. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5494. return -1;
  5495. }
  5496. return 0;
  5497. }
  5498. static int
  5499. set_blocking_mode(SOCKET sock)
  5500. {
  5501. int flags = fcntl(sock, F_GETFL, 0);
  5502. if (flags < 0) {
  5503. return -1;
  5504. }
  5505. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5506. return -1;
  5507. }
  5508. return 0;
  5509. }
  5510. #endif /* _WIN32 / else */
  5511. /* End of initial operating system specific define block. */
  5512. /* Get a random number (independent of C rand function) */
  5513. static uint64_t
  5514. get_random(void)
  5515. {
  5516. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5517. static uint64_t lcg = 0; /* Linear congruential generator */
  5518. uint64_t now = mg_get_current_time_ns();
  5519. if (lfsr == 0) {
  5520. /* lfsr will be only 0 if has not been initialized,
  5521. * so this code is called only once. */
  5522. lfsr = mg_get_current_time_ns();
  5523. lcg = mg_get_current_time_ns();
  5524. } else {
  5525. /* Get the next step of both random number generators. */
  5526. lfsr = (lfsr >> 1)
  5527. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5528. << 63);
  5529. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5530. }
  5531. /* Combining two pseudo-random number generators and a high resolution
  5532. * part
  5533. * of the current server time will make it hard (impossible?) to guess
  5534. * the
  5535. * next number. */
  5536. return (lfsr ^ lcg ^ now);
  5537. }
  5538. static int
  5539. mg_poll(struct mg_pollfd *pfd,
  5540. unsigned int n,
  5541. int milliseconds,
  5542. stop_flag_t *stop_flag)
  5543. {
  5544. /* Call poll, but only for a maximum time of a few seconds.
  5545. * This will allow to stop the server after some seconds, instead
  5546. * of having to wait for a long socket timeout. */
  5547. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5548. do {
  5549. int result;
  5550. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5551. /* Shut down signal */
  5552. return -2;
  5553. }
  5554. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5555. ms_now = milliseconds;
  5556. }
  5557. result = poll(pfd, n, ms_now);
  5558. if (result != 0) {
  5559. /* Poll returned either success (1) or error (-1).
  5560. * Forward both to the caller. */
  5561. return result;
  5562. }
  5563. /* Poll returned timeout (0). */
  5564. if (milliseconds > 0) {
  5565. milliseconds -= ms_now;
  5566. }
  5567. } while (milliseconds > 0);
  5568. /* timeout: return 0 */
  5569. return 0;
  5570. }
  5571. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5572. * descriptor.
  5573. * Return value:
  5574. * >=0 .. number of bytes successfully written
  5575. * -1 .. timeout
  5576. * -2 .. error
  5577. */
  5578. static int
  5579. push_inner(struct mg_context *ctx,
  5580. FILE *fp,
  5581. SOCKET sock,
  5582. SSL *ssl,
  5583. const char *buf,
  5584. int len,
  5585. double timeout)
  5586. {
  5587. uint64_t start = 0, now = 0, timeout_ns = 0;
  5588. int n, err;
  5589. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5590. #if defined(_WIN32)
  5591. typedef int len_t;
  5592. #else
  5593. typedef size_t len_t;
  5594. #endif
  5595. if (timeout > 0) {
  5596. now = mg_get_current_time_ns();
  5597. start = now;
  5598. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5599. }
  5600. if (ctx == NULL) {
  5601. return -2;
  5602. }
  5603. #if defined(NO_SSL)
  5604. if (ssl) {
  5605. return -2;
  5606. }
  5607. #endif
  5608. /* Try to read until it succeeds, fails, times out, or the server
  5609. * shuts down. */
  5610. for (;;) {
  5611. #if !defined(NO_SSL)
  5612. if (ssl != NULL) {
  5613. ERR_clear_error();
  5614. n = SSL_write(ssl, buf, len);
  5615. if (n <= 0) {
  5616. err = SSL_get_error(ssl, n);
  5617. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5618. err = ERRNO;
  5619. } else if ((err == SSL_ERROR_WANT_READ)
  5620. || (err == SSL_ERROR_WANT_WRITE)) {
  5621. n = 0;
  5622. } else {
  5623. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5624. ERR_clear_error();
  5625. return -2;
  5626. }
  5627. ERR_clear_error();
  5628. } else {
  5629. err = 0;
  5630. }
  5631. } else
  5632. #endif
  5633. if (fp != NULL) {
  5634. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5635. if (ferror(fp)) {
  5636. n = -1;
  5637. err = ERRNO;
  5638. } else {
  5639. err = 0;
  5640. }
  5641. } else {
  5642. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5643. err = (n < 0) ? ERRNO : 0;
  5644. #if defined(_WIN32)
  5645. if (err == WSAEWOULDBLOCK) {
  5646. err = 0;
  5647. n = 0;
  5648. }
  5649. #else
  5650. if (ERROR_TRY_AGAIN(err)) {
  5651. err = 0;
  5652. n = 0;
  5653. }
  5654. #endif
  5655. if (n < 0) {
  5656. /* shutdown of the socket at client side */
  5657. return -2;
  5658. }
  5659. }
  5660. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5661. return -2;
  5662. }
  5663. if ((n > 0) || ((n == 0) && (len == 0))) {
  5664. /* some data has been read, or no data was requested */
  5665. return n;
  5666. }
  5667. if (n < 0) {
  5668. /* socket error - check errno */
  5669. DEBUG_TRACE("send() failed, error %d", err);
  5670. /* TODO (mid): error handling depending on the error code.
  5671. * These codes are different between Windows and Linux.
  5672. * Currently there is no problem with failing send calls,
  5673. * if there is a reproducible situation, it should be
  5674. * investigated in detail.
  5675. */
  5676. return -2;
  5677. }
  5678. /* Only in case n=0 (timeout), repeat calling the write function */
  5679. /* If send failed, wait before retry */
  5680. if (fp != NULL) {
  5681. /* For files, just wait a fixed time.
  5682. * Maybe it helps, maybe not. */
  5683. mg_sleep(5);
  5684. } else {
  5685. /* For sockets, wait for the socket using poll */
  5686. struct mg_pollfd pfd[1];
  5687. int pollres;
  5688. pfd[0].fd = sock;
  5689. pfd[0].events = POLLOUT;
  5690. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5691. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5692. return -2;
  5693. }
  5694. if (pollres > 0) {
  5695. continue;
  5696. }
  5697. }
  5698. if (timeout > 0) {
  5699. now = mg_get_current_time_ns();
  5700. if ((now - start) > timeout_ns) {
  5701. /* Timeout */
  5702. break;
  5703. }
  5704. }
  5705. }
  5706. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5707. used */
  5708. return -1;
  5709. }
  5710. static int
  5711. push_all(struct mg_context *ctx,
  5712. FILE *fp,
  5713. SOCKET sock,
  5714. SSL *ssl,
  5715. const char *buf,
  5716. int len)
  5717. {
  5718. double timeout = -1.0;
  5719. int n, nwritten = 0;
  5720. if (ctx == NULL) {
  5721. return -1;
  5722. }
  5723. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5724. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5725. }
  5726. if (timeout <= 0.0) {
  5727. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5728. }
  5729. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5730. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5731. if (n < 0) {
  5732. if (nwritten == 0) {
  5733. nwritten = -1; /* Propagate the error */
  5734. }
  5735. break;
  5736. } else if (n == 0) {
  5737. break; /* No more data to write */
  5738. } else {
  5739. nwritten += n;
  5740. len -= n;
  5741. }
  5742. }
  5743. return nwritten;
  5744. }
  5745. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5746. * Return value:
  5747. * >=0 .. number of bytes successfully read
  5748. * -1 .. timeout
  5749. * -2 .. error
  5750. */
  5751. static int
  5752. pull_inner(FILE *fp,
  5753. struct mg_connection *conn,
  5754. char *buf,
  5755. int len,
  5756. double timeout)
  5757. {
  5758. int nread, err = 0;
  5759. #if defined(_WIN32)
  5760. typedef int len_t;
  5761. #else
  5762. typedef size_t len_t;
  5763. #endif
  5764. /* We need an additional wait loop around this, because in some cases
  5765. * with TLSwe may get data from the socket but not from SSL_read.
  5766. * In this case we need to repeat at least once.
  5767. */
  5768. if (fp != NULL) {
  5769. #if !defined(_WIN32_WCE)
  5770. /* Use read() instead of fread(), because if we're reading from the
  5771. * CGI pipe, fread() may block until IO buffer is filled up. We
  5772. * cannot afford to block and must pass all read bytes immediately
  5773. * to the client. */
  5774. nread = (int)read(fileno(fp), buf, (size_t)len);
  5775. #else
  5776. /* WinCE does not support CGI pipes */
  5777. nread = (int)fread(buf, 1, (size_t)len, fp);
  5778. #endif
  5779. err = (nread < 0) ? ERRNO : 0;
  5780. if ((nread == 0) && (len > 0)) {
  5781. /* Should get data, but got EOL */
  5782. return -2;
  5783. }
  5784. #if !defined(NO_SSL)
  5785. } else if (conn->ssl != NULL) {
  5786. int ssl_pending;
  5787. struct mg_pollfd pfd[1];
  5788. int pollres;
  5789. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5790. /* We already know there is no more data buffered in conn->buf
  5791. * but there is more available in the SSL layer. So don't poll
  5792. * conn->client.sock yet. */
  5793. if (ssl_pending > len) {
  5794. ssl_pending = len;
  5795. }
  5796. pollres = 1;
  5797. } else {
  5798. pfd[0].fd = conn->client.sock;
  5799. pfd[0].events = POLLIN;
  5800. pollres = mg_poll(pfd,
  5801. 1,
  5802. (int)(timeout * 1000.0),
  5803. &(conn->phys_ctx->stop_flag));
  5804. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5805. return -2;
  5806. }
  5807. }
  5808. if (pollres > 0) {
  5809. ERR_clear_error();
  5810. nread =
  5811. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5812. if (nread <= 0) {
  5813. err = SSL_get_error(conn->ssl, nread);
  5814. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5815. err = ERRNO;
  5816. } else if ((err == SSL_ERROR_WANT_READ)
  5817. || (err == SSL_ERROR_WANT_WRITE)) {
  5818. nread = 0;
  5819. } else {
  5820. /* All errors should return -2 */
  5821. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5822. ERR_clear_error();
  5823. return -2;
  5824. }
  5825. ERR_clear_error();
  5826. } else {
  5827. err = 0;
  5828. }
  5829. } else if (pollres < 0) {
  5830. /* Error */
  5831. return -2;
  5832. } else {
  5833. /* pollres = 0 means timeout */
  5834. nread = 0;
  5835. }
  5836. #endif
  5837. } else {
  5838. struct mg_pollfd pfd[1];
  5839. int pollres;
  5840. pfd[0].fd = conn->client.sock;
  5841. pfd[0].events = POLLIN;
  5842. pollres = mg_poll(pfd,
  5843. 1,
  5844. (int)(timeout * 1000.0),
  5845. &(conn->phys_ctx->stop_flag));
  5846. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5847. return -2;
  5848. }
  5849. if (pollres > 0) {
  5850. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5851. err = (nread < 0) ? ERRNO : 0;
  5852. if (nread <= 0) {
  5853. /* shutdown of the socket at client side */
  5854. return -2;
  5855. }
  5856. } else if (pollres < 0) {
  5857. /* error callint poll */
  5858. return -2;
  5859. } else {
  5860. /* pollres = 0 means timeout */
  5861. nread = 0;
  5862. }
  5863. }
  5864. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5865. return -2;
  5866. }
  5867. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5868. /* some data has been read, or no data was requested */
  5869. return nread;
  5870. }
  5871. if (nread < 0) {
  5872. /* socket error - check errno */
  5873. #if defined(_WIN32)
  5874. if (err == WSAEWOULDBLOCK) {
  5875. /* TODO (low): check if this is still required */
  5876. /* standard case if called from close_socket_gracefully */
  5877. return -2;
  5878. } else if (err == WSAETIMEDOUT) {
  5879. /* TODO (low): check if this is still required */
  5880. /* timeout is handled by the while loop */
  5881. return 0;
  5882. } else if (err == WSAECONNABORTED) {
  5883. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5884. return -2;
  5885. } else {
  5886. DEBUG_TRACE("recv() failed, error %d", err);
  5887. return -2;
  5888. }
  5889. #else
  5890. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5891. * if the timeout is reached and if the socket was set to non-
  5892. * blocking in close_socket_gracefully, so we can not distinguish
  5893. * here. We have to wait for the timeout in both cases for now.
  5894. */
  5895. if (ERROR_TRY_AGAIN(err)) {
  5896. /* TODO (low): check if this is still required */
  5897. /* EAGAIN/EWOULDBLOCK:
  5898. * standard case if called from close_socket_gracefully
  5899. * => should return -1 */
  5900. /* or timeout occurred
  5901. * => the code must stay in the while loop */
  5902. /* EINTR can be generated on a socket with a timeout set even
  5903. * when SA_RESTART is effective for all relevant signals
  5904. * (see signal(7)).
  5905. * => stay in the while loop */
  5906. } else {
  5907. DEBUG_TRACE("recv() failed, error %d", err);
  5908. return -2;
  5909. }
  5910. #endif
  5911. }
  5912. /* Timeout occurred, but no data available. */
  5913. return -1;
  5914. }
  5915. static int
  5916. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5917. {
  5918. int n, nread = 0;
  5919. double timeout = -1.0;
  5920. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5921. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5922. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5923. }
  5924. if (timeout <= 0.0) {
  5925. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5926. }
  5927. start_time = mg_get_current_time_ns();
  5928. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5929. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5930. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5931. if (n == -2) {
  5932. if (nread == 0) {
  5933. nread = -1; /* Propagate the error */
  5934. }
  5935. break;
  5936. } else if (n == -1) {
  5937. /* timeout */
  5938. if (timeout >= 0.0) {
  5939. now = mg_get_current_time_ns();
  5940. if ((now - start_time) <= timeout_ns) {
  5941. continue;
  5942. }
  5943. }
  5944. break;
  5945. } else if (n == 0) {
  5946. break; /* No more data to read */
  5947. } else {
  5948. nread += n;
  5949. len -= n;
  5950. }
  5951. }
  5952. return nread;
  5953. }
  5954. static void
  5955. discard_unread_request_data(struct mg_connection *conn)
  5956. {
  5957. char buf[MG_BUF_LEN];
  5958. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5959. ;
  5960. }
  5961. static int
  5962. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5963. {
  5964. int64_t content_len, n, buffered_len, nread;
  5965. int64_t len64 =
  5966. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5967. * int, we may not read more
  5968. * bytes */
  5969. const char *body;
  5970. if (conn == NULL) {
  5971. return 0;
  5972. }
  5973. /* If Content-Length is not set for a response with body data,
  5974. * we do not know in advance how much data should be read. */
  5975. content_len = conn->content_len;
  5976. if (content_len < 0) {
  5977. /* The body data is completed when the connection is closed. */
  5978. content_len = INT64_MAX;
  5979. }
  5980. nread = 0;
  5981. if (conn->consumed_content < content_len) {
  5982. /* Adjust number of bytes to read. */
  5983. int64_t left_to_read = content_len - conn->consumed_content;
  5984. if (left_to_read < len64) {
  5985. /* Do not read more than the total content length of the
  5986. * request.
  5987. */
  5988. len64 = left_to_read;
  5989. }
  5990. /* Return buffered data */
  5991. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5992. - conn->consumed_content;
  5993. if (buffered_len > 0) {
  5994. if (len64 < buffered_len) {
  5995. buffered_len = len64;
  5996. }
  5997. body = conn->buf + conn->request_len + conn->consumed_content;
  5998. memcpy(buf, body, (size_t)buffered_len);
  5999. len64 -= buffered_len;
  6000. conn->consumed_content += buffered_len;
  6001. nread += buffered_len;
  6002. buf = (char *)buf + buffered_len;
  6003. }
  6004. /* We have returned all buffered data. Read new data from the remote
  6005. * socket.
  6006. */
  6007. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  6008. conn->consumed_content += n;
  6009. nread += n;
  6010. } else {
  6011. nread = ((nread > 0) ? nread : n);
  6012. }
  6013. }
  6014. return (int)nread;
  6015. }
  6016. /* Forward declarations */
  6017. static void handle_request(struct mg_connection *);
  6018. #if defined(USE_HTTP2)
  6019. #if defined(NO_SSL)
  6020. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  6021. #endif
  6022. #define USE_ALPN
  6023. #include "mod_http2.inl"
  6024. /* Not supported with HTTP/2 */
  6025. #define HTTP1_only \
  6026. { \
  6027. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  6028. http2_must_use_http1(conn); \
  6029. return; \
  6030. } \
  6031. }
  6032. #else
  6033. #define HTTP1_only
  6034. #endif
  6035. int
  6036. mg_read(struct mg_connection *conn, void *buf, size_t len)
  6037. {
  6038. if (len > INT_MAX) {
  6039. len = INT_MAX;
  6040. }
  6041. if (conn == NULL) {
  6042. return 0;
  6043. }
  6044. if (conn->is_chunked) {
  6045. size_t all_read = 0;
  6046. while (len > 0) {
  6047. if (conn->is_chunked >= 3) {
  6048. /* No more data left to read */
  6049. return 0;
  6050. }
  6051. if (conn->is_chunked != 1) {
  6052. /* Has error */
  6053. return -1;
  6054. }
  6055. if (conn->consumed_content != conn->content_len) {
  6056. /* copy from the current chunk */
  6057. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  6058. if (read_ret < 1) {
  6059. /* read error */
  6060. conn->is_chunked = 2;
  6061. return -1;
  6062. }
  6063. all_read += (size_t)read_ret;
  6064. len -= (size_t)read_ret;
  6065. if (conn->consumed_content == conn->content_len) {
  6066. /* Add data bytes in the current chunk have been read,
  6067. * so we are expecting \r\n now. */
  6068. char x[2];
  6069. conn->content_len += 2;
  6070. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  6071. || (x[1] != '\n')) {
  6072. /* Protocol violation */
  6073. conn->is_chunked = 2;
  6074. return -1;
  6075. }
  6076. }
  6077. } else {
  6078. /* fetch a new chunk */
  6079. size_t i;
  6080. char lenbuf[64];
  6081. char *end = NULL;
  6082. unsigned long chunkSize = 0;
  6083. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  6084. conn->content_len++;
  6085. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  6086. lenbuf[i] = 0;
  6087. }
  6088. if ((i > 0) && (lenbuf[i] == '\r')
  6089. && (lenbuf[i - 1] != '\r')) {
  6090. continue;
  6091. }
  6092. if ((i > 1) && (lenbuf[i] == '\n')
  6093. && (lenbuf[i - 1] == '\r')) {
  6094. lenbuf[i + 1] = 0;
  6095. chunkSize = strtoul(lenbuf, &end, 16);
  6096. if (chunkSize == 0) {
  6097. /* regular end of content */
  6098. conn->is_chunked = 3;
  6099. }
  6100. break;
  6101. }
  6102. if (!isxdigit((unsigned char)lenbuf[i])) {
  6103. /* illegal character for chunk length */
  6104. conn->is_chunked = 2;
  6105. return -1;
  6106. }
  6107. }
  6108. if ((end == NULL) || (*end != '\r')) {
  6109. /* chunksize not set correctly */
  6110. conn->is_chunked = 2;
  6111. return -1;
  6112. }
  6113. if (chunkSize == 0) {
  6114. /* try discarding trailer for keep-alive */
  6115. conn->content_len += 2;
  6116. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  6117. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  6118. conn->is_chunked = 4;
  6119. }
  6120. break;
  6121. }
  6122. /* append a new chunk */
  6123. conn->content_len += (int64_t)chunkSize;
  6124. }
  6125. }
  6126. return (int)all_read;
  6127. }
  6128. return mg_read_inner(conn, buf, len);
  6129. }
  6130. int
  6131. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  6132. {
  6133. time_t now;
  6134. int n, total, allowed;
  6135. if (conn == NULL) {
  6136. return 0;
  6137. }
  6138. if (len > INT_MAX) {
  6139. return -1;
  6140. }
  6141. /* Mark connection as "data sent" */
  6142. conn->request_state = 10;
  6143. #if defined(USE_HTTP2)
  6144. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  6145. http2_data_frame_head(conn, len, 0);
  6146. }
  6147. #endif
  6148. if (conn->throttle > 0) {
  6149. if ((now = time(NULL)) != conn->last_throttle_time) {
  6150. conn->last_throttle_time = now;
  6151. conn->last_throttle_bytes = 0;
  6152. }
  6153. allowed = conn->throttle - conn->last_throttle_bytes;
  6154. if (allowed > (int)len) {
  6155. allowed = (int)len;
  6156. }
  6157. total = push_all(conn->phys_ctx,
  6158. NULL,
  6159. conn->client.sock,
  6160. conn->ssl,
  6161. (const char *)buf,
  6162. allowed);
  6163. if (total == allowed) {
  6164. buf = (const char *)buf + total;
  6165. conn->last_throttle_bytes += total;
  6166. while ((total < (int)len)
  6167. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6168. allowed = (conn->throttle > ((int)len - total))
  6169. ? (int)len - total
  6170. : conn->throttle;
  6171. n = push_all(conn->phys_ctx,
  6172. NULL,
  6173. conn->client.sock,
  6174. conn->ssl,
  6175. (const char *)buf,
  6176. allowed);
  6177. if (n != allowed) {
  6178. break;
  6179. }
  6180. sleep(1);
  6181. conn->last_throttle_bytes = allowed;
  6182. conn->last_throttle_time = time(NULL);
  6183. buf = (const char *)buf + n;
  6184. total += n;
  6185. }
  6186. }
  6187. } else {
  6188. total = push_all(conn->phys_ctx,
  6189. NULL,
  6190. conn->client.sock,
  6191. conn->ssl,
  6192. (const char *)buf,
  6193. (int)len);
  6194. }
  6195. if (total > 0) {
  6196. conn->num_bytes_sent += total;
  6197. }
  6198. return total;
  6199. }
  6200. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6201. int
  6202. mg_send_chunk(struct mg_connection *conn,
  6203. const char *chunk,
  6204. unsigned int chunk_len)
  6205. {
  6206. char lenbuf[16];
  6207. size_t lenbuf_len;
  6208. int ret;
  6209. int t;
  6210. /* First store the length information in a text buffer. */
  6211. sprintf(lenbuf, "%x\r\n", chunk_len);
  6212. lenbuf_len = strlen(lenbuf);
  6213. /* Then send length information, chunk and terminating \r\n. */
  6214. ret = mg_write(conn, lenbuf, lenbuf_len);
  6215. if (ret != (int)lenbuf_len) {
  6216. return -1;
  6217. }
  6218. t = ret;
  6219. ret = mg_write(conn, chunk, chunk_len);
  6220. if (ret != (int)chunk_len) {
  6221. return -1;
  6222. }
  6223. t += ret;
  6224. ret = mg_write(conn, "\r\n", 2);
  6225. if (ret != 2) {
  6226. return -1;
  6227. }
  6228. t += ret;
  6229. return t;
  6230. }
  6231. #if defined(GCC_DIAGNOSTIC)
  6232. /* This block forwards format strings to printf implementations,
  6233. * so we need to disable the format-nonliteral warning. */
  6234. #pragma GCC diagnostic push
  6235. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6236. #endif
  6237. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6238. static int
  6239. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6240. {
  6241. va_list ap_copy;
  6242. size_t size = MG_BUF_LEN / 4;
  6243. int len = -1;
  6244. *buf = NULL;
  6245. while (len < 0) {
  6246. if (*buf) {
  6247. mg_free(*buf);
  6248. }
  6249. size *= 4;
  6250. *buf = (char *)mg_malloc(size);
  6251. if (!*buf) {
  6252. break;
  6253. }
  6254. va_copy(ap_copy, ap);
  6255. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6256. va_end(ap_copy);
  6257. (*buf)[size - 1] = 0;
  6258. }
  6259. return len;
  6260. }
  6261. /* Print message to buffer. If buffer is large enough to hold the message,
  6262. * return buffer. If buffer is to small, allocate large enough buffer on
  6263. * heap,
  6264. * and return allocated buffer. */
  6265. static int
  6266. alloc_vprintf(char **out_buf,
  6267. char *prealloc_buf,
  6268. size_t prealloc_size,
  6269. const char *fmt,
  6270. va_list ap)
  6271. {
  6272. va_list ap_copy;
  6273. int len;
  6274. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6275. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6276. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6277. * Therefore, we make two passes: on first pass, get required message
  6278. * length.
  6279. * On second pass, actually print the message. */
  6280. va_copy(ap_copy, ap);
  6281. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6282. va_end(ap_copy);
  6283. if (len < 0) {
  6284. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6285. * Switch to alternative code path that uses incremental
  6286. * allocations.
  6287. */
  6288. va_copy(ap_copy, ap);
  6289. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6290. va_end(ap_copy);
  6291. } else if ((size_t)(len) >= prealloc_size) {
  6292. /* The pre-allocated buffer not large enough. */
  6293. /* Allocate a new buffer. */
  6294. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6295. if (!*out_buf) {
  6296. /* Allocation failed. Return -1 as "out of memory" error. */
  6297. return -1;
  6298. }
  6299. /* Buffer allocation successful. Store the string there. */
  6300. va_copy(ap_copy, ap);
  6301. IGNORE_UNUSED_RESULT(
  6302. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6303. va_end(ap_copy);
  6304. } else {
  6305. /* The pre-allocated buffer is large enough.
  6306. * Use it to store the string and return the address. */
  6307. va_copy(ap_copy, ap);
  6308. IGNORE_UNUSED_RESULT(
  6309. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6310. va_end(ap_copy);
  6311. *out_buf = prealloc_buf;
  6312. }
  6313. return len;
  6314. }
  6315. #if defined(GCC_DIAGNOSTIC)
  6316. /* Enable format-nonliteral warning again. */
  6317. #pragma GCC diagnostic pop
  6318. #endif
  6319. static int
  6320. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6321. {
  6322. char mem[MG_BUF_LEN];
  6323. char *buf = NULL;
  6324. int len;
  6325. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6326. len = mg_write(conn, buf, (size_t)len);
  6327. }
  6328. if (buf != mem) {
  6329. mg_free(buf);
  6330. }
  6331. return len;
  6332. }
  6333. int
  6334. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6335. {
  6336. va_list ap;
  6337. int result;
  6338. va_start(ap, fmt);
  6339. result = mg_vprintf(conn, fmt, ap);
  6340. va_end(ap);
  6341. return result;
  6342. }
  6343. int
  6344. mg_url_decode(const char *src,
  6345. int src_len,
  6346. char *dst,
  6347. int dst_len,
  6348. int is_form_url_encoded)
  6349. {
  6350. int i, j, a, b;
  6351. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6352. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6353. if ((i < src_len - 2) && (src[i] == '%')
  6354. && isxdigit((unsigned char)src[i + 1])
  6355. && isxdigit((unsigned char)src[i + 2])) {
  6356. a = tolower((unsigned char)src[i + 1]);
  6357. b = tolower((unsigned char)src[i + 2]);
  6358. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6359. i += 2;
  6360. } else if (is_form_url_encoded && (src[i] == '+')) {
  6361. dst[j] = ' ';
  6362. } else {
  6363. dst[j] = src[i];
  6364. }
  6365. }
  6366. dst[j] = '\0'; /* Null-terminate the destination */
  6367. return (i >= src_len) ? j : -1;
  6368. }
  6369. /* form url decoding of an entire string */
  6370. static void
  6371. url_decode_in_place(char *buf)
  6372. {
  6373. int len = (int)strlen(buf);
  6374. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6375. }
  6376. int
  6377. mg_get_var(const char *data,
  6378. size_t data_len,
  6379. const char *name,
  6380. char *dst,
  6381. size_t dst_len)
  6382. {
  6383. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6384. }
  6385. int
  6386. mg_get_var2(const char *data,
  6387. size_t data_len,
  6388. const char *name,
  6389. char *dst,
  6390. size_t dst_len,
  6391. size_t occurrence)
  6392. {
  6393. const char *p, *e, *s;
  6394. size_t name_len;
  6395. int len;
  6396. if ((dst == NULL) || (dst_len == 0)) {
  6397. len = -2;
  6398. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6399. len = -1;
  6400. dst[0] = '\0';
  6401. } else {
  6402. name_len = strlen(name);
  6403. e = data + data_len;
  6404. len = -1;
  6405. dst[0] = '\0';
  6406. /* data is "var1=val1&var2=val2...". Find variable first */
  6407. for (p = data; p + name_len < e; p++) {
  6408. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6409. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6410. /* Point p to variable value */
  6411. p += name_len + 1;
  6412. /* Point s to the end of the value */
  6413. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6414. if (s == NULL) {
  6415. s = e;
  6416. }
  6417. DEBUG_ASSERT(s >= p);
  6418. if (s < p) {
  6419. return -3;
  6420. }
  6421. /* Decode variable into destination buffer */
  6422. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6423. /* Redirect error code from -1 to -2 (destination buffer too
  6424. * small). */
  6425. if (len == -1) {
  6426. len = -2;
  6427. }
  6428. break;
  6429. }
  6430. }
  6431. }
  6432. return len;
  6433. }
  6434. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6435. int
  6436. mg_split_form_urlencoded(char *data,
  6437. struct mg_header *form_fields,
  6438. unsigned num_form_fields)
  6439. {
  6440. char *b;
  6441. int i;
  6442. int num = 0;
  6443. if (data == NULL) {
  6444. /* parameter error */
  6445. return -1;
  6446. }
  6447. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6448. /* determine the number of expected fields */
  6449. if (data[0] == 0) {
  6450. return 0;
  6451. }
  6452. /* count number of & to return the number of key-value-pairs */
  6453. num = 1;
  6454. while (*data) {
  6455. if (*data == '&') {
  6456. num++;
  6457. }
  6458. data++;
  6459. }
  6460. return num;
  6461. }
  6462. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6463. /* parameter error */
  6464. return -1;
  6465. }
  6466. for (i = 0; i < (int)num_form_fields; i++) {
  6467. /* extract key-value pairs from input data */
  6468. while ((*data == ' ') || (*data == '\t')) {
  6469. /* skip initial spaces */
  6470. data++;
  6471. }
  6472. if (*data == 0) {
  6473. /* end of string reached */
  6474. break;
  6475. }
  6476. form_fields[num].name = data;
  6477. /* find & or = */
  6478. b = data;
  6479. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6480. b++;
  6481. }
  6482. if (*b == 0) {
  6483. /* last key without value */
  6484. form_fields[num].value = NULL;
  6485. } else if (*b == '&') {
  6486. /* mid key without value */
  6487. form_fields[num].value = NULL;
  6488. } else {
  6489. /* terminate string */
  6490. *b = 0;
  6491. /* value starts after '=' */
  6492. data = b + 1;
  6493. form_fields[num].value = data;
  6494. }
  6495. /* new field is stored */
  6496. num++;
  6497. /* find a next key */
  6498. b = strchr(data, '&');
  6499. if (b == 0) {
  6500. /* no more data */
  6501. break;
  6502. } else {
  6503. /* terminate value of last field at '&' */
  6504. *b = 0;
  6505. /* next key-value-pairs starts after '&' */
  6506. data = b + 1;
  6507. }
  6508. }
  6509. /* Decode all values */
  6510. for (i = 0; i < num; i++) {
  6511. if (form_fields[i].name) {
  6512. url_decode_in_place((char *)form_fields[i].name);
  6513. }
  6514. if (form_fields[i].value) {
  6515. url_decode_in_place((char *)form_fields[i].value);
  6516. }
  6517. }
  6518. /* return number of fields found */
  6519. return num;
  6520. }
  6521. /* HCP24: some changes to compare hole var_name */
  6522. int
  6523. mg_get_cookie(const char *cookie_header,
  6524. const char *var_name,
  6525. char *dst,
  6526. size_t dst_size)
  6527. {
  6528. const char *s, *p, *end;
  6529. int name_len, len = -1;
  6530. if ((dst == NULL) || (dst_size == 0)) {
  6531. return -2;
  6532. }
  6533. dst[0] = '\0';
  6534. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6535. return -1;
  6536. }
  6537. name_len = (int)strlen(var_name);
  6538. end = s + strlen(s);
  6539. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6540. if (s[name_len] == '=') {
  6541. /* HCP24: now check is it a substring or a full cookie name */
  6542. if ((s == cookie_header) || (s[-1] == ' ')) {
  6543. s += name_len + 1;
  6544. if ((p = strchr(s, ' ')) == NULL) {
  6545. p = end;
  6546. }
  6547. if (p[-1] == ';') {
  6548. p--;
  6549. }
  6550. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6551. s++;
  6552. p--;
  6553. }
  6554. if ((size_t)(p - s) < dst_size) {
  6555. len = (int)(p - s);
  6556. mg_strlcpy(dst, s, (size_t)len + 1);
  6557. } else {
  6558. len = -3;
  6559. }
  6560. break;
  6561. }
  6562. }
  6563. }
  6564. return len;
  6565. }
  6566. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6567. static void
  6568. base64_encode(const unsigned char *src, int src_len, char *dst)
  6569. {
  6570. static const char *b64 =
  6571. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6572. int i, j, a, b, c;
  6573. for (i = j = 0; i < src_len; i += 3) {
  6574. a = src[i];
  6575. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6576. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6577. dst[j++] = b64[a >> 2];
  6578. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6579. if (i + 1 < src_len) {
  6580. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6581. }
  6582. if (i + 2 < src_len) {
  6583. dst[j++] = b64[c & 63];
  6584. }
  6585. }
  6586. while (j % 4 != 0) {
  6587. dst[j++] = '=';
  6588. }
  6589. dst[j++] = '\0';
  6590. }
  6591. #endif
  6592. #if defined(USE_LUA)
  6593. static unsigned char
  6594. b64reverse(char letter)
  6595. {
  6596. if ((letter >= 'A') && (letter <= 'Z')) {
  6597. return letter - 'A';
  6598. }
  6599. if ((letter >= 'a') && (letter <= 'z')) {
  6600. return letter - 'a' + 26;
  6601. }
  6602. if ((letter >= '0') && (letter <= '9')) {
  6603. return letter - '0' + 52;
  6604. }
  6605. if (letter == '+') {
  6606. return 62;
  6607. }
  6608. if (letter == '/') {
  6609. return 63;
  6610. }
  6611. if (letter == '=') {
  6612. return 255; /* normal end */
  6613. }
  6614. return 254; /* error */
  6615. }
  6616. static int
  6617. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6618. {
  6619. int i;
  6620. unsigned char a, b, c, d;
  6621. *dst_len = 0;
  6622. for (i = 0; i < src_len; i += 4) {
  6623. a = b64reverse(src[i]);
  6624. if (a >= 254) {
  6625. return i;
  6626. }
  6627. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6628. if (b >= 254) {
  6629. return i + 1;
  6630. }
  6631. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6632. if (c == 254) {
  6633. return i + 2;
  6634. }
  6635. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6636. if (d == 254) {
  6637. return i + 3;
  6638. }
  6639. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6640. if (c != 255) {
  6641. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6642. if (d != 255) {
  6643. dst[(*dst_len)++] = (c << 6) + d;
  6644. }
  6645. }
  6646. }
  6647. return -1;
  6648. }
  6649. #endif
  6650. static int
  6651. is_put_or_delete_method(const struct mg_connection *conn)
  6652. {
  6653. if (conn) {
  6654. const char *s = conn->request_info.request_method;
  6655. return (s != NULL)
  6656. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6657. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6658. }
  6659. return 0;
  6660. }
  6661. #if !defined(NO_FILES)
  6662. static int
  6663. extention_matches_script(
  6664. struct mg_connection *conn, /* in: request (must be valid) */
  6665. const char *filename /* in: filename (must be valid) */
  6666. )
  6667. {
  6668. #if !defined(NO_CGI)
  6669. if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], filename)
  6670. > 0) {
  6671. return 1;
  6672. }
  6673. if (match_prefix_strlen(conn->dom_ctx->config[CGI2_EXTENSIONS], filename)
  6674. > 0) {
  6675. return 1;
  6676. }
  6677. #endif
  6678. #if defined(USE_LUA)
  6679. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6680. filename)
  6681. > 0) {
  6682. return 1;
  6683. }
  6684. #endif
  6685. #if defined(USE_DUKTAPE)
  6686. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6687. filename)
  6688. > 0) {
  6689. return 1;
  6690. }
  6691. #endif
  6692. /* filename and conn could be unused, if all preocessor conditions
  6693. * are false (no script language supported). */
  6694. (void)filename;
  6695. (void)conn;
  6696. return 0;
  6697. }
  6698. static int
  6699. extention_matches_template_text(
  6700. struct mg_connection *conn, /* in: request (must be valid) */
  6701. const char *filename /* in: filename (must be valid) */
  6702. )
  6703. {
  6704. #if defined(USE_LUA)
  6705. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6706. filename)
  6707. > 0) {
  6708. return 1;
  6709. }
  6710. #endif
  6711. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6712. > 0) {
  6713. return 1;
  6714. }
  6715. return 0;
  6716. }
  6717. /* For given directory path, substitute it to valid index file.
  6718. * Return 1 if index file has been found, 0 if not found.
  6719. * If the file is found, it's stats is returned in stp. */
  6720. static int
  6721. substitute_index_file(struct mg_connection *conn,
  6722. char *path,
  6723. size_t path_len,
  6724. struct mg_file_stat *filestat)
  6725. {
  6726. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6727. struct vec filename_vec;
  6728. size_t n = strlen(path);
  6729. int found = 0;
  6730. /* The 'path' given to us points to the directory. Remove all trailing
  6731. * directory separator characters from the end of the path, and
  6732. * then append single directory separator character. */
  6733. while ((n > 0) && (path[n - 1] == '/')) {
  6734. n--;
  6735. }
  6736. path[n] = '/';
  6737. /* Traverse index files list. For each entry, append it to the given
  6738. * path and see if the file exists. If it exists, break the loop */
  6739. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6740. /* Ignore too long entries that may overflow path buffer */
  6741. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6742. continue;
  6743. }
  6744. /* Prepare full path to the index file */
  6745. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6746. /* Does it exist? */
  6747. if (mg_stat(conn, path, filestat)) {
  6748. /* Yes it does, break the loop */
  6749. found = 1;
  6750. break;
  6751. }
  6752. }
  6753. /* If no index file exists, restore directory path */
  6754. if (!found) {
  6755. path[n] = '\0';
  6756. }
  6757. return found;
  6758. }
  6759. #endif
  6760. static void
  6761. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6762. char *filename, /* out: filename */
  6763. size_t filename_buf_len, /* in: size of filename buffer */
  6764. struct mg_file_stat *filestat, /* out: file status structure */
  6765. int *is_found, /* out: file found (directly) */
  6766. int *is_script_resource, /* out: handled by a script? */
  6767. int *is_websocket_request, /* out: websocket connetion? */
  6768. int *is_put_or_delete_request, /* out: put/delete a file? */
  6769. int *is_template_text /* out: SSI file or LSP file? */
  6770. )
  6771. {
  6772. char const *accept_encoding;
  6773. #if !defined(NO_FILES)
  6774. const char *uri = conn->request_info.local_uri;
  6775. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6776. const char *rewrite;
  6777. struct vec a, b;
  6778. ptrdiff_t match_len;
  6779. char gz_path[PATH_MAX];
  6780. int truncated;
  6781. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6782. char *tmp_str;
  6783. size_t tmp_str_len, sep_pos;
  6784. int allow_substitute_script_subresources;
  6785. #endif
  6786. #else
  6787. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6788. #endif
  6789. /* Step 1: Set all initially unknown outputs to zero */
  6790. memset(filestat, 0, sizeof(*filestat));
  6791. *filename = 0;
  6792. *is_found = 0;
  6793. *is_script_resource = 0;
  6794. *is_template_text = 0;
  6795. /* Step 2: Check if the request attempts to modify the file system */
  6796. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6797. /* Step 3: Check if it is a websocket request, and modify the document
  6798. * root if required */
  6799. #if defined(USE_WEBSOCKET)
  6800. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6801. #if !defined(NO_FILES)
  6802. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6803. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6804. }
  6805. #endif /* !NO_FILES */
  6806. #else /* USE_WEBSOCKET */
  6807. *is_websocket_request = 0;
  6808. #endif /* USE_WEBSOCKET */
  6809. /* Step 4: Check if gzip encoded response is allowed */
  6810. conn->accept_gzip = 0;
  6811. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6812. if (strstr(accept_encoding, "gzip") != NULL) {
  6813. conn->accept_gzip = 1;
  6814. }
  6815. }
  6816. #if !defined(NO_FILES)
  6817. /* Step 5: If there is no root directory, don't look for files. */
  6818. /* Note that root == NULL is a regular use case here. This occurs,
  6819. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6820. * config is not required. */
  6821. if (root == NULL) {
  6822. /* all file related outputs have already been set to 0, just return
  6823. */
  6824. return;
  6825. }
  6826. /* Step 6: Determine the local file path from the root path and the
  6827. * request uri. */
  6828. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6829. * part of the path one byte on the right. */
  6830. truncated = 0;
  6831. mg_snprintf(
  6832. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6833. if (truncated) {
  6834. goto interpret_cleanup;
  6835. }
  6836. /* Step 7: URI rewriting */
  6837. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6838. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6839. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6840. mg_snprintf(conn,
  6841. &truncated,
  6842. filename,
  6843. filename_buf_len - 1,
  6844. "%.*s%s",
  6845. (int)b.len,
  6846. b.ptr,
  6847. uri + match_len);
  6848. break;
  6849. }
  6850. }
  6851. if (truncated) {
  6852. goto interpret_cleanup;
  6853. }
  6854. /* Step 8: Check if the file exists at the server */
  6855. /* Local file path and name, corresponding to requested URI
  6856. * is now stored in "filename" variable. */
  6857. if (mg_stat(conn, filename, filestat)) {
  6858. int uri_len = (int)strlen(uri);
  6859. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6860. /* 8.1: File exists. */
  6861. *is_found = 1;
  6862. /* 8.2: Check if it is a script type. */
  6863. if (extention_matches_script(conn, filename)) {
  6864. /* The request addresses a CGI resource, Lua script or
  6865. * server-side javascript.
  6866. * The URI corresponds to the script itself (like
  6867. * /path/script.cgi), and there is no additional resource
  6868. * path (like /path/script.cgi/something).
  6869. * Requests that modify (replace or delete) a resource, like
  6870. * PUT and DELETE requests, should replace/delete the script
  6871. * file.
  6872. * Requests that read or write from/to a resource, like GET and
  6873. * POST requests, should call the script and return the
  6874. * generated response. */
  6875. *is_script_resource = (!*is_put_or_delete_request);
  6876. }
  6877. /* 8.3: Check for SSI and LSP files */
  6878. if (extention_matches_template_text(conn, filename)) {
  6879. /* Same as above, but for *.lsp and *.shtml files. */
  6880. /* A "template text" is a file delivered directly to the client,
  6881. * but with some text tags replaced by dynamic content.
  6882. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6883. * (LP, LSP) file. */
  6884. *is_template_text = (!*is_put_or_delete_request);
  6885. }
  6886. /* 8.4: If the request target is a directory, there could be
  6887. * a substitute file (index.html, index.cgi, ...). */
  6888. if (filestat->is_directory && is_uri_end_slash) {
  6889. /* Use a local copy here, since substitute_index_file will
  6890. * change the content of the file status */
  6891. struct mg_file_stat tmp_filestat;
  6892. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6893. if (substitute_index_file(
  6894. conn, filename, filename_buf_len, &tmp_filestat)) {
  6895. /* Substitute file found. Copy stat to the output, then
  6896. * check if the file is a script file */
  6897. *filestat = tmp_filestat;
  6898. if (extention_matches_script(conn, filename)) {
  6899. /* Substitute file is a script file */
  6900. *is_script_resource = 1;
  6901. } else if (extention_matches_template_text(conn, filename)) {
  6902. /* Substitute file is a LSP or SSI file */
  6903. *is_template_text = 1;
  6904. } else {
  6905. /* Substitute file is a regular file */
  6906. *is_script_resource = 0;
  6907. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6908. }
  6909. }
  6910. /* If there is no substitute file, the server could return
  6911. * a directory listing in a later step */
  6912. }
  6913. return;
  6914. }
  6915. /* Step 9: Check for zipped files: */
  6916. /* If we can't find the actual file, look for the file
  6917. * with the same name but a .gz extension. If we find it,
  6918. * use that and set the gzipped flag in the file struct
  6919. * to indicate that the response need to have the content-
  6920. * encoding: gzip header.
  6921. * We can only do this if the browser declares support. */
  6922. if (conn->accept_gzip) {
  6923. mg_snprintf(
  6924. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6925. if (truncated) {
  6926. goto interpret_cleanup;
  6927. }
  6928. if (mg_stat(conn, gz_path, filestat)) {
  6929. if (filestat) {
  6930. filestat->is_gzipped = 1;
  6931. *is_found = 1;
  6932. }
  6933. /* Currently gz files can not be scripts. */
  6934. return;
  6935. }
  6936. }
  6937. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6938. /* Step 10: Script resources may handle sub-resources */
  6939. /* Support PATH_INFO for CGI scripts. */
  6940. tmp_str_len = strlen(filename);
  6941. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6942. if (!tmp_str) {
  6943. /* Out of memory */
  6944. goto interpret_cleanup;
  6945. }
  6946. memcpy(tmp_str, filename, tmp_str_len + 1);
  6947. /* Check config, if index scripts may have sub-resources */
  6948. allow_substitute_script_subresources =
  6949. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6950. "yes");
  6951. sep_pos = tmp_str_len;
  6952. while (sep_pos > 0) {
  6953. sep_pos--;
  6954. if (tmp_str[sep_pos] == '/') {
  6955. int is_script = 0, does_exist = 0;
  6956. tmp_str[sep_pos] = 0;
  6957. if (tmp_str[0]) {
  6958. is_script = extention_matches_script(conn, tmp_str);
  6959. does_exist = mg_stat(conn, tmp_str, filestat);
  6960. }
  6961. if (does_exist && is_script) {
  6962. filename[sep_pos] = 0;
  6963. memmove(filename + sep_pos + 2,
  6964. filename + sep_pos + 1,
  6965. strlen(filename + sep_pos + 1) + 1);
  6966. conn->path_info = filename + sep_pos + 1;
  6967. filename[sep_pos + 1] = '/';
  6968. *is_script_resource = 1;
  6969. *is_found = 1;
  6970. break;
  6971. }
  6972. if (allow_substitute_script_subresources) {
  6973. if (substitute_index_file(
  6974. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6975. /* some intermediate directory has an index file */
  6976. if (extention_matches_script(conn, tmp_str)) {
  6977. size_t script_name_len = strlen(tmp_str);
  6978. /* subres_name read before this memory locatio will be
  6979. overwritten */
  6980. char *subres_name = filename + sep_pos;
  6981. size_t subres_name_len = strlen(subres_name);
  6982. DEBUG_TRACE("Substitute script %s serving path %s",
  6983. tmp_str,
  6984. filename);
  6985. /* this index file is a script */
  6986. if ((script_name_len + subres_name_len + 2)
  6987. >= filename_buf_len) {
  6988. mg_free(tmp_str);
  6989. goto interpret_cleanup;
  6990. }
  6991. conn->path_info =
  6992. filename + script_name_len + 1; /* new target */
  6993. memmove(conn->path_info, subres_name, subres_name_len);
  6994. conn->path_info[subres_name_len] = 0;
  6995. memcpy(filename, tmp_str, script_name_len + 1);
  6996. *is_script_resource = 1;
  6997. *is_found = 1;
  6998. break;
  6999. } else {
  7000. DEBUG_TRACE("Substitute file %s serving path %s",
  7001. tmp_str,
  7002. filename);
  7003. /* non-script files will not have sub-resources */
  7004. filename[sep_pos] = 0;
  7005. conn->path_info = 0;
  7006. *is_script_resource = 0;
  7007. *is_found = 0;
  7008. break;
  7009. }
  7010. }
  7011. }
  7012. tmp_str[sep_pos] = '/';
  7013. }
  7014. }
  7015. mg_free(tmp_str);
  7016. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  7017. #endif /* !defined(NO_FILES) */
  7018. return;
  7019. #if !defined(NO_FILES)
  7020. /* Reset all outputs */
  7021. interpret_cleanup:
  7022. memset(filestat, 0, sizeof(*filestat));
  7023. *filename = 0;
  7024. *is_found = 0;
  7025. *is_script_resource = 0;
  7026. *is_websocket_request = 0;
  7027. *is_put_or_delete_request = 0;
  7028. #endif /* !defined(NO_FILES) */
  7029. }
  7030. /* Check whether full request is buffered. Return:
  7031. * -1 if request or response is malformed
  7032. * 0 if request or response is not yet fully buffered
  7033. * >0 actual request length, including last \r\n\r\n */
  7034. static int
  7035. get_http_header_len(const char *buf, int buflen)
  7036. {
  7037. int i;
  7038. for (i = 0; i < buflen; i++) {
  7039. /* Do an unsigned comparison in some conditions below */
  7040. const unsigned char c = (unsigned char)buf[i];
  7041. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7042. && !isprint(c)) {
  7043. /* abort scan as soon as one malformed character is found */
  7044. return -1;
  7045. }
  7046. if (i < buflen - 1) {
  7047. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7048. /* Two newline, no carriage return - not standard compliant,
  7049. * but it should be accepted */
  7050. return i + 2;
  7051. }
  7052. }
  7053. if (i < buflen - 3) {
  7054. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7055. && (buf[i + 3] == '\n')) {
  7056. /* Two \r\n - standard compliant */
  7057. return i + 4;
  7058. }
  7059. }
  7060. }
  7061. return 0;
  7062. }
  7063. #if !defined(NO_CACHING)
  7064. /* Convert month to the month number. Return -1 on error, or month number */
  7065. static int
  7066. get_month_index(const char *s)
  7067. {
  7068. size_t i;
  7069. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7070. if (!strcmp(s, month_names[i])) {
  7071. return (int)i;
  7072. }
  7073. }
  7074. return -1;
  7075. }
  7076. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7077. static time_t
  7078. parse_date_string(const char *datetime)
  7079. {
  7080. char month_str[32] = {0};
  7081. int second, minute, hour, day, month, year;
  7082. time_t result = (time_t)0;
  7083. struct tm tm;
  7084. if ((sscanf(datetime,
  7085. "%d/%3s/%d %d:%d:%d",
  7086. &day,
  7087. month_str,
  7088. &year,
  7089. &hour,
  7090. &minute,
  7091. &second)
  7092. == 6)
  7093. || (sscanf(datetime,
  7094. "%d %3s %d %d:%d:%d",
  7095. &day,
  7096. month_str,
  7097. &year,
  7098. &hour,
  7099. &minute,
  7100. &second)
  7101. == 6)
  7102. || (sscanf(datetime,
  7103. "%*3s, %d %3s %d %d:%d:%d",
  7104. &day,
  7105. month_str,
  7106. &year,
  7107. &hour,
  7108. &minute,
  7109. &second)
  7110. == 6)
  7111. || (sscanf(datetime,
  7112. "%d-%3s-%d %d:%d:%d",
  7113. &day,
  7114. month_str,
  7115. &year,
  7116. &hour,
  7117. &minute,
  7118. &second)
  7119. == 6)) {
  7120. month = get_month_index(month_str);
  7121. if ((month >= 0) && (year >= 1970)) {
  7122. memset(&tm, 0, sizeof(tm));
  7123. tm.tm_year = year - 1900;
  7124. tm.tm_mon = month;
  7125. tm.tm_mday = day;
  7126. tm.tm_hour = hour;
  7127. tm.tm_min = minute;
  7128. tm.tm_sec = second;
  7129. result = timegm(&tm);
  7130. }
  7131. }
  7132. return result;
  7133. }
  7134. #endif /* !NO_CACHING */
  7135. /* Pre-process URIs according to RFC + protect against directory disclosure
  7136. * attacks by removing '..', excessive '/' and '\' characters */
  7137. static void
  7138. remove_dot_segments(char *inout)
  7139. {
  7140. /* Windows backend protection
  7141. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7142. * in URI by slash */
  7143. char *out_end = inout;
  7144. char *in = inout;
  7145. if (!in) {
  7146. /* Param error. */
  7147. return;
  7148. }
  7149. while (*in) {
  7150. if (*in == '\\') {
  7151. *in = '/';
  7152. }
  7153. in++;
  7154. }
  7155. /* Algorithm "remove_dot_segments" from
  7156. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7157. /* Step 1:
  7158. * The input buffer is initialized.
  7159. * The output buffer is initialized to the empty string.
  7160. */
  7161. in = inout;
  7162. /* Step 2:
  7163. * While the input buffer is not empty, loop as follows:
  7164. */
  7165. /* Less than out_end of the inout buffer is used as output, so keep
  7166. * condition: out_end <= in */
  7167. while (*in) {
  7168. /* Step 2a:
  7169. * If the input buffer begins with a prefix of "../" or "./",
  7170. * then remove that prefix from the input buffer;
  7171. */
  7172. if (!strncmp(in, "../", 3)) {
  7173. in += 3;
  7174. } else if (!strncmp(in, "./", 2)) {
  7175. in += 2;
  7176. }
  7177. /* otherwise */
  7178. /* Step 2b:
  7179. * if the input buffer begins with a prefix of "/./" or "/.",
  7180. * where "." is a complete path segment, then replace that
  7181. * prefix with "/" in the input buffer;
  7182. */
  7183. else if (!strncmp(in, "/./", 3)) {
  7184. in += 2;
  7185. } else if (!strcmp(in, "/.")) {
  7186. in[1] = 0;
  7187. }
  7188. /* otherwise */
  7189. /* Step 2c:
  7190. * if the input buffer begins with a prefix of "/../" or "/..",
  7191. * where ".." is a complete path segment, then replace that
  7192. * prefix with "/" in the input buffer and remove the last
  7193. * segment and its preceding "/" (if any) from the output
  7194. * buffer;
  7195. */
  7196. else if (!strncmp(in, "/../", 4)) {
  7197. in += 3;
  7198. if (inout != out_end) {
  7199. /* remove last segment */
  7200. do {
  7201. out_end--;
  7202. } while ((inout != out_end) && (*out_end != '/'));
  7203. }
  7204. } else if (!strcmp(in, "/..")) {
  7205. in[1] = 0;
  7206. if (inout != out_end) {
  7207. /* remove last segment */
  7208. do {
  7209. out_end--;
  7210. } while ((inout != out_end) && (*out_end != '/'));
  7211. }
  7212. }
  7213. /* otherwise */
  7214. /* Step 2d:
  7215. * if the input buffer consists only of "." or "..", then remove
  7216. * that from the input buffer;
  7217. */
  7218. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7219. *in = 0;
  7220. }
  7221. /* otherwise */
  7222. /* Step 2e:
  7223. * move the first path segment in the input buffer to the end of
  7224. * the output buffer, including the initial "/" character (if
  7225. * any) and any subsequent characters up to, but not including,
  7226. * the next "/" character or the end of the input buffer.
  7227. */
  7228. else {
  7229. do {
  7230. *out_end = *in;
  7231. out_end++;
  7232. in++;
  7233. } while ((*in != 0) && (*in != '/'));
  7234. }
  7235. }
  7236. /* Step 3:
  7237. * Finally, the output buffer is returned as the result of
  7238. * remove_dot_segments.
  7239. */
  7240. /* Terminate output */
  7241. *out_end = 0;
  7242. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7243. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7244. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7245. * or "//" anymore.
  7246. */
  7247. out_end = in = inout;
  7248. while (*in) {
  7249. if (*in == '.') {
  7250. /* remove . at the end or preceding of / */
  7251. char *in_ahead = in;
  7252. do {
  7253. in_ahead++;
  7254. } while (*in_ahead == '.');
  7255. if (*in_ahead == '/') {
  7256. in = in_ahead;
  7257. if ((out_end != inout) && (out_end[-1] == '/')) {
  7258. /* remove generated // */
  7259. out_end--;
  7260. }
  7261. } else if (*in_ahead == 0) {
  7262. in = in_ahead;
  7263. } else {
  7264. do {
  7265. *out_end++ = '.';
  7266. in++;
  7267. } while (in != in_ahead);
  7268. }
  7269. } else if (*in == '/') {
  7270. /* replace // by / */
  7271. *out_end++ = '/';
  7272. do {
  7273. in++;
  7274. } while (*in == '/');
  7275. } else {
  7276. *out_end++ = *in;
  7277. in++;
  7278. }
  7279. }
  7280. *out_end = 0;
  7281. }
  7282. static const struct {
  7283. const char *extension;
  7284. size_t ext_len;
  7285. const char *mime_type;
  7286. } builtin_mime_types[] = {
  7287. /* IANA registered MIME types
  7288. * (http://www.iana.org/assignments/media-types)
  7289. * application types */
  7290. {".doc", 4, "application/msword"},
  7291. {".eps", 4, "application/postscript"},
  7292. {".exe", 4, "application/octet-stream"},
  7293. {".js", 3, "application/javascript"},
  7294. {".json", 5, "application/json"},
  7295. {".pdf", 4, "application/pdf"},
  7296. {".ps", 3, "application/postscript"},
  7297. {".rtf", 4, "application/rtf"},
  7298. {".xhtml", 6, "application/xhtml+xml"},
  7299. {".xsl", 4, "application/xml"},
  7300. {".xslt", 5, "application/xml"},
  7301. /* fonts */
  7302. {".ttf", 4, "application/font-sfnt"},
  7303. {".cff", 4, "application/font-sfnt"},
  7304. {".otf", 4, "application/font-sfnt"},
  7305. {".aat", 4, "application/font-sfnt"},
  7306. {".sil", 4, "application/font-sfnt"},
  7307. {".pfr", 4, "application/font-tdpfr"},
  7308. {".woff", 5, "application/font-woff"},
  7309. /* audio */
  7310. {".mp3", 4, "audio/mpeg"},
  7311. {".oga", 4, "audio/ogg"},
  7312. {".ogg", 4, "audio/ogg"},
  7313. /* image */
  7314. {".gif", 4, "image/gif"},
  7315. {".ief", 4, "image/ief"},
  7316. {".jpeg", 5, "image/jpeg"},
  7317. {".jpg", 4, "image/jpeg"},
  7318. {".jpm", 4, "image/jpm"},
  7319. {".jpx", 4, "image/jpx"},
  7320. {".png", 4, "image/png"},
  7321. {".svg", 4, "image/svg+xml"},
  7322. {".tif", 4, "image/tiff"},
  7323. {".tiff", 5, "image/tiff"},
  7324. /* model */
  7325. {".wrl", 4, "model/vrml"},
  7326. /* text */
  7327. {".css", 4, "text/css"},
  7328. {".csv", 4, "text/csv"},
  7329. {".htm", 4, "text/html"},
  7330. {".html", 5, "text/html"},
  7331. {".sgm", 4, "text/sgml"},
  7332. {".shtm", 5, "text/html"},
  7333. {".shtml", 6, "text/html"},
  7334. {".txt", 4, "text/plain"},
  7335. {".xml", 4, "text/xml"},
  7336. /* video */
  7337. {".mov", 4, "video/quicktime"},
  7338. {".mp4", 4, "video/mp4"},
  7339. {".mpeg", 5, "video/mpeg"},
  7340. {".mpg", 4, "video/mpeg"},
  7341. {".ogv", 4, "video/ogg"},
  7342. {".qt", 3, "video/quicktime"},
  7343. /* not registered types
  7344. * (http://reference.sitepoint.com/html/mime-types-full,
  7345. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7346. {".arj", 4, "application/x-arj-compressed"},
  7347. {".gz", 3, "application/x-gunzip"},
  7348. {".rar", 4, "application/x-arj-compressed"},
  7349. {".swf", 4, "application/x-shockwave-flash"},
  7350. {".tar", 4, "application/x-tar"},
  7351. {".tgz", 4, "application/x-tar-gz"},
  7352. {".torrent", 8, "application/x-bittorrent"},
  7353. {".ppt", 4, "application/x-mspowerpoint"},
  7354. {".xls", 4, "application/x-msexcel"},
  7355. {".zip", 4, "application/x-zip-compressed"},
  7356. {".aac",
  7357. 4,
  7358. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7359. {".aif", 4, "audio/x-aif"},
  7360. {".m3u", 4, "audio/x-mpegurl"},
  7361. {".mid", 4, "audio/x-midi"},
  7362. {".ra", 3, "audio/x-pn-realaudio"},
  7363. {".ram", 4, "audio/x-pn-realaudio"},
  7364. {".wav", 4, "audio/x-wav"},
  7365. {".bmp", 4, "image/bmp"},
  7366. {".ico", 4, "image/x-icon"},
  7367. {".pct", 4, "image/x-pct"},
  7368. {".pict", 5, "image/pict"},
  7369. {".rgb", 4, "image/x-rgb"},
  7370. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7371. {".asf", 4, "video/x-ms-asf"},
  7372. {".avi", 4, "video/x-msvideo"},
  7373. {".m4v", 4, "video/x-m4v"},
  7374. {NULL, 0, NULL}};
  7375. const char *
  7376. mg_get_builtin_mime_type(const char *path)
  7377. {
  7378. const char *ext;
  7379. size_t i, path_len;
  7380. path_len = strlen(path);
  7381. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7382. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7383. if ((path_len > builtin_mime_types[i].ext_len)
  7384. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7385. return builtin_mime_types[i].mime_type;
  7386. }
  7387. }
  7388. return "text/plain";
  7389. }
  7390. /* Look at the "path" extension and figure what mime type it has.
  7391. * Store mime type in the vector. */
  7392. static void
  7393. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7394. {
  7395. struct vec ext_vec, mime_vec;
  7396. const char *list, *ext;
  7397. size_t path_len;
  7398. path_len = strlen(path);
  7399. if ((conn == NULL) || (vec == NULL)) {
  7400. if (vec != NULL) {
  7401. memset(vec, '\0', sizeof(struct vec));
  7402. }
  7403. return;
  7404. }
  7405. /* Scan user-defined mime types first, in case user wants to
  7406. * override default mime types. */
  7407. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7408. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7409. /* ext now points to the path suffix */
  7410. ext = path + path_len - ext_vec.len;
  7411. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7412. *vec = mime_vec;
  7413. return;
  7414. }
  7415. }
  7416. vec->ptr = mg_get_builtin_mime_type(path);
  7417. vec->len = strlen(vec->ptr);
  7418. }
  7419. /* Stringify binary data. Output buffer must be twice as big as input,
  7420. * because each byte takes 2 bytes in string representation */
  7421. static void
  7422. bin2str(char *to, const unsigned char *p, size_t len)
  7423. {
  7424. static const char *hex = "0123456789abcdef";
  7425. for (; len--; p++) {
  7426. *to++ = hex[p[0] >> 4];
  7427. *to++ = hex[p[0] & 0x0f];
  7428. }
  7429. *to = '\0';
  7430. }
  7431. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7432. */
  7433. char *
  7434. mg_md5(char buf[33], ...)
  7435. {
  7436. md5_byte_t hash[16];
  7437. const char *p;
  7438. va_list ap;
  7439. md5_state_t ctx;
  7440. md5_init(&ctx);
  7441. va_start(ap, buf);
  7442. while ((p = va_arg(ap, const char *)) != NULL) {
  7443. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7444. }
  7445. va_end(ap);
  7446. md5_finish(&ctx, hash);
  7447. bin2str(buf, hash, sizeof(hash));
  7448. return buf;
  7449. }
  7450. /* Check the user's password, return 1 if OK */
  7451. static int
  7452. check_password(const char *method,
  7453. const char *ha1,
  7454. const char *uri,
  7455. const char *nonce,
  7456. const char *nc,
  7457. const char *cnonce,
  7458. const char *qop,
  7459. const char *response)
  7460. {
  7461. char ha2[32 + 1], expected_response[32 + 1];
  7462. /* Some of the parameters may be NULL */
  7463. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7464. || (qop == NULL) || (response == NULL)) {
  7465. return 0;
  7466. }
  7467. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7468. if (strlen(response) != 32) {
  7469. return 0;
  7470. }
  7471. mg_md5(ha2, method, ":", uri, NULL);
  7472. mg_md5(expected_response,
  7473. ha1,
  7474. ":",
  7475. nonce,
  7476. ":",
  7477. nc,
  7478. ":",
  7479. cnonce,
  7480. ":",
  7481. qop,
  7482. ":",
  7483. ha2,
  7484. NULL);
  7485. return mg_strcasecmp(response, expected_response) == 0;
  7486. }
  7487. #if !defined(NO_FILESYSTEMS)
  7488. /* Use the global passwords file, if specified by auth_gpass option,
  7489. * or search for .htpasswd in the requested directory. */
  7490. static void
  7491. open_auth_file(struct mg_connection *conn,
  7492. const char *path,
  7493. struct mg_file *filep)
  7494. {
  7495. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7496. char name[PATH_MAX];
  7497. const char *p, *e,
  7498. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7499. int truncated;
  7500. if (gpass != NULL) {
  7501. /* Use global passwords file */
  7502. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7503. #if defined(DEBUG)
  7504. /* Use mg_cry_internal here, since gpass has been
  7505. * configured. */
  7506. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7507. #endif
  7508. }
  7509. /* Important: using local struct mg_file to test path for
  7510. * is_directory flag. If filep is used, mg_stat() makes it
  7511. * appear as if auth file was opened.
  7512. * TODO(mid): Check if this is still required after rewriting
  7513. * mg_stat */
  7514. } else if (mg_stat(conn, path, &filep->stat)
  7515. && filep->stat.is_directory) {
  7516. mg_snprintf(conn,
  7517. &truncated,
  7518. name,
  7519. sizeof(name),
  7520. "%s/%s",
  7521. path,
  7522. PASSWORDS_FILE_NAME);
  7523. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7524. #if defined(DEBUG)
  7525. /* Don't use mg_cry_internal here, but only a trace, since
  7526. * this is a typical case. It will occur for every directory
  7527. * without a password file. */
  7528. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7529. #endif
  7530. }
  7531. } else {
  7532. /* Try to find .htpasswd in requested directory. */
  7533. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7534. if (e[0] == '/') {
  7535. break;
  7536. }
  7537. }
  7538. mg_snprintf(conn,
  7539. &truncated,
  7540. name,
  7541. sizeof(name),
  7542. "%.*s/%s",
  7543. (int)(e - p),
  7544. p,
  7545. PASSWORDS_FILE_NAME);
  7546. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7547. #if defined(DEBUG)
  7548. /* Don't use mg_cry_internal here, but only a trace, since
  7549. * this is a typical case. It will occur for every directory
  7550. * without a password file. */
  7551. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7552. #endif
  7553. }
  7554. }
  7555. }
  7556. }
  7557. #endif /* NO_FILESYSTEMS */
  7558. /* Parsed Authorization header */
  7559. struct ah {
  7560. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7561. };
  7562. /* Return 1 on success. Always initializes the ah structure. */
  7563. static int
  7564. parse_auth_header(struct mg_connection *conn,
  7565. char *buf,
  7566. size_t buf_size,
  7567. struct ah *ah)
  7568. {
  7569. char *name, *value, *s;
  7570. const char *auth_header;
  7571. uint64_t nonce;
  7572. if (!ah || !conn) {
  7573. return 0;
  7574. }
  7575. (void)memset(ah, 0, sizeof(*ah));
  7576. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7577. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7578. return 0;
  7579. }
  7580. /* Make modifiable copy of the auth header */
  7581. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7582. s = buf;
  7583. /* Parse authorization header */
  7584. for (;;) {
  7585. /* Gobble initial spaces */
  7586. while (isspace((unsigned char)*s)) {
  7587. s++;
  7588. }
  7589. name = skip_quoted(&s, "=", " ", 0);
  7590. /* Value is either quote-delimited, or ends at first comma or space.
  7591. */
  7592. if (s[0] == '\"') {
  7593. s++;
  7594. value = skip_quoted(&s, "\"", " ", '\\');
  7595. if (s[0] == ',') {
  7596. s++;
  7597. }
  7598. } else {
  7599. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7600. * uses spaces */
  7601. }
  7602. if (*name == '\0') {
  7603. break;
  7604. }
  7605. if (!strcmp(name, "username")) {
  7606. ah->user = value;
  7607. } else if (!strcmp(name, "cnonce")) {
  7608. ah->cnonce = value;
  7609. } else if (!strcmp(name, "response")) {
  7610. ah->response = value;
  7611. } else if (!strcmp(name, "uri")) {
  7612. ah->uri = value;
  7613. } else if (!strcmp(name, "qop")) {
  7614. ah->qop = value;
  7615. } else if (!strcmp(name, "nc")) {
  7616. ah->nc = value;
  7617. } else if (!strcmp(name, "nonce")) {
  7618. ah->nonce = value;
  7619. }
  7620. }
  7621. #if !defined(NO_NONCE_CHECK)
  7622. /* Read the nonce from the response. */
  7623. if (ah->nonce == NULL) {
  7624. return 0;
  7625. }
  7626. s = NULL;
  7627. nonce = strtoull(ah->nonce, &s, 10);
  7628. if ((s == NULL) || (*s != 0)) {
  7629. return 0;
  7630. }
  7631. /* Convert the nonce from the client to a number. */
  7632. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7633. /* The converted number corresponds to the time the nounce has been
  7634. * created. This should not be earlier than the server start. */
  7635. /* Server side nonce check is valuable in all situations but one:
  7636. * if the server restarts frequently, but the client should not see
  7637. * that, so the server should accept nonces from previous starts. */
  7638. /* However, the reasonable default is to not accept a nonce from a
  7639. * previous start, so if anyone changed the access rights between
  7640. * two restarts, a new login is required. */
  7641. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7642. /* nonce is from a previous start of the server and no longer valid
  7643. * (replay attack?) */
  7644. return 0;
  7645. }
  7646. /* Check if the nonce is too high, so it has not (yet) been used by the
  7647. * server. */
  7648. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7649. + conn->dom_ctx->nonce_count)) {
  7650. return 0;
  7651. }
  7652. #else
  7653. (void)nonce;
  7654. #endif
  7655. /* CGI needs it as REMOTE_USER */
  7656. if (ah->user != NULL) {
  7657. conn->request_info.remote_user =
  7658. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7659. } else {
  7660. return 0;
  7661. }
  7662. return 1;
  7663. }
  7664. static const char *
  7665. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7666. {
  7667. if (!filep) {
  7668. return NULL;
  7669. }
  7670. if (filep->access.fp != NULL) {
  7671. return fgets(buf, (int)size, filep->access.fp);
  7672. } else {
  7673. return NULL;
  7674. }
  7675. }
  7676. /* Define the initial recursion depth for procesesing htpasswd files that
  7677. * include other htpasswd
  7678. * (or even the same) files. It is not difficult to provide a file or files
  7679. * s.t. they force civetweb
  7680. * to infinitely recurse and then crash.
  7681. */
  7682. #define INITIAL_DEPTH 9
  7683. #if INITIAL_DEPTH <= 0
  7684. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7685. #endif
  7686. #if !defined(NO_FILESYSTEMS)
  7687. struct read_auth_file_struct {
  7688. struct mg_connection *conn;
  7689. struct ah ah;
  7690. const char *domain;
  7691. char buf[256 + 256 + 40];
  7692. const char *f_user;
  7693. const char *f_domain;
  7694. const char *f_ha1;
  7695. };
  7696. static int
  7697. read_auth_file(struct mg_file *filep,
  7698. struct read_auth_file_struct *workdata,
  7699. int depth)
  7700. {
  7701. int is_authorized = 0;
  7702. struct mg_file fp;
  7703. size_t l;
  7704. if (!filep || !workdata || (0 == depth)) {
  7705. return 0;
  7706. }
  7707. /* Loop over passwords file */
  7708. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7709. l = strlen(workdata->buf);
  7710. while (l > 0) {
  7711. if (isspace((unsigned char)workdata->buf[l - 1])
  7712. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7713. l--;
  7714. workdata->buf[l] = 0;
  7715. } else
  7716. break;
  7717. }
  7718. if (l < 1) {
  7719. continue;
  7720. }
  7721. workdata->f_user = workdata->buf;
  7722. if (workdata->f_user[0] == ':') {
  7723. /* user names may not contain a ':' and may not be empty,
  7724. * so lines starting with ':' may be used for a special purpose
  7725. */
  7726. if (workdata->f_user[1] == '#') {
  7727. /* :# is a comment */
  7728. continue;
  7729. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7730. if (mg_fopen(workdata->conn,
  7731. workdata->f_user + 9,
  7732. MG_FOPEN_MODE_READ,
  7733. &fp)) {
  7734. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7735. (void)mg_fclose(
  7736. &fp.access); /* ignore error on read only file */
  7737. /* No need to continue processing files once we have a
  7738. * match, since nothing will reset it back
  7739. * to 0.
  7740. */
  7741. if (is_authorized) {
  7742. return is_authorized;
  7743. }
  7744. } else {
  7745. mg_cry_internal(workdata->conn,
  7746. "%s: cannot open authorization file: %s",
  7747. __func__,
  7748. workdata->buf);
  7749. }
  7750. continue;
  7751. }
  7752. /* everything is invalid for the moment (might change in the
  7753. * future) */
  7754. mg_cry_internal(workdata->conn,
  7755. "%s: syntax error in authorization file: %s",
  7756. __func__,
  7757. workdata->buf);
  7758. continue;
  7759. }
  7760. workdata->f_domain = strchr(workdata->f_user, ':');
  7761. if (workdata->f_domain == NULL) {
  7762. mg_cry_internal(workdata->conn,
  7763. "%s: syntax error in authorization file: %s",
  7764. __func__,
  7765. workdata->buf);
  7766. continue;
  7767. }
  7768. *(char *)(workdata->f_domain) = 0;
  7769. (workdata->f_domain)++;
  7770. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7771. if (workdata->f_ha1 == NULL) {
  7772. mg_cry_internal(workdata->conn,
  7773. "%s: syntax error in authorization file: %s",
  7774. __func__,
  7775. workdata->buf);
  7776. continue;
  7777. }
  7778. *(char *)(workdata->f_ha1) = 0;
  7779. (workdata->f_ha1)++;
  7780. if (!strcmp(workdata->ah.user, workdata->f_user)
  7781. && !strcmp(workdata->domain, workdata->f_domain)) {
  7782. return check_password(workdata->conn->request_info.request_method,
  7783. workdata->f_ha1,
  7784. workdata->ah.uri,
  7785. workdata->ah.nonce,
  7786. workdata->ah.nc,
  7787. workdata->ah.cnonce,
  7788. workdata->ah.qop,
  7789. workdata->ah.response);
  7790. }
  7791. }
  7792. return is_authorized;
  7793. }
  7794. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7795. static int
  7796. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7797. {
  7798. struct read_auth_file_struct workdata;
  7799. char buf[MG_BUF_LEN];
  7800. if (!conn || !conn->dom_ctx) {
  7801. return 0;
  7802. }
  7803. memset(&workdata, 0, sizeof(workdata));
  7804. workdata.conn = conn;
  7805. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7806. return 0;
  7807. }
  7808. if (realm) {
  7809. workdata.domain = realm;
  7810. } else {
  7811. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7812. }
  7813. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7814. }
  7815. /* Public function to check http digest authentication header */
  7816. int
  7817. mg_check_digest_access_authentication(struct mg_connection *conn,
  7818. const char *realm,
  7819. const char *filename)
  7820. {
  7821. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7822. int auth;
  7823. if (!conn || !filename) {
  7824. return -1;
  7825. }
  7826. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7827. return -2;
  7828. }
  7829. auth = authorize(conn, &file, realm);
  7830. mg_fclose(&file.access);
  7831. return auth;
  7832. }
  7833. #endif /* NO_FILESYSTEMS */
  7834. /* Return 1 if request is authorised, 0 otherwise. */
  7835. static int
  7836. check_authorization(struct mg_connection *conn, const char *path)
  7837. {
  7838. #if !defined(NO_FILESYSTEMS)
  7839. char fname[PATH_MAX];
  7840. struct vec uri_vec, filename_vec;
  7841. const char *list;
  7842. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7843. int authorized = 1, truncated;
  7844. if (!conn || !conn->dom_ctx) {
  7845. return 0;
  7846. }
  7847. list = conn->dom_ctx->config[PROTECT_URI];
  7848. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7849. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7850. mg_snprintf(conn,
  7851. &truncated,
  7852. fname,
  7853. sizeof(fname),
  7854. "%.*s",
  7855. (int)filename_vec.len,
  7856. filename_vec.ptr);
  7857. if (truncated
  7858. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7859. mg_cry_internal(conn,
  7860. "%s: cannot open %s: %s",
  7861. __func__,
  7862. fname,
  7863. strerror(errno));
  7864. }
  7865. break;
  7866. }
  7867. }
  7868. if (!is_file_opened(&file.access)) {
  7869. open_auth_file(conn, path, &file);
  7870. }
  7871. if (is_file_opened(&file.access)) {
  7872. authorized = authorize(conn, &file, NULL);
  7873. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7874. }
  7875. return authorized;
  7876. #else
  7877. (void)conn;
  7878. (void)path;
  7879. return 1;
  7880. #endif /* NO_FILESYSTEMS */
  7881. }
  7882. /* Internal function. Assumes conn is valid */
  7883. static void
  7884. send_authorization_request(struct mg_connection *conn, const char *realm)
  7885. {
  7886. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7887. int trunc = 0;
  7888. char buf[128];
  7889. if (!realm) {
  7890. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7891. }
  7892. mg_lock_context(conn->phys_ctx);
  7893. nonce += conn->dom_ctx->nonce_count;
  7894. ++conn->dom_ctx->nonce_count;
  7895. mg_unlock_context(conn->phys_ctx);
  7896. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7897. conn->must_close = 1;
  7898. /* Create 401 response */
  7899. mg_response_header_start(conn, 401);
  7900. send_no_cache_header(conn);
  7901. send_additional_header(conn);
  7902. mg_response_header_add(conn, "Content-Length", "0", -1);
  7903. /* Content for "WWW-Authenticate" header */
  7904. mg_snprintf(conn,
  7905. &trunc,
  7906. buf,
  7907. sizeof(buf),
  7908. "Digest qop=\"auth\", realm=\"%s\", "
  7909. "nonce=\"%" UINT64_FMT "\"",
  7910. realm,
  7911. nonce);
  7912. if (!trunc) {
  7913. /* !trunc should always be true */
  7914. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7915. }
  7916. /* Send all headers */
  7917. mg_response_header_send(conn);
  7918. }
  7919. /* Interface function. Parameters are provided by the user, so do
  7920. * at least some basic checks.
  7921. */
  7922. int
  7923. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7924. const char *realm)
  7925. {
  7926. if (conn && conn->dom_ctx) {
  7927. send_authorization_request(conn, realm);
  7928. return 0;
  7929. }
  7930. return -1;
  7931. }
  7932. #if !defined(NO_FILES)
  7933. static int
  7934. is_authorized_for_put(struct mg_connection *conn)
  7935. {
  7936. if (conn) {
  7937. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7938. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7939. int ret = 0;
  7940. if (passfile != NULL
  7941. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7942. ret = authorize(conn, &file, NULL);
  7943. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7944. }
  7945. return ret;
  7946. }
  7947. return 0;
  7948. }
  7949. #endif
  7950. int
  7951. mg_modify_passwords_file(const char *fname,
  7952. const char *domain,
  7953. const char *user,
  7954. const char *pass)
  7955. {
  7956. int found, i;
  7957. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7958. FILE *fp, *fp2;
  7959. found = 0;
  7960. fp = fp2 = NULL;
  7961. /* Regard empty password as no password - remove user record. */
  7962. if ((pass != NULL) && (pass[0] == '\0')) {
  7963. pass = NULL;
  7964. }
  7965. /* Other arguments must not be empty */
  7966. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7967. return 0;
  7968. }
  7969. /* Using the given file format, user name and domain must not contain
  7970. * ':'
  7971. */
  7972. if (strchr(user, ':') != NULL) {
  7973. return 0;
  7974. }
  7975. if (strchr(domain, ':') != NULL) {
  7976. return 0;
  7977. }
  7978. /* Do not allow control characters like newline in user name and domain.
  7979. * Do not allow excessively long names either. */
  7980. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7981. if (iscntrl((unsigned char)user[i])) {
  7982. return 0;
  7983. }
  7984. }
  7985. if (user[i]) {
  7986. return 0;
  7987. }
  7988. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7989. if (iscntrl((unsigned char)domain[i])) {
  7990. return 0;
  7991. }
  7992. }
  7993. if (domain[i]) {
  7994. return 0;
  7995. }
  7996. /* The maximum length of the path to the password file is limited */
  7997. if ((strlen(fname) + 4) >= PATH_MAX) {
  7998. return 0;
  7999. }
  8000. /* Create a temporary file name. Length has been checked before. */
  8001. strcpy(tmp, fname);
  8002. strcat(tmp, ".tmp");
  8003. /* Create the file if does not exist */
  8004. /* Use of fopen here is OK, since fname is only ASCII */
  8005. if ((fp = fopen(fname, "a+")) != NULL) {
  8006. (void)fclose(fp);
  8007. }
  8008. /* Open the given file and temporary file */
  8009. if ((fp = fopen(fname, "r")) == NULL) {
  8010. return 0;
  8011. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  8012. fclose(fp);
  8013. return 0;
  8014. }
  8015. /* Copy the stuff to temporary file */
  8016. while (fgets(line, sizeof(line), fp) != NULL) {
  8017. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  8018. continue;
  8019. }
  8020. u[255] = 0;
  8021. d[255] = 0;
  8022. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8023. found++;
  8024. if (pass != NULL) {
  8025. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  8026. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  8027. }
  8028. } else {
  8029. fprintf(fp2, "%s", line);
  8030. }
  8031. }
  8032. /* If new user, just add it */
  8033. if (!found && (pass != NULL)) {
  8034. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  8035. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  8036. }
  8037. /* Close files */
  8038. fclose(fp);
  8039. fclose(fp2);
  8040. /* Put the temp file in place of real file */
  8041. IGNORE_UNUSED_RESULT(remove(fname));
  8042. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  8043. return 1;
  8044. }
  8045. static int
  8046. is_valid_port(unsigned long port)
  8047. {
  8048. return (port <= 0xffff);
  8049. }
  8050. static int
  8051. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8052. {
  8053. struct addrinfo hints, *res, *ressave;
  8054. int func_ret = 0;
  8055. int gai_ret;
  8056. memset(&hints, 0, sizeof(struct addrinfo));
  8057. hints.ai_family = af;
  8058. if (!resolve_src) {
  8059. hints.ai_flags = AI_NUMERICHOST;
  8060. }
  8061. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8062. if (gai_ret != 0) {
  8063. /* gai_strerror could be used to convert gai_ret to a string */
  8064. /* POSIX return values: see
  8065. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8066. */
  8067. /* Windows return values: see
  8068. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8069. */
  8070. return 0;
  8071. }
  8072. ressave = res;
  8073. while (res) {
  8074. if ((dstlen >= (size_t)res->ai_addrlen)
  8075. && (res->ai_addr->sa_family == af)) {
  8076. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8077. func_ret = 1;
  8078. }
  8079. res = res->ai_next;
  8080. }
  8081. freeaddrinfo(ressave);
  8082. return func_ret;
  8083. }
  8084. static int
  8085. connect_socket(struct mg_context *ctx /* may be NULL */,
  8086. const char *host,
  8087. int port,
  8088. int use_ssl,
  8089. char *ebuf,
  8090. size_t ebuf_len,
  8091. SOCKET *sock /* output: socket, must not be NULL */,
  8092. union usa *sa /* output: socket address, must not be NULL */
  8093. )
  8094. {
  8095. int ip_ver = 0;
  8096. int conn_ret = -1;
  8097. int sockerr = 0;
  8098. *sock = INVALID_SOCKET;
  8099. memset(sa, 0, sizeof(*sa));
  8100. if (ebuf_len > 0) {
  8101. *ebuf = 0;
  8102. }
  8103. if (host == NULL) {
  8104. mg_snprintf(NULL,
  8105. NULL, /* No truncation check for ebuf */
  8106. ebuf,
  8107. ebuf_len,
  8108. "%s",
  8109. "NULL host");
  8110. return 0;
  8111. }
  8112. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8113. mg_snprintf(NULL,
  8114. NULL, /* No truncation check for ebuf */
  8115. ebuf,
  8116. ebuf_len,
  8117. "%s",
  8118. "invalid port");
  8119. return 0;
  8120. }
  8121. #if !defined(NO_SSL)
  8122. #if !defined(NO_SSL_DL)
  8123. #if defined(OPENSSL_API_1_1)
  8124. if (use_ssl && (TLS_client_method == NULL)) {
  8125. mg_snprintf(NULL,
  8126. NULL, /* No truncation check for ebuf */
  8127. ebuf,
  8128. ebuf_len,
  8129. "%s",
  8130. "SSL is not initialized");
  8131. return 0;
  8132. }
  8133. #else
  8134. if (use_ssl && (SSLv23_client_method == NULL)) {
  8135. mg_snprintf(NULL,
  8136. NULL, /* No truncation check for ebuf */
  8137. ebuf,
  8138. ebuf_len,
  8139. "%s",
  8140. "SSL is not initialized");
  8141. return 0;
  8142. }
  8143. #endif /* OPENSSL_API_1_1 */
  8144. #else
  8145. (void)use_ssl;
  8146. #endif /* NO_SSL_DL */
  8147. #else
  8148. (void)use_ssl;
  8149. #endif /* !defined(NO_SSL) */
  8150. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8151. sa->sin.sin_port = htons((uint16_t)port);
  8152. ip_ver = 4;
  8153. #if defined(USE_IPV6)
  8154. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8155. sa->sin6.sin6_port = htons((uint16_t)port);
  8156. ip_ver = 6;
  8157. } else if (host[0] == '[') {
  8158. /* While getaddrinfo on Windows will work with [::1],
  8159. * getaddrinfo on Linux only works with ::1 (without []). */
  8160. size_t l = strlen(host + 1);
  8161. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8162. if (h) {
  8163. h[l - 1] = 0;
  8164. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8165. sa->sin6.sin6_port = htons((uint16_t)port);
  8166. ip_ver = 6;
  8167. }
  8168. mg_free(h);
  8169. }
  8170. #endif
  8171. }
  8172. if (ip_ver == 0) {
  8173. mg_snprintf(NULL,
  8174. NULL, /* No truncation check for ebuf */
  8175. ebuf,
  8176. ebuf_len,
  8177. "%s",
  8178. "host not found");
  8179. return 0;
  8180. }
  8181. if (ip_ver == 4) {
  8182. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8183. }
  8184. #if defined(USE_IPV6)
  8185. else if (ip_ver == 6) {
  8186. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8187. }
  8188. #endif
  8189. #if 0 /* Not available as client */
  8190. #if defined(USE_X_DOM_SOCKET)
  8191. else if (ip_ver == 99) {
  8192. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8193. }
  8194. #endif
  8195. #endif
  8196. if (*sock == INVALID_SOCKET) {
  8197. mg_snprintf(NULL,
  8198. NULL, /* No truncation check for ebuf */
  8199. ebuf,
  8200. ebuf_len,
  8201. "socket(): %s",
  8202. strerror(ERRNO));
  8203. return 0;
  8204. }
  8205. if (0 != set_non_blocking_mode(*sock)) {
  8206. mg_snprintf(NULL,
  8207. NULL, /* No truncation check for ebuf */
  8208. ebuf,
  8209. ebuf_len,
  8210. "Cannot set socket to non-blocking: %s",
  8211. strerror(ERRNO));
  8212. closesocket(*sock);
  8213. *sock = INVALID_SOCKET;
  8214. return 0;
  8215. }
  8216. set_close_on_exec(*sock, NULL, ctx);
  8217. if (ip_ver == 4) {
  8218. /* connected with IPv4 */
  8219. conn_ret = connect(*sock,
  8220. (struct sockaddr *)((void *)&sa->sin),
  8221. sizeof(sa->sin));
  8222. }
  8223. #if defined(USE_IPV6)
  8224. else if (ip_ver == 6) {
  8225. /* connected with IPv6 */
  8226. conn_ret = connect(*sock,
  8227. (struct sockaddr *)((void *)&sa->sin6),
  8228. sizeof(sa->sin6));
  8229. }
  8230. #endif
  8231. if (conn_ret != 0) {
  8232. sockerr = ERRNO;
  8233. }
  8234. #if defined(_WIN32)
  8235. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8236. #else
  8237. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8238. #endif
  8239. /* Data for getsockopt */
  8240. void *psockerr = &sockerr;
  8241. int ret;
  8242. #if defined(_WIN32)
  8243. int len = (int)sizeof(sockerr);
  8244. #else
  8245. socklen_t len = (socklen_t)sizeof(sockerr);
  8246. #endif
  8247. /* Data for poll */
  8248. struct mg_pollfd pfd[1];
  8249. int pollres;
  8250. int ms_wait = 10000; /* 10 second timeout */
  8251. stop_flag_t nonstop;
  8252. STOP_FLAG_ASSIGN(&nonstop, 0);
  8253. /* For a non-blocking socket, the connect sequence is:
  8254. * 1) call connect (will not block)
  8255. * 2) wait until the socket is ready for writing (select or poll)
  8256. * 3) check connection state with getsockopt
  8257. */
  8258. pfd[0].fd = *sock;
  8259. pfd[0].events = POLLOUT;
  8260. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8261. if (pollres != 1) {
  8262. /* Not connected */
  8263. mg_snprintf(NULL,
  8264. NULL, /* No truncation check for ebuf */
  8265. ebuf,
  8266. ebuf_len,
  8267. "connect(%s:%d): timeout",
  8268. host,
  8269. port);
  8270. closesocket(*sock);
  8271. *sock = INVALID_SOCKET;
  8272. return 0;
  8273. }
  8274. #if defined(_WIN32)
  8275. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8276. #else
  8277. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8278. #endif
  8279. if ((ret == 0) && (sockerr == 0)) {
  8280. conn_ret = 0;
  8281. }
  8282. }
  8283. if (conn_ret != 0) {
  8284. /* Not connected */
  8285. mg_snprintf(NULL,
  8286. NULL, /* No truncation check for ebuf */
  8287. ebuf,
  8288. ebuf_len,
  8289. "connect(%s:%d): error %s",
  8290. host,
  8291. port,
  8292. strerror(sockerr));
  8293. closesocket(*sock);
  8294. *sock = INVALID_SOCKET;
  8295. return 0;
  8296. }
  8297. return 1;
  8298. }
  8299. int
  8300. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8301. {
  8302. static const char *dont_escape = "._-$,;~()";
  8303. static const char *hex = "0123456789abcdef";
  8304. char *pos = dst;
  8305. const char *end = dst + dst_len - 1;
  8306. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8307. if (isalnum((unsigned char)*src)
  8308. || (strchr(dont_escape, *src) != NULL)) {
  8309. *pos = *src;
  8310. } else if (pos + 2 < end) {
  8311. pos[0] = '%';
  8312. pos[1] = hex[(unsigned char)*src >> 4];
  8313. pos[2] = hex[(unsigned char)*src & 0xf];
  8314. pos += 2;
  8315. } else {
  8316. break;
  8317. }
  8318. }
  8319. *pos = '\0';
  8320. return (*src == '\0') ? (int)(pos - dst) : -1;
  8321. }
  8322. /* Return 0 on success, non-zero if an error occurs. */
  8323. static int
  8324. print_dir_entry(struct de *de)
  8325. {
  8326. size_t namesize, escsize, i;
  8327. char *href, *esc, *p;
  8328. char size[64], mod[64];
  8329. #if defined(REENTRANT_TIME)
  8330. struct tm _tm;
  8331. struct tm *tm = &_tm;
  8332. #else
  8333. struct tm *tm;
  8334. #endif
  8335. /* Estimate worst case size for encoding and escaping */
  8336. namesize = strlen(de->file_name) + 1;
  8337. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8338. href = (char *)mg_malloc(namesize * 3 + escsize);
  8339. if (href == NULL) {
  8340. return -1;
  8341. }
  8342. mg_url_encode(de->file_name, href, namesize * 3);
  8343. esc = NULL;
  8344. if (escsize > 0) {
  8345. /* HTML escaping needed */
  8346. esc = href + namesize * 3;
  8347. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8348. mg_strlcpy(p, de->file_name + i, 2);
  8349. if (*p == '&') {
  8350. strcpy(p, "&amp;");
  8351. } else if (*p == '<') {
  8352. strcpy(p, "&lt;");
  8353. } else if (*p == '>') {
  8354. strcpy(p, "&gt;");
  8355. }
  8356. }
  8357. }
  8358. if (de->file.is_directory) {
  8359. mg_snprintf(de->conn,
  8360. NULL, /* Buffer is big enough */
  8361. size,
  8362. sizeof(size),
  8363. "%s",
  8364. "[DIRECTORY]");
  8365. } else {
  8366. /* We use (signed) cast below because MSVC 6 compiler cannot
  8367. * convert unsigned __int64 to double. Sigh. */
  8368. if (de->file.size < 1024) {
  8369. mg_snprintf(de->conn,
  8370. NULL, /* Buffer is big enough */
  8371. size,
  8372. sizeof(size),
  8373. "%d",
  8374. (int)de->file.size);
  8375. } else if (de->file.size < 0x100000) {
  8376. mg_snprintf(de->conn,
  8377. NULL, /* Buffer is big enough */
  8378. size,
  8379. sizeof(size),
  8380. "%.1fk",
  8381. (double)de->file.size / 1024.0);
  8382. } else if (de->file.size < 0x40000000) {
  8383. mg_snprintf(de->conn,
  8384. NULL, /* Buffer is big enough */
  8385. size,
  8386. sizeof(size),
  8387. "%.1fM",
  8388. (double)de->file.size / 1048576);
  8389. } else {
  8390. mg_snprintf(de->conn,
  8391. NULL, /* Buffer is big enough */
  8392. size,
  8393. sizeof(size),
  8394. "%.1fG",
  8395. (double)de->file.size / 1073741824);
  8396. }
  8397. }
  8398. /* Note: mg_snprintf will not cause a buffer overflow above.
  8399. * So, string truncation checks are not required here. */
  8400. #if defined(REENTRANT_TIME)
  8401. localtime_r(&de->file.last_modified, tm);
  8402. #else
  8403. tm = localtime(&de->file.last_modified);
  8404. #endif
  8405. if (tm != NULL) {
  8406. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8407. } else {
  8408. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8409. mod[sizeof(mod) - 1] = '\0';
  8410. }
  8411. mg_printf(de->conn,
  8412. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8413. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8414. href,
  8415. de->file.is_directory ? "/" : "",
  8416. esc ? esc : de->file_name,
  8417. de->file.is_directory ? "/" : "",
  8418. mod,
  8419. size);
  8420. mg_free(href);
  8421. return 0;
  8422. }
  8423. /* This function is called from send_directory() and used for
  8424. * sorting directory entries by size, or name, or modification time.
  8425. * On windows, __cdecl specification is needed in case if project is built
  8426. * with __stdcall convention. qsort always requires __cdels callback. */
  8427. static int WINCDECL
  8428. compare_dir_entries(const void *p1, const void *p2)
  8429. {
  8430. if (p1 && p2) {
  8431. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8432. const char *query_string = a->conn->request_info.query_string;
  8433. int cmp_result = 0;
  8434. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8435. query_string = "n";
  8436. }
  8437. if (a->file.is_directory && !b->file.is_directory) {
  8438. return -1; /* Always put directories on top */
  8439. } else if (!a->file.is_directory && b->file.is_directory) {
  8440. return 1; /* Always put directories on top */
  8441. } else if (*query_string == 'n') {
  8442. cmp_result = strcmp(a->file_name, b->file_name);
  8443. } else if (*query_string == 's') {
  8444. cmp_result = (a->file.size == b->file.size)
  8445. ? 0
  8446. : ((a->file.size > b->file.size) ? 1 : -1);
  8447. } else if (*query_string == 'd') {
  8448. cmp_result =
  8449. (a->file.last_modified == b->file.last_modified)
  8450. ? 0
  8451. : ((a->file.last_modified > b->file.last_modified) ? 1
  8452. : -1);
  8453. }
  8454. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8455. }
  8456. return 0;
  8457. }
  8458. static int
  8459. must_hide_file(struct mg_connection *conn, const char *path)
  8460. {
  8461. if (conn && conn->dom_ctx) {
  8462. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8463. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8464. return (match_prefix_strlen(pw_pattern, path) > 0)
  8465. || (match_prefix_strlen(pattern, path) > 0);
  8466. }
  8467. return 0;
  8468. }
  8469. #if !defined(NO_FILESYSTEMS)
  8470. static int
  8471. scan_directory(struct mg_connection *conn,
  8472. const char *dir,
  8473. void *data,
  8474. int (*cb)(struct de *, void *))
  8475. {
  8476. char path[PATH_MAX];
  8477. struct dirent *dp;
  8478. DIR *dirp;
  8479. struct de de;
  8480. int truncated;
  8481. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8482. return 0;
  8483. } else {
  8484. de.conn = conn;
  8485. while ((dp = mg_readdir(dirp)) != NULL) {
  8486. /* Do not show current dir and hidden files */
  8487. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8488. || must_hide_file(conn, dp->d_name)) {
  8489. continue;
  8490. }
  8491. mg_snprintf(
  8492. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8493. /* If we don't memset stat structure to zero, mtime will have
  8494. * garbage and strftime() will segfault later on in
  8495. * print_dir_entry(). memset is required only if mg_stat()
  8496. * fails. For more details, see
  8497. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8498. memset(&de.file, 0, sizeof(de.file));
  8499. if (truncated) {
  8500. /* If the path is not complete, skip processing. */
  8501. continue;
  8502. }
  8503. if (!mg_stat(conn, path, &de.file)) {
  8504. mg_cry_internal(conn,
  8505. "%s: mg_stat(%s) failed: %s",
  8506. __func__,
  8507. path,
  8508. strerror(ERRNO));
  8509. }
  8510. de.file_name = dp->d_name;
  8511. if (cb(&de, data)) {
  8512. /* stopped */
  8513. break;
  8514. }
  8515. }
  8516. (void)mg_closedir(dirp);
  8517. }
  8518. return 1;
  8519. }
  8520. #endif /* NO_FILESYSTEMS */
  8521. #if !defined(NO_FILES)
  8522. static int
  8523. remove_directory(struct mg_connection *conn, const char *dir)
  8524. {
  8525. char path[PATH_MAX];
  8526. struct dirent *dp;
  8527. DIR *dirp;
  8528. struct de de;
  8529. int truncated;
  8530. int ok = 1;
  8531. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8532. return 0;
  8533. } else {
  8534. de.conn = conn;
  8535. while ((dp = mg_readdir(dirp)) != NULL) {
  8536. /* Do not show current dir (but show hidden files as they will
  8537. * also be removed) */
  8538. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8539. continue;
  8540. }
  8541. mg_snprintf(
  8542. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8543. /* If we don't memset stat structure to zero, mtime will have
  8544. * garbage and strftime() will segfault later on in
  8545. * print_dir_entry(). memset is required only if mg_stat()
  8546. * fails. For more details, see
  8547. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8548. memset(&de.file, 0, sizeof(de.file));
  8549. if (truncated) {
  8550. /* Do not delete anything shorter */
  8551. ok = 0;
  8552. continue;
  8553. }
  8554. if (!mg_stat(conn, path, &de.file)) {
  8555. mg_cry_internal(conn,
  8556. "%s: mg_stat(%s) failed: %s",
  8557. __func__,
  8558. path,
  8559. strerror(ERRNO));
  8560. ok = 0;
  8561. }
  8562. if (de.file.is_directory) {
  8563. if (remove_directory(conn, path) == 0) {
  8564. ok = 0;
  8565. }
  8566. } else {
  8567. /* This will fail file is the file is in memory */
  8568. if (mg_remove(conn, path) == 0) {
  8569. ok = 0;
  8570. }
  8571. }
  8572. }
  8573. (void)mg_closedir(dirp);
  8574. IGNORE_UNUSED_RESULT(rmdir(dir));
  8575. }
  8576. return ok;
  8577. }
  8578. #endif
  8579. struct dir_scan_data {
  8580. struct de *entries;
  8581. size_t num_entries;
  8582. size_t arr_size;
  8583. };
  8584. #if !defined(NO_FILESYSTEMS)
  8585. static int
  8586. dir_scan_callback(struct de *de, void *data)
  8587. {
  8588. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8589. struct de *entries = dsd->entries;
  8590. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8591. /* Here "entries" is a temporary pointer and can be replaced,
  8592. * "dsd->entries" is the original pointer */
  8593. entries =
  8594. (struct de *)mg_realloc(entries,
  8595. dsd->arr_size * 2 * sizeof(entries[0]));
  8596. if (entries == NULL) {
  8597. /* stop scan */
  8598. return 1;
  8599. }
  8600. dsd->entries = entries;
  8601. dsd->arr_size *= 2;
  8602. }
  8603. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8604. if (entries[dsd->num_entries].file_name == NULL) {
  8605. /* stop scan */
  8606. return 1;
  8607. }
  8608. entries[dsd->num_entries].file = de->file;
  8609. entries[dsd->num_entries].conn = de->conn;
  8610. dsd->num_entries++;
  8611. return 0;
  8612. }
  8613. static void
  8614. handle_directory_request(struct mg_connection *conn, const char *dir)
  8615. {
  8616. size_t i;
  8617. int sort_direction;
  8618. struct dir_scan_data data = {NULL, 0, 128};
  8619. char date[64], *esc, *p;
  8620. const char *title;
  8621. time_t curtime = time(NULL);
  8622. if (!conn) {
  8623. return;
  8624. }
  8625. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8626. mg_send_http_error(conn,
  8627. 500,
  8628. "Error: Cannot open directory\nopendir(%s): %s",
  8629. dir,
  8630. strerror(ERRNO));
  8631. return;
  8632. }
  8633. gmt_time_string(date, sizeof(date), &curtime);
  8634. esc = NULL;
  8635. title = conn->request_info.local_uri;
  8636. if (title[strcspn(title, "&<>")]) {
  8637. /* HTML escaping needed */
  8638. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8639. if (esc) {
  8640. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8641. mg_strlcpy(p, title + i, 2);
  8642. if (*p == '&') {
  8643. strcpy(p, "&amp;");
  8644. } else if (*p == '<') {
  8645. strcpy(p, "&lt;");
  8646. } else if (*p == '>') {
  8647. strcpy(p, "&gt;");
  8648. }
  8649. }
  8650. } else {
  8651. title = "";
  8652. }
  8653. }
  8654. sort_direction = ((conn->request_info.query_string != NULL)
  8655. && (conn->request_info.query_string[0] != '\0')
  8656. && (conn->request_info.query_string[1] == 'd'))
  8657. ? 'a'
  8658. : 'd';
  8659. conn->must_close = 1;
  8660. /* Create 200 OK response */
  8661. mg_response_header_start(conn, 200);
  8662. send_static_cache_header(conn);
  8663. send_additional_header(conn);
  8664. mg_response_header_add(conn,
  8665. "Content-Type",
  8666. "text/html; charset=utf-8",
  8667. -1);
  8668. /* Send all headers */
  8669. mg_response_header_send(conn);
  8670. /* Body */
  8671. mg_printf(conn,
  8672. "<html><head><title>Index of %s</title>"
  8673. "<style>th {text-align: left;}</style></head>"
  8674. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8675. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8676. "<th><a href=\"?d%c\">Modified</a></th>"
  8677. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8678. "<tr><td colspan=\"3\"><hr></td></tr>",
  8679. esc ? esc : title,
  8680. esc ? esc : title,
  8681. sort_direction,
  8682. sort_direction,
  8683. sort_direction);
  8684. mg_free(esc);
  8685. /* Print first entry - link to a parent directory */
  8686. mg_printf(conn,
  8687. "<tr><td><a href=\"%s\">%s</a></td>"
  8688. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8689. "..",
  8690. "Parent directory",
  8691. "-",
  8692. "-");
  8693. /* Sort and print directory entries */
  8694. if (data.entries != NULL) {
  8695. qsort(data.entries,
  8696. data.num_entries,
  8697. sizeof(data.entries[0]),
  8698. compare_dir_entries);
  8699. for (i = 0; i < data.num_entries; i++) {
  8700. print_dir_entry(&data.entries[i]);
  8701. mg_free(data.entries[i].file_name);
  8702. }
  8703. mg_free(data.entries);
  8704. }
  8705. mg_printf(conn, "%s", "</table></pre></body></html>");
  8706. conn->status_code = 200;
  8707. }
  8708. #endif /* NO_FILESYSTEMS */
  8709. /* Send len bytes from the opened file to the client. */
  8710. static void
  8711. send_file_data(struct mg_connection *conn,
  8712. struct mg_file *filep,
  8713. int64_t offset,
  8714. int64_t len)
  8715. {
  8716. char buf[MG_BUF_LEN];
  8717. int to_read, num_read, num_written;
  8718. int64_t size;
  8719. if (!filep || !conn) {
  8720. return;
  8721. }
  8722. /* Sanity check the offset */
  8723. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8724. : (int64_t)(filep->stat.size);
  8725. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8726. if (len > 0 && filep->access.fp != NULL) {
  8727. /* file stored on disk */
  8728. #if defined(__linux__)
  8729. /* sendfile is only available for Linux */
  8730. if ((conn->ssl == 0) && (conn->throttle == 0)
  8731. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8732. "yes"))) {
  8733. off_t sf_offs = (off_t)offset;
  8734. ssize_t sf_sent;
  8735. int sf_file = fileno(filep->access.fp);
  8736. int loop_cnt = 0;
  8737. do {
  8738. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8739. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8740. size_t sf_tosend =
  8741. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8742. sf_sent =
  8743. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8744. if (sf_sent > 0) {
  8745. len -= sf_sent;
  8746. offset += sf_sent;
  8747. } else if (loop_cnt == 0) {
  8748. /* This file can not be sent using sendfile.
  8749. * This might be the case for pseudo-files in the
  8750. * /sys/ and /proc/ file system.
  8751. * Use the regular user mode copy code instead. */
  8752. break;
  8753. } else if (sf_sent == 0) {
  8754. /* No error, but 0 bytes sent. May be EOF? */
  8755. return;
  8756. }
  8757. loop_cnt++;
  8758. } while ((len > 0) && (sf_sent >= 0));
  8759. if (sf_sent > 0) {
  8760. return; /* OK */
  8761. }
  8762. /* sf_sent<0 means error, thus fall back to the classic way */
  8763. /* This is always the case, if sf_file is not a "normal" file,
  8764. * e.g., for sending data from the output of a CGI process. */
  8765. offset = (int64_t)sf_offs;
  8766. }
  8767. #endif
  8768. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8769. mg_cry_internal(conn,
  8770. "%s: fseeko() failed: %s",
  8771. __func__,
  8772. strerror(ERRNO));
  8773. mg_send_http_error(
  8774. conn,
  8775. 500,
  8776. "%s",
  8777. "Error: Unable to access file at requested position.");
  8778. } else {
  8779. while (len > 0) {
  8780. /* Calculate how much to read from the file in the buffer */
  8781. to_read = sizeof(buf);
  8782. if ((int64_t)to_read > len) {
  8783. to_read = (int)len;
  8784. }
  8785. /* Read from file, exit the loop on error */
  8786. if ((num_read =
  8787. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8788. <= 0) {
  8789. break;
  8790. }
  8791. /* Send read bytes to the client, exit the loop on error */
  8792. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8793. != num_read) {
  8794. break;
  8795. }
  8796. /* Both read and were successful, adjust counters */
  8797. len -= num_written;
  8798. }
  8799. }
  8800. }
  8801. }
  8802. static int
  8803. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8804. {
  8805. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8806. }
  8807. static void
  8808. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8809. {
  8810. if ((filestat != NULL) && (buf != NULL)) {
  8811. mg_snprintf(NULL,
  8812. NULL, /* All calls to construct_etag use 64 byte buffer */
  8813. buf,
  8814. buf_len,
  8815. "\"%lx.%" INT64_FMT "\"",
  8816. (unsigned long)filestat->last_modified,
  8817. filestat->size);
  8818. }
  8819. }
  8820. static void
  8821. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8822. {
  8823. if (filep != NULL && filep->fp != NULL) {
  8824. #if defined(_WIN32)
  8825. (void)conn; /* Unused. */
  8826. #else
  8827. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8828. mg_cry_internal(conn,
  8829. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8830. __func__,
  8831. strerror(ERRNO));
  8832. }
  8833. #endif
  8834. }
  8835. }
  8836. #if defined(USE_ZLIB)
  8837. #include "mod_zlib.inl"
  8838. #endif
  8839. #if !defined(NO_FILESYSTEMS)
  8840. static void
  8841. handle_static_file_request(struct mg_connection *conn,
  8842. const char *path,
  8843. struct mg_file *filep,
  8844. const char *mime_type,
  8845. const char *additional_headers)
  8846. {
  8847. char lm[64], etag[64];
  8848. char range[128]; /* large enough, so there will be no overflow */
  8849. const char *range_hdr;
  8850. int64_t cl, r1, r2;
  8851. struct vec mime_vec;
  8852. int n, truncated;
  8853. char gz_path[PATH_MAX];
  8854. const char *encoding = 0;
  8855. const char *origin_hdr;
  8856. const char *cors_orig_cfg;
  8857. const char *cors1, *cors2;
  8858. int is_head_request;
  8859. #if defined(USE_ZLIB)
  8860. /* Compression is allowed, unless there is a reason not to use
  8861. * compression. If the file is already compressed, too small or a
  8862. * "range" request was made, on the fly compression is not possible. */
  8863. int allow_on_the_fly_compression = 1;
  8864. #endif
  8865. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8866. return;
  8867. }
  8868. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8869. if (mime_type == NULL) {
  8870. get_mime_type(conn, path, &mime_vec);
  8871. } else {
  8872. mime_vec.ptr = mime_type;
  8873. mime_vec.len = strlen(mime_type);
  8874. }
  8875. if (filep->stat.size > INT64_MAX) {
  8876. mg_send_http_error(conn,
  8877. 500,
  8878. "Error: File size is too large to send\n%" INT64_FMT,
  8879. filep->stat.size);
  8880. return;
  8881. }
  8882. cl = (int64_t)filep->stat.size;
  8883. conn->status_code = 200;
  8884. range[0] = '\0';
  8885. #if defined(USE_ZLIB)
  8886. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8887. * it's important to rewrite the filename after resolving
  8888. * the mime type from it, to preserve the actual file's type */
  8889. if (!conn->accept_gzip) {
  8890. allow_on_the_fly_compression = 0;
  8891. }
  8892. #endif
  8893. /* Check if there is a range header */
  8894. range_hdr = mg_get_header(conn, "Range");
  8895. /* For gzipped files, add *.gz */
  8896. if (filep->stat.is_gzipped) {
  8897. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8898. if (truncated) {
  8899. mg_send_http_error(conn,
  8900. 500,
  8901. "Error: Path of zipped file too long (%s)",
  8902. path);
  8903. return;
  8904. }
  8905. path = gz_path;
  8906. encoding = "gzip";
  8907. #if defined(USE_ZLIB)
  8908. /* File is already compressed. No "on the fly" compression. */
  8909. allow_on_the_fly_compression = 0;
  8910. #endif
  8911. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8912. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8913. struct mg_file_stat file_stat;
  8914. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8915. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8916. && !file_stat.is_directory) {
  8917. file_stat.is_gzipped = 1;
  8918. filep->stat = file_stat;
  8919. cl = (int64_t)filep->stat.size;
  8920. path = gz_path;
  8921. encoding = "gzip";
  8922. #if defined(USE_ZLIB)
  8923. /* File is already compressed. No "on the fly" compression. */
  8924. allow_on_the_fly_compression = 0;
  8925. #endif
  8926. }
  8927. }
  8928. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8929. mg_send_http_error(conn,
  8930. 500,
  8931. "Error: Cannot open file\nfopen(%s): %s",
  8932. path,
  8933. strerror(ERRNO));
  8934. return;
  8935. }
  8936. fclose_on_exec(&filep->access, conn);
  8937. /* If "Range" request was made: parse header, send only selected part
  8938. * of the file. */
  8939. r1 = r2 = 0;
  8940. if ((range_hdr != NULL)
  8941. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8942. && (r2 >= 0)) {
  8943. /* actually, range requests don't play well with a pre-gzipped
  8944. * file (since the range is specified in the uncompressed space) */
  8945. if (filep->stat.is_gzipped) {
  8946. mg_send_http_error(
  8947. conn,
  8948. 416, /* 416 = Range Not Satisfiable */
  8949. "%s",
  8950. "Error: Range requests in gzipped files are not supported");
  8951. (void)mg_fclose(
  8952. &filep->access); /* ignore error on read only file */
  8953. return;
  8954. }
  8955. conn->status_code = 206;
  8956. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8957. mg_snprintf(conn,
  8958. NULL, /* range buffer is big enough */
  8959. range,
  8960. sizeof(range),
  8961. "bytes "
  8962. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8963. r1,
  8964. r1 + cl - 1,
  8965. filep->stat.size);
  8966. #if defined(USE_ZLIB)
  8967. /* Do not compress ranges. */
  8968. allow_on_the_fly_compression = 0;
  8969. #endif
  8970. }
  8971. /* Do not compress small files. Small files do not benefit from file
  8972. * compression, but there is still some overhead. */
  8973. #if defined(USE_ZLIB)
  8974. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8975. /* File is below the size limit. */
  8976. allow_on_the_fly_compression = 0;
  8977. }
  8978. #endif
  8979. /* Standard CORS header */
  8980. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8981. origin_hdr = mg_get_header(conn, "Origin");
  8982. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8983. /* Cross-origin resource sharing (CORS), see
  8984. * http://www.html5rocks.com/en/tutorials/cors/,
  8985. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8986. * -
  8987. * preflight is not supported for files. */
  8988. cors1 = "Access-Control-Allow-Origin";
  8989. cors2 = cors_orig_cfg;
  8990. } else {
  8991. cors1 = cors2 = "";
  8992. }
  8993. /* Prepare Etag, and Last-Modified headers. */
  8994. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8995. construct_etag(etag, sizeof(etag), &filep->stat);
  8996. /* Create 2xx (200, 206) response */
  8997. mg_response_header_start(conn, conn->status_code);
  8998. send_static_cache_header(conn);
  8999. send_additional_header(conn);
  9000. mg_response_header_add(conn,
  9001. "Content-Type",
  9002. mime_vec.ptr,
  9003. (int)mime_vec.len);
  9004. if (cors1[0] != 0) {
  9005. mg_response_header_add(conn, cors1, cors2, -1);
  9006. }
  9007. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9008. mg_response_header_add(conn, "Etag", etag, -1);
  9009. #if defined(USE_ZLIB)
  9010. /* On the fly compression allowed */
  9011. if (allow_on_the_fly_compression) {
  9012. /* For on the fly compression, we don't know the content size in
  9013. * advance, so we have to use chunked encoding */
  9014. encoding = "gzip";
  9015. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9016. /* HTTP/2 is always using "chunks" (frames) */
  9017. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9018. }
  9019. } else
  9020. #endif
  9021. {
  9022. /* Without on-the-fly compression, we know the content-length
  9023. * and we can use ranges (with on-the-fly compression we cannot).
  9024. * So we send these response headers only in this case. */
  9025. char len[32];
  9026. int trunc = 0;
  9027. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9028. if (!trunc) {
  9029. mg_response_header_add(conn, "Content-Length", len, -1);
  9030. }
  9031. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9032. }
  9033. if (encoding) {
  9034. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9035. }
  9036. if (range[0] != 0) {
  9037. mg_response_header_add(conn, "Content-Range", range, -1);
  9038. }
  9039. /* The code above does not add any header starting with X- to make
  9040. * sure no one of the additional_headers is included twice */
  9041. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9042. mg_response_header_add_lines(conn, additional_headers);
  9043. }
  9044. /* Send all headers */
  9045. mg_response_header_send(conn);
  9046. if (!is_head_request) {
  9047. #if defined(USE_ZLIB)
  9048. if (allow_on_the_fly_compression) {
  9049. /* Compress and send */
  9050. send_compressed_data(conn, filep);
  9051. } else
  9052. #endif
  9053. {
  9054. /* Send file directly */
  9055. send_file_data(conn, filep, r1, cl);
  9056. }
  9057. }
  9058. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9059. }
  9060. int
  9061. mg_send_file_body(struct mg_connection *conn, const char *path)
  9062. {
  9063. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9064. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9065. return -1;
  9066. }
  9067. fclose_on_exec(&file.access, conn);
  9068. send_file_data(conn, &file, 0, INT64_MAX);
  9069. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9070. return 0; /* >= 0 for OK */
  9071. }
  9072. #endif /* NO_FILESYSTEMS */
  9073. #if !defined(NO_CACHING)
  9074. /* Return True if we should reply 304 Not Modified. */
  9075. static int
  9076. is_not_modified(const struct mg_connection *conn,
  9077. const struct mg_file_stat *filestat)
  9078. {
  9079. char etag[64];
  9080. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9081. const char *inm = mg_get_header(conn, "If-None-Match");
  9082. construct_etag(etag, sizeof(etag), filestat);
  9083. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9084. || ((ims != NULL)
  9085. && (filestat->last_modified <= parse_date_string(ims)));
  9086. }
  9087. static void
  9088. handle_not_modified_static_file_request(struct mg_connection *conn,
  9089. struct mg_file *filep)
  9090. {
  9091. char lm[64], etag[64];
  9092. if ((conn == NULL) || (filep == NULL)) {
  9093. return;
  9094. }
  9095. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9096. construct_etag(etag, sizeof(etag), &filep->stat);
  9097. /* Create 304 "not modified" response */
  9098. mg_response_header_start(conn, 304);
  9099. send_static_cache_header(conn);
  9100. send_additional_header(conn);
  9101. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9102. mg_response_header_add(conn, "Etag", etag, -1);
  9103. /* Send all headers */
  9104. mg_response_header_send(conn);
  9105. }
  9106. #endif
  9107. #if !defined(NO_FILESYSTEMS)
  9108. void
  9109. mg_send_file(struct mg_connection *conn, const char *path)
  9110. {
  9111. mg_send_mime_file2(conn, path, NULL, NULL);
  9112. }
  9113. void
  9114. mg_send_mime_file(struct mg_connection *conn,
  9115. const char *path,
  9116. const char *mime_type)
  9117. {
  9118. mg_send_mime_file2(conn, path, mime_type, NULL);
  9119. }
  9120. void
  9121. mg_send_mime_file2(struct mg_connection *conn,
  9122. const char *path,
  9123. const char *mime_type,
  9124. const char *additional_headers)
  9125. {
  9126. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9127. if (!conn) {
  9128. /* No conn */
  9129. return;
  9130. }
  9131. if (mg_stat(conn, path, &file.stat)) {
  9132. #if !defined(NO_CACHING)
  9133. if (is_not_modified(conn, &file.stat)) {
  9134. /* Send 304 "Not Modified" - this must not send any body data */
  9135. handle_not_modified_static_file_request(conn, &file);
  9136. } else
  9137. #endif /* NO_CACHING */
  9138. if (file.stat.is_directory) {
  9139. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9140. "yes")) {
  9141. handle_directory_request(conn, path);
  9142. } else {
  9143. mg_send_http_error(conn,
  9144. 403,
  9145. "%s",
  9146. "Error: Directory listing denied");
  9147. }
  9148. } else {
  9149. handle_static_file_request(
  9150. conn, path, &file, mime_type, additional_headers);
  9151. }
  9152. } else {
  9153. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9154. }
  9155. }
  9156. /* For a given PUT path, create all intermediate subdirectories.
  9157. * Return 0 if the path itself is a directory.
  9158. * Return 1 if the path leads to a file.
  9159. * Return -1 for if the path is too long.
  9160. * Return -2 if path can not be created.
  9161. */
  9162. static int
  9163. put_dir(struct mg_connection *conn, const char *path)
  9164. {
  9165. char buf[PATH_MAX];
  9166. const char *s, *p;
  9167. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9168. size_t len;
  9169. int res = 1;
  9170. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9171. len = (size_t)(p - path);
  9172. if (len >= sizeof(buf)) {
  9173. /* path too long */
  9174. res = -1;
  9175. break;
  9176. }
  9177. memcpy(buf, path, len);
  9178. buf[len] = '\0';
  9179. /* Try to create intermediate directory */
  9180. DEBUG_TRACE("mkdir(%s)", buf);
  9181. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9182. /* path does not exixt and can not be created */
  9183. res = -2;
  9184. break;
  9185. }
  9186. /* Is path itself a directory? */
  9187. if (p[1] == '\0') {
  9188. res = 0;
  9189. }
  9190. }
  9191. return res;
  9192. }
  9193. static void
  9194. remove_bad_file(const struct mg_connection *conn, const char *path)
  9195. {
  9196. int r = mg_remove(conn, path);
  9197. if (r != 0) {
  9198. mg_cry_internal(conn,
  9199. "%s: Cannot remove invalid file %s",
  9200. __func__,
  9201. path);
  9202. }
  9203. }
  9204. long long
  9205. mg_store_body(struct mg_connection *conn, const char *path)
  9206. {
  9207. char buf[MG_BUF_LEN];
  9208. long long len = 0;
  9209. int ret, n;
  9210. struct mg_file fi;
  9211. if (conn->consumed_content != 0) {
  9212. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9213. return -11;
  9214. }
  9215. ret = put_dir(conn, path);
  9216. if (ret < 0) {
  9217. /* -1 for path too long,
  9218. * -2 for path can not be created. */
  9219. return ret;
  9220. }
  9221. if (ret != 1) {
  9222. /* Return 0 means, path itself is a directory. */
  9223. return 0;
  9224. }
  9225. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9226. return -12;
  9227. }
  9228. ret = mg_read(conn, buf, sizeof(buf));
  9229. while (ret > 0) {
  9230. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9231. if (n != ret) {
  9232. (void)mg_fclose(
  9233. &fi.access); /* File is bad and will be removed anyway. */
  9234. remove_bad_file(conn, path);
  9235. return -13;
  9236. }
  9237. len += ret;
  9238. ret = mg_read(conn, buf, sizeof(buf));
  9239. }
  9240. /* File is open for writing. If fclose fails, there was probably an
  9241. * error flushing the buffer to disk, so the file on disk might be
  9242. * broken. Delete it and return an error to the caller. */
  9243. if (mg_fclose(&fi.access) != 0) {
  9244. remove_bad_file(conn, path);
  9245. return -14;
  9246. }
  9247. return len;
  9248. }
  9249. #endif /* NO_FILESYSTEMS */
  9250. /* Parse a buffer:
  9251. * Forward the string pointer till the end of a word, then
  9252. * terminate it and forward till the begin of the next word.
  9253. */
  9254. static int
  9255. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9256. {
  9257. /* Forward until a space is found - use isgraph here */
  9258. /* See http://www.cplusplus.com/reference/cctype/ */
  9259. while (isgraph((unsigned char)**ppw)) {
  9260. (*ppw)++;
  9261. }
  9262. /* Check end of word */
  9263. if (eol) {
  9264. /* must be a end of line */
  9265. if ((**ppw != '\r') && (**ppw != '\n')) {
  9266. return -1;
  9267. }
  9268. } else {
  9269. /* must be a end of a word, but not a line */
  9270. if (**ppw != ' ') {
  9271. return -1;
  9272. }
  9273. }
  9274. /* Terminate and forward to the next word */
  9275. do {
  9276. **ppw = 0;
  9277. (*ppw)++;
  9278. } while (isspace((unsigned char)**ppw));
  9279. /* Check after term */
  9280. if (!eol) {
  9281. /* if it's not the end of line, there must be a next word */
  9282. if (!isgraph((unsigned char)**ppw)) {
  9283. return -1;
  9284. }
  9285. }
  9286. /* ok */
  9287. return 1;
  9288. }
  9289. /* Parse HTTP headers from the given buffer, advance buf pointer
  9290. * to the point where parsing stopped.
  9291. * All parameters must be valid pointers (not NULL).
  9292. * Return <0 on error. */
  9293. static int
  9294. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9295. {
  9296. int i;
  9297. int num_headers = 0;
  9298. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9299. char *dp = *buf;
  9300. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9301. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9302. dp++;
  9303. }
  9304. if (dp == *buf) {
  9305. /* End of headers reached. */
  9306. break;
  9307. }
  9308. /* Drop all spaces after header name before : */
  9309. while (*dp == ' ') {
  9310. *dp = 0;
  9311. dp++;
  9312. }
  9313. if (*dp != ':') {
  9314. /* This is not a valid field. */
  9315. return -1;
  9316. }
  9317. /* End of header key (*dp == ':') */
  9318. /* Truncate here and set the key name */
  9319. *dp = 0;
  9320. hdr[i].name = *buf;
  9321. /* Skip all spaces */
  9322. do {
  9323. dp++;
  9324. } while ((*dp == ' ') || (*dp == '\t'));
  9325. /* The rest of the line is the value */
  9326. hdr[i].value = dp;
  9327. /* Find end of line */
  9328. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9329. dp++;
  9330. };
  9331. /* eliminate \r */
  9332. if (*dp == '\r') {
  9333. *dp = 0;
  9334. dp++;
  9335. if (*dp != '\n') {
  9336. /* This is not a valid line. */
  9337. return -1;
  9338. }
  9339. }
  9340. /* here *dp is either 0 or '\n' */
  9341. /* in any case, we have a new header */
  9342. num_headers = i + 1;
  9343. if (*dp) {
  9344. *dp = 0;
  9345. dp++;
  9346. *buf = dp;
  9347. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9348. /* This is the end of the header */
  9349. break;
  9350. }
  9351. } else {
  9352. *buf = dp;
  9353. break;
  9354. }
  9355. }
  9356. return num_headers;
  9357. }
  9358. struct mg_http_method_info {
  9359. const char *name;
  9360. int request_has_body;
  9361. int response_has_body;
  9362. int is_safe;
  9363. int is_idempotent;
  9364. int is_cacheable;
  9365. };
  9366. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9367. static const struct mg_http_method_info http_methods[] = {
  9368. /* HTTP (RFC 2616) */
  9369. {"GET", 0, 1, 1, 1, 1},
  9370. {"POST", 1, 1, 0, 0, 0},
  9371. {"PUT", 1, 0, 0, 1, 0},
  9372. {"DELETE", 0, 0, 0, 1, 0},
  9373. {"HEAD", 0, 0, 1, 1, 1},
  9374. {"OPTIONS", 0, 0, 1, 1, 0},
  9375. {"CONNECT", 1, 1, 0, 0, 0},
  9376. /* TRACE method (RFC 2616) is not supported for security reasons */
  9377. /* PATCH method (RFC 5789) */
  9378. {"PATCH", 1, 0, 0, 0, 0},
  9379. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9380. /* WEBDAV (RFC 2518) */
  9381. {"PROPFIND", 0, 1, 1, 1, 0},
  9382. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9383. * Some PROPFIND results MAY be cached, with care,
  9384. * as there is no cache validation mechanism for
  9385. * most properties. This method is both safe and
  9386. * idempotent (see Section 9.1 of [RFC2616]). */
  9387. {"MKCOL", 0, 0, 0, 1, 0},
  9388. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9389. * When MKCOL is invoked without a request body,
  9390. * the newly created collection SHOULD have no
  9391. * members. A MKCOL request message may contain
  9392. * a message body. The precise behavior of a MKCOL
  9393. * request when the body is present is undefined,
  9394. * ... ==> We do not support MKCOL with body data.
  9395. * This method is idempotent, but not safe (see
  9396. * Section 9.1 of [RFC2616]). Responses to this
  9397. * method MUST NOT be cached. */
  9398. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9399. {"LOCK", 1, 1, 0, 0, 0},
  9400. {"UNLOCK", 1, 0, 0, 0, 0},
  9401. {"PROPPATCH", 1, 1, 0, 0, 0},
  9402. /* Unsupported WEBDAV Methods: */
  9403. /* COPY, MOVE (RFC 2518) */
  9404. /* + 11 methods from RFC 3253 */
  9405. /* ORDERPATCH (RFC 3648) */
  9406. /* ACL (RFC 3744) */
  9407. /* SEARCH (RFC 5323) */
  9408. /* + MicroSoft extensions
  9409. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9410. /* REPORT method (RFC 3253) */
  9411. {"REPORT", 1, 1, 1, 1, 1},
  9412. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9413. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9414. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9415. * to be useful for REST in case a "GET request with body" is
  9416. * required. */
  9417. {NULL, 0, 0, 0, 0, 0}
  9418. /* end of list */
  9419. };
  9420. static const struct mg_http_method_info *
  9421. get_http_method_info(const char *method)
  9422. {
  9423. /* Check if the method is known to the server. The list of all known
  9424. * HTTP methods can be found here at
  9425. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9426. */
  9427. const struct mg_http_method_info *m = http_methods;
  9428. while (m->name) {
  9429. if (!strcmp(m->name, method)) {
  9430. return m;
  9431. }
  9432. m++;
  9433. }
  9434. return NULL;
  9435. }
  9436. static int
  9437. is_valid_http_method(const char *method)
  9438. {
  9439. return (get_http_method_info(method) != NULL);
  9440. }
  9441. /* Parse HTTP request, fill in mg_request_info structure.
  9442. * This function modifies the buffer by NUL-terminating
  9443. * HTTP request components, header names and header values.
  9444. * Parameters:
  9445. * buf (in/out): pointer to the HTTP header to parse and split
  9446. * len (in): length of HTTP header buffer
  9447. * re (out): parsed header as mg_request_info
  9448. * buf and ri must be valid pointers (not NULL), len>0.
  9449. * Returns <0 on error. */
  9450. static int
  9451. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9452. {
  9453. int request_length;
  9454. int init_skip = 0;
  9455. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9456. * remote_port */
  9457. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9458. NULL;
  9459. ri->num_headers = 0;
  9460. /* RFC says that all initial whitespaces should be ingored */
  9461. /* This included all leading \r and \n (isspace) */
  9462. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9463. while ((len > 0) && isspace((unsigned char)*buf)) {
  9464. buf++;
  9465. len--;
  9466. init_skip++;
  9467. }
  9468. if (len == 0) {
  9469. /* Incomplete request */
  9470. return 0;
  9471. }
  9472. /* Control characters are not allowed, including zero */
  9473. if (iscntrl((unsigned char)*buf)) {
  9474. return -1;
  9475. }
  9476. /* Find end of HTTP header */
  9477. request_length = get_http_header_len(buf, len);
  9478. if (request_length <= 0) {
  9479. return request_length;
  9480. }
  9481. buf[request_length - 1] = '\0';
  9482. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9483. return -1;
  9484. }
  9485. /* The first word has to be the HTTP method */
  9486. ri->request_method = buf;
  9487. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9488. return -1;
  9489. }
  9490. /* Check for a valid http method */
  9491. if (!is_valid_http_method(ri->request_method)) {
  9492. return -1;
  9493. }
  9494. /* The second word is the URI */
  9495. ri->request_uri = buf;
  9496. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9497. return -1;
  9498. }
  9499. /* Next would be the HTTP version */
  9500. ri->http_version = buf;
  9501. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9502. return -1;
  9503. }
  9504. /* Check for a valid HTTP version key */
  9505. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9506. /* Invalid request */
  9507. return -1;
  9508. }
  9509. ri->http_version += 5;
  9510. /* Parse all HTTP headers */
  9511. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9512. if (ri->num_headers < 0) {
  9513. /* Error while parsing headers */
  9514. return -1;
  9515. }
  9516. return request_length + init_skip;
  9517. }
  9518. static int
  9519. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9520. {
  9521. int response_length;
  9522. int init_skip = 0;
  9523. char *tmp, *tmp2;
  9524. long l;
  9525. /* Initialize elements. */
  9526. ri->http_version = ri->status_text = NULL;
  9527. ri->num_headers = ri->status_code = 0;
  9528. /* RFC says that all initial whitespaces should be ingored */
  9529. /* This included all leading \r and \n (isspace) */
  9530. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9531. while ((len > 0) && isspace((unsigned char)*buf)) {
  9532. buf++;
  9533. len--;
  9534. init_skip++;
  9535. }
  9536. if (len == 0) {
  9537. /* Incomplete request */
  9538. return 0;
  9539. }
  9540. /* Control characters are not allowed, including zero */
  9541. if (iscntrl((unsigned char)*buf)) {
  9542. return -1;
  9543. }
  9544. /* Find end of HTTP header */
  9545. response_length = get_http_header_len(buf, len);
  9546. if (response_length <= 0) {
  9547. return response_length;
  9548. }
  9549. buf[response_length - 1] = '\0';
  9550. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9551. return -1;
  9552. }
  9553. /* The first word is the HTTP version */
  9554. /* Check for a valid HTTP version key */
  9555. if (strncmp(buf, "HTTP/", 5) != 0) {
  9556. /* Invalid request */
  9557. return -1;
  9558. }
  9559. buf += 5;
  9560. if (!isgraph((unsigned char)buf[0])) {
  9561. /* Invalid request */
  9562. return -1;
  9563. }
  9564. ri->http_version = buf;
  9565. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9566. return -1;
  9567. }
  9568. /* The second word is the status as a number */
  9569. tmp = buf;
  9570. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9571. return -1;
  9572. }
  9573. l = strtol(tmp, &tmp2, 10);
  9574. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9575. /* Everything else but a 3 digit code is invalid */
  9576. return -1;
  9577. }
  9578. ri->status_code = (int)l;
  9579. /* The rest of the line is the status text */
  9580. ri->status_text = buf;
  9581. /* Find end of status text */
  9582. /* isgraph or isspace = isprint */
  9583. while (isprint((unsigned char)*buf)) {
  9584. buf++;
  9585. }
  9586. if ((*buf != '\r') && (*buf != '\n')) {
  9587. return -1;
  9588. }
  9589. /* Terminate string and forward buf to next line */
  9590. do {
  9591. *buf = 0;
  9592. buf++;
  9593. } while (isspace((unsigned char)*buf));
  9594. /* Parse all HTTP headers */
  9595. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9596. if (ri->num_headers < 0) {
  9597. /* Error while parsing headers */
  9598. return -1;
  9599. }
  9600. return response_length + init_skip;
  9601. }
  9602. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9603. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9604. * buffer (which marks the end of HTTP request). Buffer buf may already
  9605. * have some data. The length of the data is stored in nread.
  9606. * Upon every read operation, increase nread by the number of bytes read. */
  9607. static int
  9608. read_message(FILE *fp,
  9609. struct mg_connection *conn,
  9610. char *buf,
  9611. int bufsiz,
  9612. int *nread)
  9613. {
  9614. int request_len, n = 0;
  9615. struct timespec last_action_time;
  9616. double request_timeout;
  9617. if (!conn) {
  9618. return 0;
  9619. }
  9620. memset(&last_action_time, 0, sizeof(last_action_time));
  9621. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9622. /* value of request_timeout is in seconds, config in milliseconds */
  9623. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9624. } else {
  9625. request_timeout =
  9626. atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  9627. }
  9628. if (conn->handled_requests > 0) {
  9629. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9630. request_timeout =
  9631. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9632. }
  9633. }
  9634. request_len = get_http_header_len(buf, *nread);
  9635. while (request_len == 0) {
  9636. /* Full request not yet received */
  9637. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9638. /* Server is to be stopped. */
  9639. return -1;
  9640. }
  9641. if (*nread >= bufsiz) {
  9642. /* Request too long */
  9643. return -2;
  9644. }
  9645. n = pull_inner(
  9646. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9647. if (n == -2) {
  9648. /* Receive error */
  9649. return -1;
  9650. }
  9651. /* update clock after every read request */
  9652. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9653. if (n > 0) {
  9654. *nread += n;
  9655. request_len = get_http_header_len(buf, *nread);
  9656. }
  9657. if ((request_len == 0) && (request_timeout >= 0)) {
  9658. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9659. > request_timeout) {
  9660. /* Timeout */
  9661. return -1;
  9662. }
  9663. }
  9664. }
  9665. return request_len;
  9666. }
  9667. #if !defined(NO_CGI) || !defined(NO_FILES)
  9668. static int
  9669. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9670. {
  9671. const char *expect;
  9672. char buf[MG_BUF_LEN];
  9673. int success = 0;
  9674. if (!conn) {
  9675. return 0;
  9676. }
  9677. expect = mg_get_header(conn, "Expect");
  9678. DEBUG_ASSERT(fp != NULL);
  9679. if (!fp) {
  9680. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9681. return 0;
  9682. }
  9683. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9684. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9685. */
  9686. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9687. } else {
  9688. if (expect != NULL) {
  9689. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9690. conn->status_code = 100;
  9691. } else {
  9692. conn->status_code = 200;
  9693. }
  9694. DEBUG_ASSERT(conn->consumed_content == 0);
  9695. if (conn->consumed_content != 0) {
  9696. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9697. return 0;
  9698. }
  9699. for (;;) {
  9700. int nread = mg_read(conn, buf, sizeof(buf));
  9701. if (nread <= 0) {
  9702. success = (nread == 0);
  9703. break;
  9704. }
  9705. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9706. break;
  9707. }
  9708. }
  9709. /* Each error code path in this function must send an error */
  9710. if (!success) {
  9711. /* NOTE: Maybe some data has already been sent. */
  9712. /* TODO (low): If some data has been sent, a correct error
  9713. * reply can no longer be sent, so just close the connection */
  9714. mg_send_http_error(conn, 500, "%s", "");
  9715. }
  9716. }
  9717. return success;
  9718. }
  9719. #endif
  9720. #if defined(USE_TIMERS)
  9721. #define TIMER_API static
  9722. #include "timer.inl"
  9723. #endif /* USE_TIMERS */
  9724. #if !defined(NO_CGI)
  9725. /* This structure helps to create an environment for the spawned CGI
  9726. * program.
  9727. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9728. * last element must be NULL.
  9729. * However, on Windows there is a requirement that all these
  9730. * VARIABLE=VALUE\0
  9731. * strings must reside in a contiguous buffer. The end of the buffer is
  9732. * marked by two '\0' characters.
  9733. * We satisfy both worlds: we create an envp array (which is vars), all
  9734. * entries are actually pointers inside buf. */
  9735. struct cgi_environment {
  9736. struct mg_connection *conn;
  9737. /* Data block */
  9738. char *buf; /* Environment buffer */
  9739. size_t buflen; /* Space available in buf */
  9740. size_t bufused; /* Space taken in buf */
  9741. /* Index block */
  9742. char **var; /* char **envp */
  9743. size_t varlen; /* Number of variables available in var */
  9744. size_t varused; /* Number of variables stored in var */
  9745. };
  9746. static void addenv(struct cgi_environment *env,
  9747. PRINTF_FORMAT_STRING(const char *fmt),
  9748. ...) PRINTF_ARGS(2, 3);
  9749. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9750. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9751. static void
  9752. addenv(struct cgi_environment *env, const char *fmt, ...)
  9753. {
  9754. size_t i, n, space;
  9755. int truncated = 0;
  9756. char *added;
  9757. va_list ap;
  9758. if ((env->varlen - env->varused) < 2) {
  9759. mg_cry_internal(env->conn,
  9760. "%s: Cannot register CGI variable [%s]",
  9761. __func__,
  9762. fmt);
  9763. return;
  9764. }
  9765. /* Calculate how much space is left in the buffer */
  9766. space = (env->buflen - env->bufused);
  9767. do {
  9768. /* Space for "\0\0" is always needed. */
  9769. if (space <= 2) {
  9770. /* Allocate new buffer */
  9771. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9772. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9773. if (!added) {
  9774. /* Out of memory */
  9775. mg_cry_internal(
  9776. env->conn,
  9777. "%s: Cannot allocate memory for CGI variable [%s]",
  9778. __func__,
  9779. fmt);
  9780. return;
  9781. }
  9782. /* Retarget pointers */
  9783. env->buf = added;
  9784. env->buflen = n;
  9785. for (i = 0, n = 0; i < env->varused; i++) {
  9786. env->var[i] = added + n;
  9787. n += strlen(added + n) + 1;
  9788. }
  9789. space = (env->buflen - env->bufused);
  9790. }
  9791. /* Make a pointer to the free space int the buffer */
  9792. added = env->buf + env->bufused;
  9793. /* Copy VARIABLE=VALUE\0 string into the free space */
  9794. va_start(ap, fmt);
  9795. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9796. va_end(ap);
  9797. /* Do not add truncated strings to the environment */
  9798. if (truncated) {
  9799. /* Reallocate the buffer */
  9800. space = 0;
  9801. }
  9802. } while (truncated);
  9803. /* Calculate number of bytes added to the environment */
  9804. n = strlen(added) + 1;
  9805. env->bufused += n;
  9806. /* Append a pointer to the added string into the envp array */
  9807. env->var[env->varused] = added;
  9808. env->varused++;
  9809. }
  9810. /* Return 0 on success, non-zero if an error occurs. */
  9811. static int
  9812. prepare_cgi_environment(struct mg_connection *conn,
  9813. const char *prog,
  9814. struct cgi_environment *env)
  9815. {
  9816. const char *s;
  9817. struct vec var_vec;
  9818. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9819. int i, truncated, uri_len;
  9820. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9821. return -1;
  9822. }
  9823. env->conn = conn;
  9824. env->buflen = CGI_ENVIRONMENT_SIZE;
  9825. env->bufused = 0;
  9826. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9827. if (env->buf == NULL) {
  9828. mg_cry_internal(conn,
  9829. "%s: Not enough memory for environmental buffer",
  9830. __func__);
  9831. return -1;
  9832. }
  9833. env->varlen = MAX_CGI_ENVIR_VARS;
  9834. env->varused = 0;
  9835. env->var =
  9836. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9837. if (env->var == NULL) {
  9838. mg_cry_internal(conn,
  9839. "%s: Not enough memory for environmental variables",
  9840. __func__);
  9841. mg_free(env->buf);
  9842. return -1;
  9843. }
  9844. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9845. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9846. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9847. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9848. /* Prepare the environment block */
  9849. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9850. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9851. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9852. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9853. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9854. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9855. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9856. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9857. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9858. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9859. /* SCRIPT_NAME */
  9860. uri_len = (int)strlen(conn->request_info.local_uri);
  9861. if (conn->path_info == NULL) {
  9862. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9863. /* URI: /path_to_script/script.cgi */
  9864. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9865. } else {
  9866. /* URI: /path_to_script/ ... using index.cgi */
  9867. const char *index_file = strrchr(prog, '/');
  9868. if (index_file) {
  9869. addenv(env,
  9870. "SCRIPT_NAME=%s%s",
  9871. conn->request_info.local_uri,
  9872. index_file + 1);
  9873. }
  9874. }
  9875. } else {
  9876. /* URI: /path_to_script/script.cgi/path_info */
  9877. addenv(env,
  9878. "SCRIPT_NAME=%.*s",
  9879. uri_len - (int)strlen(conn->path_info),
  9880. conn->request_info.local_uri);
  9881. }
  9882. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9883. if (conn->path_info == NULL) {
  9884. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9885. } else {
  9886. addenv(env,
  9887. "PATH_TRANSLATED=%s%s",
  9888. conn->dom_ctx->config[DOCUMENT_ROOT],
  9889. conn->path_info);
  9890. }
  9891. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9892. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9893. addenv(env, "CONTENT_TYPE=%s", s);
  9894. }
  9895. if (conn->request_info.query_string != NULL) {
  9896. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9897. }
  9898. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9899. addenv(env, "CONTENT_LENGTH=%s", s);
  9900. }
  9901. if ((s = getenv("PATH")) != NULL) {
  9902. addenv(env, "PATH=%s", s);
  9903. }
  9904. if (conn->path_info != NULL) {
  9905. addenv(env, "PATH_INFO=%s", conn->path_info);
  9906. }
  9907. if (conn->status_code > 0) {
  9908. /* CGI error handler should show the status code */
  9909. addenv(env, "STATUS=%d", conn->status_code);
  9910. }
  9911. #if defined(_WIN32)
  9912. if ((s = getenv("COMSPEC")) != NULL) {
  9913. addenv(env, "COMSPEC=%s", s);
  9914. }
  9915. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9916. addenv(env, "SYSTEMROOT=%s", s);
  9917. }
  9918. if ((s = getenv("SystemDrive")) != NULL) {
  9919. addenv(env, "SystemDrive=%s", s);
  9920. }
  9921. if ((s = getenv("ProgramFiles")) != NULL) {
  9922. addenv(env, "ProgramFiles=%s", s);
  9923. }
  9924. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9925. addenv(env, "ProgramFiles(x86)=%s", s);
  9926. }
  9927. #else
  9928. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9929. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9930. }
  9931. #endif /* _WIN32 */
  9932. if ((s = getenv("PERLLIB")) != NULL) {
  9933. addenv(env, "PERLLIB=%s", s);
  9934. }
  9935. if (conn->request_info.remote_user != NULL) {
  9936. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9937. addenv(env, "%s", "AUTH_TYPE=Digest");
  9938. }
  9939. /* Add all headers as HTTP_* variables */
  9940. for (i = 0; i < conn->request_info.num_headers; i++) {
  9941. (void)mg_snprintf(conn,
  9942. &truncated,
  9943. http_var_name,
  9944. sizeof(http_var_name),
  9945. "HTTP_%s",
  9946. conn->request_info.http_headers[i].name);
  9947. if (truncated) {
  9948. mg_cry_internal(conn,
  9949. "%s: HTTP header variable too long [%s]",
  9950. __func__,
  9951. conn->request_info.http_headers[i].name);
  9952. continue;
  9953. }
  9954. /* Convert variable name into uppercase, and change - to _ */
  9955. for (p = http_var_name; *p != '\0'; p++) {
  9956. if (*p == '-') {
  9957. *p = '_';
  9958. }
  9959. *p = (char)toupper((unsigned char)*p);
  9960. }
  9961. addenv(env,
  9962. "%s=%s",
  9963. http_var_name,
  9964. conn->request_info.http_headers[i].value);
  9965. }
  9966. /* Add user-specified variables */
  9967. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9968. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9969. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9970. }
  9971. env->var[env->varused] = NULL;
  9972. env->buf[env->bufused] = '\0';
  9973. return 0;
  9974. }
  9975. /* Data for CGI process control: PID and number of references */
  9976. struct process_control_data {
  9977. pid_t pid;
  9978. ptrdiff_t references;
  9979. };
  9980. static int
  9981. abort_cgi_process(void *data)
  9982. {
  9983. /* Waitpid checks for child status and won't work for a pid that does
  9984. * not identify a child of the current process. Thus, if the pid is
  9985. * reused, we will not affect a different process. */
  9986. struct process_control_data *proc = (struct process_control_data *)data;
  9987. int status = 0;
  9988. ptrdiff_t refs;
  9989. pid_t ret_pid;
  9990. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9991. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9992. /* Stop child process */
  9993. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9994. kill(proc->pid, SIGABRT);
  9995. /* Wait until process is terminated (don't leave zombies) */
  9996. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9997. ;
  9998. } else {
  9999. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10000. }
  10001. /* Dec reference counter */
  10002. refs = mg_atomic_dec(&proc->references);
  10003. if (refs == 0) {
  10004. /* no more references - free data */
  10005. mg_free(data);
  10006. }
  10007. return 0;
  10008. }
  10009. /* Local (static) function assumes all arguments are valid. */
  10010. static void
  10011. handle_cgi_request(struct mg_connection *conn, const char *prog)
  10012. {
  10013. char *buf;
  10014. size_t buflen;
  10015. int headers_len, data_len, i, truncated;
  10016. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10017. const char *status, *status_text, *connection_state;
  10018. char *pbuf, dir[PATH_MAX], *p;
  10019. struct mg_request_info ri;
  10020. struct cgi_environment blk;
  10021. FILE *in = NULL, *out = NULL, *err = NULL;
  10022. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10023. pid_t pid = (pid_t)-1;
  10024. struct process_control_data *proc = NULL;
  10025. #if defined(USE_TIMERS)
  10026. double cgi_timeout;
  10027. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  10028. /* Get timeout in seconds */
  10029. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  10030. } else {
  10031. cgi_timeout =
  10032. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10033. }
  10034. #endif
  10035. buf = NULL;
  10036. buflen = conn->phys_ctx->max_request_size;
  10037. i = prepare_cgi_environment(conn, prog, &blk);
  10038. if (i != 0) {
  10039. blk.buf = NULL;
  10040. blk.var = NULL;
  10041. goto done;
  10042. }
  10043. /* CGI must be executed in its own directory. 'dir' must point to the
  10044. * directory containing executable program, 'p' must point to the
  10045. * executable program name relative to 'dir'. */
  10046. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10047. if (truncated) {
  10048. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10049. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10050. goto done;
  10051. }
  10052. if ((p = strrchr(dir, '/')) != NULL) {
  10053. *p++ = '\0';
  10054. } else {
  10055. dir[0] = '.';
  10056. dir[1] = '\0';
  10057. p = (char *)prog;
  10058. }
  10059. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10060. status = strerror(ERRNO);
  10061. mg_cry_internal(
  10062. conn,
  10063. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10064. prog,
  10065. status);
  10066. mg_send_http_error(conn,
  10067. 500,
  10068. "Error: Cannot create CGI pipe: %s",
  10069. status);
  10070. goto done;
  10071. }
  10072. proc = (struct process_control_data *)
  10073. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10074. if (proc == NULL) {
  10075. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10076. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10077. goto done;
  10078. }
  10079. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10080. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  10081. if (pid == (pid_t)-1) {
  10082. status = strerror(ERRNO);
  10083. mg_cry_internal(
  10084. conn,
  10085. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10086. prog,
  10087. status);
  10088. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10089. mg_free(proc);
  10090. proc = NULL;
  10091. goto done;
  10092. }
  10093. /* Store data in shared process_control_data */
  10094. proc->pid = pid;
  10095. proc->references = 1;
  10096. #if defined(USE_TIMERS)
  10097. if (cgi_timeout > 0.0) {
  10098. proc->references = 2;
  10099. // Start a timer for CGI
  10100. timer_add(conn->phys_ctx,
  10101. cgi_timeout /* in seconds */,
  10102. 0.0,
  10103. 1,
  10104. abort_cgi_process,
  10105. (void *)proc,
  10106. NULL);
  10107. }
  10108. #endif
  10109. /* Parent closes only one side of the pipes.
  10110. * If we don't mark them as closed, close() attempt before
  10111. * return from this function throws an exception on Windows.
  10112. * Windows does not like when closed descriptor is closed again. */
  10113. (void)close(fdin[0]);
  10114. (void)close(fdout[1]);
  10115. (void)close(fderr[1]);
  10116. fdin[0] = fdout[1] = fderr[1] = -1;
  10117. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10118. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10119. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10120. status = strerror(ERRNO);
  10121. mg_cry_internal(conn,
  10122. "Error: CGI program \"%s\": Can not open fd: %s",
  10123. prog,
  10124. status);
  10125. mg_send_http_error(conn,
  10126. 500,
  10127. "Error: CGI can not open fd\nfdopen: %s",
  10128. status);
  10129. goto done;
  10130. }
  10131. setbuf(in, NULL);
  10132. setbuf(out, NULL);
  10133. setbuf(err, NULL);
  10134. fout.access.fp = out;
  10135. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10136. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10137. conn->content_len);
  10138. /* This is a POST/PUT request, or another request with body data. */
  10139. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10140. /* Error sending the body data */
  10141. mg_cry_internal(
  10142. conn,
  10143. "Error: CGI program \"%s\": Forward body data failed",
  10144. prog);
  10145. goto done;
  10146. }
  10147. }
  10148. /* Close so child gets an EOF. */
  10149. fclose(in);
  10150. in = NULL;
  10151. fdin[1] = -1;
  10152. /* Now read CGI reply into a buffer. We need to set correct
  10153. * status code, thus we need to see all HTTP headers first.
  10154. * Do not send anything back to client, until we buffer in all
  10155. * HTTP headers. */
  10156. data_len = 0;
  10157. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10158. if (buf == NULL) {
  10159. mg_send_http_error(conn,
  10160. 500,
  10161. "Error: Not enough memory for CGI buffer (%u bytes)",
  10162. (unsigned int)buflen);
  10163. mg_cry_internal(
  10164. conn,
  10165. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10166. "bytes)",
  10167. prog,
  10168. (unsigned int)buflen);
  10169. goto done;
  10170. }
  10171. DEBUG_TRACE("CGI: %s", "wait for response");
  10172. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10173. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10174. if (headers_len <= 0) {
  10175. /* Could not parse the CGI response. Check if some error message on
  10176. * stderr. */
  10177. i = pull_all(err, conn, buf, (int)buflen);
  10178. if (i > 0) {
  10179. /* CGI program explicitly sent an error */
  10180. /* Write the error message to the internal log */
  10181. mg_cry_internal(conn,
  10182. "Error: CGI program \"%s\" sent error "
  10183. "message: [%.*s]",
  10184. prog,
  10185. i,
  10186. buf);
  10187. /* Don't send the error message back to the client */
  10188. mg_send_http_error(conn,
  10189. 500,
  10190. "Error: CGI program \"%s\" failed.",
  10191. prog);
  10192. } else {
  10193. /* CGI program did not explicitly send an error, but a broken
  10194. * respon header */
  10195. mg_cry_internal(conn,
  10196. "Error: CGI program sent malformed or too big "
  10197. "(>%u bytes) HTTP headers: [%.*s]",
  10198. (unsigned)buflen,
  10199. data_len,
  10200. buf);
  10201. mg_send_http_error(conn,
  10202. 500,
  10203. "Error: CGI program sent malformed or too big "
  10204. "(>%u bytes) HTTP headers: [%.*s]",
  10205. (unsigned)buflen,
  10206. data_len,
  10207. buf);
  10208. }
  10209. /* in both cases, abort processing CGI */
  10210. goto done;
  10211. }
  10212. pbuf = buf;
  10213. buf[headers_len - 1] = '\0';
  10214. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10215. /* Make up and send the status line */
  10216. status_text = "OK";
  10217. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10218. != NULL) {
  10219. conn->status_code = atoi(status);
  10220. status_text = status;
  10221. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10222. status_text++;
  10223. }
  10224. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10225. != NULL) {
  10226. conn->status_code = 307;
  10227. } else {
  10228. conn->status_code = 200;
  10229. }
  10230. connection_state =
  10231. get_header(ri.http_headers, ri.num_headers, "Connection");
  10232. if (!header_has_option(connection_state, "keep-alive")) {
  10233. conn->must_close = 1;
  10234. }
  10235. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10236. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10237. /* Send headers */
  10238. for (i = 0; i < ri.num_headers; i++) {
  10239. DEBUG_TRACE("CGI header: %s: %s",
  10240. ri.http_headers[i].name,
  10241. ri.http_headers[i].value);
  10242. mg_printf(conn,
  10243. "%s: %s\r\n",
  10244. ri.http_headers[i].name,
  10245. ri.http_headers[i].value);
  10246. }
  10247. mg_write(conn, "\r\n", 2);
  10248. /* Send chunk of data that may have been read after the headers */
  10249. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10250. /* Read the rest of CGI output and send to the client */
  10251. DEBUG_TRACE("CGI: %s", "forward all data");
  10252. send_file_data(conn, &fout, 0, INT64_MAX);
  10253. DEBUG_TRACE("CGI: %s", "all data sent");
  10254. done:
  10255. mg_free(blk.var);
  10256. mg_free(blk.buf);
  10257. if (pid != (pid_t)-1) {
  10258. abort_cgi_process((void *)proc);
  10259. }
  10260. if (fdin[0] != -1) {
  10261. close(fdin[0]);
  10262. }
  10263. if (fdout[1] != -1) {
  10264. close(fdout[1]);
  10265. }
  10266. if (fderr[1] != -1) {
  10267. close(fderr[1]);
  10268. }
  10269. if (in != NULL) {
  10270. fclose(in);
  10271. } else if (fdin[1] != -1) {
  10272. close(fdin[1]);
  10273. }
  10274. if (out != NULL) {
  10275. fclose(out);
  10276. } else if (fdout[0] != -1) {
  10277. close(fdout[0]);
  10278. }
  10279. if (err != NULL) {
  10280. fclose(err);
  10281. } else if (fderr[0] != -1) {
  10282. close(fderr[0]);
  10283. }
  10284. mg_free(buf);
  10285. }
  10286. #endif /* !NO_CGI */
  10287. #if !defined(NO_FILES)
  10288. static void
  10289. mkcol(struct mg_connection *conn, const char *path)
  10290. {
  10291. int rc, body_len;
  10292. struct de de;
  10293. if (conn == NULL) {
  10294. return;
  10295. }
  10296. /* TODO (mid): Check the mg_send_http_error situations in this function
  10297. */
  10298. memset(&de.file, 0, sizeof(de.file));
  10299. if (!mg_stat(conn, path, &de.file)) {
  10300. mg_cry_internal(conn,
  10301. "%s: mg_stat(%s) failed: %s",
  10302. __func__,
  10303. path,
  10304. strerror(ERRNO));
  10305. }
  10306. if (de.file.last_modified) {
  10307. /* TODO (mid): This check does not seem to make any sense ! */
  10308. /* TODO (mid): Add a webdav unit test first, before changing
  10309. * anything here. */
  10310. mg_send_http_error(
  10311. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10312. return;
  10313. }
  10314. body_len = conn->data_len - conn->request_len;
  10315. if (body_len > 0) {
  10316. mg_send_http_error(
  10317. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10318. return;
  10319. }
  10320. rc = mg_mkdir(conn, path, 0755);
  10321. if (rc == 0) {
  10322. /* Create 201 "Created" response */
  10323. mg_response_header_start(conn, 201);
  10324. send_static_cache_header(conn);
  10325. send_additional_header(conn);
  10326. mg_response_header_add(conn, "Content-Length", "0", -1);
  10327. /* Send all headers - there is no body */
  10328. mg_response_header_send(conn);
  10329. } else {
  10330. if (errno == EEXIST) {
  10331. mg_send_http_error(
  10332. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10333. } else if (errno == EACCES) {
  10334. mg_send_http_error(
  10335. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10336. } else if (errno == ENOENT) {
  10337. mg_send_http_error(
  10338. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10339. } else {
  10340. mg_send_http_error(
  10341. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10342. }
  10343. }
  10344. }
  10345. static void
  10346. put_file(struct mg_connection *conn, const char *path)
  10347. {
  10348. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10349. const char *range;
  10350. int64_t r1, r2;
  10351. int rc;
  10352. if (conn == NULL) {
  10353. return;
  10354. }
  10355. if (mg_stat(conn, path, &file.stat)) {
  10356. /* File already exists */
  10357. conn->status_code = 200;
  10358. if (file.stat.is_directory) {
  10359. /* This is an already existing directory,
  10360. * so there is nothing to do for the server. */
  10361. rc = 0;
  10362. } else {
  10363. /* File exists and is not a directory. */
  10364. /* Can it be replaced? */
  10365. /* Check if the server may write this file */
  10366. if (access(path, W_OK) == 0) {
  10367. /* Access granted */
  10368. rc = 1;
  10369. } else {
  10370. mg_send_http_error(
  10371. conn,
  10372. 403,
  10373. "Error: Put not possible\nReplacing %s is not allowed",
  10374. path);
  10375. return;
  10376. }
  10377. }
  10378. } else {
  10379. /* File should be created */
  10380. conn->status_code = 201;
  10381. rc = put_dir(conn, path);
  10382. }
  10383. if (rc == 0) {
  10384. /* put_dir returns 0 if path is a directory */
  10385. /* Create response */
  10386. mg_response_header_start(conn, conn->status_code);
  10387. send_no_cache_header(conn);
  10388. send_additional_header(conn);
  10389. mg_response_header_add(conn, "Content-Length", "0", -1);
  10390. /* Send all headers - there is no body */
  10391. mg_response_header_send(conn);
  10392. /* Request to create a directory has been fulfilled successfully.
  10393. * No need to put a file. */
  10394. return;
  10395. }
  10396. if (rc == -1) {
  10397. /* put_dir returns -1 if the path is too long */
  10398. mg_send_http_error(conn,
  10399. 414,
  10400. "Error: Path too long\nput_dir(%s): %s",
  10401. path,
  10402. strerror(ERRNO));
  10403. return;
  10404. }
  10405. if (rc == -2) {
  10406. /* put_dir returns -2 if the directory can not be created */
  10407. mg_send_http_error(conn,
  10408. 500,
  10409. "Error: Can not create directory\nput_dir(%s): %s",
  10410. path,
  10411. strerror(ERRNO));
  10412. return;
  10413. }
  10414. /* A file should be created or overwritten. */
  10415. /* Currently CivetWeb does not nead read+write access. */
  10416. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10417. || file.access.fp == NULL) {
  10418. (void)mg_fclose(&file.access);
  10419. mg_send_http_error(conn,
  10420. 500,
  10421. "Error: Can not create file\nfopen(%s): %s",
  10422. path,
  10423. strerror(ERRNO));
  10424. return;
  10425. }
  10426. fclose_on_exec(&file.access, conn);
  10427. range = mg_get_header(conn, "Content-Range");
  10428. r1 = r2 = 0;
  10429. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10430. conn->status_code = 206; /* Partial content */
  10431. fseeko(file.access.fp, r1, SEEK_SET);
  10432. }
  10433. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10434. /* forward_body_data failed.
  10435. * The error code has already been sent to the client,
  10436. * and conn->status_code is already set. */
  10437. (void)mg_fclose(&file.access);
  10438. return;
  10439. }
  10440. if (mg_fclose(&file.access) != 0) {
  10441. /* fclose failed. This might have different reasons, but a likely
  10442. * one is "no space on disk", http 507. */
  10443. conn->status_code = 507;
  10444. }
  10445. /* Create response (status_code has been set before) */
  10446. mg_response_header_start(conn, conn->status_code);
  10447. send_no_cache_header(conn);
  10448. send_additional_header(conn);
  10449. mg_response_header_add(conn, "Content-Length", "0", -1);
  10450. /* Send all headers - there is no body */
  10451. mg_response_header_send(conn);
  10452. }
  10453. static void
  10454. delete_file(struct mg_connection *conn, const char *path)
  10455. {
  10456. struct de de;
  10457. memset(&de.file, 0, sizeof(de.file));
  10458. if (!mg_stat(conn, path, &de.file)) {
  10459. /* mg_stat returns 0 if the file does not exist */
  10460. mg_send_http_error(conn,
  10461. 404,
  10462. "Error: Cannot delete file\nFile %s not found",
  10463. path);
  10464. return;
  10465. }
  10466. if (de.file.is_directory) {
  10467. if (remove_directory(conn, path)) {
  10468. /* Delete is successful: Return 204 without content. */
  10469. mg_send_http_error(conn, 204, "%s", "");
  10470. } else {
  10471. /* Delete is not successful: Return 500 (Server error). */
  10472. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10473. }
  10474. return;
  10475. }
  10476. /* This is an existing file (not a directory).
  10477. * Check if write permission is granted. */
  10478. if (access(path, W_OK) != 0) {
  10479. /* File is read only */
  10480. mg_send_http_error(
  10481. conn,
  10482. 403,
  10483. "Error: Delete not possible\nDeleting %s is not allowed",
  10484. path);
  10485. return;
  10486. }
  10487. /* Try to delete it. */
  10488. if (mg_remove(conn, path) == 0) {
  10489. /* Delete was successful: Return 204 without content. */
  10490. mg_response_header_start(conn, 204);
  10491. send_no_cache_header(conn);
  10492. send_additional_header(conn);
  10493. mg_response_header_add(conn, "Content-Length", "0", -1);
  10494. mg_response_header_send(conn);
  10495. } else {
  10496. /* Delete not successful (file locked). */
  10497. mg_send_http_error(conn,
  10498. 423,
  10499. "Error: Cannot delete file\nremove(%s): %s",
  10500. path,
  10501. strerror(ERRNO));
  10502. }
  10503. }
  10504. #endif /* !NO_FILES */
  10505. #if !defined(NO_FILESYSTEMS)
  10506. static void
  10507. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10508. static void
  10509. do_ssi_include(struct mg_connection *conn,
  10510. const char *ssi,
  10511. char *tag,
  10512. int include_level)
  10513. {
  10514. char file_name[MG_BUF_LEN], path[512], *p;
  10515. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10516. size_t len;
  10517. int truncated = 0;
  10518. if (conn == NULL) {
  10519. return;
  10520. }
  10521. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10522. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10523. * always < MG_BUF_LEN. */
  10524. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10525. /* File name is relative to the webserver root */
  10526. file_name[511] = 0;
  10527. (void)mg_snprintf(conn,
  10528. &truncated,
  10529. path,
  10530. sizeof(path),
  10531. "%s/%s",
  10532. conn->dom_ctx->config[DOCUMENT_ROOT],
  10533. file_name);
  10534. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10535. /* File name is relative to the webserver working directory
  10536. * or it is absolute system path */
  10537. file_name[511] = 0;
  10538. (void)
  10539. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10540. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10541. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10542. /* File name is relative to the currect document */
  10543. file_name[511] = 0;
  10544. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10545. if (!truncated) {
  10546. if ((p = strrchr(path, '/')) != NULL) {
  10547. p[1] = '\0';
  10548. }
  10549. len = strlen(path);
  10550. (void)mg_snprintf(conn,
  10551. &truncated,
  10552. path + len,
  10553. sizeof(path) - len,
  10554. "%s",
  10555. file_name);
  10556. }
  10557. } else {
  10558. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10559. return;
  10560. }
  10561. if (truncated) {
  10562. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10563. return;
  10564. }
  10565. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10566. mg_cry_internal(conn,
  10567. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10568. tag,
  10569. path,
  10570. strerror(ERRNO));
  10571. } else {
  10572. fclose_on_exec(&file.access, conn);
  10573. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10574. > 0) {
  10575. send_ssi_file(conn, path, &file, include_level + 1);
  10576. } else {
  10577. send_file_data(conn, &file, 0, INT64_MAX);
  10578. }
  10579. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10580. }
  10581. }
  10582. #if !defined(NO_POPEN)
  10583. static void
  10584. do_ssi_exec(struct mg_connection *conn, char *tag)
  10585. {
  10586. char cmd[1024] = "";
  10587. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10588. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10589. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10590. } else {
  10591. cmd[1023] = 0;
  10592. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10593. mg_cry_internal(conn,
  10594. "Cannot SSI #exec: [%s]: %s",
  10595. cmd,
  10596. strerror(ERRNO));
  10597. } else {
  10598. send_file_data(conn, &file, 0, INT64_MAX);
  10599. pclose(file.access.fp);
  10600. }
  10601. }
  10602. }
  10603. #endif /* !NO_POPEN */
  10604. static int
  10605. mg_fgetc(struct mg_file *filep)
  10606. {
  10607. if (filep == NULL) {
  10608. return EOF;
  10609. }
  10610. if (filep->access.fp != NULL) {
  10611. return fgetc(filep->access.fp);
  10612. } else {
  10613. return EOF;
  10614. }
  10615. }
  10616. static void
  10617. send_ssi_file(struct mg_connection *conn,
  10618. const char *path,
  10619. struct mg_file *filep,
  10620. int include_level)
  10621. {
  10622. char buf[MG_BUF_LEN];
  10623. int ch, len, in_tag, in_ssi_tag;
  10624. if (include_level > 10) {
  10625. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10626. return;
  10627. }
  10628. in_tag = in_ssi_tag = len = 0;
  10629. /* Read file, byte by byte, and look for SSI include tags */
  10630. while ((ch = mg_fgetc(filep)) != EOF) {
  10631. if (in_tag) {
  10632. /* We are in a tag, either SSI tag or html tag */
  10633. if (ch == '>') {
  10634. /* Tag is closing */
  10635. buf[len++] = '>';
  10636. if (in_ssi_tag) {
  10637. /* Handle SSI tag */
  10638. buf[len] = 0;
  10639. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10640. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10641. #if !defined(NO_POPEN)
  10642. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10643. do_ssi_exec(conn, buf + 9);
  10644. #endif /* !NO_POPEN */
  10645. } else {
  10646. mg_cry_internal(conn,
  10647. "%s: unknown SSI "
  10648. "command: \"%s\"",
  10649. path,
  10650. buf);
  10651. }
  10652. len = 0;
  10653. in_ssi_tag = in_tag = 0;
  10654. } else {
  10655. /* Not an SSI tag */
  10656. /* Flush buffer */
  10657. (void)mg_write(conn, buf, (size_t)len);
  10658. len = 0;
  10659. in_tag = 0;
  10660. }
  10661. } else {
  10662. /* Tag is still open */
  10663. buf[len++] = (char)(ch & 0xff);
  10664. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10665. /* All SSI tags start with <!--# */
  10666. in_ssi_tag = 1;
  10667. }
  10668. if ((len + 2) > (int)sizeof(buf)) {
  10669. /* Tag to long for buffer */
  10670. mg_cry_internal(conn, "%s: tag is too large", path);
  10671. return;
  10672. }
  10673. }
  10674. } else {
  10675. /* We are not in a tag yet. */
  10676. if (ch == '<') {
  10677. /* Tag is opening */
  10678. in_tag = 1;
  10679. if (len > 0) {
  10680. /* Flush current buffer.
  10681. * Buffer is filled with "len" bytes. */
  10682. (void)mg_write(conn, buf, (size_t)len);
  10683. }
  10684. /* Store the < */
  10685. len = 1;
  10686. buf[0] = '<';
  10687. } else {
  10688. /* No Tag */
  10689. /* Add data to buffer */
  10690. buf[len++] = (char)(ch & 0xff);
  10691. /* Flush if buffer is full */
  10692. if (len == (int)sizeof(buf)) {
  10693. mg_write(conn, buf, (size_t)len);
  10694. len = 0;
  10695. }
  10696. }
  10697. }
  10698. }
  10699. /* Send the rest of buffered data */
  10700. if (len > 0) {
  10701. mg_write(conn, buf, (size_t)len);
  10702. }
  10703. }
  10704. static void
  10705. handle_ssi_file_request(struct mg_connection *conn,
  10706. const char *path,
  10707. struct mg_file *filep)
  10708. {
  10709. char date[64];
  10710. time_t curtime = time(NULL);
  10711. const char *cors_orig_cfg;
  10712. const char *cors1, *cors2;
  10713. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10714. return;
  10715. }
  10716. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10717. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10718. /* Cross-origin resource sharing (CORS). */
  10719. cors1 = "Access-Control-Allow-Origin";
  10720. cors2 = cors_orig_cfg;
  10721. } else {
  10722. cors1 = cors2 = "";
  10723. }
  10724. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10725. /* File exists (precondition for calling this function),
  10726. * but can not be opened by the server. */
  10727. mg_send_http_error(conn,
  10728. 500,
  10729. "Error: Cannot read file\nfopen(%s): %s",
  10730. path,
  10731. strerror(ERRNO));
  10732. } else {
  10733. /* Set "must_close" for HTTP/1.x, since we do not know the
  10734. * content length */
  10735. conn->must_close = 1;
  10736. gmt_time_string(date, sizeof(date), &curtime);
  10737. fclose_on_exec(&filep->access, conn);
  10738. /* 200 OK response */
  10739. mg_response_header_start(conn, 200);
  10740. send_no_cache_header(conn);
  10741. send_additional_header(conn);
  10742. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10743. if (cors1[0]) {
  10744. mg_response_header_add(conn, cors1, cors2, -1);
  10745. }
  10746. mg_response_header_send(conn);
  10747. /* Header sent, now send body */
  10748. send_ssi_file(conn, path, filep, 0);
  10749. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10750. }
  10751. }
  10752. #endif /* NO_FILESYSTEMS */
  10753. #if !defined(NO_FILES)
  10754. static void
  10755. send_options(struct mg_connection *conn)
  10756. {
  10757. if (!conn) {
  10758. return;
  10759. }
  10760. /* We do not set a "Cache-Control" header here, but leave the default.
  10761. * Since browsers do not send an OPTIONS request, we can not test the
  10762. * effect anyway. */
  10763. mg_response_header_start(conn, 200);
  10764. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10765. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10766. /* Use the same as before */
  10767. mg_response_header_add(
  10768. conn,
  10769. "Allow",
  10770. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10771. -1);
  10772. mg_response_header_add(conn, "DAV", "1", -1);
  10773. } else {
  10774. /* TODO: Check this later for HTTP/2 */
  10775. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10776. }
  10777. send_additional_header(conn);
  10778. mg_response_header_send(conn);
  10779. }
  10780. /* Writes PROPFIND properties for a collection element */
  10781. static int
  10782. print_props(struct mg_connection *conn,
  10783. const char *uri,
  10784. const char *name,
  10785. struct mg_file_stat *filep)
  10786. {
  10787. size_t href_size, i, j;
  10788. int len;
  10789. char *href, mtime[64];
  10790. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10791. return 0;
  10792. }
  10793. /* Estimate worst case size for encoding */
  10794. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10795. href = (char *)mg_malloc(href_size);
  10796. if (href == NULL) {
  10797. return 0;
  10798. }
  10799. len = mg_url_encode(uri, href, href_size);
  10800. if (len >= 0) {
  10801. /* Append an extra string */
  10802. mg_url_encode(name, href + len, href_size - (size_t)len);
  10803. }
  10804. /* Directory separator should be preserved. */
  10805. for (i = j = 0; href[i]; j++) {
  10806. if (!strncmp(href + i, "%2f", 3)) {
  10807. href[j] = '/';
  10808. i += 3;
  10809. } else {
  10810. href[j] = href[i++];
  10811. }
  10812. }
  10813. href[j] = '\0';
  10814. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10815. mg_printf(conn,
  10816. "<d:response>"
  10817. "<d:href>%s</d:href>"
  10818. "<d:propstat>"
  10819. "<d:prop>"
  10820. "<d:resourcetype>%s</d:resourcetype>"
  10821. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10822. "<d:getlastmodified>%s</d:getlastmodified>"
  10823. "</d:prop>"
  10824. "<d:status>HTTP/1.1 200 OK</d:status>"
  10825. "</d:propstat>"
  10826. "</d:response>\n",
  10827. href,
  10828. filep->is_directory ? "<d:collection/>" : "",
  10829. filep->size,
  10830. mtime);
  10831. mg_free(href);
  10832. return 1;
  10833. }
  10834. static int
  10835. print_dav_dir_entry(struct de *de, void *data)
  10836. {
  10837. struct mg_connection *conn = (struct mg_connection *)data;
  10838. if (!de || !conn
  10839. || !print_props(
  10840. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10841. /* stop scan */
  10842. return 1;
  10843. }
  10844. return 0;
  10845. }
  10846. static void
  10847. handle_propfind(struct mg_connection *conn,
  10848. const char *path,
  10849. struct mg_file_stat *filep)
  10850. {
  10851. const char *depth = mg_get_header(conn, "Depth");
  10852. char date[64];
  10853. time_t curtime = time(NULL);
  10854. gmt_time_string(date, sizeof(date), &curtime);
  10855. if (!conn || !path || !filep || !conn->dom_ctx) {
  10856. return;
  10857. }
  10858. conn->must_close = 1;
  10859. /* return 207 "Multi-Status" */
  10860. mg_response_header_start(conn, 207);
  10861. send_static_cache_header(conn);
  10862. send_additional_header(conn);
  10863. mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10864. mg_response_header_send(conn);
  10865. /* Content */
  10866. mg_printf(conn,
  10867. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10868. "<d:multistatus xmlns:d='DAV:'>\n");
  10869. /* Print properties for the requested resource itself */
  10870. print_props(conn, conn->request_info.local_uri, "", filep);
  10871. /* If it is a directory, print directory entries too if Depth is not 0
  10872. */
  10873. if (filep->is_directory
  10874. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10875. "yes")
  10876. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10877. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10878. }
  10879. mg_printf(conn, "%s\n", "</d:multistatus>");
  10880. }
  10881. #endif
  10882. void
  10883. mg_lock_connection(struct mg_connection *conn)
  10884. {
  10885. if (conn) {
  10886. (void)pthread_mutex_lock(&conn->mutex);
  10887. }
  10888. }
  10889. void
  10890. mg_unlock_connection(struct mg_connection *conn)
  10891. {
  10892. if (conn) {
  10893. (void)pthread_mutex_unlock(&conn->mutex);
  10894. }
  10895. }
  10896. void
  10897. mg_lock_context(struct mg_context *ctx)
  10898. {
  10899. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10900. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10901. }
  10902. }
  10903. void
  10904. mg_unlock_context(struct mg_context *ctx)
  10905. {
  10906. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10907. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10908. }
  10909. }
  10910. #if defined(USE_LUA)
  10911. #include "mod_lua.inl"
  10912. #endif /* USE_LUA */
  10913. #if defined(USE_DUKTAPE)
  10914. #include "mod_duktape.inl"
  10915. #endif /* USE_DUKTAPE */
  10916. #if defined(USE_WEBSOCKET)
  10917. #if !defined(NO_SSL_DL)
  10918. #define SHA_API static
  10919. #include "sha1.inl"
  10920. #endif
  10921. static int
  10922. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10923. {
  10924. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10925. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10926. SHA_CTX sha_ctx;
  10927. int truncated;
  10928. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10929. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10930. if (truncated) {
  10931. conn->must_close = 1;
  10932. return 0;
  10933. }
  10934. DEBUG_TRACE("%s", "Send websocket handshake");
  10935. SHA1_Init(&sha_ctx);
  10936. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10937. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10938. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10939. mg_printf(conn,
  10940. "HTTP/1.1 101 Switching Protocols\r\n"
  10941. "Upgrade: websocket\r\n"
  10942. "Connection: Upgrade\r\n"
  10943. "Sec-WebSocket-Accept: %s\r\n",
  10944. b64_sha);
  10945. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10946. // Send negotiated compression extension parameters
  10947. websocket_deflate_response(conn);
  10948. #endif
  10949. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10950. mg_printf(conn,
  10951. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10952. conn->request_info.acceptedWebSocketSubprotocol);
  10953. } else {
  10954. mg_printf(conn, "%s", "\r\n");
  10955. }
  10956. return 1;
  10957. }
  10958. #if !defined(MG_MAX_UNANSWERED_PING)
  10959. /* Configuration of the maximum number of websocket PINGs that might
  10960. * stay unanswered before the connection is considered broken.
  10961. * Note: The name of this define may still change (until it is
  10962. * defined as a compile parameter in a documentation).
  10963. */
  10964. #define MG_MAX_UNANSWERED_PING (5)
  10965. #endif
  10966. static void
  10967. read_websocket(struct mg_connection *conn,
  10968. mg_websocket_data_handler ws_data_handler,
  10969. void *callback_data)
  10970. {
  10971. /* Pointer to the beginning of the portion of the incoming websocket
  10972. * message queue.
  10973. * The original websocket upgrade request is never removed, so the queue
  10974. * begins after it. */
  10975. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10976. int n, error, exit_by_callback;
  10977. int ret;
  10978. /* body_len is the length of the entire queue in bytes
  10979. * len is the length of the current message
  10980. * data_len is the length of the current message's data payload
  10981. * header_len is the length of the current message's header */
  10982. size_t i, len, mask_len = 0, header_len, body_len;
  10983. uint64_t data_len = 0;
  10984. /* "The masking key is a 32-bit value chosen at random by the client."
  10985. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10986. */
  10987. unsigned char mask[4];
  10988. /* data points to the place where the message is stored when passed to
  10989. * the websocket_data callback. This is either mem on the stack, or a
  10990. * dynamically allocated buffer if it is too large. */
  10991. unsigned char mem[4096];
  10992. unsigned char mop; /* mask flag and opcode */
  10993. /* Variables used for connection monitoring */
  10994. double timeout = -1.0;
  10995. int enable_ping_pong = 0;
  10996. int ping_count = 0;
  10997. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10998. enable_ping_pong =
  10999. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11000. "yes");
  11001. }
  11002. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11003. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11004. }
  11005. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11006. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11007. }
  11008. if (timeout <= 0.0) {
  11009. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11010. }
  11011. /* Enter data processing loop */
  11012. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11013. conn->request_info.remote_addr,
  11014. conn->request_info.remote_port);
  11015. conn->in_websocket_handling = 1;
  11016. mg_set_thread_name("wsock");
  11017. /* Loop continuously, reading messages from the socket, invoking the
  11018. * callback, and waiting repeatedly until an error occurs. */
  11019. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11020. && (!conn->must_close)) {
  11021. header_len = 0;
  11022. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11023. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11024. len = buf[1] & 127;
  11025. mask_len = (buf[1] & 128) ? 4 : 0;
  11026. if ((len < 126) && (body_len >= mask_len)) {
  11027. /* inline 7-bit length field */
  11028. data_len = len;
  11029. header_len = 2 + mask_len;
  11030. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11031. /* 16-bit length field */
  11032. header_len = 4 + mask_len;
  11033. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11034. } else if (body_len >= (10 + mask_len)) {
  11035. /* 64-bit length field */
  11036. uint32_t l1, l2;
  11037. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11038. memcpy(&l2, &buf[6], 4);
  11039. header_len = 10 + mask_len;
  11040. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11041. if (data_len > (uint64_t)0x7FFF0000ul) {
  11042. /* no can do */
  11043. mg_cry_internal(
  11044. conn,
  11045. "%s",
  11046. "websocket out of memory; closing connection");
  11047. break;
  11048. }
  11049. }
  11050. }
  11051. if ((header_len > 0) && (body_len >= header_len)) {
  11052. /* Allocate space to hold websocket payload */
  11053. unsigned char *data = mem;
  11054. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11055. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11056. conn->phys_ctx);
  11057. if (data == NULL) {
  11058. /* Allocation failed, exit the loop and then close the
  11059. * connection */
  11060. mg_cry_internal(
  11061. conn,
  11062. "%s",
  11063. "websocket out of memory; closing connection");
  11064. break;
  11065. }
  11066. }
  11067. /* Copy the mask before we shift the queue and destroy it */
  11068. if (mask_len > 0) {
  11069. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11070. } else {
  11071. memset(mask, 0, sizeof(mask));
  11072. }
  11073. /* Read frame payload from the first message in the queue into
  11074. * data and advance the queue by moving the memory in place. */
  11075. DEBUG_ASSERT(body_len >= header_len);
  11076. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11077. mop = buf[0]; /* current mask and opcode */
  11078. /* Overflow case */
  11079. len = body_len - header_len;
  11080. memcpy(data, buf + header_len, len);
  11081. error = 0;
  11082. while ((uint64_t)len < data_len) {
  11083. n = pull_inner(NULL,
  11084. conn,
  11085. (char *)(data + len),
  11086. (int)(data_len - len),
  11087. timeout);
  11088. if (n <= -2) {
  11089. error = 1;
  11090. break;
  11091. } else if (n > 0) {
  11092. len += (size_t)n;
  11093. } else {
  11094. /* Timeout: should retry */
  11095. /* TODO: retry condition */
  11096. }
  11097. }
  11098. if (error) {
  11099. mg_cry_internal(
  11100. conn,
  11101. "%s",
  11102. "Websocket pull failed; closing connection");
  11103. if (data != mem) {
  11104. mg_free(data);
  11105. }
  11106. break;
  11107. }
  11108. conn->data_len = conn->request_len;
  11109. } else {
  11110. mop = buf[0]; /* current mask and opcode, overwritten by
  11111. * memmove() */
  11112. /* Length of the message being read at the front of the
  11113. * queue. Cast to 31 bit is OK, since we limited
  11114. * data_len before. */
  11115. len = (size_t)data_len + header_len;
  11116. /* Copy the data payload into the data pointer for the
  11117. * callback. Cast to 31 bit is OK, since we
  11118. * limited data_len */
  11119. memcpy(data, buf + header_len, (size_t)data_len);
  11120. /* Move the queue forward len bytes */
  11121. memmove(buf, buf + len, body_len - len);
  11122. /* Mark the queue as advanced */
  11123. conn->data_len -= (int)len;
  11124. }
  11125. /* Apply mask if necessary */
  11126. if (mask_len > 0) {
  11127. for (i = 0; i < (size_t)data_len; i++) {
  11128. data[i] ^= mask[i & 3];
  11129. }
  11130. }
  11131. exit_by_callback = 0;
  11132. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11133. /* filter PONG messages */
  11134. DEBUG_TRACE("PONG from %s:%u",
  11135. conn->request_info.remote_addr,
  11136. conn->request_info.remote_port);
  11137. /* No unanwered PINGs left */
  11138. ping_count = 0;
  11139. } else if (enable_ping_pong
  11140. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11141. /* reply PING messages */
  11142. DEBUG_TRACE("Reply PING from %s:%u",
  11143. conn->request_info.remote_addr,
  11144. conn->request_info.remote_port);
  11145. ret = mg_websocket_write(conn,
  11146. MG_WEBSOCKET_OPCODE_PONG,
  11147. (char *)data,
  11148. (size_t)data_len);
  11149. if (ret <= 0) {
  11150. /* Error: send failed */
  11151. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11152. break;
  11153. }
  11154. } else {
  11155. /* Exit the loop if callback signals to exit (server side),
  11156. * or "connection close" opcode received (client side). */
  11157. if (ws_data_handler != NULL) {
  11158. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11159. if (mop & 0x40) {
  11160. /* Inflate the data received if bit RSV1 is set. */
  11161. if (!conn->websocket_deflate_initialized) {
  11162. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11163. exit_by_callback = 1;
  11164. }
  11165. if (!exit_by_callback) {
  11166. size_t inflate_buf_size_old = 0;
  11167. size_t inflate_buf_size =
  11168. data_len
  11169. * 10; // Initial guess of the inflated message
  11170. // size. We double the memory when needed.
  11171. Bytef *inflated;
  11172. Bytef *new_mem;
  11173. conn->websocket_inflate_state.avail_in =
  11174. (uInt)(data_len + 4);
  11175. conn->websocket_inflate_state.next_in = data;
  11176. // Add trailing 0x00 0x00 0xff 0xff bytes
  11177. data[data_len] = '\x00';
  11178. data[data_len + 1] = '\x00';
  11179. data[data_len + 2] = '\xff';
  11180. data[data_len + 3] = '\xff';
  11181. do {
  11182. if (inflate_buf_size_old == 0) {
  11183. new_mem = mg_calloc(inflate_buf_size,
  11184. sizeof(Bytef));
  11185. } else {
  11186. inflate_buf_size *= 2;
  11187. new_mem =
  11188. mg_realloc(inflated, inflate_buf_size);
  11189. }
  11190. if (new_mem == NULL) {
  11191. mg_cry_internal(
  11192. conn,
  11193. "Out of memory: Cannot allocate "
  11194. "inflate buffer of %zu bytes",
  11195. inflate_buf_size);
  11196. exit_by_callback = 1;
  11197. break;
  11198. }
  11199. inflated = new_mem;
  11200. conn->websocket_inflate_state.avail_out =
  11201. (uInt)(inflate_buf_size
  11202. - inflate_buf_size_old);
  11203. conn->websocket_inflate_state.next_out =
  11204. inflated + inflate_buf_size_old;
  11205. int ret =
  11206. inflate(&conn->websocket_inflate_state,
  11207. Z_SYNC_FLUSH);
  11208. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11209. || ret == Z_MEM_ERROR) {
  11210. mg_cry_internal(
  11211. conn,
  11212. "ZLIB inflate error: %i %s",
  11213. ret,
  11214. (conn->websocket_inflate_state.msg
  11215. ? conn->websocket_inflate_state.msg
  11216. : "<no error message>"));
  11217. exit_by_callback = 1;
  11218. break;
  11219. }
  11220. inflate_buf_size_old = inflate_buf_size;
  11221. } while (conn->websocket_inflate_state.avail_out
  11222. == 0);
  11223. inflate_buf_size -=
  11224. conn->websocket_inflate_state.avail_out;
  11225. if (!ws_data_handler(conn,
  11226. mop,
  11227. (char *)inflated,
  11228. inflate_buf_size,
  11229. callback_data)) {
  11230. exit_by_callback = 1;
  11231. }
  11232. mg_free(inflated);
  11233. }
  11234. } else
  11235. #endif
  11236. if (!ws_data_handler(conn,
  11237. mop,
  11238. (char *)data,
  11239. (size_t)data_len,
  11240. callback_data)) {
  11241. exit_by_callback = 1;
  11242. }
  11243. }
  11244. }
  11245. /* It a buffer has been allocated, free it again */
  11246. if (data != mem) {
  11247. mg_free(data);
  11248. }
  11249. if (exit_by_callback) {
  11250. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11251. conn->request_info.remote_addr,
  11252. conn->request_info.remote_port);
  11253. break;
  11254. }
  11255. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11256. /* Opcode == 8, connection close */
  11257. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11258. conn->request_info.remote_addr,
  11259. conn->request_info.remote_port);
  11260. break;
  11261. }
  11262. /* Not breaking the loop, process next websocket frame. */
  11263. } else {
  11264. /* Read from the socket into the next available location in the
  11265. * message queue. */
  11266. n = pull_inner(NULL,
  11267. conn,
  11268. conn->buf + conn->data_len,
  11269. conn->buf_size - conn->data_len,
  11270. timeout);
  11271. if (n <= -2) {
  11272. /* Error, no bytes read */
  11273. DEBUG_TRACE("PULL from %s:%u failed",
  11274. conn->request_info.remote_addr,
  11275. conn->request_info.remote_port);
  11276. break;
  11277. }
  11278. if (n > 0) {
  11279. conn->data_len += n;
  11280. /* Reset open PING count */
  11281. ping_count = 0;
  11282. } else {
  11283. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11284. && (!conn->must_close)) {
  11285. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11286. /* Stop sending PING */
  11287. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11288. "- closing connection",
  11289. ping_count,
  11290. conn->request_info.remote_addr,
  11291. conn->request_info.remote_port);
  11292. break;
  11293. }
  11294. if (enable_ping_pong) {
  11295. /* Send Websocket PING message */
  11296. DEBUG_TRACE("PING to %s:%u",
  11297. conn->request_info.remote_addr,
  11298. conn->request_info.remote_port);
  11299. ret = mg_websocket_write(conn,
  11300. MG_WEBSOCKET_OPCODE_PING,
  11301. NULL,
  11302. 0);
  11303. if (ret <= 0) {
  11304. /* Error: send failed */
  11305. DEBUG_TRACE("Send PING failed (%i)", ret);
  11306. break;
  11307. }
  11308. ping_count++;
  11309. }
  11310. }
  11311. /* Timeout: should retry */
  11312. /* TODO: get timeout def */
  11313. }
  11314. }
  11315. }
  11316. /* Leave data processing loop */
  11317. mg_set_thread_name("worker");
  11318. conn->in_websocket_handling = 0;
  11319. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11320. conn->request_info.remote_addr,
  11321. conn->request_info.remote_port);
  11322. }
  11323. static int
  11324. mg_websocket_write_exec(struct mg_connection *conn,
  11325. int opcode,
  11326. const char *data,
  11327. size_t dataLen,
  11328. uint32_t masking_key)
  11329. {
  11330. unsigned char header[14];
  11331. size_t headerLen;
  11332. int retval;
  11333. #if defined(GCC_DIAGNOSTIC)
  11334. /* Disable spurious conversion warning for GCC */
  11335. #pragma GCC diagnostic push
  11336. #pragma GCC diagnostic ignored "-Wconversion"
  11337. #endif
  11338. /* Note that POSIX/Winsock's send() is threadsafe
  11339. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11340. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11341. * push(), although that is only a problem if the packet is large or
  11342. * outgoing buffer is full). */
  11343. /* TODO: Check if this lock should be moved to user land.
  11344. * Currently the server sets this lock for websockets, but
  11345. * not for any other connection. It must be set for every
  11346. * conn read/written by more than one thread, no matter if
  11347. * it is a websocket or regular connection. */
  11348. (void)mg_lock_connection(conn);
  11349. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11350. size_t deflated_size;
  11351. Bytef *deflated;
  11352. // Deflate websocket messages over 100kb
  11353. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11354. if (use_deflate) {
  11355. if (!conn->websocket_deflate_initialized) {
  11356. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11357. return 0;
  11358. }
  11359. // Deflating the message
  11360. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11361. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11362. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11363. deflated_size = compressBound((uLong)dataLen);
  11364. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11365. if (deflated == NULL) {
  11366. mg_cry_internal(
  11367. conn,
  11368. "Out of memory: Cannot allocate deflate buffer of %zu bytes",
  11369. deflated_size);
  11370. mg_unlock_connection(conn);
  11371. return -1;
  11372. }
  11373. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11374. conn->websocket_deflate_state.next_out = deflated;
  11375. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11376. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11377. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11378. } else
  11379. #endif
  11380. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11381. #if defined(GCC_DIAGNOSTIC)
  11382. #pragma GCC diagnostic pop
  11383. #endif
  11384. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11385. if (dataLen < 126) {
  11386. /* inline 7-bit length field */
  11387. header[1] = (unsigned char)dataLen;
  11388. headerLen = 2;
  11389. } else if (dataLen <= 0xFFFF) {
  11390. /* 16-bit length field */
  11391. uint16_t len = htons((uint16_t)dataLen);
  11392. header[1] = 126;
  11393. memcpy(header + 2, &len, 2);
  11394. headerLen = 4;
  11395. } else {
  11396. /* 64-bit length field */
  11397. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11398. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11399. header[1] = 127;
  11400. memcpy(header + 2, &len1, 4);
  11401. memcpy(header + 6, &len2, 4);
  11402. headerLen = 10;
  11403. }
  11404. if (masking_key) {
  11405. /* add mask */
  11406. header[1] |= 0x80;
  11407. memcpy(header + headerLen, &masking_key, 4);
  11408. headerLen += 4;
  11409. }
  11410. retval = mg_write(conn, header, headerLen);
  11411. if (retval != (int)headerLen) {
  11412. /* Did not send complete header */
  11413. retval = -1;
  11414. } else {
  11415. if (dataLen > 0) {
  11416. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11417. if (use_deflate) {
  11418. retval = mg_write(conn, deflated, dataLen);
  11419. mg_free(deflated);
  11420. } else
  11421. #endif
  11422. retval = mg_write(conn, data, dataLen);
  11423. }
  11424. /* if dataLen == 0, the header length (2) is returned */
  11425. }
  11426. /* TODO: Remove this unlock as well, when lock is removed. */
  11427. mg_unlock_connection(conn);
  11428. return retval;
  11429. }
  11430. int
  11431. mg_websocket_write(struct mg_connection *conn,
  11432. int opcode,
  11433. const char *data,
  11434. size_t dataLen)
  11435. {
  11436. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11437. }
  11438. static void
  11439. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11440. {
  11441. size_t i = 0;
  11442. i = 0;
  11443. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11444. /* Convert in 32 bit words, if data is 4 byte aligned */
  11445. while (i < (in_len - 3)) {
  11446. *(uint32_t *)(void *)(out + i) =
  11447. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11448. i += 4;
  11449. }
  11450. }
  11451. if (i != in_len) {
  11452. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11453. while (i < in_len) {
  11454. *(uint8_t *)(void *)(out + i) =
  11455. *(uint8_t *)(void *)(in + i)
  11456. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11457. i++;
  11458. }
  11459. }
  11460. }
  11461. int
  11462. mg_websocket_client_write(struct mg_connection *conn,
  11463. int opcode,
  11464. const char *data,
  11465. size_t dataLen)
  11466. {
  11467. int retval = -1;
  11468. char *masked_data =
  11469. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11470. uint32_t masking_key = 0;
  11471. if (masked_data == NULL) {
  11472. /* Return -1 in an error case */
  11473. mg_cry_internal(conn,
  11474. "%s",
  11475. "Cannot allocate buffer for masked websocket response: "
  11476. "Out of memory");
  11477. return -1;
  11478. }
  11479. do {
  11480. /* Get a masking key - but not 0 */
  11481. masking_key = (uint32_t)get_random();
  11482. } while (masking_key == 0);
  11483. mask_data(data, dataLen, masking_key, masked_data);
  11484. retval = mg_websocket_write_exec(
  11485. conn, opcode, masked_data, dataLen, masking_key);
  11486. mg_free(masked_data);
  11487. return retval;
  11488. }
  11489. static void
  11490. handle_websocket_request(struct mg_connection *conn,
  11491. const char *path,
  11492. int is_callback_resource,
  11493. struct mg_websocket_subprotocols *subprotocols,
  11494. mg_websocket_connect_handler ws_connect_handler,
  11495. mg_websocket_ready_handler ws_ready_handler,
  11496. mg_websocket_data_handler ws_data_handler,
  11497. mg_websocket_close_handler ws_close_handler,
  11498. void *cbData)
  11499. {
  11500. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11501. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11502. ptrdiff_t lua_websock = 0;
  11503. #if !defined(USE_LUA)
  11504. (void)path;
  11505. #endif
  11506. /* Step 1: Check websocket protocol version. */
  11507. /* Step 1.1: Check Sec-WebSocket-Key. */
  11508. if (!websock_key) {
  11509. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11510. * requires a Sec-WebSocket-Key header.
  11511. */
  11512. /* It could be the hixie draft version
  11513. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11514. */
  11515. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11516. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11517. char key3[8];
  11518. if ((key1 != NULL) && (key2 != NULL)) {
  11519. /* This version uses 8 byte body data in a GET request */
  11520. conn->content_len = 8;
  11521. if (8 == mg_read(conn, key3, 8)) {
  11522. /* This is the hixie version */
  11523. mg_send_http_error(conn,
  11524. 426,
  11525. "%s",
  11526. "Protocol upgrade to RFC 6455 required");
  11527. return;
  11528. }
  11529. }
  11530. /* This is an unknown version */
  11531. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11532. return;
  11533. }
  11534. /* Step 1.2: Check websocket protocol version. */
  11535. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11536. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11537. /* Reject wrong versions */
  11538. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11539. return;
  11540. }
  11541. /* Step 1.3: Could check for "Host", but we do not really nead this
  11542. * value for anything, so just ignore it. */
  11543. /* Step 2: If a callback is responsible, call it. */
  11544. if (is_callback_resource) {
  11545. /* Step 2.1 check and select subprotocol */
  11546. const char *protocols[64]; // max 64 headers
  11547. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11548. "Sec-WebSocket-Protocol",
  11549. protocols,
  11550. 64);
  11551. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11552. int cnt = 0;
  11553. int idx;
  11554. unsigned long len;
  11555. const char *sep, *curSubProtocol,
  11556. *acceptedWebSocketSubprotocol = NULL;
  11557. /* look for matching subprotocol */
  11558. do {
  11559. const char *protocol = protocols[cnt];
  11560. do {
  11561. sep = strchr(protocol, ',');
  11562. curSubProtocol = protocol;
  11563. len = sep ? (unsigned long)(sep - protocol)
  11564. : (unsigned long)strlen(protocol);
  11565. while (sep && isspace((unsigned char)*++sep))
  11566. ; // ignore leading whitespaces
  11567. protocol = sep;
  11568. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11569. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11570. && (strncmp(curSubProtocol,
  11571. subprotocols->subprotocols[idx],
  11572. len)
  11573. == 0)) {
  11574. acceptedWebSocketSubprotocol =
  11575. subprotocols->subprotocols[idx];
  11576. break;
  11577. }
  11578. }
  11579. } while (sep && !acceptedWebSocketSubprotocol);
  11580. } while (++cnt < nbSubprotocolHeader
  11581. && !acceptedWebSocketSubprotocol);
  11582. conn->request_info.acceptedWebSocketSubprotocol =
  11583. acceptedWebSocketSubprotocol;
  11584. } else if (nbSubprotocolHeader > 0) {
  11585. /* keep legacy behavior */
  11586. const char *protocol = protocols[0];
  11587. /* The protocol is a comma separated list of names. */
  11588. /* The server must only return one value from this list. */
  11589. /* First check if it is a list or just a single value. */
  11590. const char *sep = strrchr(protocol, ',');
  11591. if (sep == NULL) {
  11592. /* Just a single protocol -> accept it. */
  11593. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11594. } else {
  11595. /* Multiple protocols -> accept the last one. */
  11596. /* This is just a quick fix if the client offers multiple
  11597. * protocols. The handler should have a list of accepted
  11598. * protocols on his own
  11599. * and use it to select one protocol among those the client
  11600. * has
  11601. * offered.
  11602. */
  11603. while (isspace((unsigned char)*++sep)) {
  11604. ; /* ignore leading whitespaces */
  11605. }
  11606. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11607. }
  11608. }
  11609. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11610. websocket_deflate_negotiate(conn);
  11611. #endif
  11612. if ((ws_connect_handler != NULL)
  11613. && (ws_connect_handler(conn, cbData) != 0)) {
  11614. /* C callback has returned non-zero, do not proceed with
  11615. * handshake.
  11616. */
  11617. /* Note that C callbacks are no longer called when Lua is
  11618. * responsible, so C can no longer filter callbacks for Lua. */
  11619. return;
  11620. }
  11621. }
  11622. #if defined(USE_LUA)
  11623. /* Step 3: No callback. Check if Lua is responsible. */
  11624. else {
  11625. /* Step 3.1: Check if Lua is responsible. */
  11626. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11627. lua_websock = match_prefix_strlen(
  11628. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11629. }
  11630. if (lua_websock) {
  11631. /* Step 3.2: Lua is responsible: call it. */
  11632. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11633. if (!conn->lua_websocket_state) {
  11634. /* Lua rejected the new client */
  11635. return;
  11636. }
  11637. }
  11638. }
  11639. #endif
  11640. /* Step 4: Check if there is a responsible websocket handler. */
  11641. if (!is_callback_resource && !lua_websock) {
  11642. /* There is no callback, and Lua is not responsible either. */
  11643. /* Reply with a 404 Not Found. We are still at a standard
  11644. * HTTP request here, before the websocket handshake, so
  11645. * we can still send standard HTTP error replies. */
  11646. mg_send_http_error(conn, 404, "%s", "Not found");
  11647. return;
  11648. }
  11649. /* Step 5: The websocket connection has been accepted */
  11650. if (!send_websocket_handshake(conn, websock_key)) {
  11651. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11652. return;
  11653. }
  11654. /* Step 6: Call the ready handler */
  11655. if (is_callback_resource) {
  11656. if (ws_ready_handler != NULL) {
  11657. ws_ready_handler(conn, cbData);
  11658. }
  11659. #if defined(USE_LUA)
  11660. } else if (lua_websock) {
  11661. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11662. /* the ready handler returned false */
  11663. return;
  11664. }
  11665. #endif
  11666. }
  11667. /* Step 7: Enter the read loop */
  11668. if (is_callback_resource) {
  11669. read_websocket(conn, ws_data_handler, cbData);
  11670. #if defined(USE_LUA)
  11671. } else if (lua_websock) {
  11672. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11673. #endif
  11674. }
  11675. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11676. /* Step 8: Close the deflate & inflate buffers */
  11677. if (conn->websocket_deflate_initialized) {
  11678. deflateEnd(&conn->websocket_deflate_state);
  11679. inflateEnd(&conn->websocket_inflate_state);
  11680. }
  11681. #endif
  11682. /* Step 9: Call the close handler */
  11683. if (ws_close_handler) {
  11684. ws_close_handler(conn, cbData);
  11685. }
  11686. }
  11687. #endif /* !USE_WEBSOCKET */
  11688. /* Is upgrade request:
  11689. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11690. * 1 = upgrade to websocket
  11691. * 2 = upgrade to HTTP/2
  11692. * -1 = upgrade to unknown protocol
  11693. */
  11694. static int
  11695. should_switch_to_protocol(const struct mg_connection *conn)
  11696. {
  11697. const char *upgrade, *connection;
  11698. /* A websocket protocoll has the following HTTP headers:
  11699. *
  11700. * Connection: Upgrade
  11701. * Upgrade: Websocket
  11702. */
  11703. connection = mg_get_header(conn, "Connection");
  11704. if (connection == NULL) {
  11705. return PROTOCOL_TYPE_HTTP1;
  11706. }
  11707. if (!mg_strcasestr(connection, "upgrade")) {
  11708. return PROTOCOL_TYPE_HTTP1;
  11709. }
  11710. upgrade = mg_get_header(conn, "Upgrade");
  11711. if (upgrade == NULL) {
  11712. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11713. return -1;
  11714. }
  11715. /* Upgrade to ... */
  11716. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11717. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11718. * "Sec-WebSocket-Version" are also required.
  11719. * Don't check them here, since even an unsupported websocket protocol
  11720. * request still IS a websocket request (in contrast to a standard HTTP
  11721. * request). It will fail later in handle_websocket_request.
  11722. */
  11723. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11724. }
  11725. if (0 != mg_strcasestr(upgrade, "h2")) {
  11726. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11727. }
  11728. /* Upgrade to another protocol */
  11729. return -1;
  11730. }
  11731. static int
  11732. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11733. {
  11734. int n;
  11735. unsigned int a, b, c, d, slash;
  11736. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11737. slash = 32;
  11738. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11739. n = 0;
  11740. }
  11741. }
  11742. if ((n > 0) && ((size_t)n == vec->len)) {
  11743. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11744. /* IPv4 format */
  11745. if (sa->sa.sa_family == AF_INET) {
  11746. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11747. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11748. | ((uint32_t)c << 8) | (uint32_t)d;
  11749. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11750. return (ip & mask) == net;
  11751. }
  11752. return 0;
  11753. }
  11754. }
  11755. #if defined(USE_IPV6)
  11756. else {
  11757. char ad[50];
  11758. const char *p;
  11759. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11760. slash = 128;
  11761. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11762. n = 0;
  11763. }
  11764. }
  11765. if ((n <= 0) && no_strict) {
  11766. /* no square brackets? */
  11767. p = strchr(vec->ptr, '/');
  11768. if (p && (p < (vec->ptr + vec->len))) {
  11769. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11770. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11771. n += (int)(p - vec->ptr);
  11772. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11773. } else {
  11774. n = 0;
  11775. }
  11776. } else if (vec->len < sizeof(ad)) {
  11777. n = (int)vec->len;
  11778. slash = 128;
  11779. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11780. }
  11781. }
  11782. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11783. p = ad;
  11784. c = 0;
  11785. /* zone indexes are unsupported, at least two colons are needed */
  11786. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11787. if (*(p++) == ':') {
  11788. c++;
  11789. }
  11790. }
  11791. if ((*p == '\0') && (c >= 2)) {
  11792. struct sockaddr_in6 sin6;
  11793. unsigned int i;
  11794. /* for strict validation, an actual IPv6 argument is needed */
  11795. if (sa->sa.sa_family != AF_INET6) {
  11796. return 0;
  11797. }
  11798. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11799. /* IPv6 format */
  11800. for (i = 0; i < 16; i++) {
  11801. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11802. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11803. uint8_t mask = 0;
  11804. if (8 * i + 8 < slash) {
  11805. mask = 0xFFu;
  11806. } else if (8 * i < slash) {
  11807. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11808. }
  11809. if ((ip & mask) != net) {
  11810. return 0;
  11811. }
  11812. }
  11813. return 1;
  11814. }
  11815. }
  11816. }
  11817. }
  11818. #else
  11819. (void)no_strict;
  11820. #endif
  11821. /* malformed */
  11822. return -1;
  11823. }
  11824. static int
  11825. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11826. {
  11827. int throttle = 0;
  11828. struct vec vec, val;
  11829. char mult;
  11830. double v;
  11831. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11832. mult = ',';
  11833. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11834. || (v < 0)
  11835. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11836. && (mult != ','))) {
  11837. continue;
  11838. }
  11839. v *= (lowercase(&mult) == 'k')
  11840. ? 1024
  11841. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11842. if (vec.len == 1 && vec.ptr[0] == '*') {
  11843. throttle = (int)v;
  11844. } else {
  11845. int matched = parse_match_net(&vec, rsa, 0);
  11846. if (matched >= 0) {
  11847. /* a valid IP subnet */
  11848. if (matched) {
  11849. throttle = (int)v;
  11850. }
  11851. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11852. throttle = (int)v;
  11853. }
  11854. }
  11855. }
  11856. return throttle;
  11857. }
  11858. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11859. #include "handle_form.inl"
  11860. static int
  11861. get_first_ssl_listener_index(const struct mg_context *ctx)
  11862. {
  11863. unsigned int i;
  11864. int idx = -1;
  11865. if (ctx) {
  11866. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11867. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11868. }
  11869. }
  11870. return idx;
  11871. }
  11872. /* Return host (without port) */
  11873. static void
  11874. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11875. {
  11876. const char *host_header =
  11877. get_header(ri->http_headers, ri->num_headers, "Host");
  11878. host->ptr = NULL;
  11879. host->len = 0;
  11880. if (host_header != NULL) {
  11881. char *pos;
  11882. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11883. * is found. */
  11884. if (*host_header == '[') {
  11885. pos = strchr(host_header, ']');
  11886. if (!pos) {
  11887. /* Malformed hostname starts with '[', but no ']' found */
  11888. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11889. return;
  11890. }
  11891. /* terminate after ']' */
  11892. host->ptr = host_header;
  11893. host->len = (size_t)(pos + 1 - host_header);
  11894. } else {
  11895. /* Otherwise, a ':' separates hostname and port number */
  11896. pos = strchr(host_header, ':');
  11897. if (pos != NULL) {
  11898. host->len = (size_t)(pos - host_header);
  11899. } else {
  11900. host->len = strlen(host_header);
  11901. }
  11902. host->ptr = host_header;
  11903. }
  11904. }
  11905. }
  11906. static int
  11907. switch_domain_context(struct mg_connection *conn)
  11908. {
  11909. struct vec host;
  11910. get_host_from_request_info(&host, &conn->request_info);
  11911. if (host.ptr) {
  11912. if (conn->ssl) {
  11913. /* This is a HTTPS connection, maybe we have a hostname
  11914. * from SNI (set in ssl_servername_callback). */
  11915. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11916. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11917. /* We are not using the default domain */
  11918. if ((strlen(sslhost) != host.len)
  11919. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11920. /* Mismatch between SNI domain and HTTP domain */
  11921. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11922. sslhost,
  11923. (int)host.len,
  11924. host.ptr);
  11925. return 0;
  11926. }
  11927. }
  11928. } else {
  11929. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11930. while (dom) {
  11931. if ((strlen(dom->config[AUTHENTICATION_DOMAIN]) == host.len)
  11932. && !mg_strncasecmp(host.ptr,
  11933. dom->config[AUTHENTICATION_DOMAIN],
  11934. host.len)) {
  11935. /* Found matching domain */
  11936. DEBUG_TRACE("HTTP domain %s found",
  11937. dom->config[AUTHENTICATION_DOMAIN]);
  11938. /* TODO: Check if this is a HTTP or HTTPS domain */
  11939. conn->dom_ctx = dom;
  11940. break;
  11941. }
  11942. mg_lock_context(conn->phys_ctx);
  11943. dom = dom->next;
  11944. mg_unlock_context(conn->phys_ctx);
  11945. }
  11946. }
  11947. } else {
  11948. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11949. return 1;
  11950. }
  11951. DEBUG_TRACE("HTTP%s Host: %.*s",
  11952. conn->ssl ? "S" : "",
  11953. (int)host.len,
  11954. host.ptr);
  11955. return 1;
  11956. }
  11957. static int mg_construct_local_link(const struct mg_connection *conn,
  11958. char *buf,
  11959. size_t buflen,
  11960. const char *define_proto,
  11961. int define_port,
  11962. const char *define_uri);
  11963. static void
  11964. redirect_to_https_port(struct mg_connection *conn, int port)
  11965. {
  11966. char target_url[MG_BUF_LEN];
  11967. int truncated = 0;
  11968. const char *expect_proto =
  11969. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11970. /* Use "308 Permanent Redirect" */
  11971. int redirect_code = 308;
  11972. /* In any case, close the current connection */
  11973. conn->must_close = 1;
  11974. /* Send host, port, uri and (if it exists) ?query_string */
  11975. if (mg_construct_local_link(
  11976. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11977. < 0) {
  11978. truncated = 1;
  11979. } else if (conn->request_info.query_string != NULL) {
  11980. size_t slen1 = strlen(target_url);
  11981. size_t slen2 = strlen(conn->request_info.query_string);
  11982. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11983. target_url[slen1] = '?';
  11984. memcpy(target_url + slen1 + 1,
  11985. conn->request_info.query_string,
  11986. slen2);
  11987. target_url[slen1 + slen2 + 1] = 0;
  11988. } else {
  11989. truncated = 1;
  11990. }
  11991. }
  11992. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11993. * is used as buffer size) */
  11994. if (truncated) {
  11995. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11996. return;
  11997. }
  11998. /* Use redirect helper function */
  11999. mg_send_http_redirect(conn, target_url, redirect_code);
  12000. }
  12001. static void
  12002. mg_set_handler_type(struct mg_context *phys_ctx,
  12003. struct mg_domain_context *dom_ctx,
  12004. const char *uri,
  12005. int handler_type,
  12006. int is_delete_request,
  12007. mg_request_handler handler,
  12008. struct mg_websocket_subprotocols *subprotocols,
  12009. mg_websocket_connect_handler connect_handler,
  12010. mg_websocket_ready_handler ready_handler,
  12011. mg_websocket_data_handler data_handler,
  12012. mg_websocket_close_handler close_handler,
  12013. mg_authorization_handler auth_handler,
  12014. void *cbdata)
  12015. {
  12016. struct mg_handler_info *tmp_rh, **lastref;
  12017. size_t urilen = strlen(uri);
  12018. if (handler_type == WEBSOCKET_HANDLER) {
  12019. DEBUG_ASSERT(handler == NULL);
  12020. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12021. || ready_handler != NULL || data_handler != NULL
  12022. || close_handler != NULL);
  12023. DEBUG_ASSERT(auth_handler == NULL);
  12024. if (handler != NULL) {
  12025. return;
  12026. }
  12027. if (!is_delete_request && (connect_handler == NULL)
  12028. && (ready_handler == NULL) && (data_handler == NULL)
  12029. && (close_handler == NULL)) {
  12030. return;
  12031. }
  12032. if (auth_handler != NULL) {
  12033. return;
  12034. }
  12035. } else if (handler_type == REQUEST_HANDLER) {
  12036. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12037. && data_handler == NULL && close_handler == NULL);
  12038. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12039. DEBUG_ASSERT(auth_handler == NULL);
  12040. if ((connect_handler != NULL) || (ready_handler != NULL)
  12041. || (data_handler != NULL) || (close_handler != NULL)) {
  12042. return;
  12043. }
  12044. if (!is_delete_request && (handler == NULL)) {
  12045. return;
  12046. }
  12047. if (auth_handler != NULL) {
  12048. return;
  12049. }
  12050. } else { /* AUTH_HANDLER */
  12051. DEBUG_ASSERT(handler == NULL);
  12052. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12053. && data_handler == NULL && close_handler == NULL);
  12054. DEBUG_ASSERT(auth_handler != NULL);
  12055. if (handler != NULL) {
  12056. return;
  12057. }
  12058. if ((connect_handler != NULL) || (ready_handler != NULL)
  12059. || (data_handler != NULL) || (close_handler != NULL)) {
  12060. return;
  12061. }
  12062. if (!is_delete_request && (auth_handler == NULL)) {
  12063. return;
  12064. }
  12065. }
  12066. if (!phys_ctx || !dom_ctx) {
  12067. return;
  12068. }
  12069. mg_lock_context(phys_ctx);
  12070. /* first try to find an existing handler */
  12071. do {
  12072. lastref = &(dom_ctx->handlers);
  12073. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12074. tmp_rh = tmp_rh->next) {
  12075. if (tmp_rh->handler_type == handler_type
  12076. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12077. if (!is_delete_request) {
  12078. /* update existing handler */
  12079. if (handler_type == REQUEST_HANDLER) {
  12080. /* Wait for end of use before updating */
  12081. if (tmp_rh->refcount) {
  12082. mg_unlock_context(phys_ctx);
  12083. mg_sleep(1);
  12084. mg_lock_context(phys_ctx);
  12085. /* tmp_rh might have been freed, search again. */
  12086. break;
  12087. }
  12088. /* Ok, the handler is no more use -> Update it */
  12089. tmp_rh->handler = handler;
  12090. } else if (handler_type == WEBSOCKET_HANDLER) {
  12091. tmp_rh->subprotocols = subprotocols;
  12092. tmp_rh->connect_handler = connect_handler;
  12093. tmp_rh->ready_handler = ready_handler;
  12094. tmp_rh->data_handler = data_handler;
  12095. tmp_rh->close_handler = close_handler;
  12096. } else { /* AUTH_HANDLER */
  12097. tmp_rh->auth_handler = auth_handler;
  12098. }
  12099. tmp_rh->cbdata = cbdata;
  12100. } else {
  12101. /* remove existing handler */
  12102. if (handler_type == REQUEST_HANDLER) {
  12103. /* Wait for end of use before removing */
  12104. if (tmp_rh->refcount) {
  12105. tmp_rh->removing = 1;
  12106. mg_unlock_context(phys_ctx);
  12107. mg_sleep(1);
  12108. mg_lock_context(phys_ctx);
  12109. /* tmp_rh might have been freed, search again. */
  12110. break;
  12111. }
  12112. /* Ok, the handler is no more used */
  12113. }
  12114. *lastref = tmp_rh->next;
  12115. mg_free(tmp_rh->uri);
  12116. mg_free(tmp_rh);
  12117. }
  12118. mg_unlock_context(phys_ctx);
  12119. return;
  12120. }
  12121. lastref = &(tmp_rh->next);
  12122. }
  12123. } while (tmp_rh != NULL);
  12124. if (is_delete_request) {
  12125. /* no handler to set, this was a remove request to a non-existing
  12126. * handler */
  12127. mg_unlock_context(phys_ctx);
  12128. return;
  12129. }
  12130. tmp_rh =
  12131. (struct mg_handler_info *)mg_calloc_ctx(1,
  12132. sizeof(struct mg_handler_info),
  12133. phys_ctx);
  12134. if (tmp_rh == NULL) {
  12135. mg_unlock_context(phys_ctx);
  12136. mg_cry_ctx_internal(phys_ctx,
  12137. "%s",
  12138. "Cannot create new request handler struct, OOM");
  12139. return;
  12140. }
  12141. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12142. if (!tmp_rh->uri) {
  12143. mg_unlock_context(phys_ctx);
  12144. mg_free(tmp_rh);
  12145. mg_cry_ctx_internal(phys_ctx,
  12146. "%s",
  12147. "Cannot create new request handler struct, OOM");
  12148. return;
  12149. }
  12150. tmp_rh->uri_len = urilen;
  12151. if (handler_type == REQUEST_HANDLER) {
  12152. tmp_rh->refcount = 0;
  12153. tmp_rh->removing = 0;
  12154. tmp_rh->handler = handler;
  12155. } else if (handler_type == WEBSOCKET_HANDLER) {
  12156. tmp_rh->subprotocols = subprotocols;
  12157. tmp_rh->connect_handler = connect_handler;
  12158. tmp_rh->ready_handler = ready_handler;
  12159. tmp_rh->data_handler = data_handler;
  12160. tmp_rh->close_handler = close_handler;
  12161. } else { /* AUTH_HANDLER */
  12162. tmp_rh->auth_handler = auth_handler;
  12163. }
  12164. tmp_rh->cbdata = cbdata;
  12165. tmp_rh->handler_type = handler_type;
  12166. tmp_rh->next = NULL;
  12167. *lastref = tmp_rh;
  12168. mg_unlock_context(phys_ctx);
  12169. }
  12170. void
  12171. mg_set_request_handler(struct mg_context *ctx,
  12172. const char *uri,
  12173. mg_request_handler handler,
  12174. void *cbdata)
  12175. {
  12176. mg_set_handler_type(ctx,
  12177. &(ctx->dd),
  12178. uri,
  12179. REQUEST_HANDLER,
  12180. handler == NULL,
  12181. handler,
  12182. NULL,
  12183. NULL,
  12184. NULL,
  12185. NULL,
  12186. NULL,
  12187. NULL,
  12188. cbdata);
  12189. }
  12190. void
  12191. mg_set_websocket_handler(struct mg_context *ctx,
  12192. const char *uri,
  12193. mg_websocket_connect_handler connect_handler,
  12194. mg_websocket_ready_handler ready_handler,
  12195. mg_websocket_data_handler data_handler,
  12196. mg_websocket_close_handler close_handler,
  12197. void *cbdata)
  12198. {
  12199. mg_set_websocket_handler_with_subprotocols(ctx,
  12200. uri,
  12201. NULL,
  12202. connect_handler,
  12203. ready_handler,
  12204. data_handler,
  12205. close_handler,
  12206. cbdata);
  12207. }
  12208. void
  12209. mg_set_websocket_handler_with_subprotocols(
  12210. struct mg_context *ctx,
  12211. const char *uri,
  12212. struct mg_websocket_subprotocols *subprotocols,
  12213. mg_websocket_connect_handler connect_handler,
  12214. mg_websocket_ready_handler ready_handler,
  12215. mg_websocket_data_handler data_handler,
  12216. mg_websocket_close_handler close_handler,
  12217. void *cbdata)
  12218. {
  12219. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12220. && (data_handler == NULL)
  12221. && (close_handler == NULL);
  12222. mg_set_handler_type(ctx,
  12223. &(ctx->dd),
  12224. uri,
  12225. WEBSOCKET_HANDLER,
  12226. is_delete_request,
  12227. NULL,
  12228. subprotocols,
  12229. connect_handler,
  12230. ready_handler,
  12231. data_handler,
  12232. close_handler,
  12233. NULL,
  12234. cbdata);
  12235. }
  12236. void
  12237. mg_set_auth_handler(struct mg_context *ctx,
  12238. const char *uri,
  12239. mg_authorization_handler handler,
  12240. void *cbdata)
  12241. {
  12242. mg_set_handler_type(ctx,
  12243. &(ctx->dd),
  12244. uri,
  12245. AUTH_HANDLER,
  12246. handler == NULL,
  12247. NULL,
  12248. NULL,
  12249. NULL,
  12250. NULL,
  12251. NULL,
  12252. NULL,
  12253. handler,
  12254. cbdata);
  12255. }
  12256. static int
  12257. get_request_handler(struct mg_connection *conn,
  12258. int handler_type,
  12259. mg_request_handler *handler,
  12260. struct mg_websocket_subprotocols **subprotocols,
  12261. mg_websocket_connect_handler *connect_handler,
  12262. mg_websocket_ready_handler *ready_handler,
  12263. mg_websocket_data_handler *data_handler,
  12264. mg_websocket_close_handler *close_handler,
  12265. mg_authorization_handler *auth_handler,
  12266. void **cbdata,
  12267. struct mg_handler_info **handler_info)
  12268. {
  12269. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12270. if (request_info) {
  12271. const char *uri = request_info->local_uri;
  12272. size_t urilen = strlen(uri);
  12273. struct mg_handler_info *tmp_rh;
  12274. int step, matched;
  12275. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12276. return 0;
  12277. }
  12278. mg_lock_context(conn->phys_ctx);
  12279. for (step = 0; step < 3; step++) {
  12280. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12281. tmp_rh = tmp_rh->next) {
  12282. if (tmp_rh->handler_type != handler_type) {
  12283. continue;
  12284. }
  12285. if (step == 0) {
  12286. /* first try for an exact match */
  12287. matched = (tmp_rh->uri_len == urilen)
  12288. && (strcmp(tmp_rh->uri, uri) == 0);
  12289. } else if (step == 1) {
  12290. /* next try for a partial match, we will accept
  12291. uri/something */
  12292. matched =
  12293. (tmp_rh->uri_len < urilen)
  12294. && (uri[tmp_rh->uri_len] == '/')
  12295. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12296. } else {
  12297. /* finally try for pattern match */
  12298. matched =
  12299. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12300. }
  12301. if (matched) {
  12302. if (handler_type == WEBSOCKET_HANDLER) {
  12303. *subprotocols = tmp_rh->subprotocols;
  12304. *connect_handler = tmp_rh->connect_handler;
  12305. *ready_handler = tmp_rh->ready_handler;
  12306. *data_handler = tmp_rh->data_handler;
  12307. *close_handler = tmp_rh->close_handler;
  12308. } else if (handler_type == REQUEST_HANDLER) {
  12309. if (tmp_rh->removing) {
  12310. /* Treat as none found */
  12311. step = 2;
  12312. break;
  12313. }
  12314. *handler = tmp_rh->handler;
  12315. /* Acquire handler and give it back */
  12316. tmp_rh->refcount++;
  12317. *handler_info = tmp_rh;
  12318. } else { /* AUTH_HANDLER */
  12319. *auth_handler = tmp_rh->auth_handler;
  12320. }
  12321. *cbdata = tmp_rh->cbdata;
  12322. mg_unlock_context(conn->phys_ctx);
  12323. return 1;
  12324. }
  12325. }
  12326. }
  12327. mg_unlock_context(conn->phys_ctx);
  12328. }
  12329. return 0; /* none found */
  12330. }
  12331. /* Check if the script file is in a path, allowed for script files.
  12332. * This can be used if uploading files is possible not only for the server
  12333. * admin, and the upload mechanism does not check the file extension.
  12334. */
  12335. static int
  12336. is_in_script_path(const struct mg_connection *conn, const char *path)
  12337. {
  12338. /* TODO (Feature): Add config value for allowed script path.
  12339. * Default: All allowed. */
  12340. (void)conn;
  12341. (void)path;
  12342. return 1;
  12343. }
  12344. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12345. static int
  12346. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12347. int bits,
  12348. char *data,
  12349. size_t len,
  12350. void *cbdata)
  12351. {
  12352. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12353. if (pcallbacks->websocket_data) {
  12354. return pcallbacks->websocket_data(conn, bits, data, len);
  12355. }
  12356. /* No handler set - assume "OK" */
  12357. return 1;
  12358. }
  12359. static void
  12360. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12361. void *cbdata)
  12362. {
  12363. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12364. if (pcallbacks->connection_close) {
  12365. pcallbacks->connection_close(conn);
  12366. }
  12367. }
  12368. #endif
  12369. /* This is the heart of the Civetweb's logic.
  12370. * This function is called when the request is read, parsed and validated,
  12371. * and Civetweb must decide what action to take: serve a file, or
  12372. * a directory, or call embedded function, etcetera. */
  12373. static void
  12374. handle_request(struct mg_connection *conn)
  12375. {
  12376. struct mg_request_info *ri = &conn->request_info;
  12377. char path[PATH_MAX];
  12378. int uri_len, ssl_index;
  12379. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12380. is_put_or_delete_request = 0, is_callback_resource = 0,
  12381. is_template_text_file = 0;
  12382. int i;
  12383. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12384. mg_request_handler callback_handler = NULL;
  12385. struct mg_handler_info *handler_info = NULL;
  12386. struct mg_websocket_subprotocols *subprotocols;
  12387. mg_websocket_connect_handler ws_connect_handler = NULL;
  12388. mg_websocket_ready_handler ws_ready_handler = NULL;
  12389. mg_websocket_data_handler ws_data_handler = NULL;
  12390. mg_websocket_close_handler ws_close_handler = NULL;
  12391. void *callback_data = NULL;
  12392. mg_authorization_handler auth_handler = NULL;
  12393. void *auth_callback_data = NULL;
  12394. int handler_type;
  12395. time_t curtime = time(NULL);
  12396. char date[64];
  12397. path[0] = 0;
  12398. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12399. conn->request_state = 0;
  12400. /* 1. get the request url */
  12401. /* 1.1. split into url and query string */
  12402. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12403. != NULL) {
  12404. *((char *)conn->request_info.query_string++) = '\0';
  12405. }
  12406. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12407. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12408. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12409. if (ssl_index >= 0) {
  12410. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12411. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12412. redirect_to_https_port(conn, port);
  12413. } else {
  12414. /* A http to https forward port has been specified,
  12415. * but no https port to forward to. */
  12416. mg_send_http_error(conn,
  12417. 503,
  12418. "%s",
  12419. "Error: SSL forward not configured properly");
  12420. mg_cry_internal(conn,
  12421. "%s",
  12422. "Can not redirect to SSL, no SSL port available");
  12423. }
  12424. return;
  12425. }
  12426. uri_len = (int)strlen(ri->local_uri);
  12427. /* 1.3. decode url (if config says so) */
  12428. if (should_decode_url(conn)) {
  12429. mg_url_decode(
  12430. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12431. if (conn->request_info.query_string) {
  12432. url_decode_in_place((char *)conn->request_info.query_string);
  12433. }
  12434. }
  12435. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12436. * not possible */
  12437. remove_dot_segments((char *)ri->local_uri);
  12438. /* step 1. completed, the url is known now */
  12439. uri_len = (int)strlen(ri->local_uri);
  12440. DEBUG_TRACE("URL: %s", ri->local_uri);
  12441. /* 2. if this ip has limited speed, set it for this connection */
  12442. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12443. &conn->client.rsa,
  12444. ri->local_uri);
  12445. /* 3. call a "handle everything" callback, if registered */
  12446. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12447. /* Note that since V1.7 the "begin_request" function is called
  12448. * before an authorization check. If an authorization check is
  12449. * required, use a request_handler instead. */
  12450. i = conn->phys_ctx->callbacks.begin_request(conn);
  12451. if (i > 0) {
  12452. /* callback already processed the request. Store the
  12453. return value as a status code for the access log. */
  12454. conn->status_code = i;
  12455. if (!conn->must_close) {
  12456. discard_unread_request_data(conn);
  12457. }
  12458. return;
  12459. } else if (i == 0) {
  12460. /* civetweb should process the request */
  12461. } else {
  12462. /* unspecified - may change with the next version */
  12463. return;
  12464. }
  12465. }
  12466. /* request not yet handled by a handler or redirect, so the request
  12467. * is processed here */
  12468. /* 4. Check for CORS preflight requests and handle them (if configured).
  12469. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12470. */
  12471. if (!strcmp(ri->request_method, "OPTIONS")) {
  12472. /* Send a response to CORS preflights only if
  12473. * access_control_allow_methods is not NULL and not an empty string.
  12474. * In this case, scripts can still handle CORS. */
  12475. const char *cors_meth_cfg =
  12476. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12477. const char *cors_orig_cfg =
  12478. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12479. const char *cors_origin =
  12480. get_header(ri->http_headers, ri->num_headers, "Origin");
  12481. const char *cors_acrm = get_header(ri->http_headers,
  12482. ri->num_headers,
  12483. "Access-Control-Request-Method");
  12484. /* Todo: check if cors_origin is in cors_orig_cfg.
  12485. * Or, let the client check this. */
  12486. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12487. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12488. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12489. /* This is a valid CORS preflight, and the server is configured
  12490. * to handle it automatically. */
  12491. const char *cors_acrh =
  12492. get_header(ri->http_headers,
  12493. ri->num_headers,
  12494. "Access-Control-Request-Headers");
  12495. gmt_time_string(date, sizeof(date), &curtime);
  12496. mg_printf(conn,
  12497. "HTTP/1.1 200 OK\r\n"
  12498. "Date: %s\r\n"
  12499. "Access-Control-Allow-Origin: %s\r\n"
  12500. "Access-Control-Allow-Methods: %s\r\n"
  12501. "Content-Length: 0\r\n"
  12502. "Connection: %s\r\n",
  12503. date,
  12504. cors_orig_cfg,
  12505. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12506. suggest_connection_header(conn));
  12507. if (cors_acrh != NULL) {
  12508. /* CORS request is asking for additional headers */
  12509. const char *cors_hdr_cfg =
  12510. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12511. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12512. /* Allow only if access_control_allow_headers is
  12513. * not NULL and not an empty string. If this
  12514. * configuration is set to *, allow everything.
  12515. * Otherwise this configuration must be a list
  12516. * of allowed HTTP header names. */
  12517. mg_printf(conn,
  12518. "Access-Control-Allow-Headers: %s\r\n",
  12519. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12520. : cors_hdr_cfg));
  12521. }
  12522. }
  12523. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12524. mg_printf(conn, "\r\n");
  12525. return;
  12526. }
  12527. }
  12528. /* 5. interpret the url to find out how the request must be handled
  12529. */
  12530. /* 5.1. first test, if the request targets the regular http(s)://
  12531. * protocol namespace or the websocket ws(s):// protocol namespace.
  12532. */
  12533. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12534. #if defined(USE_WEBSOCKET)
  12535. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12536. #else
  12537. handler_type = REQUEST_HANDLER;
  12538. #endif /* defined(USE_WEBSOCKET) */
  12539. if (is_websocket_request) {
  12540. HTTP1_only;
  12541. }
  12542. /* 5.2. check if the request will be handled by a callback */
  12543. if (get_request_handler(conn,
  12544. handler_type,
  12545. &callback_handler,
  12546. &subprotocols,
  12547. &ws_connect_handler,
  12548. &ws_ready_handler,
  12549. &ws_data_handler,
  12550. &ws_close_handler,
  12551. NULL,
  12552. &callback_data,
  12553. &handler_info)) {
  12554. /* 5.2.1. A callback will handle this request. All requests
  12555. * handled by a callback have to be considered as requests
  12556. * to a script resource. */
  12557. is_callback_resource = 1;
  12558. is_script_resource = 1;
  12559. is_put_or_delete_request = is_put_or_delete_method(conn);
  12560. } else {
  12561. no_callback_resource:
  12562. /* 5.2.2. No callback is responsible for this request. The URI
  12563. * addresses a file based resource (static content or Lua/cgi
  12564. * scripts in the file system). */
  12565. is_callback_resource = 0;
  12566. interpret_uri(conn,
  12567. path,
  12568. sizeof(path),
  12569. &file.stat,
  12570. &is_found,
  12571. &is_script_resource,
  12572. &is_websocket_request,
  12573. &is_put_or_delete_request,
  12574. &is_template_text_file);
  12575. }
  12576. /* 6. authorization check */
  12577. /* 6.1. a custom authorization handler is installed */
  12578. if (get_request_handler(conn,
  12579. AUTH_HANDLER,
  12580. NULL,
  12581. NULL,
  12582. NULL,
  12583. NULL,
  12584. NULL,
  12585. NULL,
  12586. &auth_handler,
  12587. &auth_callback_data,
  12588. NULL)) {
  12589. if (!auth_handler(conn, auth_callback_data)) {
  12590. return;
  12591. }
  12592. } else if (is_put_or_delete_request && !is_script_resource
  12593. && !is_callback_resource) {
  12594. HTTP1_only;
  12595. /* 6.2. this request is a PUT/DELETE to a real file */
  12596. /* 6.2.1. thus, the server must have real files */
  12597. #if defined(NO_FILES)
  12598. if (1) {
  12599. #else
  12600. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12601. #endif
  12602. /* This server does not have any real files, thus the
  12603. * PUT/DELETE methods are not valid. */
  12604. mg_send_http_error(conn,
  12605. 405,
  12606. "%s method not allowed",
  12607. conn->request_info.request_method);
  12608. return;
  12609. }
  12610. #if !defined(NO_FILES)
  12611. /* 6.2.2. Check if put authorization for static files is
  12612. * available.
  12613. */
  12614. if (!is_authorized_for_put(conn)) {
  12615. send_authorization_request(conn, NULL);
  12616. return;
  12617. }
  12618. #endif
  12619. } else {
  12620. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12621. * or it is a PUT or DELETE request to a resource that does not
  12622. * correspond to a file. Check authorization. */
  12623. if (!check_authorization(conn, path)) {
  12624. send_authorization_request(conn, NULL);
  12625. return;
  12626. }
  12627. }
  12628. /* request is authorized or does not need authorization */
  12629. /* 7. check if there are request handlers for this uri */
  12630. if (is_callback_resource) {
  12631. HTTP1_only;
  12632. if (!is_websocket_request) {
  12633. i = callback_handler(conn, callback_data);
  12634. /* Callback handler will not be used anymore. Release it */
  12635. mg_lock_context(conn->phys_ctx);
  12636. handler_info->refcount--;
  12637. mg_unlock_context(conn->phys_ctx);
  12638. if (i > 0) {
  12639. /* Do nothing, callback has served the request. Store
  12640. * then return value as status code for the log and discard
  12641. * all data from the client not used by the callback. */
  12642. conn->status_code = i;
  12643. if (!conn->must_close) {
  12644. discard_unread_request_data(conn);
  12645. }
  12646. } else {
  12647. /* The handler did NOT handle the request. */
  12648. /* Some proper reactions would be:
  12649. * a) close the connections without sending anything
  12650. * b) send a 404 not found
  12651. * c) try if there is a file matching the URI
  12652. * It would be possible to do a, b or c in the callback
  12653. * implementation, and return 1 - we cannot do anything
  12654. * here, that is not possible in the callback.
  12655. *
  12656. * TODO: What would be the best reaction here?
  12657. * (Note: The reaction may change, if there is a better
  12658. * idea.)
  12659. */
  12660. /* For the moment, use option c: We look for a proper file,
  12661. * but since a file request is not always a script resource,
  12662. * the authorization check might be different. */
  12663. interpret_uri(conn,
  12664. path,
  12665. sizeof(path),
  12666. &file.stat,
  12667. &is_found,
  12668. &is_script_resource,
  12669. &is_websocket_request,
  12670. &is_put_or_delete_request,
  12671. &is_template_text_file);
  12672. callback_handler = NULL;
  12673. /* Here we are at a dead end:
  12674. * According to URI matching, a callback should be
  12675. * responsible for handling the request,
  12676. * we called it, but the callback declared itself
  12677. * not responsible.
  12678. * We use a goto here, to get out of this dead end,
  12679. * and continue with the default handling.
  12680. * A goto here is simpler and better to understand
  12681. * than some curious loop. */
  12682. goto no_callback_resource;
  12683. }
  12684. } else {
  12685. #if defined(USE_WEBSOCKET)
  12686. handle_websocket_request(conn,
  12687. path,
  12688. is_callback_resource,
  12689. subprotocols,
  12690. ws_connect_handler,
  12691. ws_ready_handler,
  12692. ws_data_handler,
  12693. ws_close_handler,
  12694. callback_data);
  12695. #endif
  12696. }
  12697. return;
  12698. }
  12699. /* 8. handle websocket requests */
  12700. #if defined(USE_WEBSOCKET)
  12701. if (is_websocket_request) {
  12702. HTTP1_only;
  12703. if (is_script_resource) {
  12704. if (is_in_script_path(conn, path)) {
  12705. /* Websocket Lua script */
  12706. handle_websocket_request(conn,
  12707. path,
  12708. 0 /* Lua Script */,
  12709. NULL,
  12710. NULL,
  12711. NULL,
  12712. NULL,
  12713. NULL,
  12714. conn->phys_ctx->user_data);
  12715. } else {
  12716. /* Script was in an illegal path */
  12717. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12718. }
  12719. } else {
  12720. mg_send_http_error(conn, 404, "%s", "Not found");
  12721. }
  12722. return;
  12723. } else
  12724. #endif
  12725. #if defined(NO_FILES)
  12726. /* 9a. In case the server uses only callbacks, this uri is
  12727. * unknown.
  12728. * Then, all request handling ends here. */
  12729. mg_send_http_error(conn, 404, "%s", "Not Found");
  12730. #else
  12731. /* 9b. This request is either for a static file or resource handled
  12732. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12733. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12734. mg_send_http_error(conn, 404, "%s", "Not Found");
  12735. return;
  12736. }
  12737. /* 10. Request is handled by a script */
  12738. if (is_script_resource) {
  12739. HTTP1_only;
  12740. handle_file_based_request(conn, path, &file);
  12741. return;
  12742. }
  12743. /* 11. Handle put/delete/mkcol requests */
  12744. if (is_put_or_delete_request) {
  12745. HTTP1_only;
  12746. /* 11.1. PUT method */
  12747. if (!strcmp(ri->request_method, "PUT")) {
  12748. put_file(conn, path);
  12749. return;
  12750. }
  12751. /* 11.2. DELETE method */
  12752. if (!strcmp(ri->request_method, "DELETE")) {
  12753. delete_file(conn, path);
  12754. return;
  12755. }
  12756. /* 11.3. MKCOL method */
  12757. if (!strcmp(ri->request_method, "MKCOL")) {
  12758. mkcol(conn, path);
  12759. return;
  12760. }
  12761. /* 11.4. PATCH method
  12762. * This method is not supported for static resources,
  12763. * only for scripts (Lua, CGI) and callbacks. */
  12764. mg_send_http_error(conn,
  12765. 405,
  12766. "%s method not allowed",
  12767. conn->request_info.request_method);
  12768. return;
  12769. }
  12770. /* 11. File does not exist, or it was configured that it should be
  12771. * hidden */
  12772. if (!is_found || (must_hide_file(conn, path))) {
  12773. mg_send_http_error(conn, 404, "%s", "Not found");
  12774. return;
  12775. }
  12776. /* 12. Directory uris should end with a slash */
  12777. if (file.stat.is_directory && (uri_len > 0)
  12778. && (ri->local_uri[uri_len - 1] != '/')) {
  12779. size_t len = strlen(ri->request_uri);
  12780. char *new_path = mg_malloc_ctx(len + 2, conn->phys_ctx);
  12781. if (!new_path) {
  12782. mg_send_http_error(conn, 500, "out or memory");
  12783. } else {
  12784. memcpy(new_path, ri->request_uri, len);
  12785. new_path[len] = '/';
  12786. new_path[len + 1] = 0;
  12787. mg_send_http_redirect(conn, new_path, 301);
  12788. }
  12789. return;
  12790. }
  12791. /* 13. Handle other methods than GET/HEAD */
  12792. /* 13.1. Handle PROPFIND */
  12793. if (!strcmp(ri->request_method, "PROPFIND")) {
  12794. handle_propfind(conn, path, &file.stat);
  12795. return;
  12796. }
  12797. /* 13.2. Handle OPTIONS for files */
  12798. if (!strcmp(ri->request_method, "OPTIONS")) {
  12799. /* This standard handler is only used for real files.
  12800. * Scripts should support the OPTIONS method themselves, to allow a
  12801. * maximum flexibility.
  12802. * Lua and CGI scripts may fully support CORS this way (including
  12803. * preflights). */
  12804. send_options(conn);
  12805. return;
  12806. }
  12807. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12808. if ((0 != strcmp(ri->request_method, "GET"))
  12809. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12810. mg_send_http_error(conn,
  12811. 405,
  12812. "%s method not allowed",
  12813. conn->request_info.request_method);
  12814. return;
  12815. }
  12816. /* 14. directories */
  12817. if (file.stat.is_directory) {
  12818. /* Substitute files have already been handled above. */
  12819. /* Here we can either generate and send a directory listing,
  12820. * or send an "access denied" error. */
  12821. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12822. "yes")) {
  12823. handle_directory_request(conn, path);
  12824. } else {
  12825. mg_send_http_error(conn,
  12826. 403,
  12827. "%s",
  12828. "Error: Directory listing denied");
  12829. }
  12830. return;
  12831. }
  12832. /* 15. Files with search/replace patterns: LSP and SSI */
  12833. if (is_template_text_file) {
  12834. HTTP1_only;
  12835. handle_file_based_request(conn, path, &file);
  12836. return;
  12837. }
  12838. /* 16. Static file - maybe cached */
  12839. #if !defined(NO_CACHING)
  12840. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12841. /* Send 304 "Not Modified" - this must not send any body data */
  12842. handle_not_modified_static_file_request(conn, &file);
  12843. return;
  12844. }
  12845. #endif /* !NO_CACHING */
  12846. /* 17. Static file - not cached */
  12847. handle_static_file_request(conn, path, &file, NULL, NULL);
  12848. #endif /* !defined(NO_FILES) */
  12849. }
  12850. #if !defined(NO_FILESYSTEMS)
  12851. static void
  12852. handle_file_based_request(struct mg_connection *conn,
  12853. const char *path,
  12854. struct mg_file *file)
  12855. {
  12856. if (!conn || !conn->dom_ctx) {
  12857. return;
  12858. }
  12859. if (0) {
  12860. #if defined(USE_LUA)
  12861. } else if (match_prefix_strlen(
  12862. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS], path)
  12863. > 0) {
  12864. if (is_in_script_path(conn, path)) {
  12865. /* Lua server page: an SSI like page containing mostly plain
  12866. * html code plus some tags with server generated contents. */
  12867. handle_lsp_request(conn, path, file, NULL);
  12868. } else {
  12869. /* Script was in an illegal path */
  12870. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12871. }
  12872. } else if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12873. path)
  12874. > 0) {
  12875. if (is_in_script_path(conn, path)) {
  12876. /* Lua in-server module script: a CGI like script used to
  12877. * generate
  12878. * the
  12879. * entire reply. */
  12880. mg_exec_lua_script(conn, path, NULL);
  12881. } else {
  12882. /* Script was in an illegal path */
  12883. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12884. }
  12885. #endif
  12886. #if defined(USE_DUKTAPE)
  12887. } else if (match_prefix_strlen(
  12888. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS], path)
  12889. > 0) {
  12890. if (is_in_script_path(conn, path)) {
  12891. /* Call duktape to generate the page */
  12892. mg_exec_duktape_script(conn, path);
  12893. } else {
  12894. /* Script was in an illegal path */
  12895. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12896. }
  12897. #endif
  12898. #if !defined(NO_CGI)
  12899. } else if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], path)
  12900. > 0) {
  12901. if (is_in_script_path(conn, path)) {
  12902. /* CGI scripts may support all HTTP methods */
  12903. handle_cgi_request(conn, path);
  12904. } else {
  12905. /* Script was in an illegal path */
  12906. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12907. }
  12908. #endif /* !NO_CGI */
  12909. } else if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  12910. > 0) {
  12911. if (is_in_script_path(conn, path)) {
  12912. handle_ssi_file_request(conn, path, file);
  12913. } else {
  12914. /* Script was in an illegal path */
  12915. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12916. }
  12917. #if !defined(NO_CACHING)
  12918. } else if ((!conn->in_error_handler)
  12919. && is_not_modified(conn, &file->stat)) {
  12920. /* Send 304 "Not Modified" - this must not send any body data */
  12921. handle_not_modified_static_file_request(conn, file);
  12922. #endif /* !NO_CACHING */
  12923. } else {
  12924. handle_static_file_request(conn, path, file, NULL, NULL);
  12925. }
  12926. }
  12927. #endif /* NO_FILESYSTEMS */
  12928. static void
  12929. close_all_listening_sockets(struct mg_context *ctx)
  12930. {
  12931. unsigned int i;
  12932. if (!ctx) {
  12933. return;
  12934. }
  12935. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12936. closesocket(ctx->listening_sockets[i].sock);
  12937. #if defined(USE_X_DOM_SOCKET)
  12938. /* For unix domain sockets, the socket name represents a file that has
  12939. * to be deleted. */
  12940. /* See
  12941. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  12942. */
  12943. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  12944. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  12945. IGNORE_UNUSED_RESULT(
  12946. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  12947. }
  12948. #endif
  12949. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12950. }
  12951. mg_free(ctx->listening_sockets);
  12952. ctx->listening_sockets = NULL;
  12953. mg_free(ctx->listening_socket_fds);
  12954. ctx->listening_socket_fds = NULL;
  12955. }
  12956. /* Valid listening port specification is: [ip_address:]port[s]
  12957. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12958. * Examples for IPv6: [::]:80, [::1]:80,
  12959. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12960. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12961. * In order to bind to both, IPv4 and IPv6, you can either add
  12962. * both ports using 8080,[::]:8080, or the short form +8080.
  12963. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12964. * one only accepting IPv4 the other only IPv6. +8080 creates
  12965. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12966. * environment, they might work differently, or might not work
  12967. * at all - it must be tested what options work best in the
  12968. * relevant network environment.
  12969. */
  12970. static int
  12971. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12972. {
  12973. unsigned int a, b, c, d;
  12974. unsigned port;
  12975. unsigned long portUL;
  12976. int ch, len;
  12977. const char *cb;
  12978. char *endptr;
  12979. #if defined(USE_IPV6)
  12980. char buf[100] = {0};
  12981. #endif
  12982. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12983. * Also, all-zeroes in the socket address means binding to all addresses
  12984. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12985. memset(so, 0, sizeof(*so));
  12986. so->lsa.sin.sin_family = AF_INET;
  12987. *ip_version = 0;
  12988. /* Initialize len as invalid. */
  12989. port = 0;
  12990. len = 0;
  12991. /* Test for different ways to format this string */
  12992. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12993. == 5) {
  12994. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12995. so->lsa.sin.sin_addr.s_addr =
  12996. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12997. so->lsa.sin.sin_port = htons((uint16_t)port);
  12998. *ip_version = 4;
  12999. #if defined(USE_IPV6)
  13000. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13001. && ((size_t)len <= vec->len)
  13002. && mg_inet_pton(
  13003. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13004. /* IPv6 address, examples: see above */
  13005. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13006. */
  13007. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13008. *ip_version = 6;
  13009. #endif
  13010. } else if ((vec->ptr[0] == '+')
  13011. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  13012. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13013. /* Add 1 to len for the + character we skipped before */
  13014. len++;
  13015. #if defined(USE_IPV6)
  13016. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13017. so->lsa.sin6.sin6_family = AF_INET6;
  13018. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13019. *ip_version = 4 + 6;
  13020. #else
  13021. /* Bind to IPv4 only, since IPv6 is not built in. */
  13022. so->lsa.sin.sin_port = htons((uint16_t)port);
  13023. *ip_version = 4;
  13024. #endif
  13025. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13026. && (vec->ptr != endptr)) {
  13027. len = (int)(endptr - vec->ptr);
  13028. port = (uint16_t)portUL;
  13029. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13030. so->lsa.sin.sin_port = htons((uint16_t)port);
  13031. *ip_version = 4;
  13032. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13033. /* String could be a hostname. This check algotithm
  13034. * will only work for RFC 952 compliant hostnames,
  13035. * starting with a letter, containing only letters,
  13036. * digits and hyphen ('-'). Newer specs may allow
  13037. * more, but this is not guaranteed here, since it
  13038. * may interfere with rules for port option lists. */
  13039. /* According to RFC 1035, hostnames are restricted to 255 characters
  13040. * in total (63 between two dots). */
  13041. char hostname[256];
  13042. size_t hostnlen = (size_t)(cb - vec->ptr);
  13043. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13044. /* This would be invalid in any case */
  13045. *ip_version = 0;
  13046. return 0;
  13047. }
  13048. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13049. if (mg_inet_pton(
  13050. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13051. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13052. *ip_version = 4;
  13053. so->lsa.sin.sin_port = htons((uint16_t)port);
  13054. len += (int)(hostnlen + 1);
  13055. } else {
  13056. len = 0;
  13057. }
  13058. #if defined(USE_IPV6)
  13059. } else if (mg_inet_pton(AF_INET6,
  13060. hostname,
  13061. &so->lsa.sin6,
  13062. sizeof(so->lsa.sin6),
  13063. 1)) {
  13064. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13065. *ip_version = 6;
  13066. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13067. len += (int)(hostnlen + 1);
  13068. } else {
  13069. len = 0;
  13070. }
  13071. #endif
  13072. } else {
  13073. len = 0;
  13074. }
  13075. #if defined(USE_X_DOM_SOCKET)
  13076. } else if (vec->ptr[0] == 'x') {
  13077. /* unix (linux) domain socket */
  13078. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13079. len = vec->len;
  13080. so->lsa.sun.sun_family = AF_UNIX;
  13081. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13082. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13083. port = 0;
  13084. *ip_version = 99;
  13085. } else {
  13086. /* String too long */
  13087. len = 0;
  13088. }
  13089. #endif
  13090. } else {
  13091. /* Parsing failure. */
  13092. len = 0;
  13093. }
  13094. /* sscanf and the option splitting code ensure the following condition
  13095. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13096. if ((len > 0) && is_valid_port(port)
  13097. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13098. /* Next character after the port number */
  13099. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13100. so->is_ssl = (ch == 's');
  13101. so->ssl_redir = (ch == 'r');
  13102. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13103. return 1;
  13104. }
  13105. }
  13106. /* Reset ip_version to 0 if there is an error */
  13107. *ip_version = 0;
  13108. return 0;
  13109. }
  13110. /* Is there any SSL port in use? */
  13111. static int
  13112. is_ssl_port_used(const char *ports)
  13113. {
  13114. if (ports) {
  13115. /* There are several different allowed syntax variants:
  13116. * - "80" for a single port using every network interface
  13117. * - "localhost:80" for a single port using only localhost
  13118. * - "80,localhost:8080" for two ports, one bound to localhost
  13119. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13120. * to IPv4 localhost, one to IPv6 localhost
  13121. * - "+80" use port 80 for IPv4 and IPv6
  13122. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13123. * for both: IPv4 and IPv4
  13124. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13125. * additionally port 8080 bound to localhost connections
  13126. *
  13127. * If we just look for 's' anywhere in the string, "localhost:80"
  13128. * will be detected as SSL (false positive).
  13129. * Looking for 's' after a digit may cause false positives in
  13130. * "my24service:8080".
  13131. * Looking from 's' backward if there are only ':' and numbers
  13132. * before will not work for "24service:8080" (non SSL, port 8080)
  13133. * or "24s" (SSL, port 24).
  13134. *
  13135. * Remark: Initially hostnames were not allowed to start with a
  13136. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13137. * Section 2.1).
  13138. *
  13139. * To get this correct, the entire string must be parsed as a whole,
  13140. * reading it as a list element for element and parsing with an
  13141. * algorithm equivalent to parse_port_string.
  13142. *
  13143. * In fact, we use local interface names here, not arbitrary
  13144. * hostnames, so in most cases the only name will be "localhost".
  13145. *
  13146. * So, for now, we use this simple algorithm, that may still return
  13147. * a false positive in bizarre cases.
  13148. */
  13149. int i;
  13150. int portslen = (int)strlen(ports);
  13151. char prevIsNumber = 0;
  13152. for (i = 0; i < portslen; i++) {
  13153. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13154. return 1;
  13155. }
  13156. if (ports[i] >= '0' && ports[i] <= '9') {
  13157. prevIsNumber = 1;
  13158. } else {
  13159. prevIsNumber = 0;
  13160. }
  13161. }
  13162. }
  13163. return 0;
  13164. }
  13165. static int
  13166. set_ports_option(struct mg_context *phys_ctx)
  13167. {
  13168. const char *list;
  13169. int on = 1;
  13170. #if defined(USE_IPV6)
  13171. int off = 0;
  13172. #endif
  13173. struct vec vec;
  13174. struct socket so, *ptr;
  13175. struct mg_pollfd *pfd;
  13176. union usa usa;
  13177. socklen_t len;
  13178. int ip_version;
  13179. int portsTotal = 0;
  13180. int portsOk = 0;
  13181. const char *opt_txt;
  13182. long opt_listen_backlog;
  13183. if (!phys_ctx) {
  13184. return 0;
  13185. }
  13186. memset(&so, 0, sizeof(so));
  13187. memset(&usa, 0, sizeof(usa));
  13188. len = sizeof(usa);
  13189. list = phys_ctx->dd.config[LISTENING_PORTS];
  13190. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13191. portsTotal++;
  13192. if (!parse_port_string(&vec, &so, &ip_version)) {
  13193. mg_cry_ctx_internal(
  13194. phys_ctx,
  13195. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13196. (int)vec.len,
  13197. vec.ptr,
  13198. portsTotal,
  13199. "[IP_ADDRESS:]PORT[s|r]");
  13200. continue;
  13201. }
  13202. #if !defined(NO_SSL)
  13203. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13204. mg_cry_ctx_internal(phys_ctx,
  13205. "Cannot add SSL socket (entry %i)",
  13206. portsTotal);
  13207. continue;
  13208. }
  13209. #endif
  13210. /* Create socket. */
  13211. /* For a list of protocol numbers (e.g., TCP==6) see:
  13212. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13213. */
  13214. if ((so.sock =
  13215. socket(so.lsa.sa.sa_family,
  13216. SOCK_STREAM,
  13217. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13218. == INVALID_SOCKET) {
  13219. mg_cry_ctx_internal(phys_ctx,
  13220. "cannot create socket (entry %i)",
  13221. portsTotal);
  13222. continue;
  13223. }
  13224. #if defined(_WIN32)
  13225. /* Windows SO_REUSEADDR lets many procs binds to a
  13226. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13227. * if someone already has the socket -- DTL */
  13228. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13229. * Windows might need a few seconds before
  13230. * the same port can be used again in the
  13231. * same process, so a short Sleep may be
  13232. * required between mg_stop and mg_start.
  13233. */
  13234. if (setsockopt(so.sock,
  13235. SOL_SOCKET,
  13236. SO_EXCLUSIVEADDRUSE,
  13237. (SOCK_OPT_TYPE)&on,
  13238. sizeof(on))
  13239. != 0) {
  13240. /* Set reuse option, but don't abort on errors. */
  13241. mg_cry_ctx_internal(
  13242. phys_ctx,
  13243. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13244. portsTotal);
  13245. }
  13246. #else
  13247. if (setsockopt(so.sock,
  13248. SOL_SOCKET,
  13249. SO_REUSEADDR,
  13250. (SOCK_OPT_TYPE)&on,
  13251. sizeof(on))
  13252. != 0) {
  13253. /* Set reuse option, but don't abort on errors. */
  13254. mg_cry_ctx_internal(
  13255. phys_ctx,
  13256. "cannot set socket option SO_REUSEADDR (entry %i)",
  13257. portsTotal);
  13258. }
  13259. #endif
  13260. #if defined(USE_X_DOM_SOCKET)
  13261. if (ip_version == 99) {
  13262. /* Unix domain socket */
  13263. } else
  13264. #endif
  13265. if (ip_version > 4) {
  13266. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13267. #if defined(USE_IPV6)
  13268. if (ip_version > 6) {
  13269. if (so.lsa.sa.sa_family == AF_INET6
  13270. && setsockopt(so.sock,
  13271. IPPROTO_IPV6,
  13272. IPV6_V6ONLY,
  13273. (void *)&off,
  13274. sizeof(off))
  13275. != 0) {
  13276. /* Set IPv6 only option, but don't abort on errors. */
  13277. mg_cry_ctx_internal(phys_ctx,
  13278. "cannot set socket option "
  13279. "IPV6_V6ONLY=off (entry %i)",
  13280. portsTotal);
  13281. }
  13282. } else {
  13283. if (so.lsa.sa.sa_family == AF_INET6
  13284. && setsockopt(so.sock,
  13285. IPPROTO_IPV6,
  13286. IPV6_V6ONLY,
  13287. (void *)&on,
  13288. sizeof(on))
  13289. != 0) {
  13290. /* Set IPv6 only option, but don't abort on errors. */
  13291. mg_cry_ctx_internal(phys_ctx,
  13292. "cannot set socket option "
  13293. "IPV6_V6ONLY=on (entry %i)",
  13294. portsTotal);
  13295. }
  13296. }
  13297. #else
  13298. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13299. closesocket(so.sock);
  13300. so.sock = INVALID_SOCKET;
  13301. continue;
  13302. #endif
  13303. }
  13304. if (so.lsa.sa.sa_family == AF_INET) {
  13305. len = sizeof(so.lsa.sin);
  13306. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13307. mg_cry_ctx_internal(phys_ctx,
  13308. "cannot bind to %.*s: %d (%s)",
  13309. (int)vec.len,
  13310. vec.ptr,
  13311. (int)ERRNO,
  13312. strerror(errno));
  13313. closesocket(so.sock);
  13314. so.sock = INVALID_SOCKET;
  13315. continue;
  13316. }
  13317. }
  13318. #if defined(USE_IPV6)
  13319. else if (so.lsa.sa.sa_family == AF_INET6) {
  13320. len = sizeof(so.lsa.sin6);
  13321. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13322. mg_cry_ctx_internal(phys_ctx,
  13323. "cannot bind to IPv6 %.*s: %d (%s)",
  13324. (int)vec.len,
  13325. vec.ptr,
  13326. (int)ERRNO,
  13327. strerror(errno));
  13328. closesocket(so.sock);
  13329. so.sock = INVALID_SOCKET;
  13330. continue;
  13331. }
  13332. }
  13333. #endif
  13334. #if defined(USE_X_DOM_SOCKET)
  13335. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13336. len = sizeof(so.lsa.sun);
  13337. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13338. mg_cry_ctx_internal(phys_ctx,
  13339. "cannot bind to unix socket %s: %d (%s)",
  13340. so.lsa.sun.sun_path,
  13341. (int)ERRNO,
  13342. strerror(errno));
  13343. closesocket(so.sock);
  13344. so.sock = INVALID_SOCKET;
  13345. continue;
  13346. }
  13347. }
  13348. #endif
  13349. else {
  13350. mg_cry_ctx_internal(
  13351. phys_ctx,
  13352. "cannot bind: address family not supported (entry %i)",
  13353. portsTotal);
  13354. closesocket(so.sock);
  13355. so.sock = INVALID_SOCKET;
  13356. continue;
  13357. }
  13358. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13359. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13360. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13361. mg_cry_ctx_internal(phys_ctx,
  13362. "%s value \"%s\" is invalid",
  13363. config_options[LISTEN_BACKLOG_SIZE].name,
  13364. opt_txt);
  13365. closesocket(so.sock);
  13366. so.sock = INVALID_SOCKET;
  13367. continue;
  13368. }
  13369. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13370. mg_cry_ctx_internal(phys_ctx,
  13371. "cannot listen to %.*s: %d (%s)",
  13372. (int)vec.len,
  13373. vec.ptr,
  13374. (int)ERRNO,
  13375. strerror(errno));
  13376. closesocket(so.sock);
  13377. so.sock = INVALID_SOCKET;
  13378. continue;
  13379. }
  13380. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13381. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13382. int err = (int)ERRNO;
  13383. mg_cry_ctx_internal(phys_ctx,
  13384. "call to getsockname failed %.*s: %d (%s)",
  13385. (int)vec.len,
  13386. vec.ptr,
  13387. err,
  13388. strerror(errno));
  13389. closesocket(so.sock);
  13390. so.sock = INVALID_SOCKET;
  13391. continue;
  13392. }
  13393. /* Update lsa port in case of random free ports */
  13394. #if defined(USE_IPV6)
  13395. if (so.lsa.sa.sa_family == AF_INET6) {
  13396. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13397. } else
  13398. #endif
  13399. {
  13400. so.lsa.sin.sin_port = usa.sin.sin_port;
  13401. }
  13402. if ((ptr = (struct socket *)
  13403. mg_realloc_ctx(phys_ctx->listening_sockets,
  13404. (phys_ctx->num_listening_sockets + 1)
  13405. * sizeof(phys_ctx->listening_sockets[0]),
  13406. phys_ctx))
  13407. == NULL) {
  13408. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13409. closesocket(so.sock);
  13410. so.sock = INVALID_SOCKET;
  13411. continue;
  13412. }
  13413. if ((pfd = (struct mg_pollfd *)
  13414. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13415. (phys_ctx->num_listening_sockets + 1)
  13416. * sizeof(phys_ctx->listening_socket_fds[0]),
  13417. phys_ctx))
  13418. == NULL) {
  13419. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13420. closesocket(so.sock);
  13421. so.sock = INVALID_SOCKET;
  13422. mg_free(ptr);
  13423. continue;
  13424. }
  13425. set_close_on_exec(so.sock, NULL, phys_ctx);
  13426. phys_ctx->listening_sockets = ptr;
  13427. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13428. phys_ctx->listening_socket_fds = pfd;
  13429. phys_ctx->num_listening_sockets++;
  13430. portsOk++;
  13431. }
  13432. if (portsOk != portsTotal) {
  13433. close_all_listening_sockets(phys_ctx);
  13434. portsOk = 0;
  13435. }
  13436. return portsOk;
  13437. }
  13438. static const char *
  13439. header_val(const struct mg_connection *conn, const char *header)
  13440. {
  13441. const char *header_value;
  13442. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13443. return "-";
  13444. } else {
  13445. return header_value;
  13446. }
  13447. }
  13448. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13449. static void log_access(const struct mg_connection *conn);
  13450. #include "external_log_access.inl"
  13451. #elif !defined(NO_FILESYSTEMS)
  13452. static void
  13453. log_access(const struct mg_connection *conn)
  13454. {
  13455. const struct mg_request_info *ri;
  13456. struct mg_file fi;
  13457. char date[64], src_addr[IP_ADDR_STR_LEN];
  13458. struct tm *tm;
  13459. const char *referer;
  13460. const char *user_agent;
  13461. char buf[4096];
  13462. if (!conn || !conn->dom_ctx) {
  13463. return;
  13464. }
  13465. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13466. if (mg_fopen(conn,
  13467. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13468. MG_FOPEN_MODE_APPEND,
  13469. &fi)
  13470. == 0) {
  13471. fi.access.fp = NULL;
  13472. }
  13473. } else {
  13474. fi.access.fp = NULL;
  13475. }
  13476. /* Log is written to a file and/or a callback. If both are not set,
  13477. * executing the rest of the function is pointless. */
  13478. if ((fi.access.fp == NULL)
  13479. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13480. return;
  13481. }
  13482. tm = localtime(&conn->conn_birth_time);
  13483. if (tm != NULL) {
  13484. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13485. } else {
  13486. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13487. date[sizeof(date) - 1] = '\0';
  13488. }
  13489. ri = &conn->request_info;
  13490. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13491. referer = header_val(conn, "Referer");
  13492. user_agent = header_val(conn, "User-Agent");
  13493. mg_snprintf(conn,
  13494. NULL, /* Ignore truncation in access log */
  13495. buf,
  13496. sizeof(buf),
  13497. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13498. src_addr,
  13499. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13500. date,
  13501. ri->request_method ? ri->request_method : "-",
  13502. ri->request_uri ? ri->request_uri : "-",
  13503. ri->query_string ? "?" : "",
  13504. ri->query_string ? ri->query_string : "",
  13505. ri->http_version,
  13506. conn->status_code,
  13507. conn->num_bytes_sent,
  13508. referer,
  13509. user_agent);
  13510. if (conn->phys_ctx->callbacks.log_access) {
  13511. conn->phys_ctx->callbacks.log_access(conn, buf);
  13512. }
  13513. if (fi.access.fp) {
  13514. int ok = 1;
  13515. flockfile(fi.access.fp);
  13516. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13517. ok = 0;
  13518. }
  13519. if (fflush(fi.access.fp) != 0) {
  13520. ok = 0;
  13521. }
  13522. funlockfile(fi.access.fp);
  13523. if (mg_fclose(&fi.access) != 0) {
  13524. ok = 0;
  13525. }
  13526. if (!ok) {
  13527. mg_cry_internal(conn,
  13528. "Error writing log file %s",
  13529. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13530. }
  13531. }
  13532. }
  13533. #else
  13534. #error Must either enable filesystems or provide a custom log_access implementation
  13535. #endif /* Externally provided function */
  13536. /* Verify given socket address against the ACL.
  13537. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13538. */
  13539. static int
  13540. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13541. {
  13542. int allowed, flag, matched;
  13543. struct vec vec;
  13544. if (phys_ctx) {
  13545. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13546. /* If any ACL is set, deny by default */
  13547. allowed = (list == NULL) ? '+' : '-';
  13548. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13549. flag = vec.ptr[0];
  13550. matched = -1;
  13551. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13552. vec.ptr++;
  13553. vec.len--;
  13554. matched = parse_match_net(&vec, sa, 1);
  13555. }
  13556. if (matched < 0) {
  13557. mg_cry_ctx_internal(phys_ctx,
  13558. "%s: subnet must be [+|-]IP-addr[/x]",
  13559. __func__);
  13560. return -1;
  13561. }
  13562. if (matched) {
  13563. allowed = flag;
  13564. }
  13565. }
  13566. return allowed == '+';
  13567. }
  13568. return -1;
  13569. }
  13570. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13571. static int
  13572. set_uid_option(struct mg_context *phys_ctx)
  13573. {
  13574. int success = 0;
  13575. if (phys_ctx) {
  13576. /* We are currently running as curr_uid. */
  13577. const uid_t curr_uid = getuid();
  13578. /* If set, we want to run as run_as_user. */
  13579. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13580. const struct passwd *to_pw = NULL;
  13581. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13582. /* run_as_user does not exist on the system. We can't proceed
  13583. * further. */
  13584. mg_cry_ctx_internal(phys_ctx,
  13585. "%s: unknown user [%s]",
  13586. __func__,
  13587. run_as_user);
  13588. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13589. /* There was either no request to change user, or we're already
  13590. * running as run_as_user. Nothing else to do.
  13591. */
  13592. success = 1;
  13593. } else {
  13594. /* Valid change request. */
  13595. if (setgid(to_pw->pw_gid) == -1) {
  13596. mg_cry_ctx_internal(phys_ctx,
  13597. "%s: setgid(%s): %s",
  13598. __func__,
  13599. run_as_user,
  13600. strerror(errno));
  13601. } else if (setgroups(0, NULL) == -1) {
  13602. mg_cry_ctx_internal(phys_ctx,
  13603. "%s: setgroups(): %s",
  13604. __func__,
  13605. strerror(errno));
  13606. } else if (setuid(to_pw->pw_uid) == -1) {
  13607. mg_cry_ctx_internal(phys_ctx,
  13608. "%s: setuid(%s): %s",
  13609. __func__,
  13610. run_as_user,
  13611. strerror(errno));
  13612. } else {
  13613. success = 1;
  13614. }
  13615. }
  13616. }
  13617. return success;
  13618. }
  13619. #endif /* !_WIN32 */
  13620. static void
  13621. tls_dtor(void *key)
  13622. {
  13623. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13624. /* key == pthread_getspecific(sTlsKey); */
  13625. if (tls) {
  13626. if (tls->is_master == 2) {
  13627. tls->is_master = -3; /* Mark memory as dead */
  13628. mg_free(tls);
  13629. }
  13630. }
  13631. pthread_setspecific(sTlsKey, NULL);
  13632. }
  13633. #if !defined(NO_SSL)
  13634. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13635. struct mg_domain_context *dom_ctx,
  13636. const char *pem,
  13637. const char *chain);
  13638. static const char *ssl_error(void);
  13639. static int
  13640. refresh_trust(struct mg_connection *conn)
  13641. {
  13642. struct stat cert_buf;
  13643. int64_t t = 0;
  13644. const char *pem;
  13645. const char *chain;
  13646. int should_verify_peer;
  13647. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13648. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13649. * refresh_trust still can not work. */
  13650. return 0;
  13651. }
  13652. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13653. if (chain == NULL) {
  13654. /* pem is not NULL here */
  13655. chain = pem;
  13656. }
  13657. if (*chain == 0) {
  13658. chain = NULL;
  13659. }
  13660. if (stat(pem, &cert_buf) != -1) {
  13661. t = (int64_t)cert_buf.st_mtime;
  13662. }
  13663. mg_lock_context(conn->phys_ctx);
  13664. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13665. conn->dom_ctx->ssl_cert_last_mtime = t;
  13666. should_verify_peer = 0;
  13667. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13668. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13669. == 0) {
  13670. should_verify_peer = 1;
  13671. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13672. "optional")
  13673. == 0) {
  13674. should_verify_peer = 1;
  13675. }
  13676. }
  13677. if (should_verify_peer) {
  13678. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13679. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13680. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13681. ca_file,
  13682. ca_path)
  13683. != 1) {
  13684. mg_unlock_context(conn->phys_ctx);
  13685. mg_cry_ctx_internal(
  13686. conn->phys_ctx,
  13687. "SSL_CTX_load_verify_locations error: %s "
  13688. "ssl_verify_peer requires setting "
  13689. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13690. "present in "
  13691. "the .conf file?",
  13692. ssl_error());
  13693. return 0;
  13694. }
  13695. }
  13696. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13697. mg_unlock_context(conn->phys_ctx);
  13698. return 0;
  13699. }
  13700. }
  13701. mg_unlock_context(conn->phys_ctx);
  13702. return 1;
  13703. }
  13704. #if defined(OPENSSL_API_1_1)
  13705. #else
  13706. static pthread_mutex_t *ssl_mutexes;
  13707. #endif /* OPENSSL_API_1_1 */
  13708. static int
  13709. sslize(struct mg_connection *conn,
  13710. int (*func)(SSL *),
  13711. const struct mg_client_options *client_options)
  13712. {
  13713. int ret, err;
  13714. int short_trust;
  13715. unsigned timeout = 1024;
  13716. unsigned i;
  13717. if (!conn) {
  13718. return 0;
  13719. }
  13720. short_trust =
  13721. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13722. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13723. if (short_trust) {
  13724. int trust_ret = refresh_trust(conn);
  13725. if (!trust_ret) {
  13726. return trust_ret;
  13727. }
  13728. }
  13729. mg_lock_context(conn->phys_ctx);
  13730. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13731. mg_unlock_context(conn->phys_ctx);
  13732. if (conn->ssl == NULL) {
  13733. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13734. OPENSSL_REMOVE_THREAD_STATE();
  13735. return 0;
  13736. }
  13737. SSL_set_app_data(conn->ssl, (char *)conn);
  13738. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13739. if (ret != 1) {
  13740. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13741. SSL_free(conn->ssl);
  13742. conn->ssl = NULL;
  13743. OPENSSL_REMOVE_THREAD_STATE();
  13744. return 0;
  13745. }
  13746. if (client_options) {
  13747. if (client_options->host_name) {
  13748. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13749. }
  13750. }
  13751. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13752. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13753. /* NOTE: The loop below acts as a back-off, so we can end
  13754. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13755. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13756. if (to >= 0) {
  13757. timeout = (unsigned)to;
  13758. }
  13759. }
  13760. /* SSL functions may fail and require to be called again:
  13761. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13762. * Here "func" could be SSL_connect or SSL_accept. */
  13763. for (i = 0; i <= timeout; i += 50) {
  13764. ERR_clear_error();
  13765. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13766. ret = func(conn->ssl);
  13767. if (ret != 1) {
  13768. err = SSL_get_error(conn->ssl, ret);
  13769. if ((err == SSL_ERROR_WANT_CONNECT)
  13770. || (err == SSL_ERROR_WANT_ACCEPT)
  13771. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13772. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13773. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13774. /* Don't wait if the server is going to be stopped. */
  13775. break;
  13776. }
  13777. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13778. /* Simply retry the function call. */
  13779. mg_sleep(50);
  13780. } else {
  13781. /* Need to retry the function call "later".
  13782. * See https://linux.die.net/man/3/ssl_get_error
  13783. * This is typical for non-blocking sockets. */
  13784. struct mg_pollfd pfd;
  13785. int pollres;
  13786. pfd.fd = conn->client.sock;
  13787. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13788. || (err == SSL_ERROR_WANT_WRITE))
  13789. ? POLLOUT
  13790. : POLLIN;
  13791. pollres =
  13792. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13793. if (pollres < 0) {
  13794. /* Break if error occured (-1)
  13795. * or server shutdown (-2) */
  13796. break;
  13797. }
  13798. }
  13799. } else if (err == SSL_ERROR_SYSCALL) {
  13800. /* This is an IO error. Look at errno. */
  13801. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13802. break;
  13803. } else {
  13804. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13805. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13806. break;
  13807. }
  13808. } else {
  13809. /* success */
  13810. break;
  13811. }
  13812. }
  13813. ERR_clear_error();
  13814. if (ret != 1) {
  13815. SSL_free(conn->ssl);
  13816. conn->ssl = NULL;
  13817. OPENSSL_REMOVE_THREAD_STATE();
  13818. return 0;
  13819. }
  13820. return 1;
  13821. }
  13822. /* Return OpenSSL error message (from CRYPTO lib) */
  13823. static const char *
  13824. ssl_error(void)
  13825. {
  13826. unsigned long err;
  13827. err = ERR_get_error();
  13828. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13829. }
  13830. static int
  13831. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13832. {
  13833. int i;
  13834. const char hexdigit[] = "0123456789abcdef";
  13835. if ((memlen <= 0) || (buflen <= 0)) {
  13836. return 0;
  13837. }
  13838. if (buflen < (3 * memlen)) {
  13839. return 0;
  13840. }
  13841. for (i = 0; i < memlen; i++) {
  13842. if (i > 0) {
  13843. buf[3 * i - 1] = ' ';
  13844. }
  13845. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13846. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13847. }
  13848. buf[3 * memlen - 1] = 0;
  13849. return 1;
  13850. }
  13851. static int
  13852. ssl_get_client_cert_info(const struct mg_connection *conn,
  13853. struct mg_client_cert *client_cert)
  13854. {
  13855. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13856. if (cert) {
  13857. char str_buf[1024];
  13858. unsigned char buf[256];
  13859. char *str_serial = NULL;
  13860. unsigned int ulen;
  13861. int ilen;
  13862. unsigned char *tmp_buf;
  13863. unsigned char *tmp_p;
  13864. /* Handle to algorithm used for fingerprint */
  13865. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13866. /* Get Subject and issuer */
  13867. X509_NAME *subj = X509_get_subject_name(cert);
  13868. X509_NAME *iss = X509_get_issuer_name(cert);
  13869. /* Get serial number */
  13870. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13871. /* Translate serial number to a hex string */
  13872. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13873. if (serial_bn) {
  13874. str_serial = BN_bn2hex(serial_bn);
  13875. BN_free(serial_bn);
  13876. }
  13877. client_cert->serial =
  13878. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13879. /* Translate subject and issuer to a string */
  13880. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13881. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13882. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13883. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13884. /* Calculate SHA1 fingerprint and store as a hex string */
  13885. ulen = 0;
  13886. /* ASN1_digest is deprecated. Do the calculation manually,
  13887. * using EVP_Digest. */
  13888. ilen = i2d_X509(cert, NULL);
  13889. tmp_buf = (ilen > 0)
  13890. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13891. conn->phys_ctx)
  13892. : NULL;
  13893. if (tmp_buf) {
  13894. tmp_p = tmp_buf;
  13895. (void)i2d_X509(cert, &tmp_p);
  13896. if (!EVP_Digest(
  13897. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13898. ulen = 0;
  13899. }
  13900. mg_free(tmp_buf);
  13901. }
  13902. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13903. *str_buf = 0;
  13904. }
  13905. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13906. client_cert->peer_cert = (void *)cert;
  13907. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13908. * see https://linux.die.net/man/3/bn_bn2hex */
  13909. OPENSSL_free(str_serial);
  13910. return 1;
  13911. }
  13912. return 0;
  13913. }
  13914. #if defined(OPENSSL_API_1_1)
  13915. #else
  13916. static void
  13917. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13918. {
  13919. (void)line;
  13920. (void)file;
  13921. if (mode & 1) {
  13922. /* 1 is CRYPTO_LOCK */
  13923. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13924. } else {
  13925. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13926. }
  13927. }
  13928. #endif /* OPENSSL_API_1_1 */
  13929. #if !defined(NO_SSL_DL)
  13930. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13931. static void *
  13932. load_tls_dll(char *ebuf,
  13933. size_t ebuf_len,
  13934. const char *dll_name,
  13935. struct ssl_func *sw,
  13936. int *feature_missing)
  13937. {
  13938. union {
  13939. void *p;
  13940. void (*fp)(void);
  13941. } u;
  13942. void *dll_handle;
  13943. struct ssl_func *fp;
  13944. int ok;
  13945. int truncated = 0;
  13946. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13947. mg_snprintf(NULL,
  13948. NULL, /* No truncation check for ebuf */
  13949. ebuf,
  13950. ebuf_len,
  13951. "%s: cannot load %s",
  13952. __func__,
  13953. dll_name);
  13954. return NULL;
  13955. }
  13956. ok = 1;
  13957. for (fp = sw; fp->name != NULL; fp++) {
  13958. #if defined(_WIN32)
  13959. /* GetProcAddress() returns pointer to function */
  13960. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13961. #else
  13962. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13963. * pointers to function pointers. We need to use a union to make a
  13964. * cast. */
  13965. u.p = dlsym(dll_handle, fp->name);
  13966. #endif /* _WIN32 */
  13967. /* Set pointer (might be NULL) */
  13968. fp->ptr = u.fp;
  13969. if (u.fp == NULL) {
  13970. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13971. if (feature_missing) {
  13972. feature_missing[fp->required]++;
  13973. }
  13974. if (fp->required == TLS_Mandatory) {
  13975. /* Mandatory function is missing */
  13976. if (ok) {
  13977. /* This is the first missing function.
  13978. * Create a new error message. */
  13979. mg_snprintf(NULL,
  13980. &truncated,
  13981. ebuf,
  13982. ebuf_len,
  13983. "%s: %s: cannot find %s",
  13984. __func__,
  13985. dll_name,
  13986. fp->name);
  13987. ok = 0;
  13988. } else {
  13989. /* This is yet anothermissing function.
  13990. * Append existing error message. */
  13991. size_t cur_len = strlen(ebuf);
  13992. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13993. mg_snprintf(NULL,
  13994. &truncated,
  13995. ebuf + cur_len,
  13996. ebuf_len - cur_len - 3,
  13997. ", %s",
  13998. fp->name);
  13999. if (truncated) {
  14000. /* If truncated, add "..." */
  14001. strcat(ebuf, "...");
  14002. }
  14003. }
  14004. }
  14005. }
  14006. }
  14007. }
  14008. if (!ok) {
  14009. (void)dlclose(dll_handle);
  14010. return NULL;
  14011. }
  14012. return dll_handle;
  14013. }
  14014. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14015. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14016. #endif /* NO_SSL_DL */
  14017. #if defined(SSL_ALREADY_INITIALIZED)
  14018. static volatile ptrdiff_t cryptolib_users =
  14019. 1; /* Reference counter for crypto library. */
  14020. #else
  14021. static volatile ptrdiff_t cryptolib_users =
  14022. 0; /* Reference counter for crypto library. */
  14023. #endif
  14024. static int
  14025. initialize_ssl(char *ebuf, size_t ebuf_len)
  14026. {
  14027. #if !defined(OPENSSL_API_1_1)
  14028. int i, num_locks;
  14029. size_t size;
  14030. #endif
  14031. if (ebuf_len > 0) {
  14032. ebuf[0] = 0;
  14033. }
  14034. #if !defined(NO_SSL_DL)
  14035. if (!cryptolib_dll_handle) {
  14036. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14037. cryptolib_dll_handle = load_tls_dll(
  14038. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14039. if (!cryptolib_dll_handle) {
  14040. mg_snprintf(NULL,
  14041. NULL, /* No truncation check for ebuf */
  14042. ebuf,
  14043. ebuf_len,
  14044. "%s: error loading library %s",
  14045. __func__,
  14046. CRYPTO_LIB);
  14047. DEBUG_TRACE("%s", ebuf);
  14048. return 0;
  14049. }
  14050. }
  14051. #endif /* NO_SSL_DL */
  14052. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14053. return 1;
  14054. }
  14055. #if !defined(OPENSSL_API_1_1)
  14056. /* Initialize locking callbacks, needed for thread safety.
  14057. * http://www.openssl.org/support/faq.html#PROG1
  14058. */
  14059. num_locks = CRYPTO_num_locks();
  14060. if (num_locks < 0) {
  14061. num_locks = 0;
  14062. }
  14063. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14064. /* allocate mutex array, if required */
  14065. if (num_locks == 0) {
  14066. /* No mutex array required */
  14067. ssl_mutexes = NULL;
  14068. } else {
  14069. /* Mutex array required - allocate it */
  14070. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14071. /* Check OOM */
  14072. if (ssl_mutexes == NULL) {
  14073. mg_snprintf(NULL,
  14074. NULL, /* No truncation check for ebuf */
  14075. ebuf,
  14076. ebuf_len,
  14077. "%s: cannot allocate mutexes: %s",
  14078. __func__,
  14079. ssl_error());
  14080. DEBUG_TRACE("%s", ebuf);
  14081. return 0;
  14082. }
  14083. /* initialize mutex array */
  14084. for (i = 0; i < num_locks; i++) {
  14085. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14086. mg_snprintf(NULL,
  14087. NULL, /* No truncation check for ebuf */
  14088. ebuf,
  14089. ebuf_len,
  14090. "%s: error initializing mutex %i of %i",
  14091. __func__,
  14092. i,
  14093. num_locks);
  14094. DEBUG_TRACE("%s", ebuf);
  14095. mg_free(ssl_mutexes);
  14096. return 0;
  14097. }
  14098. }
  14099. }
  14100. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14101. CRYPTO_set_id_callback(&mg_current_thread_id);
  14102. #endif /* OPENSSL_API_1_1 */
  14103. #if !defined(NO_SSL_DL)
  14104. if (!ssllib_dll_handle) {
  14105. ssllib_dll_handle =
  14106. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14107. if (!ssllib_dll_handle) {
  14108. #if !defined(OPENSSL_API_1_1)
  14109. mg_free(ssl_mutexes);
  14110. #endif
  14111. DEBUG_TRACE("%s", ebuf);
  14112. return 0;
  14113. }
  14114. }
  14115. #endif /* NO_SSL_DL */
  14116. #if defined(OPENSSL_API_1_1)
  14117. /* Initialize SSL library */
  14118. OPENSSL_init_ssl(0, NULL);
  14119. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14120. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14121. NULL);
  14122. #else
  14123. /* Initialize SSL library */
  14124. SSL_library_init();
  14125. SSL_load_error_strings();
  14126. #endif
  14127. return 1;
  14128. }
  14129. static int
  14130. ssl_use_pem_file(struct mg_context *phys_ctx,
  14131. struct mg_domain_context *dom_ctx,
  14132. const char *pem,
  14133. const char *chain)
  14134. {
  14135. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14136. mg_cry_ctx_internal(phys_ctx,
  14137. "%s: cannot open certificate file %s: %s",
  14138. __func__,
  14139. pem,
  14140. ssl_error());
  14141. return 0;
  14142. }
  14143. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14144. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14145. mg_cry_ctx_internal(phys_ctx,
  14146. "%s: cannot open private key file %s: %s",
  14147. __func__,
  14148. pem,
  14149. ssl_error());
  14150. return 0;
  14151. }
  14152. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14153. mg_cry_ctx_internal(phys_ctx,
  14154. "%s: certificate and private key do not match: %s",
  14155. __func__,
  14156. pem);
  14157. return 0;
  14158. }
  14159. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14160. * chain files that contain private keys and certificates in
  14161. * SSL_CTX_use_certificate_chain_file.
  14162. * The CivetWeb-Server used pem-Files that contained both information.
  14163. * In order to make wolfSSL work, it is split in two files.
  14164. * One file that contains key and certificate used by the server and
  14165. * an optional chain file for the ssl stack.
  14166. */
  14167. if (chain) {
  14168. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14169. mg_cry_ctx_internal(phys_ctx,
  14170. "%s: cannot use certificate chain file %s: %s",
  14171. __func__,
  14172. chain,
  14173. ssl_error());
  14174. return 0;
  14175. }
  14176. }
  14177. return 1;
  14178. }
  14179. #if defined(OPENSSL_API_1_1)
  14180. static unsigned long
  14181. ssl_get_protocol(int version_id)
  14182. {
  14183. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14184. if (version_id > 0)
  14185. ret |= SSL_OP_NO_SSLv2;
  14186. if (version_id > 1)
  14187. ret |= SSL_OP_NO_SSLv3;
  14188. if (version_id > 2)
  14189. ret |= SSL_OP_NO_TLSv1;
  14190. if (version_id > 3)
  14191. ret |= SSL_OP_NO_TLSv1_1;
  14192. if (version_id > 4)
  14193. ret |= SSL_OP_NO_TLSv1_2;
  14194. #if defined(SSL_OP_NO_TLSv1_3)
  14195. if (version_id > 5)
  14196. ret |= SSL_OP_NO_TLSv1_3;
  14197. #endif
  14198. return ret;
  14199. }
  14200. #else
  14201. static long
  14202. ssl_get_protocol(int version_id)
  14203. {
  14204. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14205. if (version_id > 0)
  14206. ret |= SSL_OP_NO_SSLv2;
  14207. if (version_id > 1)
  14208. ret |= SSL_OP_NO_SSLv3;
  14209. if (version_id > 2)
  14210. ret |= SSL_OP_NO_TLSv1;
  14211. if (version_id > 3)
  14212. ret |= SSL_OP_NO_TLSv1_1;
  14213. if (version_id > 4)
  14214. ret |= SSL_OP_NO_TLSv1_2;
  14215. #if defined(SSL_OP_NO_TLSv1_3)
  14216. if (version_id > 5)
  14217. ret |= SSL_OP_NO_TLSv1_3;
  14218. #endif
  14219. return (long)ret;
  14220. }
  14221. #endif /* OPENSSL_API_1_1 */
  14222. /* SSL callback documentation:
  14223. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14224. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14225. * https://linux.die.net/man/3/ssl_set_info_callback */
  14226. /* Note: There is no "const" for the first argument in the documentation
  14227. * examples, however some (maybe most, but not all) headers of OpenSSL
  14228. * versions / OpenSSL compatibility layers have it. Having a different
  14229. * definition will cause a warning in C and an error in C++. Use "const SSL
  14230. * *", while automatical conversion from "SSL *" works for all compilers,
  14231. * but not other way around */
  14232. static void
  14233. ssl_info_callback(const SSL *ssl, int what, int ret)
  14234. {
  14235. (void)ret;
  14236. if (what & SSL_CB_HANDSHAKE_START) {
  14237. SSL_get_app_data(ssl);
  14238. }
  14239. if (what & SSL_CB_HANDSHAKE_DONE) {
  14240. /* TODO: check for openSSL 1.1 */
  14241. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14242. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14243. }
  14244. }
  14245. static int
  14246. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14247. {
  14248. #if defined(GCC_DIAGNOSTIC)
  14249. #pragma GCC diagnostic push
  14250. #pragma GCC diagnostic ignored "-Wcast-align"
  14251. #endif /* defined(GCC_DIAGNOSTIC) */
  14252. /* We used an aligned pointer in SSL_set_app_data */
  14253. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14254. #if defined(GCC_DIAGNOSTIC)
  14255. #pragma GCC diagnostic pop
  14256. #endif /* defined(GCC_DIAGNOSTIC) */
  14257. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14258. (void)ad;
  14259. (void)arg;
  14260. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14261. DEBUG_ASSERT(0);
  14262. return SSL_TLSEXT_ERR_NOACK;
  14263. }
  14264. conn->dom_ctx = &(conn->phys_ctx->dd);
  14265. /* Old clients (Win XP) will not support SNI. Then, there
  14266. * is no server name available in the request - we can
  14267. * only work with the default certificate.
  14268. * Multiple HTTPS hosts on one IP+port are only possible
  14269. * with a certificate containing all alternative names.
  14270. */
  14271. if ((servername == NULL) || (*servername == 0)) {
  14272. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14273. mg_lock_context(conn->phys_ctx);
  14274. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14275. mg_unlock_context(conn->phys_ctx);
  14276. return SSL_TLSEXT_ERR_NOACK;
  14277. }
  14278. DEBUG_TRACE("TLS connection to host %s", servername);
  14279. while (conn->dom_ctx) {
  14280. if (!mg_strcasecmp(servername,
  14281. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14282. /* Found matching domain */
  14283. DEBUG_TRACE("TLS domain %s found",
  14284. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14285. break;
  14286. }
  14287. mg_lock_context(conn->phys_ctx);
  14288. conn->dom_ctx = conn->dom_ctx->next;
  14289. mg_unlock_context(conn->phys_ctx);
  14290. }
  14291. if (conn->dom_ctx == NULL) {
  14292. /* Default domain */
  14293. DEBUG_TRACE("TLS default domain %s used",
  14294. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14295. conn->dom_ctx = &(conn->phys_ctx->dd);
  14296. }
  14297. mg_lock_context(conn->phys_ctx);
  14298. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14299. mg_unlock_context(conn->phys_ctx);
  14300. return SSL_TLSEXT_ERR_OK;
  14301. }
  14302. #if defined(USE_ALPN)
  14303. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14304. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14305. alpn_proto_list + 3 + 8,
  14306. NULL};
  14307. #if defined(USE_HTTP2)
  14308. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14309. alpn_proto_list + 3,
  14310. alpn_proto_list + 3 + 8,
  14311. NULL};
  14312. #endif
  14313. static int
  14314. alpn_select_cb(SSL *ssl,
  14315. const unsigned char **out,
  14316. unsigned char *outlen,
  14317. const unsigned char *in,
  14318. unsigned int inlen,
  14319. void *arg)
  14320. {
  14321. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14322. unsigned int i, j, enable_http2 = 0;
  14323. const char **alpn_proto_order = alpn_proto_order_http1;
  14324. struct mg_workerTLS *tls =
  14325. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14326. (void)ssl;
  14327. if (tls == NULL) {
  14328. /* Need to store protocol in Thread Local Storage */
  14329. /* If there is no Thread Local Storage, don't use ALPN */
  14330. return SSL_TLSEXT_ERR_NOACK;
  14331. }
  14332. #if defined(USE_HTTP2)
  14333. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14334. if (enable_http2) {
  14335. alpn_proto_order = alpn_proto_order_http2;
  14336. }
  14337. #endif
  14338. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14339. /* check all accepted protocols in this order */
  14340. const char *alpn_proto = alpn_proto_order[j];
  14341. /* search input for matching protocol */
  14342. for (i = 0; i < inlen; i++) {
  14343. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14344. *out = in + i + 1;
  14345. *outlen = in[i];
  14346. tls->alpn_proto = alpn_proto;
  14347. return SSL_TLSEXT_ERR_OK;
  14348. }
  14349. }
  14350. }
  14351. /* Nothing found */
  14352. return SSL_TLSEXT_ERR_NOACK;
  14353. }
  14354. static int
  14355. next_protos_advertised_cb(SSL *ssl,
  14356. const unsigned char **data,
  14357. unsigned int *len,
  14358. void *arg)
  14359. {
  14360. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14361. *data = (const unsigned char *)alpn_proto_list;
  14362. *len = (unsigned int)strlen((const char *)data);
  14363. (void)ssl;
  14364. (void)dom_ctx;
  14365. return SSL_TLSEXT_ERR_OK;
  14366. }
  14367. static int
  14368. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14369. {
  14370. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14371. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14372. (const unsigned char *)alpn_proto_list,
  14373. alpn_len);
  14374. if (ret != 0) {
  14375. mg_cry_ctx_internal(phys_ctx,
  14376. "SSL_CTX_set_alpn_protos error: %s",
  14377. ssl_error());
  14378. }
  14379. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14380. alpn_select_cb,
  14381. (void *)dom_ctx);
  14382. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14383. next_protos_advertised_cb,
  14384. (void *)dom_ctx);
  14385. return ret;
  14386. }
  14387. #endif
  14388. /* Setup SSL CTX as required by CivetWeb */
  14389. static int
  14390. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14391. struct mg_domain_context *dom_ctx,
  14392. const char *pem,
  14393. const char *chain)
  14394. {
  14395. int callback_ret;
  14396. int should_verify_peer;
  14397. int peer_certificate_optional;
  14398. const char *ca_path;
  14399. const char *ca_file;
  14400. int use_default_verify_paths;
  14401. int verify_depth;
  14402. struct timespec now_mt;
  14403. md5_byte_t ssl_context_id[16];
  14404. md5_state_t md5state;
  14405. int protocol_ver;
  14406. int ssl_cache_timeout;
  14407. #if defined(OPENSSL_API_1_1)
  14408. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14409. mg_cry_ctx_internal(phys_ctx,
  14410. "SSL_CTX_new (server) error: %s",
  14411. ssl_error());
  14412. return 0;
  14413. }
  14414. #else
  14415. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14416. mg_cry_ctx_internal(phys_ctx,
  14417. "SSL_CTX_new (server) error: %s",
  14418. ssl_error());
  14419. return 0;
  14420. }
  14421. #endif /* OPENSSL_API_1_1 */
  14422. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14423. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14424. | SSL_OP_NO_TLSv1_1);
  14425. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14426. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14427. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14428. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14429. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14430. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14431. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14432. #if defined(SSL_OP_NO_RENEGOTIATION)
  14433. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14434. #endif
  14435. #if !defined(NO_SSL_DL)
  14436. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14437. #endif /* NO_SSL_DL */
  14438. /* In SSL documentation examples callback defined without const
  14439. * specifier 'void (*)(SSL *, int, int)' See:
  14440. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14441. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14442. * But in the source code const SSL is used:
  14443. * 'void (*)(const SSL *, int, int)' See:
  14444. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14445. * Problem about wrong documentation described, but not resolved:
  14446. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14447. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14448. * But when compiled with modern C++ compiler, correct const should be
  14449. * provided
  14450. */
  14451. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14452. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14453. ssl_servername_callback);
  14454. /* If a callback has been specified, call it. */
  14455. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14456. ? 0
  14457. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14458. phys_ctx->user_data));
  14459. /* If callback returns 0, civetweb sets up the SSL certificate.
  14460. * If it returns 1, civetweb assumes the calback already did this.
  14461. * If it returns -1, initializing ssl fails. */
  14462. if (callback_ret < 0) {
  14463. mg_cry_ctx_internal(phys_ctx,
  14464. "SSL callback returned error: %i",
  14465. callback_ret);
  14466. return 0;
  14467. }
  14468. if (callback_ret > 0) {
  14469. /* Callback did everything. */
  14470. return 1;
  14471. }
  14472. /* If a domain callback has been specified, call it. */
  14473. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14474. ? 0
  14475. : (phys_ctx->callbacks.init_ssl_domain(
  14476. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14477. dom_ctx->ssl_ctx,
  14478. phys_ctx->user_data));
  14479. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14480. * If it returns 1, civetweb assumes the calback already did this.
  14481. * If it returns -1, initializing ssl fails. */
  14482. if (callback_ret < 0) {
  14483. mg_cry_ctx_internal(phys_ctx,
  14484. "Domain SSL callback returned error: %i",
  14485. callback_ret);
  14486. return 0;
  14487. }
  14488. if (callback_ret > 0) {
  14489. /* Domain callback did everything. */
  14490. return 1;
  14491. }
  14492. /* Use some combination of start time, domain and port as a SSL
  14493. * context ID. This should be unique on the current machine. */
  14494. md5_init(&md5state);
  14495. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14496. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14497. md5_append(&md5state,
  14498. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14499. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14500. md5_append(&md5state,
  14501. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14502. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14503. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14504. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14505. md5_finish(&md5state, ssl_context_id);
  14506. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14507. (unsigned char *)ssl_context_id,
  14508. sizeof(ssl_context_id));
  14509. if (pem != NULL) {
  14510. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14511. return 0;
  14512. }
  14513. }
  14514. /* Should we support client certificates? */
  14515. /* Default is "no". */
  14516. should_verify_peer = 0;
  14517. peer_certificate_optional = 0;
  14518. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14519. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14520. /* Yes, they are mandatory */
  14521. should_verify_peer = 1;
  14522. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14523. "optional")
  14524. == 0) {
  14525. /* Yes, they are optional */
  14526. should_verify_peer = 1;
  14527. peer_certificate_optional = 1;
  14528. }
  14529. }
  14530. use_default_verify_paths =
  14531. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14532. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14533. == 0);
  14534. if (should_verify_peer) {
  14535. ca_path = dom_ctx->config[SSL_CA_PATH];
  14536. ca_file = dom_ctx->config[SSL_CA_FILE];
  14537. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14538. != 1) {
  14539. mg_cry_ctx_internal(phys_ctx,
  14540. "SSL_CTX_load_verify_locations error: %s "
  14541. "ssl_verify_peer requires setting "
  14542. "either ssl_ca_path or ssl_ca_file. "
  14543. "Is any of them present in the "
  14544. ".conf file?",
  14545. ssl_error());
  14546. return 0;
  14547. }
  14548. if (peer_certificate_optional) {
  14549. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14550. } else {
  14551. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14552. SSL_VERIFY_PEER
  14553. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14554. NULL);
  14555. }
  14556. if (use_default_verify_paths
  14557. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14558. mg_cry_ctx_internal(phys_ctx,
  14559. "SSL_CTX_set_default_verify_paths error: %s",
  14560. ssl_error());
  14561. return 0;
  14562. }
  14563. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14564. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14565. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14566. }
  14567. }
  14568. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14569. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14570. dom_ctx->config[SSL_CIPHER_LIST])
  14571. != 1) {
  14572. mg_cry_ctx_internal(phys_ctx,
  14573. "SSL_CTX_set_cipher_list error: %s",
  14574. ssl_error());
  14575. }
  14576. }
  14577. /* SSL session caching */
  14578. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14579. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14580. : 0);
  14581. if (ssl_cache_timeout > 0) {
  14582. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14583. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14584. * default */
  14585. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14586. }
  14587. #if defined(USE_ALPN)
  14588. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14589. #if !defined(NO_SSL_DL)
  14590. if (!tls_feature_missing[TLS_ALPN])
  14591. #endif
  14592. {
  14593. init_alpn(phys_ctx, dom_ctx);
  14594. }
  14595. #endif
  14596. return 1;
  14597. }
  14598. /* Check if SSL is required.
  14599. * If so, dynamically load SSL library
  14600. * and set up ctx->ssl_ctx pointer. */
  14601. static int
  14602. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14603. {
  14604. void *ssl_ctx = 0;
  14605. int callback_ret;
  14606. const char *pem;
  14607. const char *chain;
  14608. char ebuf[128];
  14609. if (!phys_ctx) {
  14610. return 0;
  14611. }
  14612. if (!dom_ctx) {
  14613. dom_ctx = &(phys_ctx->dd);
  14614. }
  14615. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14616. /* No SSL port is set. No need to setup SSL. */
  14617. return 1;
  14618. }
  14619. /* Check for external SSL_CTX */
  14620. callback_ret =
  14621. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14622. ? 0
  14623. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14624. phys_ctx->user_data));
  14625. if (callback_ret < 0) {
  14626. /* Callback exists and returns <0: Initializing failed. */
  14627. mg_cry_ctx_internal(phys_ctx,
  14628. "external_ssl_ctx callback returned error: %i",
  14629. callback_ret);
  14630. return 0;
  14631. } else if (callback_ret > 0) {
  14632. /* Callback exists and returns >0: Initializing complete,
  14633. * civetweb should not modify the SSL context. */
  14634. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14635. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14636. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14637. return 0;
  14638. }
  14639. return 1;
  14640. }
  14641. /* If the callback does not exist or return 0, civetweb must initialize
  14642. * the SSL context. Handle "domain" callback next. */
  14643. /* Check for external domain SSL_CTX callback. */
  14644. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14645. ? 0
  14646. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14647. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14648. &ssl_ctx,
  14649. phys_ctx->user_data));
  14650. if (callback_ret < 0) {
  14651. /* Callback < 0: Error. Abort init. */
  14652. mg_cry_ctx_internal(
  14653. phys_ctx,
  14654. "external_ssl_ctx_domain callback returned error: %i",
  14655. callback_ret);
  14656. return 0;
  14657. } else if (callback_ret > 0) {
  14658. /* Callback > 0: Consider init done. */
  14659. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14660. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14661. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14662. return 0;
  14663. }
  14664. return 1;
  14665. }
  14666. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14667. * 0, CivetWeb should continue initializing SSL */
  14668. /* If PEM file is not specified and the init_ssl callbacks
  14669. * are not specified, setup will fail. */
  14670. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14671. && (phys_ctx->callbacks.init_ssl == NULL)
  14672. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14673. /* No certificate and no init_ssl callbacks:
  14674. * Essential data to set up TLS is missing.
  14675. */
  14676. mg_cry_ctx_internal(phys_ctx,
  14677. "Initializing SSL failed: -%s is not set",
  14678. config_options[SSL_CERTIFICATE].name);
  14679. return 0;
  14680. }
  14681. /* If a certificate chain is configured, use it. */
  14682. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14683. if (chain == NULL) {
  14684. /* Default: certificate chain in PEM file */
  14685. chain = pem;
  14686. }
  14687. if ((chain != NULL) && (*chain == 0)) {
  14688. /* If the chain is an empty string, don't use it. */
  14689. chain = NULL;
  14690. }
  14691. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14692. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14693. return 0;
  14694. }
  14695. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14696. }
  14697. static void
  14698. uninitialize_ssl(void)
  14699. {
  14700. #if defined(OPENSSL_API_1_1)
  14701. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14702. /* Shutdown according to
  14703. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14704. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14705. */
  14706. CONF_modules_unload(1);
  14707. #else
  14708. int i;
  14709. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14710. /* Shutdown according to
  14711. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14712. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14713. */
  14714. CRYPTO_set_locking_callback(NULL);
  14715. CRYPTO_set_id_callback(NULL);
  14716. ENGINE_cleanup();
  14717. CONF_modules_unload(1);
  14718. ERR_free_strings();
  14719. EVP_cleanup();
  14720. CRYPTO_cleanup_all_ex_data();
  14721. OPENSSL_REMOVE_THREAD_STATE();
  14722. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14723. pthread_mutex_destroy(&ssl_mutexes[i]);
  14724. }
  14725. mg_free(ssl_mutexes);
  14726. ssl_mutexes = NULL;
  14727. #endif /* OPENSSL_API_1_1 */
  14728. }
  14729. }
  14730. #endif /* !NO_SSL */
  14731. #if !defined(NO_FILESYSTEMS)
  14732. static int
  14733. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14734. {
  14735. if (phys_ctx) {
  14736. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14737. const char *path;
  14738. struct mg_connection fc;
  14739. if (!dom_ctx) {
  14740. dom_ctx = &(phys_ctx->dd);
  14741. }
  14742. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14743. if ((path != NULL)
  14744. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14745. mg_cry_ctx_internal(phys_ctx,
  14746. "Cannot open %s: %s",
  14747. path,
  14748. strerror(ERRNO));
  14749. return 0;
  14750. }
  14751. return 1;
  14752. }
  14753. return 0;
  14754. }
  14755. #endif /* NO_FILESYSTEMS */
  14756. static int
  14757. set_acl_option(struct mg_context *phys_ctx)
  14758. {
  14759. union usa sa;
  14760. memset(&sa, 0, sizeof(sa));
  14761. #if defined(USE_IPV6)
  14762. sa.sin6.sin6_family = AF_INET6;
  14763. #else
  14764. sa.sin.sin_family = AF_INET;
  14765. #endif
  14766. return check_acl(phys_ctx, &sa) != -1;
  14767. }
  14768. static void
  14769. reset_per_request_attributes(struct mg_connection *conn)
  14770. {
  14771. if (!conn) {
  14772. return;
  14773. }
  14774. conn->num_bytes_sent = conn->consumed_content = 0;
  14775. conn->path_info = NULL;
  14776. conn->status_code = -1;
  14777. conn->content_len = -1;
  14778. conn->is_chunked = 0;
  14779. conn->must_close = 0;
  14780. conn->request_len = 0;
  14781. conn->request_state = 0;
  14782. conn->throttle = 0;
  14783. conn->accept_gzip = 0;
  14784. conn->response_info.content_length = conn->request_info.content_length = -1;
  14785. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14786. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14787. conn->response_info.status_text = NULL;
  14788. conn->response_info.status_code = 0;
  14789. conn->request_info.remote_user = NULL;
  14790. conn->request_info.request_method = NULL;
  14791. conn->request_info.request_uri = NULL;
  14792. conn->request_info.local_uri = NULL;
  14793. #if defined(MG_LEGACY_INTERFACE)
  14794. /* Legacy before split into local_uri and request_uri */
  14795. conn->request_info.uri = NULL;
  14796. #endif
  14797. }
  14798. static int
  14799. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  14800. {
  14801. if ((so->lsa.sa.sa_family == AF_INET)
  14802. || (so->lsa.sa.sa_family == AF_INET6)) {
  14803. /* Only for TCP sockets */
  14804. if (setsockopt(so->sock,
  14805. IPPROTO_TCP,
  14806. TCP_NODELAY,
  14807. (SOCK_OPT_TYPE)&nodelay_on,
  14808. sizeof(nodelay_on))
  14809. != 0) {
  14810. /* Error */
  14811. return 1;
  14812. }
  14813. }
  14814. /* OK */
  14815. return 0;
  14816. }
  14817. #if !defined(__ZEPHYR__)
  14818. static void
  14819. close_socket_gracefully(struct mg_connection *conn)
  14820. {
  14821. #if defined(_WIN32)
  14822. char buf[MG_BUF_LEN];
  14823. int n;
  14824. #endif
  14825. struct linger linger;
  14826. int error_code = 0;
  14827. int linger_timeout = -2;
  14828. socklen_t opt_len = sizeof(error_code);
  14829. if (!conn) {
  14830. return;
  14831. }
  14832. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14833. * "Note that enabling a nonzero timeout on a nonblocking socket
  14834. * is not recommended.", so set it to blocking now */
  14835. set_blocking_mode(conn->client.sock);
  14836. /* Send FIN to the client */
  14837. shutdown(conn->client.sock, SHUTDOWN_WR);
  14838. #if defined(_WIN32)
  14839. /* Read and discard pending incoming data. If we do not do that and
  14840. * close
  14841. * the socket, the data in the send buffer may be discarded. This
  14842. * behaviour is seen on Windows, when client keeps sending data
  14843. * when server decides to close the connection; then when client
  14844. * does recv() it gets no data back. */
  14845. do {
  14846. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14847. } while (n > 0);
  14848. #endif
  14849. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14850. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14851. }
  14852. /* Set linger option according to configuration */
  14853. if (linger_timeout >= 0) {
  14854. /* Set linger option to avoid socket hanging out after close. This
  14855. * prevent ephemeral port exhaust problem under high QPS. */
  14856. linger.l_onoff = 1;
  14857. #if defined(_MSC_VER)
  14858. #pragma warning(push)
  14859. #pragma warning(disable : 4244)
  14860. #endif
  14861. #if defined(GCC_DIAGNOSTIC)
  14862. #pragma GCC diagnostic push
  14863. #pragma GCC diagnostic ignored "-Wconversion"
  14864. #endif
  14865. /* Data type of linger structure elements may differ,
  14866. * so we don't know what cast we need here.
  14867. * Disable type conversion warnings. */
  14868. linger.l_linger = (linger_timeout + 999) / 1000;
  14869. #if defined(GCC_DIAGNOSTIC)
  14870. #pragma GCC diagnostic pop
  14871. #endif
  14872. #if defined(_MSC_VER)
  14873. #pragma warning(pop)
  14874. #endif
  14875. } else {
  14876. linger.l_onoff = 0;
  14877. linger.l_linger = 0;
  14878. }
  14879. if (linger_timeout < -1) {
  14880. /* Default: don't configure any linger */
  14881. } else if (getsockopt(conn->client.sock,
  14882. SOL_SOCKET,
  14883. SO_ERROR,
  14884. #if defined(_WIN32) /* WinSock uses different data type here */
  14885. (char *)&error_code,
  14886. #else
  14887. &error_code,
  14888. #endif
  14889. &opt_len)
  14890. != 0) {
  14891. /* Cannot determine if socket is already closed. This should
  14892. * not occur and never did in a test. Log an error message
  14893. * and continue. */
  14894. mg_cry_internal(conn,
  14895. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14896. __func__,
  14897. strerror(ERRNO));
  14898. #if defined(_WIN32)
  14899. } else if (error_code == WSAECONNRESET) {
  14900. #else
  14901. } else if (error_code == ECONNRESET) {
  14902. #endif
  14903. /* Socket already closed by client/peer, close socket without linger
  14904. */
  14905. } else {
  14906. /* Set linger timeout */
  14907. if (setsockopt(conn->client.sock,
  14908. SOL_SOCKET,
  14909. SO_LINGER,
  14910. (char *)&linger,
  14911. sizeof(linger))
  14912. != 0) {
  14913. mg_cry_internal(
  14914. conn,
  14915. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14916. __func__,
  14917. linger.l_onoff,
  14918. linger.l_linger,
  14919. strerror(ERRNO));
  14920. }
  14921. }
  14922. /* Now we know that our FIN is ACK-ed, safe to close */
  14923. closesocket(conn->client.sock);
  14924. conn->client.sock = INVALID_SOCKET;
  14925. }
  14926. #endif
  14927. static void
  14928. close_connection(struct mg_connection *conn)
  14929. {
  14930. #if defined(USE_SERVER_STATS)
  14931. conn->conn_state = 6; /* to close */
  14932. #endif
  14933. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14934. if (conn->lua_websocket_state) {
  14935. lua_websocket_close(conn, conn->lua_websocket_state);
  14936. conn->lua_websocket_state = NULL;
  14937. }
  14938. #endif
  14939. mg_lock_connection(conn);
  14940. /* Set close flag, so keep-alive loops will stop */
  14941. conn->must_close = 1;
  14942. /* call the connection_close callback if assigned */
  14943. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14944. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14945. conn->phys_ctx->callbacks.connection_close(conn);
  14946. }
  14947. }
  14948. /* Reset user data, after close callback is called.
  14949. * Do not reuse it. If the user needs a destructor,
  14950. * it must be done in the connection_close callback. */
  14951. mg_set_user_connection_data(conn, NULL);
  14952. #if defined(USE_SERVER_STATS)
  14953. conn->conn_state = 7; /* closing */
  14954. #endif
  14955. #if !defined(NO_SSL)
  14956. if (conn->ssl != NULL) {
  14957. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14958. */
  14959. SSL_shutdown(conn->ssl);
  14960. SSL_free(conn->ssl);
  14961. OPENSSL_REMOVE_THREAD_STATE();
  14962. conn->ssl = NULL;
  14963. }
  14964. #endif
  14965. if (conn->client.sock != INVALID_SOCKET) {
  14966. #if defined(__ZEPHYR__)
  14967. closesocket(conn->client.sock);
  14968. #else
  14969. close_socket_gracefully(conn);
  14970. #endif
  14971. conn->client.sock = INVALID_SOCKET;
  14972. }
  14973. mg_unlock_connection(conn);
  14974. #if defined(USE_SERVER_STATS)
  14975. conn->conn_state = 8; /* closed */
  14976. #endif
  14977. }
  14978. void
  14979. mg_close_connection(struct mg_connection *conn)
  14980. {
  14981. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14982. return;
  14983. }
  14984. #if defined(USE_WEBSOCKET)
  14985. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14986. if (conn->in_websocket_handling) {
  14987. /* Set close flag, so the server thread can exit. */
  14988. conn->must_close = 1;
  14989. return;
  14990. }
  14991. }
  14992. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14993. unsigned int i;
  14994. /* client context: loops must end */
  14995. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14996. conn->must_close = 1;
  14997. /* We need to get the client thread out of the select/recv call
  14998. * here. */
  14999. /* Since we use a sleep quantum of some seconds to check for recv
  15000. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15001. /* join worker thread */
  15002. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15003. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15004. }
  15005. }
  15006. #endif /* defined(USE_WEBSOCKET) */
  15007. close_connection(conn);
  15008. #if !defined(NO_SSL)
  15009. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15010. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15011. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15012. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15013. }
  15014. #endif
  15015. #if defined(USE_WEBSOCKET)
  15016. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15017. mg_free(conn->phys_ctx->worker_threadids);
  15018. (void)pthread_mutex_destroy(&conn->mutex);
  15019. mg_free(conn);
  15020. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15021. (void)pthread_mutex_destroy(&conn->mutex);
  15022. mg_free(conn);
  15023. }
  15024. #else
  15025. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15026. (void)pthread_mutex_destroy(&conn->mutex);
  15027. mg_free(conn);
  15028. }
  15029. #endif /* defined(USE_WEBSOCKET) */
  15030. }
  15031. static struct mg_connection *
  15032. mg_connect_client_impl(const struct mg_client_options *client_options,
  15033. int use_ssl,
  15034. char *ebuf,
  15035. size_t ebuf_len)
  15036. {
  15037. struct mg_connection *conn = NULL;
  15038. SOCKET sock;
  15039. union usa sa;
  15040. struct sockaddr *psa;
  15041. socklen_t len;
  15042. unsigned max_req_size =
  15043. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15044. /* Size of structures, aligned to 8 bytes */
  15045. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15046. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15047. conn =
  15048. (struct mg_connection *)mg_calloc(1,
  15049. conn_size + ctx_size + max_req_size);
  15050. if (conn == NULL) {
  15051. mg_snprintf(NULL,
  15052. NULL, /* No truncation check for ebuf */
  15053. ebuf,
  15054. ebuf_len,
  15055. "calloc(): %s",
  15056. strerror(ERRNO));
  15057. return NULL;
  15058. }
  15059. #if defined(GCC_DIAGNOSTIC)
  15060. #pragma GCC diagnostic push
  15061. #pragma GCC diagnostic ignored "-Wcast-align"
  15062. #endif /* defined(GCC_DIAGNOSTIC) */
  15063. /* conn_size is aligned to 8 bytes */
  15064. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15065. #if defined(GCC_DIAGNOSTIC)
  15066. #pragma GCC diagnostic pop
  15067. #endif /* defined(GCC_DIAGNOSTIC) */
  15068. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15069. conn->buf_size = (int)max_req_size;
  15070. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15071. conn->dom_ctx = &(conn->phys_ctx->dd);
  15072. if (!connect_socket(conn->phys_ctx,
  15073. client_options->host,
  15074. client_options->port,
  15075. use_ssl,
  15076. ebuf,
  15077. ebuf_len,
  15078. &sock,
  15079. &sa)) {
  15080. /* ebuf is set by connect_socket,
  15081. * free all memory and return NULL; */
  15082. mg_free(conn);
  15083. return NULL;
  15084. }
  15085. #if !defined(NO_SSL)
  15086. #if defined(OPENSSL_API_1_1)
  15087. if (use_ssl
  15088. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15089. == NULL) {
  15090. mg_snprintf(NULL,
  15091. NULL, /* No truncation check for ebuf */
  15092. ebuf,
  15093. ebuf_len,
  15094. "SSL_CTX_new error: %s",
  15095. ssl_error());
  15096. closesocket(sock);
  15097. mg_free(conn);
  15098. return NULL;
  15099. }
  15100. #else
  15101. if (use_ssl
  15102. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15103. == NULL) {
  15104. mg_snprintf(NULL,
  15105. NULL, /* No truncation check for ebuf */
  15106. ebuf,
  15107. ebuf_len,
  15108. "SSL_CTX_new error: %s",
  15109. ssl_error());
  15110. closesocket(sock);
  15111. mg_free(conn);
  15112. return NULL;
  15113. }
  15114. #endif /* OPENSSL_API_1_1 */
  15115. #endif /* NO_SSL */
  15116. #if defined(USE_IPV6)
  15117. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15118. : sizeof(conn->client.rsa.sin6);
  15119. psa = (sa.sa.sa_family == AF_INET)
  15120. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15121. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15122. #else
  15123. len = sizeof(conn->client.rsa.sin);
  15124. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15125. #endif
  15126. conn->client.sock = sock;
  15127. conn->client.lsa = sa;
  15128. if (getsockname(sock, psa, &len) != 0) {
  15129. mg_cry_internal(conn,
  15130. "%s: getsockname() failed: %s",
  15131. __func__,
  15132. strerror(ERRNO));
  15133. }
  15134. conn->client.is_ssl = use_ssl ? 1 : 0;
  15135. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15136. mg_snprintf(NULL,
  15137. NULL, /* No truncation check for ebuf */
  15138. ebuf,
  15139. ebuf_len,
  15140. "Can not create mutex");
  15141. #if !defined(NO_SSL)
  15142. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15143. #endif
  15144. closesocket(sock);
  15145. mg_free(conn);
  15146. return NULL;
  15147. }
  15148. #if !defined(NO_SSL)
  15149. if (use_ssl) {
  15150. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15151. * SSL_CTX_set_verify call is needed to switch off server
  15152. * certificate checking, which is off by default in OpenSSL and
  15153. * on in yaSSL. */
  15154. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15155. * SSL_VERIFY_PEER, verify_ssl_server); */
  15156. if (client_options->client_cert) {
  15157. if (!ssl_use_pem_file(conn->phys_ctx,
  15158. conn->dom_ctx,
  15159. client_options->client_cert,
  15160. NULL)) {
  15161. mg_snprintf(NULL,
  15162. NULL, /* No truncation check for ebuf */
  15163. ebuf,
  15164. ebuf_len,
  15165. "Can not use SSL client certificate");
  15166. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15167. closesocket(sock);
  15168. mg_free(conn);
  15169. return NULL;
  15170. }
  15171. }
  15172. if (client_options->server_cert) {
  15173. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15174. client_options->server_cert,
  15175. NULL)
  15176. != 1) {
  15177. mg_cry_internal(conn,
  15178. "SSL_CTX_load_verify_locations error: %s ",
  15179. ssl_error());
  15180. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15181. closesocket(sock);
  15182. mg_free(conn);
  15183. return NULL;
  15184. }
  15185. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15186. } else {
  15187. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15188. }
  15189. if (!sslize(conn, SSL_connect, client_options)) {
  15190. mg_snprintf(NULL,
  15191. NULL, /* No truncation check for ebuf */
  15192. ebuf,
  15193. ebuf_len,
  15194. "SSL connection error");
  15195. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15196. closesocket(sock);
  15197. mg_free(conn);
  15198. return NULL;
  15199. }
  15200. }
  15201. #endif
  15202. return conn;
  15203. }
  15204. CIVETWEB_API struct mg_connection *
  15205. mg_connect_client_secure(const struct mg_client_options *client_options,
  15206. char *error_buffer,
  15207. size_t error_buffer_size)
  15208. {
  15209. return mg_connect_client_impl(client_options,
  15210. 1,
  15211. error_buffer,
  15212. error_buffer_size);
  15213. }
  15214. struct mg_connection *
  15215. mg_connect_client(const char *host,
  15216. int port,
  15217. int use_ssl,
  15218. char *error_buffer,
  15219. size_t error_buffer_size)
  15220. {
  15221. struct mg_client_options opts;
  15222. memset(&opts, 0, sizeof(opts));
  15223. opts.host = host;
  15224. opts.port = port;
  15225. return mg_connect_client_impl(&opts,
  15226. use_ssl,
  15227. error_buffer,
  15228. error_buffer_size);
  15229. }
  15230. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15231. struct mg_connection *
  15232. mg_connect_client2(const char *host,
  15233. const char *protocol,
  15234. int port,
  15235. const char *path,
  15236. struct mg_init_data *init,
  15237. struct mg_error_data *error)
  15238. {
  15239. int is_ssl, is_ws;
  15240. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15241. if (error != NULL) {
  15242. error->code = 0;
  15243. if (error->text_buffer_size > 0) {
  15244. *error->text = 0;
  15245. }
  15246. }
  15247. if ((host == NULL) || (protocol == NULL)) {
  15248. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15249. mg_snprintf(NULL,
  15250. NULL, /* No truncation check for error buffers */
  15251. error->text,
  15252. error->text_buffer_size,
  15253. "%s",
  15254. "Invalid parameters");
  15255. }
  15256. return NULL;
  15257. }
  15258. /* check all known protocolls */
  15259. if (!mg_strcasecmp(protocol, "http")) {
  15260. is_ssl = 0;
  15261. is_ws = 0;
  15262. } else if (!mg_strcasecmp(protocol, "https")) {
  15263. is_ssl = 1;
  15264. is_ws = 0;
  15265. #if defined(USE_WEBSOCKET)
  15266. } else if (!mg_strcasecmp(protocol, "ws")) {
  15267. is_ssl = 0;
  15268. is_ws = 1;
  15269. } else if (!mg_strcasecmp(protocol, "wss")) {
  15270. is_ssl = 1;
  15271. is_ws = 1;
  15272. #endif
  15273. } else {
  15274. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15275. mg_snprintf(NULL,
  15276. NULL, /* No truncation check for error buffers */
  15277. error->text,
  15278. error->text_buffer_size,
  15279. "Protocol %s not supported",
  15280. protocol);
  15281. }
  15282. return NULL;
  15283. }
  15284. /* TODO: The current implementation here just calls the old
  15285. * implementations, without using any new options. This is just a first
  15286. * step to test the new interfaces. */
  15287. #if defined(USE_WEBSOCKET)
  15288. if (is_ws) {
  15289. /* TODO: implement all options */
  15290. return mg_connect_websocket_client(
  15291. host,
  15292. port,
  15293. is_ssl,
  15294. ((error != NULL) ? error->text : NULL),
  15295. ((error != NULL) ? error->text_buffer_size : 0),
  15296. (path ? path : ""),
  15297. NULL /* TODO: origin */,
  15298. experimental_websocket_client_data_wrapper,
  15299. experimental_websocket_client_close_wrapper,
  15300. (void *)init->callbacks);
  15301. }
  15302. #endif
  15303. /* TODO: all additional options */
  15304. struct mg_client_options opts;
  15305. memset(&opts, 0, sizeof(opts));
  15306. opts.host = host;
  15307. opts.port = port;
  15308. return mg_connect_client_impl(&opts,
  15309. is_ssl,
  15310. ((error != NULL) ? error->text : NULL),
  15311. ((error != NULL) ? error->text_buffer_size
  15312. : 0));
  15313. }
  15314. #endif
  15315. static const struct {
  15316. const char *proto;
  15317. size_t proto_len;
  15318. unsigned default_port;
  15319. } abs_uri_protocols[] = {{"http://", 7, 80},
  15320. {"https://", 8, 443},
  15321. {"ws://", 5, 80},
  15322. {"wss://", 6, 443},
  15323. {NULL, 0, 0}};
  15324. /* Check if the uri is valid.
  15325. * return 0 for invalid uri,
  15326. * return 1 for *,
  15327. * return 2 for relative uri,
  15328. * return 3 for absolute uri without port,
  15329. * return 4 for absolute uri with port */
  15330. static int
  15331. get_uri_type(const char *uri)
  15332. {
  15333. int i;
  15334. const char *hostend, *portbegin;
  15335. char *portend;
  15336. unsigned long port;
  15337. /* According to the HTTP standard
  15338. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15339. * URI can be an asterisk (*) or should start with slash (relative uri),
  15340. * or it should start with the protocol (absolute uri). */
  15341. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15342. /* asterisk */
  15343. return 1;
  15344. }
  15345. /* Valid URIs according to RFC 3986
  15346. * (https://www.ietf.org/rfc/rfc3986.txt)
  15347. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15348. * and unreserved characters A-Z a-z 0-9 and -._~
  15349. * and % encoded symbols.
  15350. */
  15351. for (i = 0; uri[i] != 0; i++) {
  15352. if (uri[i] < 33) {
  15353. /* control characters and spaces are invalid */
  15354. return 0;
  15355. }
  15356. /* Allow everything else here (See #894) */
  15357. }
  15358. /* A relative uri starts with a / character */
  15359. if (uri[0] == '/') {
  15360. /* relative uri */
  15361. return 2;
  15362. }
  15363. /* It could be an absolute uri: */
  15364. /* This function only checks if the uri is valid, not if it is
  15365. * addressing the current server. So civetweb can also be used
  15366. * as a proxy server. */
  15367. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15368. if (mg_strncasecmp(uri,
  15369. abs_uri_protocols[i].proto,
  15370. abs_uri_protocols[i].proto_len)
  15371. == 0) {
  15372. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15373. if (!hostend) {
  15374. return 0;
  15375. }
  15376. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15377. if (!portbegin) {
  15378. return 3;
  15379. }
  15380. port = strtoul(portbegin + 1, &portend, 10);
  15381. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15382. return 0;
  15383. }
  15384. return 4;
  15385. }
  15386. }
  15387. return 0;
  15388. }
  15389. /* Return NULL or the relative uri at the current server */
  15390. static const char *
  15391. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15392. {
  15393. const char *server_domain;
  15394. size_t server_domain_len;
  15395. size_t request_domain_len = 0;
  15396. unsigned long port = 0;
  15397. int i, auth_domain_check_enabled;
  15398. const char *hostbegin = NULL;
  15399. const char *hostend = NULL;
  15400. const char *portbegin;
  15401. char *portend;
  15402. auth_domain_check_enabled =
  15403. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15404. /* DNS is case insensitive, so use case insensitive string compare here
  15405. */
  15406. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15407. if (mg_strncasecmp(uri,
  15408. abs_uri_protocols[i].proto,
  15409. abs_uri_protocols[i].proto_len)
  15410. == 0) {
  15411. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15412. hostend = strchr(hostbegin, '/');
  15413. if (!hostend) {
  15414. return 0;
  15415. }
  15416. portbegin = strchr(hostbegin, ':');
  15417. if ((!portbegin) || (portbegin > hostend)) {
  15418. port = abs_uri_protocols[i].default_port;
  15419. request_domain_len = (size_t)(hostend - hostbegin);
  15420. } else {
  15421. port = strtoul(portbegin + 1, &portend, 10);
  15422. if ((portend != hostend) || (port <= 0)
  15423. || !is_valid_port(port)) {
  15424. return 0;
  15425. }
  15426. request_domain_len = (size_t)(portbegin - hostbegin);
  15427. }
  15428. /* protocol found, port set */
  15429. break;
  15430. }
  15431. }
  15432. if (!port) {
  15433. /* port remains 0 if the protocol is not found */
  15434. return 0;
  15435. }
  15436. /* Check if the request is directed to a different server. */
  15437. /* First check if the port is the same. */
  15438. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15439. /* Request is directed to a different port */
  15440. return 0;
  15441. }
  15442. /* Finally check if the server corresponds to the authentication
  15443. * domain of the server (the server domain).
  15444. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15445. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15446. * but do not allow substrings (like
  15447. * http://notmydomain.com/path/file.ext
  15448. * or http://mydomain.com.fake/path/file.ext).
  15449. */
  15450. if (auth_domain_check_enabled) {
  15451. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15452. server_domain_len = strlen(server_domain);
  15453. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15454. return 0;
  15455. }
  15456. if ((request_domain_len == server_domain_len)
  15457. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15458. /* Request is directed to this server - full name match. */
  15459. } else {
  15460. if (request_domain_len < (server_domain_len + 2)) {
  15461. /* Request is directed to another server: The server name
  15462. * is longer than the request name.
  15463. * Drop this case here to avoid overflows in the
  15464. * following checks. */
  15465. return 0;
  15466. }
  15467. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15468. /* Request is directed to another server: It could be a
  15469. * substring
  15470. * like notmyserver.com */
  15471. return 0;
  15472. }
  15473. if (0
  15474. != memcmp(server_domain,
  15475. hostbegin + request_domain_len - server_domain_len,
  15476. server_domain_len)) {
  15477. /* Request is directed to another server:
  15478. * The server name is different. */
  15479. return 0;
  15480. }
  15481. }
  15482. }
  15483. return hostend;
  15484. }
  15485. static int
  15486. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15487. {
  15488. if (ebuf_len > 0) {
  15489. ebuf[0] = '\0';
  15490. }
  15491. *err = 0;
  15492. reset_per_request_attributes(conn);
  15493. if (!conn) {
  15494. mg_snprintf(conn,
  15495. NULL, /* No truncation check for ebuf */
  15496. ebuf,
  15497. ebuf_len,
  15498. "%s",
  15499. "Internal error");
  15500. *err = 500;
  15501. return 0;
  15502. }
  15503. /* Set the time the request was received. This value should be used for
  15504. * timeouts. */
  15505. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15506. conn->request_len =
  15507. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15508. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15509. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15510. mg_snprintf(conn,
  15511. NULL, /* No truncation check for ebuf */
  15512. ebuf,
  15513. ebuf_len,
  15514. "%s",
  15515. "Invalid message size");
  15516. *err = 500;
  15517. return 0;
  15518. }
  15519. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15520. mg_snprintf(conn,
  15521. NULL, /* No truncation check for ebuf */
  15522. ebuf,
  15523. ebuf_len,
  15524. "%s",
  15525. "Message too large");
  15526. *err = 413;
  15527. return 0;
  15528. }
  15529. if (conn->request_len <= 0) {
  15530. if (conn->data_len > 0) {
  15531. mg_snprintf(conn,
  15532. NULL, /* No truncation check for ebuf */
  15533. ebuf,
  15534. ebuf_len,
  15535. "%s",
  15536. "Malformed message");
  15537. *err = 400;
  15538. } else {
  15539. /* Server did not recv anything -> just close the connection */
  15540. conn->must_close = 1;
  15541. mg_snprintf(conn,
  15542. NULL, /* No truncation check for ebuf */
  15543. ebuf,
  15544. ebuf_len,
  15545. "%s",
  15546. "No data received");
  15547. *err = 0;
  15548. }
  15549. return 0;
  15550. }
  15551. return 1;
  15552. }
  15553. static int
  15554. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15555. {
  15556. const char *cl;
  15557. conn->connection_type =
  15558. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15559. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15560. return 0;
  15561. }
  15562. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15563. <= 0) {
  15564. mg_snprintf(conn,
  15565. NULL, /* No truncation check for ebuf */
  15566. ebuf,
  15567. ebuf_len,
  15568. "%s",
  15569. "Bad request");
  15570. *err = 400;
  15571. return 0;
  15572. }
  15573. /* Message is a valid request */
  15574. if (!switch_domain_context(conn)) {
  15575. mg_snprintf(conn,
  15576. NULL, /* No truncation check for ebuf */
  15577. ebuf,
  15578. ebuf_len,
  15579. "%s",
  15580. "Bad request: Host mismatch");
  15581. *err = 400;
  15582. return 0;
  15583. }
  15584. if (((cl = get_header(conn->request_info.http_headers,
  15585. conn->request_info.num_headers,
  15586. "Transfer-Encoding"))
  15587. != NULL)
  15588. && mg_strcasecmp(cl, "identity")) {
  15589. if (mg_strcasecmp(cl, "chunked")) {
  15590. mg_snprintf(conn,
  15591. NULL, /* No truncation check for ebuf */
  15592. ebuf,
  15593. ebuf_len,
  15594. "%s",
  15595. "Bad request");
  15596. *err = 400;
  15597. return 0;
  15598. }
  15599. conn->is_chunked = 1;
  15600. conn->content_len = 0; /* not yet read */
  15601. } else if ((cl = get_header(conn->request_info.http_headers,
  15602. conn->request_info.num_headers,
  15603. "Content-Length"))
  15604. != NULL) {
  15605. /* Request has content length set */
  15606. char *endptr = NULL;
  15607. conn->content_len = strtoll(cl, &endptr, 10);
  15608. if ((endptr == cl) || (conn->content_len < 0)) {
  15609. mg_snprintf(conn,
  15610. NULL, /* No truncation check for ebuf */
  15611. ebuf,
  15612. ebuf_len,
  15613. "%s",
  15614. "Bad request");
  15615. *err = 411;
  15616. return 0;
  15617. }
  15618. /* Publish the content length back to the request info. */
  15619. conn->request_info.content_length = conn->content_len;
  15620. } else {
  15621. /* There is no exception, see RFC7230. */
  15622. conn->content_len = 0;
  15623. }
  15624. return 1;
  15625. }
  15626. /* conn is assumed to be valid in this internal function */
  15627. static int
  15628. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15629. {
  15630. const char *cl;
  15631. conn->connection_type =
  15632. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15633. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15634. return 0;
  15635. }
  15636. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15637. <= 0) {
  15638. mg_snprintf(conn,
  15639. NULL, /* No truncation check for ebuf */
  15640. ebuf,
  15641. ebuf_len,
  15642. "%s",
  15643. "Bad response");
  15644. *err = 400;
  15645. return 0;
  15646. }
  15647. /* Message is a valid response */
  15648. if (((cl = get_header(conn->response_info.http_headers,
  15649. conn->response_info.num_headers,
  15650. "Transfer-Encoding"))
  15651. != NULL)
  15652. && mg_strcasecmp(cl, "identity")) {
  15653. if (mg_strcasecmp(cl, "chunked")) {
  15654. mg_snprintf(conn,
  15655. NULL, /* No truncation check for ebuf */
  15656. ebuf,
  15657. ebuf_len,
  15658. "%s",
  15659. "Bad request");
  15660. *err = 400;
  15661. return 0;
  15662. }
  15663. conn->is_chunked = 1;
  15664. conn->content_len = 0; /* not yet read */
  15665. } else if ((cl = get_header(conn->response_info.http_headers,
  15666. conn->response_info.num_headers,
  15667. "Content-Length"))
  15668. != NULL) {
  15669. char *endptr = NULL;
  15670. conn->content_len = strtoll(cl, &endptr, 10);
  15671. if ((endptr == cl) || (conn->content_len < 0)) {
  15672. mg_snprintf(conn,
  15673. NULL, /* No truncation check for ebuf */
  15674. ebuf,
  15675. ebuf_len,
  15676. "%s",
  15677. "Bad request");
  15678. *err = 411;
  15679. return 0;
  15680. }
  15681. /* Publish the content length back to the response info. */
  15682. conn->response_info.content_length = conn->content_len;
  15683. /* TODO: check if it is still used in response_info */
  15684. conn->request_info.content_length = conn->content_len;
  15685. /* TODO: we should also consider HEAD method */
  15686. if (conn->response_info.status_code == 304) {
  15687. conn->content_len = 0;
  15688. }
  15689. } else {
  15690. /* TODO: we should also consider HEAD method */
  15691. if (((conn->response_info.status_code >= 100)
  15692. && (conn->response_info.status_code <= 199))
  15693. || (conn->response_info.status_code == 204)
  15694. || (conn->response_info.status_code == 304)) {
  15695. conn->content_len = 0;
  15696. } else {
  15697. conn->content_len = -1; /* unknown content length */
  15698. }
  15699. }
  15700. return 1;
  15701. }
  15702. int
  15703. mg_get_response(struct mg_connection *conn,
  15704. char *ebuf,
  15705. size_t ebuf_len,
  15706. int timeout)
  15707. {
  15708. int err, ret;
  15709. char txt[32]; /* will not overflow */
  15710. char *save_timeout;
  15711. char *new_timeout;
  15712. if (ebuf_len > 0) {
  15713. ebuf[0] = '\0';
  15714. }
  15715. if (!conn) {
  15716. mg_snprintf(conn,
  15717. NULL, /* No truncation check for ebuf */
  15718. ebuf,
  15719. ebuf_len,
  15720. "%s",
  15721. "Parameter error");
  15722. return -1;
  15723. }
  15724. /* Reset the previous responses */
  15725. conn->data_len = 0;
  15726. /* Implementation of API function for HTTP clients */
  15727. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15728. if (timeout >= 0) {
  15729. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15730. new_timeout = txt;
  15731. } else {
  15732. new_timeout = NULL;
  15733. }
  15734. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15735. ret = get_response(conn, ebuf, ebuf_len, &err);
  15736. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15737. #if defined(MG_LEGACY_INTERFACE)
  15738. /* TODO: 1) uri is deprecated;
  15739. * 2) here, ri.uri is the http response code */
  15740. conn->request_info.uri = conn->request_info.request_uri;
  15741. #endif
  15742. conn->request_info.local_uri = conn->request_info.request_uri;
  15743. /* TODO (mid): Define proper return values - maybe return length?
  15744. * For the first test use <0 for error and >0 for OK */
  15745. return (ret == 0) ? -1 : +1;
  15746. }
  15747. struct mg_connection *
  15748. mg_download(const char *host,
  15749. int port,
  15750. int use_ssl,
  15751. char *ebuf,
  15752. size_t ebuf_len,
  15753. const char *fmt,
  15754. ...)
  15755. {
  15756. struct mg_connection *conn;
  15757. va_list ap;
  15758. int i;
  15759. int reqerr;
  15760. if (ebuf_len > 0) {
  15761. ebuf[0] = '\0';
  15762. }
  15763. va_start(ap, fmt);
  15764. /* open a connection */
  15765. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15766. if (conn != NULL) {
  15767. i = mg_vprintf(conn, fmt, ap);
  15768. if (i <= 0) {
  15769. mg_snprintf(conn,
  15770. NULL, /* No truncation check for ebuf */
  15771. ebuf,
  15772. ebuf_len,
  15773. "%s",
  15774. "Error sending request");
  15775. } else {
  15776. /* make sure the buffer is clear */
  15777. conn->data_len = 0;
  15778. get_response(conn, ebuf, ebuf_len, &reqerr);
  15779. #if defined(MG_LEGACY_INTERFACE)
  15780. /* TODO: 1) uri is deprecated;
  15781. * 2) here, ri.uri is the http response code */
  15782. conn->request_info.uri = conn->request_info.request_uri;
  15783. #endif
  15784. conn->request_info.local_uri = conn->request_info.request_uri;
  15785. }
  15786. }
  15787. /* if an error occurred, close the connection */
  15788. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15789. mg_close_connection(conn);
  15790. conn = NULL;
  15791. }
  15792. va_end(ap);
  15793. return conn;
  15794. }
  15795. struct websocket_client_thread_data {
  15796. struct mg_connection *conn;
  15797. mg_websocket_data_handler data_handler;
  15798. mg_websocket_close_handler close_handler;
  15799. void *callback_data;
  15800. };
  15801. #if defined(USE_WEBSOCKET)
  15802. #if defined(_WIN32)
  15803. static unsigned __stdcall websocket_client_thread(void *data)
  15804. #else
  15805. static void *
  15806. websocket_client_thread(void *data)
  15807. #endif
  15808. {
  15809. struct websocket_client_thread_data *cdata =
  15810. (struct websocket_client_thread_data *)data;
  15811. void *user_thread_ptr = NULL;
  15812. #if !defined(_WIN32)
  15813. struct sigaction sa;
  15814. /* Ignore SIGPIPE */
  15815. memset(&sa, 0, sizeof(sa));
  15816. sa.sa_handler = SIG_IGN;
  15817. sigaction(SIGPIPE, &sa, NULL);
  15818. #endif
  15819. mg_set_thread_name("ws-clnt");
  15820. if (cdata->conn->phys_ctx) {
  15821. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15822. /* 3 indicates a websocket client thread */
  15823. /* TODO: check if conn->phys_ctx can be set */
  15824. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15825. cdata->conn->phys_ctx, 3);
  15826. }
  15827. }
  15828. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15829. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15830. if (cdata->close_handler != NULL) {
  15831. cdata->close_handler(cdata->conn, cdata->callback_data);
  15832. }
  15833. /* The websocket_client context has only this thread. If it runs out,
  15834. set the stop_flag to 2 (= "stopped"). */
  15835. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15836. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15837. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15838. 3,
  15839. user_thread_ptr);
  15840. }
  15841. mg_free((void *)cdata);
  15842. #if defined(_WIN32)
  15843. return 0;
  15844. #else
  15845. return NULL;
  15846. #endif
  15847. }
  15848. #endif
  15849. static struct mg_connection *
  15850. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15851. int use_ssl,
  15852. char *error_buffer,
  15853. size_t error_buffer_size,
  15854. const char *path,
  15855. const char *origin,
  15856. const char *extensions,
  15857. mg_websocket_data_handler data_func,
  15858. mg_websocket_close_handler close_func,
  15859. void *user_data)
  15860. {
  15861. struct mg_connection *conn = NULL;
  15862. #if defined(USE_WEBSOCKET)
  15863. struct websocket_client_thread_data *thread_data;
  15864. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15865. const char *host = client_options->host;
  15866. int i;
  15867. #if defined(__clang__)
  15868. #pragma clang diagnostic push
  15869. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15870. #endif
  15871. /* Establish the client connection and request upgrade */
  15872. conn = mg_connect_client_impl(client_options,
  15873. use_ssl,
  15874. error_buffer,
  15875. error_buffer_size);
  15876. /* Connection object will be null if something goes wrong */
  15877. if (conn == NULL) {
  15878. /* error_buffer should be already filled ... */
  15879. if (!error_buffer[0]) {
  15880. /* ... if not add an error message */
  15881. mg_snprintf(conn,
  15882. NULL, /* No truncation check for ebuf */
  15883. error_buffer,
  15884. error_buffer_size,
  15885. "Unexpected error");
  15886. }
  15887. return NULL;
  15888. }
  15889. if (origin != NULL) {
  15890. if (extensions != NULL) {
  15891. i = mg_printf(conn,
  15892. "GET %s HTTP/1.1\r\n"
  15893. "Host: %s\r\n"
  15894. "Upgrade: websocket\r\n"
  15895. "Connection: Upgrade\r\n"
  15896. "Sec-WebSocket-Key: %s\r\n"
  15897. "Sec-WebSocket-Version: 13\r\n"
  15898. "Sec-WebSocket-Extensions: %s\r\n"
  15899. "Origin: %s\r\n"
  15900. "\r\n",
  15901. path,
  15902. host,
  15903. magic,
  15904. extensions,
  15905. origin);
  15906. } else {
  15907. i = mg_printf(conn,
  15908. "GET %s HTTP/1.1\r\n"
  15909. "Host: %s\r\n"
  15910. "Upgrade: websocket\r\n"
  15911. "Connection: Upgrade\r\n"
  15912. "Sec-WebSocket-Key: %s\r\n"
  15913. "Sec-WebSocket-Version: 13\r\n"
  15914. "Origin: %s\r\n"
  15915. "\r\n",
  15916. path,
  15917. host,
  15918. magic,
  15919. origin);
  15920. }
  15921. } else {
  15922. if (extensions != NULL) {
  15923. i = mg_printf(conn,
  15924. "GET %s HTTP/1.1\r\n"
  15925. "Host: %s\r\n"
  15926. "Upgrade: websocket\r\n"
  15927. "Connection: Upgrade\r\n"
  15928. "Sec-WebSocket-Key: %s\r\n"
  15929. "Sec-WebSocket-Version: 13\r\n"
  15930. "Sec-WebSocket-Extensions: %s\r\n"
  15931. "\r\n",
  15932. path,
  15933. host,
  15934. magic,
  15935. extensions);
  15936. } else {
  15937. i = mg_printf(conn,
  15938. "GET %s HTTP/1.1\r\n"
  15939. "Host: %s\r\n"
  15940. "Upgrade: websocket\r\n"
  15941. "Connection: Upgrade\r\n"
  15942. "Sec-WebSocket-Key: %s\r\n"
  15943. "Sec-WebSocket-Version: 13\r\n"
  15944. "\r\n",
  15945. path,
  15946. host,
  15947. magic);
  15948. }
  15949. }
  15950. if (i <= 0) {
  15951. mg_snprintf(conn,
  15952. NULL, /* No truncation check for ebuf */
  15953. error_buffer,
  15954. error_buffer_size,
  15955. "%s",
  15956. "Error sending request");
  15957. mg_close_connection(conn);
  15958. return NULL;
  15959. }
  15960. conn->data_len = 0;
  15961. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15962. mg_close_connection(conn);
  15963. return NULL;
  15964. }
  15965. conn->request_info.local_uri = conn->request_info.request_uri;
  15966. #if defined(__clang__)
  15967. #pragma clang diagnostic pop
  15968. #endif
  15969. if (conn->response_info.status_code != 101) {
  15970. /* We sent an "upgrade" request. For a correct websocket
  15971. * protocol handshake, we expect a "101 Continue" response.
  15972. * Otherwise it is a protocol violation. Maybe the HTTP
  15973. * Server does not know websockets. */
  15974. if (!*error_buffer) {
  15975. /* set an error, if not yet set */
  15976. mg_snprintf(conn,
  15977. NULL, /* No truncation check for ebuf */
  15978. error_buffer,
  15979. error_buffer_size,
  15980. "Unexpected server reply");
  15981. }
  15982. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15983. mg_close_connection(conn);
  15984. return NULL;
  15985. }
  15986. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15987. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15988. if (!thread_data) {
  15989. DEBUG_TRACE("%s\r\n", "Out of memory");
  15990. mg_close_connection(conn);
  15991. return NULL;
  15992. }
  15993. thread_data->conn = conn;
  15994. thread_data->data_handler = data_func;
  15995. thread_data->close_handler = close_func;
  15996. thread_data->callback_data = user_data;
  15997. conn->phys_ctx->worker_threadids =
  15998. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15999. if (!conn->phys_ctx->worker_threadids) {
  16000. DEBUG_TRACE("%s\r\n", "Out of memory");
  16001. mg_free(thread_data);
  16002. mg_close_connection(conn);
  16003. return NULL;
  16004. }
  16005. /* Now upgrade to ws/wss client context */
  16006. conn->phys_ctx->user_data = user_data;
  16007. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16008. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16009. /* Start a thread to read the websocket client connection
  16010. * This thread will automatically stop when mg_disconnect is
  16011. * called on the client connection */
  16012. if (mg_start_thread_with_id(websocket_client_thread,
  16013. thread_data,
  16014. conn->phys_ctx->worker_threadids)
  16015. != 0) {
  16016. conn->phys_ctx->cfg_worker_threads = 0;
  16017. mg_free(thread_data);
  16018. mg_close_connection(conn);
  16019. conn = NULL;
  16020. DEBUG_TRACE("%s",
  16021. "Websocket client connect thread could not be started\r\n");
  16022. }
  16023. #else
  16024. /* Appease "unused parameter" warnings */
  16025. (void)client_options;
  16026. (void)use_ssl;
  16027. (void)error_buffer;
  16028. (void)error_buffer_size;
  16029. (void)path;
  16030. (void)origin;
  16031. (void)user_data;
  16032. (void)data_func;
  16033. (void)close_func;
  16034. #endif
  16035. return conn;
  16036. }
  16037. struct mg_connection *
  16038. mg_connect_websocket_client(const char *host,
  16039. int port,
  16040. int use_ssl,
  16041. char *error_buffer,
  16042. size_t error_buffer_size,
  16043. const char *path,
  16044. const char *origin,
  16045. mg_websocket_data_handler data_func,
  16046. mg_websocket_close_handler close_func,
  16047. void *user_data)
  16048. {
  16049. struct mg_client_options client_options;
  16050. memset(&client_options, 0, sizeof(client_options));
  16051. client_options.host = host;
  16052. client_options.port = port;
  16053. return mg_connect_websocket_client_impl(&client_options,
  16054. use_ssl,
  16055. error_buffer,
  16056. error_buffer_size,
  16057. path,
  16058. origin,
  16059. NULL,
  16060. data_func,
  16061. close_func,
  16062. user_data);
  16063. }
  16064. struct mg_connection *
  16065. mg_connect_websocket_client_secure(
  16066. const struct mg_client_options *client_options,
  16067. char *error_buffer,
  16068. size_t error_buffer_size,
  16069. const char *path,
  16070. const char *origin,
  16071. mg_websocket_data_handler data_func,
  16072. mg_websocket_close_handler close_func,
  16073. void *user_data)
  16074. {
  16075. if (!client_options) {
  16076. return NULL;
  16077. }
  16078. return mg_connect_websocket_client_impl(client_options,
  16079. 1,
  16080. error_buffer,
  16081. error_buffer_size,
  16082. path,
  16083. origin,
  16084. NULL,
  16085. data_func,
  16086. close_func,
  16087. user_data);
  16088. }
  16089. struct mg_connection *
  16090. mg_connect_websocket_client_extensions(const char *host,
  16091. int port,
  16092. int use_ssl,
  16093. char *error_buffer,
  16094. size_t error_buffer_size,
  16095. const char *path,
  16096. const char *origin,
  16097. const char *extensions,
  16098. mg_websocket_data_handler data_func,
  16099. mg_websocket_close_handler close_func,
  16100. void *user_data)
  16101. {
  16102. struct mg_client_options client_options;
  16103. memset(&client_options, 0, sizeof(client_options));
  16104. client_options.host = host;
  16105. client_options.port = port;
  16106. return mg_connect_websocket_client_impl(&client_options,
  16107. use_ssl,
  16108. error_buffer,
  16109. error_buffer_size,
  16110. path,
  16111. origin,
  16112. extensions,
  16113. data_func,
  16114. close_func,
  16115. user_data);
  16116. }
  16117. struct mg_connection *
  16118. mg_connect_websocket_client_secure_extensions(
  16119. const struct mg_client_options *client_options,
  16120. char *error_buffer,
  16121. size_t error_buffer_size,
  16122. const char *path,
  16123. const char *origin,
  16124. const char *extensions,
  16125. mg_websocket_data_handler data_func,
  16126. mg_websocket_close_handler close_func,
  16127. void *user_data)
  16128. {
  16129. if (!client_options) {
  16130. return NULL;
  16131. }
  16132. return mg_connect_websocket_client_impl(client_options,
  16133. 1,
  16134. error_buffer,
  16135. error_buffer_size,
  16136. path,
  16137. origin,
  16138. extensions,
  16139. data_func,
  16140. close_func,
  16141. user_data);
  16142. }
  16143. /* Prepare connection data structure */
  16144. static void
  16145. init_connection(struct mg_connection *conn)
  16146. {
  16147. /* Is keep alive allowed by the server */
  16148. int keep_alive_enabled =
  16149. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16150. if (!keep_alive_enabled) {
  16151. conn->must_close = 1;
  16152. }
  16153. /* Important: on new connection, reset the receiving buffer. Credit
  16154. * goes to crule42. */
  16155. conn->data_len = 0;
  16156. conn->handled_requests = 0;
  16157. conn->connection_type = CONNECTION_TYPE_INVALID;
  16158. mg_set_user_connection_data(conn, NULL);
  16159. #if defined(USE_SERVER_STATS)
  16160. conn->conn_state = 2; /* init */
  16161. #endif
  16162. /* call the init_connection callback if assigned */
  16163. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16164. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16165. void *conn_data = NULL;
  16166. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16167. mg_set_user_connection_data(conn, conn_data);
  16168. }
  16169. }
  16170. }
  16171. /* Process a connection - may handle multiple requests
  16172. * using the same connection.
  16173. * Must be called with a valid connection (conn and
  16174. * conn->phys_ctx must be valid).
  16175. */
  16176. static void
  16177. process_new_connection(struct mg_connection *conn)
  16178. {
  16179. struct mg_request_info *ri = &conn->request_info;
  16180. int keep_alive, discard_len;
  16181. char ebuf[100];
  16182. const char *hostend;
  16183. int reqerr, uri_type;
  16184. #if defined(USE_SERVER_STATS)
  16185. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16186. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16187. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16188. #endif
  16189. DEBUG_TRACE("Start processing connection from %s",
  16190. conn->request_info.remote_addr);
  16191. /* Loop over multiple requests sent using the same connection
  16192. * (while "keep alive"). */
  16193. do {
  16194. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16195. conn->handled_requests + 1);
  16196. #if defined(USE_SERVER_STATS)
  16197. conn->conn_state = 3; /* ready */
  16198. #endif
  16199. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16200. /* The request sent by the client could not be understood by
  16201. * the server, or it was incomplete or a timeout. Send an
  16202. * error message and close the connection. */
  16203. if (reqerr > 0) {
  16204. DEBUG_ASSERT(ebuf[0] != '\0');
  16205. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16206. }
  16207. } else if (strcmp(ri->http_version, "1.0")
  16208. && strcmp(ri->http_version, "1.1")) {
  16209. /* HTTP/2 is not allowed here */
  16210. mg_snprintf(conn,
  16211. NULL, /* No truncation check for ebuf */
  16212. ebuf,
  16213. sizeof(ebuf),
  16214. "Bad HTTP version: [%s]",
  16215. ri->http_version);
  16216. mg_send_http_error(conn, 505, "%s", ebuf);
  16217. }
  16218. if (ebuf[0] == '\0') {
  16219. uri_type = get_uri_type(conn->request_info.request_uri);
  16220. switch (uri_type) {
  16221. case 1:
  16222. /* Asterisk */
  16223. conn->request_info.local_uri = 0;
  16224. /* TODO: Deal with '*'. */
  16225. break;
  16226. case 2:
  16227. /* relative uri */
  16228. conn->request_info.local_uri = conn->request_info.request_uri;
  16229. break;
  16230. case 3:
  16231. case 4:
  16232. /* absolute uri (with/without port) */
  16233. hostend = get_rel_url_at_current_server(
  16234. conn->request_info.request_uri, conn);
  16235. if (hostend) {
  16236. conn->request_info.local_uri = hostend;
  16237. } else {
  16238. conn->request_info.local_uri = NULL;
  16239. }
  16240. break;
  16241. default:
  16242. mg_snprintf(conn,
  16243. NULL, /* No truncation check for ebuf */
  16244. ebuf,
  16245. sizeof(ebuf),
  16246. "Invalid URI");
  16247. mg_send_http_error(conn, 400, "%s", ebuf);
  16248. conn->request_info.local_uri = NULL;
  16249. break;
  16250. }
  16251. #if defined(MG_LEGACY_INTERFACE)
  16252. /* Legacy before split into local_uri and request_uri */
  16253. conn->request_info.uri = conn->request_info.local_uri;
  16254. #endif
  16255. }
  16256. if (ebuf[0] != '\0') {
  16257. conn->protocol_type = -1;
  16258. } else {
  16259. /* HTTP/1 allows protocol upgrade */
  16260. conn->protocol_type = should_switch_to_protocol(conn);
  16261. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16262. /* This will occur, if a HTTP/1.1 request should be upgraded
  16263. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16264. * Since most (all?) major browsers only support HTTP/2 using
  16265. * ALPN, this is hard to test and very low priority.
  16266. * Deactivate it (at least for now).
  16267. */
  16268. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16269. }
  16270. }
  16271. DEBUG_TRACE("http: %s, error: %s",
  16272. (ri->http_version ? ri->http_version : "none"),
  16273. (ebuf[0] ? ebuf : "none"));
  16274. if (ebuf[0] == '\0') {
  16275. if (conn->request_info.local_uri) {
  16276. /* handle request to local server */
  16277. #if defined(USE_SERVER_STATS)
  16278. conn->conn_state = 4; /* processing */
  16279. #endif
  16280. handle_request(conn);
  16281. #if defined(USE_SERVER_STATS)
  16282. conn->conn_state = 5; /* processed */
  16283. mg_atomic_add64(&(conn->phys_ctx->total_data_read),
  16284. conn->consumed_content);
  16285. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  16286. conn->num_bytes_sent);
  16287. #endif
  16288. DEBUG_TRACE("%s", "handle_request done");
  16289. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16290. conn->phys_ctx->callbacks.end_request(conn,
  16291. conn->status_code);
  16292. DEBUG_TRACE("%s", "end_request callback done");
  16293. }
  16294. log_access(conn);
  16295. } else {
  16296. /* TODO: handle non-local request (PROXY) */
  16297. conn->must_close = 1;
  16298. }
  16299. } else {
  16300. conn->must_close = 1;
  16301. }
  16302. /* Response complete. Free header buffer */
  16303. free_buffered_response_header_list(conn);
  16304. if (ri->remote_user != NULL) {
  16305. mg_free((void *)ri->remote_user);
  16306. /* Important! When having connections with and without auth
  16307. * would cause double free and then crash */
  16308. ri->remote_user = NULL;
  16309. }
  16310. /* NOTE(lsm): order is important here. should_keep_alive() call
  16311. * is using parsed request, which will be invalid after
  16312. * memmove's below.
  16313. * Therefore, memorize should_keep_alive() result now for later
  16314. * use in loop exit condition. */
  16315. /* Enable it only if this request is completely discardable. */
  16316. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16317. && should_keep_alive(conn) && (conn->content_len >= 0)
  16318. && (conn->request_len > 0)
  16319. && ((conn->is_chunked == 4)
  16320. || (!conn->is_chunked
  16321. && ((conn->consumed_content == conn->content_len)
  16322. || ((conn->request_len + conn->content_len)
  16323. <= conn->data_len))))
  16324. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16325. if (keep_alive) {
  16326. /* Discard all buffered data for this request */
  16327. discard_len =
  16328. ((conn->request_len + conn->content_len) < conn->data_len)
  16329. ? (int)(conn->request_len + conn->content_len)
  16330. : conn->data_len;
  16331. conn->data_len -= discard_len;
  16332. if (conn->data_len > 0) {
  16333. DEBUG_TRACE("discard_len = %d", discard_len);
  16334. memmove(conn->buf,
  16335. conn->buf + discard_len,
  16336. (size_t)conn->data_len);
  16337. }
  16338. }
  16339. DEBUG_ASSERT(conn->data_len >= 0);
  16340. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16341. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16342. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16343. (long int)conn->data_len,
  16344. (long int)conn->buf_size);
  16345. break;
  16346. }
  16347. conn->handled_requests++;
  16348. } while (keep_alive);
  16349. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16350. conn->request_info.remote_addr,
  16351. difftime(time(NULL), conn->conn_birth_time));
  16352. close_connection(conn);
  16353. #if defined(USE_SERVER_STATS)
  16354. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16355. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16356. #endif
  16357. }
  16358. #if defined(ALTERNATIVE_QUEUE)
  16359. static void
  16360. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16361. {
  16362. unsigned int i;
  16363. while (!ctx->stop_flag) {
  16364. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16365. /* find a free worker slot and signal it */
  16366. if (ctx->client_socks[i].in_use == 2) {
  16367. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16368. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16369. ctx->client_socks[i] = *sp;
  16370. ctx->client_socks[i].in_use = 1;
  16371. /* socket has been moved to the consumer */
  16372. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16373. (void)event_signal(ctx->client_wait_events[i]);
  16374. return;
  16375. }
  16376. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16377. }
  16378. }
  16379. /* queue is full */
  16380. mg_sleep(1);
  16381. }
  16382. /* must consume */
  16383. set_blocking_mode(sp->sock);
  16384. closesocket(sp->sock);
  16385. }
  16386. static int
  16387. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16388. {
  16389. DEBUG_TRACE("%s", "going idle");
  16390. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16391. ctx->client_socks[thread_index].in_use = 2;
  16392. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16393. event_wait(ctx->client_wait_events[thread_index]);
  16394. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16395. *sp = ctx->client_socks[thread_index];
  16396. if (ctx->stop_flag) {
  16397. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16398. if (sp->in_use == 1) {
  16399. /* must consume */
  16400. set_blocking_mode(sp->sock);
  16401. closesocket(sp->sock);
  16402. }
  16403. return 0;
  16404. }
  16405. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16406. if (sp->in_use == 1) {
  16407. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16408. return 1;
  16409. }
  16410. /* must not reach here */
  16411. DEBUG_ASSERT(0);
  16412. return 0;
  16413. }
  16414. #else /* ALTERNATIVE_QUEUE */
  16415. /* Worker threads take accepted socket from the queue */
  16416. static int
  16417. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16418. {
  16419. (void)thread_index;
  16420. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16421. DEBUG_TRACE("%s", "going idle");
  16422. /* If the queue is empty, wait. We're idle at this point. */
  16423. while ((ctx->sq_head == ctx->sq_tail)
  16424. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16425. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16426. }
  16427. /* If we're stopping, sq_head may be equal to sq_tail. */
  16428. if (ctx->sq_head > ctx->sq_tail) {
  16429. /* Copy socket from the queue and increment tail */
  16430. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16431. ctx->sq_tail++;
  16432. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16433. /* Wrap pointers if needed */
  16434. while (ctx->sq_tail > ctx->sq_size) {
  16435. ctx->sq_tail -= ctx->sq_size;
  16436. ctx->sq_head -= ctx->sq_size;
  16437. }
  16438. }
  16439. (void)pthread_cond_signal(&ctx->sq_empty);
  16440. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16441. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16442. }
  16443. /* Master thread adds accepted socket to a queue */
  16444. static void
  16445. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16446. {
  16447. int queue_filled;
  16448. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16449. queue_filled = ctx->sq_head - ctx->sq_tail;
  16450. /* If the queue is full, wait */
  16451. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16452. && (queue_filled >= ctx->sq_size)) {
  16453. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16454. #if defined(USE_SERVER_STATS)
  16455. if (queue_filled > ctx->sq_max_fill) {
  16456. ctx->sq_max_fill = queue_filled;
  16457. }
  16458. #endif
  16459. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16460. ctx->sq_blocked = 0; /* Not blocked now */
  16461. queue_filled = ctx->sq_head - ctx->sq_tail;
  16462. }
  16463. if (queue_filled < ctx->sq_size) {
  16464. /* Copy socket to the queue and increment head */
  16465. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16466. ctx->sq_head++;
  16467. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16468. }
  16469. queue_filled = ctx->sq_head - ctx->sq_tail;
  16470. #if defined(USE_SERVER_STATS)
  16471. if (queue_filled > ctx->sq_max_fill) {
  16472. ctx->sq_max_fill = queue_filled;
  16473. }
  16474. #endif
  16475. (void)pthread_cond_signal(&ctx->sq_full);
  16476. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16477. }
  16478. #endif /* ALTERNATIVE_QUEUE */
  16479. static void
  16480. worker_thread_run(struct mg_connection *conn)
  16481. {
  16482. struct mg_context *ctx = conn->phys_ctx;
  16483. int thread_index;
  16484. struct mg_workerTLS tls;
  16485. mg_set_thread_name("worker");
  16486. tls.is_master = 0;
  16487. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16488. #if defined(_WIN32)
  16489. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16490. #endif
  16491. /* Initialize thread local storage before calling any callback */
  16492. pthread_setspecific(sTlsKey, &tls);
  16493. /* Check if there is a user callback */
  16494. if (ctx->callbacks.init_thread) {
  16495. /* call init_thread for a worker thread (type 1), and store the
  16496. * return value */
  16497. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16498. } else {
  16499. /* No callback: set user pointer to NULL */
  16500. tls.user_ptr = NULL;
  16501. }
  16502. /* Connection structure has been pre-allocated */
  16503. thread_index = (int)(conn - ctx->worker_connections);
  16504. if ((thread_index < 0)
  16505. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16506. mg_cry_ctx_internal(ctx,
  16507. "Internal error: Invalid worker index %i",
  16508. thread_index);
  16509. return;
  16510. }
  16511. /* Request buffers are not pre-allocated. They are private to the
  16512. * request and do not contain any state information that might be
  16513. * of interest to anyone observing a server status. */
  16514. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16515. if (conn->buf == NULL) {
  16516. mg_cry_ctx_internal(
  16517. ctx,
  16518. "Out of memory: Cannot allocate buffer for worker %i",
  16519. thread_index);
  16520. return;
  16521. }
  16522. conn->buf_size = (int)ctx->max_request_size;
  16523. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16524. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16525. conn->request_info.user_data = ctx->user_data;
  16526. /* Allocate a mutex for this connection to allow communication both
  16527. * within the request handler and from elsewhere in the application
  16528. */
  16529. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16530. mg_free(conn->buf);
  16531. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16532. return;
  16533. }
  16534. #if defined(USE_SERVER_STATS)
  16535. conn->conn_state = 1; /* not consumed */
  16536. #endif
  16537. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16538. * signal sq_empty condvar to wake up the master waiting in
  16539. * produce_socket() */
  16540. while (consume_socket(ctx, &conn->client, thread_index)) {
  16541. /* New connections must start with new protocol negotiation */
  16542. tls.alpn_proto = NULL;
  16543. #if defined(USE_SERVER_STATS)
  16544. conn->conn_close_time = 0;
  16545. #endif
  16546. conn->conn_birth_time = time(NULL);
  16547. /* Fill in IP, port info early so even if SSL setup below fails,
  16548. * error handler would have the corresponding info.
  16549. * Thanks to Johannes Winkelmann for the patch.
  16550. */
  16551. conn->request_info.remote_port =
  16552. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16553. conn->request_info.server_port =
  16554. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16555. sockaddr_to_string(conn->request_info.remote_addr,
  16556. sizeof(conn->request_info.remote_addr),
  16557. &conn->client.rsa);
  16558. DEBUG_TRACE("Start processing connection from %s",
  16559. conn->request_info.remote_addr);
  16560. conn->request_info.is_ssl = conn->client.is_ssl;
  16561. if (conn->client.is_ssl) {
  16562. #if !defined(NO_SSL)
  16563. /* HTTPS connection */
  16564. if (sslize(conn, SSL_accept, NULL)) {
  16565. /* conn->dom_ctx is set in get_request */
  16566. /* Get SSL client certificate information (if set) */
  16567. struct mg_client_cert client_cert;
  16568. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16569. conn->request_info.client_cert = &client_cert;
  16570. }
  16571. /* process HTTPS connection */
  16572. #if defined(USE_HTTP2)
  16573. if ((tls.alpn_proto != NULL)
  16574. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16575. /* process HTTPS/2 connection */
  16576. init_connection(conn);
  16577. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16578. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16579. conn->content_len =
  16580. -1; /* content length is not predefined */
  16581. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16582. process_new_http2_connection(conn);
  16583. } else
  16584. #endif
  16585. {
  16586. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16587. init_connection(conn);
  16588. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16589. /* Start with HTTP, WS will be an "upgrade" request later */
  16590. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16591. process_new_connection(conn);
  16592. }
  16593. /* Free client certificate info */
  16594. if (conn->request_info.client_cert) {
  16595. mg_free((void *)(conn->request_info.client_cert->subject));
  16596. mg_free((void *)(conn->request_info.client_cert->issuer));
  16597. mg_free((void *)(conn->request_info.client_cert->serial));
  16598. mg_free((void *)(conn->request_info.client_cert->finger));
  16599. /* Free certificate memory */
  16600. X509_free(
  16601. (X509 *)conn->request_info.client_cert->peer_cert);
  16602. conn->request_info.client_cert->peer_cert = 0;
  16603. conn->request_info.client_cert->subject = 0;
  16604. conn->request_info.client_cert->issuer = 0;
  16605. conn->request_info.client_cert->serial = 0;
  16606. conn->request_info.client_cert->finger = 0;
  16607. conn->request_info.client_cert = 0;
  16608. }
  16609. } else {
  16610. /* make sure the connection is cleaned up on SSL failure */
  16611. close_connection(conn);
  16612. }
  16613. #endif
  16614. } else {
  16615. /* process HTTP connection */
  16616. init_connection(conn);
  16617. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16618. /* Start with HTTP, WS will be an "upgrade" request later */
  16619. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16620. process_new_connection(conn);
  16621. }
  16622. DEBUG_TRACE("%s", "Connection closed");
  16623. #if defined(USE_SERVER_STATS)
  16624. conn->conn_close_time = time(NULL);
  16625. #endif
  16626. }
  16627. /* Call exit thread user callback */
  16628. if (ctx->callbacks.exit_thread) {
  16629. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16630. }
  16631. /* delete thread local storage objects */
  16632. pthread_setspecific(sTlsKey, NULL);
  16633. #if defined(_WIN32)
  16634. CloseHandle(tls.pthread_cond_helper_mutex);
  16635. #endif
  16636. pthread_mutex_destroy(&conn->mutex);
  16637. /* Free the request buffer. */
  16638. conn->buf_size = 0;
  16639. mg_free(conn->buf);
  16640. conn->buf = NULL;
  16641. #if defined(USE_SERVER_STATS)
  16642. conn->conn_state = 9; /* done */
  16643. #endif
  16644. DEBUG_TRACE("%s", "exiting");
  16645. }
  16646. /* Threads have different return types on Windows and Unix. */
  16647. #if defined(_WIN32)
  16648. static unsigned __stdcall worker_thread(void *thread_func_param)
  16649. {
  16650. worker_thread_run((struct mg_connection *)thread_func_param);
  16651. return 0;
  16652. }
  16653. #else
  16654. static void *
  16655. worker_thread(void *thread_func_param)
  16656. {
  16657. #if !defined(__ZEPHYR__)
  16658. struct sigaction sa;
  16659. /* Ignore SIGPIPE */
  16660. memset(&sa, 0, sizeof(sa));
  16661. sa.sa_handler = SIG_IGN;
  16662. sigaction(SIGPIPE, &sa, NULL);
  16663. #endif
  16664. worker_thread_run((struct mg_connection *)thread_func_param);
  16665. return NULL;
  16666. }
  16667. #endif /* _WIN32 */
  16668. /* This is an internal function, thus all arguments are expected to be
  16669. * valid - a NULL check is not required. */
  16670. static void
  16671. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16672. {
  16673. struct socket so;
  16674. char src_addr[IP_ADDR_STR_LEN];
  16675. socklen_t len = sizeof(so.rsa);
  16676. #if !defined(__ZEPHYR__)
  16677. int on = 1;
  16678. #endif
  16679. memset(&so, 0, sizeof(so));
  16680. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16681. == INVALID_SOCKET) {
  16682. } else if (check_acl(ctx, &so.rsa) != 1) {
  16683. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16684. mg_cry_ctx_internal(ctx,
  16685. "%s: %s is not allowed to connect",
  16686. __func__,
  16687. src_addr);
  16688. closesocket(so.sock);
  16689. } else {
  16690. /* Put so socket structure into the queue */
  16691. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16692. set_close_on_exec(so.sock, NULL, ctx);
  16693. so.is_ssl = listener->is_ssl;
  16694. so.ssl_redir = listener->ssl_redir;
  16695. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16696. mg_cry_ctx_internal(ctx,
  16697. "%s: getsockname() failed: %s",
  16698. __func__,
  16699. strerror(ERRNO));
  16700. }
  16701. #if !defined(__ZEPHYR__)
  16702. if ((so.lsa.sa.sa_family == AF_INET)
  16703. || (so.lsa.sa.sa_family == AF_INET6)) {
  16704. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  16705. * This is needed because if HTTP-level keep-alive
  16706. * is enabled, and client resets the connection, server won't get
  16707. * TCP FIN or RST and will keep the connection open forever. With
  16708. * TCP keep-alive, next keep-alive handshake will figure out that
  16709. * the client is down and will close the server end.
  16710. * Thanks to Igor Klopov who suggested the patch. */
  16711. if (setsockopt(so.sock,
  16712. SOL_SOCKET,
  16713. SO_KEEPALIVE,
  16714. (SOCK_OPT_TYPE)&on,
  16715. sizeof(on))
  16716. != 0) {
  16717. mg_cry_ctx_internal(
  16718. ctx,
  16719. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16720. __func__,
  16721. strerror(ERRNO));
  16722. }
  16723. }
  16724. #endif
  16725. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16726. * to effectively fill up the underlying IP packet payload and
  16727. * reduce the overhead of sending lots of small buffers. However
  16728. * this hurts the server's throughput (ie. operations per second)
  16729. * when HTTP 1.1 persistent connections are used and the responses
  16730. * are relatively small (eg. less than 1400 bytes).
  16731. */
  16732. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16733. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16734. if (set_tcp_nodelay(&so, 1) != 0) {
  16735. mg_cry_ctx_internal(
  16736. ctx,
  16737. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16738. __func__,
  16739. strerror(ERRNO));
  16740. }
  16741. }
  16742. /* The "non blocking" property should already be
  16743. * inherited from the parent socket. Set it for
  16744. * non-compliant socket implementations. */
  16745. set_non_blocking_mode(so.sock);
  16746. so.in_use = 0;
  16747. produce_socket(ctx, &so);
  16748. }
  16749. }
  16750. static void
  16751. master_thread_run(struct mg_context *ctx)
  16752. {
  16753. struct mg_workerTLS tls;
  16754. struct mg_pollfd *pfd;
  16755. unsigned int i;
  16756. unsigned int workerthreadcount;
  16757. if (!ctx) {
  16758. return;
  16759. }
  16760. mg_set_thread_name("master");
  16761. /* Increase priority of the master thread */
  16762. #if defined(_WIN32)
  16763. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16764. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16765. int min_prio = sched_get_priority_min(SCHED_RR);
  16766. int max_prio = sched_get_priority_max(SCHED_RR);
  16767. if ((min_prio >= 0) && (max_prio >= 0)
  16768. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16769. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16770. struct sched_param sched_param = {0};
  16771. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16772. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16773. }
  16774. #endif
  16775. /* Initialize thread local storage */
  16776. #if defined(_WIN32)
  16777. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16778. #endif
  16779. tls.is_master = 1;
  16780. pthread_setspecific(sTlsKey, &tls);
  16781. if (ctx->callbacks.init_thread) {
  16782. /* Callback for the master thread (type 0) */
  16783. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16784. } else {
  16785. tls.user_ptr = NULL;
  16786. }
  16787. /* Lua background script "start" event */
  16788. #if defined(USE_LUA)
  16789. if (ctx->lua_background_state) {
  16790. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16791. /* call "start()" in Lua */
  16792. lua_getglobal(lstate, "start");
  16793. (void)lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16794. }
  16795. #endif
  16796. /* Server starts *now* */
  16797. ctx->start_time = time(NULL);
  16798. /* Server accept loop */
  16799. pfd = ctx->listening_socket_fds;
  16800. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16801. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16802. pfd[i].fd = ctx->listening_sockets[i].sock;
  16803. pfd[i].events = POLLIN;
  16804. }
  16805. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16806. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16807. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16808. * successful poll, and POLLIN is defined as
  16809. * (POLLRDNORM | POLLRDBAND)
  16810. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16811. * pfd[i].revents == POLLIN. */
  16812. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16813. && (pfd[i].revents & POLLIN)) {
  16814. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16815. }
  16816. }
  16817. }
  16818. }
  16819. /* Here stop_flag is 1 - Initiate shutdown. */
  16820. DEBUG_TRACE("%s", "stopping workers");
  16821. /* Stop signal received: somebody called mg_stop. Quit. */
  16822. close_all_listening_sockets(ctx);
  16823. /* Wakeup workers that are waiting for connections to handle. */
  16824. #if defined(ALTERNATIVE_QUEUE)
  16825. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16826. event_signal(ctx->client_wait_events[i]);
  16827. }
  16828. #else
  16829. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16830. pthread_cond_broadcast(&ctx->sq_full);
  16831. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16832. #endif
  16833. /* Join all worker threads to avoid leaking threads. */
  16834. workerthreadcount = ctx->cfg_worker_threads;
  16835. for (i = 0; i < workerthreadcount; i++) {
  16836. if (ctx->worker_threadids[i] != 0) {
  16837. mg_join_thread(ctx->worker_threadids[i]);
  16838. }
  16839. }
  16840. #if defined(USE_LUA)
  16841. /* Free Lua state of lua background task */
  16842. if (ctx->lua_background_state) {
  16843. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16844. /* call "stop()" in Lua */
  16845. lua_getglobal(lstate, "stop");
  16846. (void)lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16847. lua_close(lstate);
  16848. ctx->lua_background_state = 0;
  16849. }
  16850. #endif
  16851. DEBUG_TRACE("%s", "exiting");
  16852. /* call exit thread callback */
  16853. if (ctx->callbacks.exit_thread) {
  16854. /* Callback for the master thread (type 0) */
  16855. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16856. }
  16857. #if defined(_WIN32)
  16858. CloseHandle(tls.pthread_cond_helper_mutex);
  16859. #endif
  16860. pthread_setspecific(sTlsKey, NULL);
  16861. /* Signal mg_stop() that we're done.
  16862. * WARNING: This must be the very last thing this
  16863. * thread does, as ctx becomes invalid after this line. */
  16864. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16865. }
  16866. /* Threads have different return types on Windows and Unix. */
  16867. #if defined(_WIN32)
  16868. static unsigned __stdcall master_thread(void *thread_func_param)
  16869. {
  16870. master_thread_run((struct mg_context *)thread_func_param);
  16871. return 0;
  16872. }
  16873. #else
  16874. static void *
  16875. master_thread(void *thread_func_param)
  16876. {
  16877. #if !defined(__ZEPHYR__)
  16878. struct sigaction sa;
  16879. /* Ignore SIGPIPE */
  16880. memset(&sa, 0, sizeof(sa));
  16881. sa.sa_handler = SIG_IGN;
  16882. sigaction(SIGPIPE, &sa, NULL);
  16883. #endif
  16884. master_thread_run((struct mg_context *)thread_func_param);
  16885. return NULL;
  16886. }
  16887. #endif /* _WIN32 */
  16888. static void
  16889. free_context(struct mg_context *ctx)
  16890. {
  16891. int i;
  16892. struct mg_handler_info *tmp_rh;
  16893. if (ctx == NULL) {
  16894. return;
  16895. }
  16896. /* Call user callback */
  16897. if (ctx->callbacks.exit_context) {
  16898. ctx->callbacks.exit_context(ctx);
  16899. }
  16900. /* All threads exited, no sync is needed. Destroy thread mutex and
  16901. * condvars
  16902. */
  16903. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16904. #if defined(ALTERNATIVE_QUEUE)
  16905. mg_free(ctx->client_socks);
  16906. if (ctx->client_wait_events != NULL) {
  16907. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16908. event_destroy(ctx->client_wait_events[i]);
  16909. }
  16910. mg_free(ctx->client_wait_events);
  16911. }
  16912. #else
  16913. (void)pthread_cond_destroy(&ctx->sq_empty);
  16914. (void)pthread_cond_destroy(&ctx->sq_full);
  16915. mg_free(ctx->squeue);
  16916. #endif
  16917. /* Destroy other context global data structures mutex */
  16918. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16919. /* Deallocate config parameters */
  16920. for (i = 0; i < NUM_OPTIONS; i++) {
  16921. if (ctx->dd.config[i] != NULL) {
  16922. #if defined(_MSC_VER)
  16923. #pragma warning(suppress : 6001)
  16924. #endif
  16925. mg_free(ctx->dd.config[i]);
  16926. }
  16927. }
  16928. /* Deallocate request handlers */
  16929. while (ctx->dd.handlers) {
  16930. tmp_rh = ctx->dd.handlers;
  16931. ctx->dd.handlers = tmp_rh->next;
  16932. mg_free(tmp_rh->uri);
  16933. mg_free(tmp_rh);
  16934. }
  16935. #if !defined(NO_SSL)
  16936. /* Deallocate SSL context */
  16937. if (ctx->dd.ssl_ctx != NULL) {
  16938. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16939. int callback_ret =
  16940. (ctx->callbacks.external_ssl_ctx == NULL)
  16941. ? 0
  16942. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16943. if (callback_ret == 0) {
  16944. SSL_CTX_free(ctx->dd.ssl_ctx);
  16945. }
  16946. /* else: ignore error and ommit SSL_CTX_free in case
  16947. * callback_ret is 1 */
  16948. }
  16949. #endif /* !NO_SSL */
  16950. /* Deallocate worker thread ID array */
  16951. mg_free(ctx->worker_threadids);
  16952. /* Deallocate worker thread ID array */
  16953. mg_free(ctx->worker_connections);
  16954. /* deallocate system name string */
  16955. mg_free(ctx->systemName);
  16956. /* Deallocate context itself */
  16957. mg_free(ctx);
  16958. }
  16959. void
  16960. mg_stop(struct mg_context *ctx)
  16961. {
  16962. pthread_t mt;
  16963. if (!ctx) {
  16964. return;
  16965. }
  16966. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16967. * two threads is not allowed. */
  16968. mt = ctx->masterthreadid;
  16969. if (mt == 0) {
  16970. return;
  16971. }
  16972. ctx->masterthreadid = 0;
  16973. /* Set stop flag, so all threads know they have to exit. */
  16974. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16975. /* Join timer thread */
  16976. #if defined(USE_TIMERS)
  16977. timers_exit(ctx);
  16978. #endif
  16979. /* Wait until everything has stopped. */
  16980. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16981. (void)mg_sleep(10);
  16982. }
  16983. /* Wait to stop master thread */
  16984. mg_join_thread(mt);
  16985. /* Close remaining Lua states */
  16986. #if defined(USE_LUA)
  16987. lua_ctx_exit(ctx);
  16988. #endif
  16989. /* Free memory */
  16990. free_context(ctx);
  16991. }
  16992. static void
  16993. get_system_name(char **sysName)
  16994. {
  16995. #if defined(_WIN32)
  16996. #if defined(_WIN32_WCE)
  16997. *sysName = mg_strdup("WinCE");
  16998. #else
  16999. char name[128];
  17000. DWORD dwVersion = 0;
  17001. DWORD dwMajorVersion = 0;
  17002. DWORD dwMinorVersion = 0;
  17003. DWORD dwBuild = 0;
  17004. BOOL wowRet, isWoW = FALSE;
  17005. #if defined(_MSC_VER)
  17006. #pragma warning(push)
  17007. /* GetVersion was declared deprecated */
  17008. #pragma warning(disable : 4996)
  17009. #endif
  17010. dwVersion = GetVersion();
  17011. #if defined(_MSC_VER)
  17012. #pragma warning(pop)
  17013. #endif
  17014. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17015. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17016. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17017. (void)dwBuild;
  17018. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17019. sprintf(name,
  17020. "Windows %u.%u%s",
  17021. (unsigned)dwMajorVersion,
  17022. (unsigned)dwMinorVersion,
  17023. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17024. *sysName = mg_strdup(name);
  17025. #endif
  17026. #elif defined(__ZEPHYR__)
  17027. *sysName = mg_strdup("Zephyr OS");
  17028. #else
  17029. struct utsname name;
  17030. memset(&name, 0, sizeof(name));
  17031. uname(&name);
  17032. *sysName = mg_strdup(name.sysname);
  17033. #endif
  17034. }
  17035. static void
  17036. legacy_init(const char **options)
  17037. {
  17038. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17039. if (options) {
  17040. const char **run_options = options;
  17041. const char *optname = config_options[LISTENING_PORTS].name;
  17042. /* Try to find the "listening_ports" option */
  17043. while (*run_options) {
  17044. if (!strcmp(*run_options, optname)) {
  17045. ports_option = run_options[1];
  17046. }
  17047. run_options += 2;
  17048. }
  17049. }
  17050. if (is_ssl_port_used(ports_option)) {
  17051. /* Initialize with SSL support */
  17052. mg_init_library(MG_FEATURES_TLS);
  17053. } else {
  17054. /* Initialize without SSL support */
  17055. mg_init_library(MG_FEATURES_DEFAULT);
  17056. }
  17057. }
  17058. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  17059. static
  17060. #endif
  17061. struct mg_context *
  17062. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17063. {
  17064. struct mg_context *ctx;
  17065. const char *name, *value, *default_value;
  17066. int idx, ok, workerthreadcount;
  17067. unsigned int i;
  17068. int itmp;
  17069. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17070. const char **options =
  17071. ((init != NULL) ? (init->configuration_options) : (NULL));
  17072. struct mg_workerTLS tls;
  17073. if (error != NULL) {
  17074. error->code = 0;
  17075. if (error->text_buffer_size > 0) {
  17076. *error->text = 0;
  17077. }
  17078. }
  17079. if (mg_init_library_called == 0) {
  17080. /* Legacy INIT, if mg_start is called without mg_init_library.
  17081. * Note: This will cause a memory leak when unloading the library.
  17082. */
  17083. legacy_init(options);
  17084. }
  17085. if (mg_init_library_called == 0) {
  17086. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17087. mg_snprintf(NULL,
  17088. NULL, /* No truncation check for error buffers */
  17089. error->text,
  17090. error->text_buffer_size,
  17091. "%s",
  17092. "Library uninitialized");
  17093. }
  17094. return NULL;
  17095. }
  17096. /* Allocate context and initialize reasonable general case defaults. */
  17097. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  17098. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17099. mg_snprintf(NULL,
  17100. NULL, /* No truncation check for error buffers */
  17101. error->text,
  17102. error->text_buffer_size,
  17103. "%s",
  17104. "Out of memory");
  17105. }
  17106. return NULL;
  17107. }
  17108. /* Random number generator will initialize at the first call */
  17109. ctx->dd.auth_nonce_mask =
  17110. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17111. /* Save started thread index to reuse in other external API calls
  17112. * For the sake of thread synchronization all non-civetweb threads
  17113. * can be considered as single external thread */
  17114. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17115. tls.is_master = -1; /* Thread calling mg_start */
  17116. tls.thread_idx = ctx->starter_thread_idx;
  17117. #if defined(_WIN32)
  17118. tls.pthread_cond_helper_mutex = NULL;
  17119. #endif
  17120. pthread_setspecific(sTlsKey, &tls);
  17121. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17122. #if !defined(ALTERNATIVE_QUEUE)
  17123. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17124. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17125. ctx->sq_blocked = 0;
  17126. #endif
  17127. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17128. if (!ok) {
  17129. const char *err_msg =
  17130. "Cannot initialize thread synchronization objects";
  17131. /* Fatal error - abort start. However, this situation should never
  17132. * occur in practice. */
  17133. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17134. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17135. mg_snprintf(NULL,
  17136. NULL, /* No truncation check for error buffers */
  17137. error->text,
  17138. error->text_buffer_size,
  17139. "%s",
  17140. err_msg);
  17141. }
  17142. mg_free(ctx);
  17143. pthread_setspecific(sTlsKey, NULL);
  17144. return NULL;
  17145. }
  17146. if ((init != NULL) && (init->callbacks != NULL)) {
  17147. /* Set all callbacks except exit_context. */
  17148. ctx->callbacks = *init->callbacks;
  17149. exit_callback = init->callbacks->exit_context;
  17150. /* The exit callback is activated once the context is successfully
  17151. * created. It should not be called, if an incomplete context object
  17152. * is deleted during a failed initialization. */
  17153. ctx->callbacks.exit_context = 0;
  17154. }
  17155. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17156. ctx->dd.handlers = NULL;
  17157. ctx->dd.next = NULL;
  17158. #if defined(USE_LUA)
  17159. lua_ctx_init(ctx);
  17160. #endif
  17161. /* Store options */
  17162. while (options && (name = *options++) != NULL) {
  17163. if ((idx = get_option_index(name)) == -1) {
  17164. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17165. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17166. mg_snprintf(NULL,
  17167. NULL, /* No truncation check for error buffers */
  17168. error->text,
  17169. error->text_buffer_size,
  17170. "Invalid configuration option: %s",
  17171. name);
  17172. }
  17173. free_context(ctx);
  17174. pthread_setspecific(sTlsKey, NULL);
  17175. return NULL;
  17176. } else if ((value = *options++) == NULL) {
  17177. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17178. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17179. mg_snprintf(NULL,
  17180. NULL, /* No truncation check for error buffers */
  17181. error->text,
  17182. error->text_buffer_size,
  17183. "Invalid configuration option value: %s",
  17184. name);
  17185. }
  17186. free_context(ctx);
  17187. pthread_setspecific(sTlsKey, NULL);
  17188. return NULL;
  17189. }
  17190. if (ctx->dd.config[idx] != NULL) {
  17191. /* A duplicate configuration option is not an error - the last
  17192. * option value will be used. */
  17193. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17194. mg_free(ctx->dd.config[idx]);
  17195. }
  17196. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17197. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17198. }
  17199. /* Set default value if needed */
  17200. for (i = 0; config_options[i].name != NULL; i++) {
  17201. default_value = config_options[i].default_value;
  17202. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17203. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17204. }
  17205. }
  17206. /* Request size option */
  17207. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17208. if (itmp < 1024) {
  17209. mg_cry_ctx_internal(ctx,
  17210. "%s too small",
  17211. config_options[MAX_REQUEST_SIZE].name);
  17212. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17213. mg_snprintf(NULL,
  17214. NULL, /* No truncation check for error buffers */
  17215. error->text,
  17216. error->text_buffer_size,
  17217. "Invalid configuration option value: %s",
  17218. config_options[MAX_REQUEST_SIZE].name);
  17219. }
  17220. free_context(ctx);
  17221. pthread_setspecific(sTlsKey, NULL);
  17222. return NULL;
  17223. }
  17224. ctx->max_request_size = (unsigned)itmp;
  17225. /* Queue length */
  17226. #if !defined(ALTERNATIVE_QUEUE)
  17227. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17228. if (itmp < 1) {
  17229. mg_cry_ctx_internal(ctx,
  17230. "%s too small",
  17231. config_options[CONNECTION_QUEUE_SIZE].name);
  17232. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17233. mg_snprintf(NULL,
  17234. NULL, /* No truncation check for error buffers */
  17235. error->text,
  17236. error->text_buffer_size,
  17237. "Invalid configuration option value: %s",
  17238. config_options[CONNECTION_QUEUE_SIZE].name);
  17239. }
  17240. free_context(ctx);
  17241. pthread_setspecific(sTlsKey, NULL);
  17242. return NULL;
  17243. }
  17244. ctx->squeue =
  17245. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17246. if (ctx->squeue == NULL) {
  17247. mg_cry_ctx_internal(ctx,
  17248. "Out of memory: Cannot allocate %s",
  17249. config_options[CONNECTION_QUEUE_SIZE].name);
  17250. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17251. mg_snprintf(NULL,
  17252. NULL, /* No truncation check for error buffers */
  17253. error->text,
  17254. error->text_buffer_size,
  17255. "Out of memory: Cannot allocate %s",
  17256. config_options[CONNECTION_QUEUE_SIZE].name);
  17257. }
  17258. free_context(ctx);
  17259. pthread_setspecific(sTlsKey, NULL);
  17260. return NULL;
  17261. }
  17262. ctx->sq_size = itmp;
  17263. #endif
  17264. /* Worker thread count option */
  17265. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17266. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17267. if (workerthreadcount <= 0) {
  17268. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17269. } else {
  17270. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17271. }
  17272. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17273. mg_snprintf(NULL,
  17274. NULL, /* No truncation check for error buffers */
  17275. error->text,
  17276. error->text_buffer_size,
  17277. "Invalid configuration option value: %s",
  17278. config_options[NUM_THREADS].name);
  17279. }
  17280. free_context(ctx);
  17281. pthread_setspecific(sTlsKey, NULL);
  17282. return NULL;
  17283. }
  17284. /* Document root */
  17285. #if defined(NO_FILES)
  17286. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17287. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17288. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17289. mg_snprintf(NULL,
  17290. NULL, /* No truncation check for error buffers */
  17291. error->text,
  17292. error->text_buffer_size,
  17293. "Invalid configuration option value: %s",
  17294. config_options[DOCUMENT_ROOT].name);
  17295. }
  17296. free_context(ctx);
  17297. pthread_setspecific(sTlsKey, NULL);
  17298. return NULL;
  17299. }
  17300. #endif
  17301. get_system_name(&ctx->systemName);
  17302. #if defined(USE_LUA)
  17303. /* If a Lua background script has been configured, start it. */
  17304. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17305. char ebuf[256];
  17306. struct vec opt_vec;
  17307. struct vec eq_vec;
  17308. const char *sparams;
  17309. /* Create a Lua state, load all standard libraries and the mg table */
  17310. lua_State *state = mg_lua_context_script_prepare(
  17311. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17312. if (!state) {
  17313. mg_cry_ctx_internal(ctx,
  17314. "lua_background_script load error: %s",
  17315. ebuf);
  17316. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17317. mg_snprintf(NULL,
  17318. NULL, /* No truncation check for error buffers */
  17319. error->text,
  17320. error->text_buffer_size,
  17321. "Error in script %s: %s",
  17322. config_options[DOCUMENT_ROOT].name,
  17323. ebuf);
  17324. }
  17325. free_context(ctx);
  17326. pthread_setspecific(sTlsKey, NULL);
  17327. return NULL;
  17328. }
  17329. /* Add a table with parameters into mg.params */
  17330. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17331. if (sparams && sparams[0]) {
  17332. lua_getglobal(state, "mg");
  17333. lua_pushstring(state, "params");
  17334. lua_newtable(state);
  17335. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17336. != NULL) {
  17337. reg_llstring(
  17338. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17339. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17340. break;
  17341. }
  17342. lua_rawset(state, -3);
  17343. lua_pop(state, 1);
  17344. }
  17345. /* Call script */
  17346. state = mg_lua_context_script_run(state,
  17347. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17348. ctx,
  17349. ebuf,
  17350. sizeof(ebuf));
  17351. if (!state) {
  17352. mg_cry_ctx_internal(ctx,
  17353. "lua_background_script start error: %s",
  17354. ebuf);
  17355. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17356. mg_snprintf(NULL,
  17357. NULL, /* No truncation check for error buffers */
  17358. error->text,
  17359. error->text_buffer_size,
  17360. "Error in script %s: %s",
  17361. config_options[DOCUMENT_ROOT].name,
  17362. ebuf);
  17363. }
  17364. free_context(ctx);
  17365. pthread_setspecific(sTlsKey, NULL);
  17366. return NULL;
  17367. }
  17368. /* state remains valid */
  17369. ctx->lua_background_state = (void *)state;
  17370. } else {
  17371. ctx->lua_background_state = 0;
  17372. }
  17373. #endif
  17374. /* Step by step initialization of ctx - depending on build options */
  17375. #if !defined(NO_FILESYSTEMS)
  17376. if (!set_gpass_option(ctx, NULL)) {
  17377. const char *err_msg = "Invalid global password file";
  17378. /* Fatal error - abort start. */
  17379. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17380. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17381. mg_snprintf(NULL,
  17382. NULL, /* No truncation check for error buffers */
  17383. error->text,
  17384. error->text_buffer_size,
  17385. "%s",
  17386. err_msg);
  17387. }
  17388. free_context(ctx);
  17389. pthread_setspecific(sTlsKey, NULL);
  17390. return NULL;
  17391. }
  17392. #endif
  17393. #if !defined(NO_SSL)
  17394. if (!init_ssl_ctx(ctx, NULL)) {
  17395. const char *err_msg = "Error initializing SSL context";
  17396. /* Fatal error - abort start. */
  17397. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17398. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17399. mg_snprintf(NULL,
  17400. NULL, /* No truncation check for error buffers */
  17401. error->text,
  17402. error->text_buffer_size,
  17403. "%s",
  17404. err_msg);
  17405. }
  17406. free_context(ctx);
  17407. pthread_setspecific(sTlsKey, NULL);
  17408. return NULL;
  17409. }
  17410. #endif
  17411. if (!set_ports_option(ctx)) {
  17412. const char *err_msg = "Failed to setup server ports";
  17413. /* Fatal error - abort start. */
  17414. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17415. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17416. mg_snprintf(NULL,
  17417. NULL, /* No truncation check for error buffers */
  17418. error->text,
  17419. error->text_buffer_size,
  17420. "%s",
  17421. err_msg);
  17422. }
  17423. free_context(ctx);
  17424. pthread_setspecific(sTlsKey, NULL);
  17425. return NULL;
  17426. }
  17427. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17428. if (!set_uid_option(ctx)) {
  17429. const char *err_msg = "Failed to run as configured user";
  17430. /* Fatal error - abort start. */
  17431. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17432. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17433. mg_snprintf(NULL,
  17434. NULL, /* No truncation check for error buffers */
  17435. error->text,
  17436. error->text_buffer_size,
  17437. "%s",
  17438. err_msg);
  17439. }
  17440. free_context(ctx);
  17441. pthread_setspecific(sTlsKey, NULL);
  17442. return NULL;
  17443. }
  17444. #endif
  17445. if (!set_acl_option(ctx)) {
  17446. const char *err_msg = "Failed to setup access control list";
  17447. /* Fatal error - abort start. */
  17448. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17449. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17450. mg_snprintf(NULL,
  17451. NULL, /* No truncation check for error buffers */
  17452. error->text,
  17453. error->text_buffer_size,
  17454. "%s",
  17455. err_msg);
  17456. }
  17457. free_context(ctx);
  17458. pthread_setspecific(sTlsKey, NULL);
  17459. return NULL;
  17460. }
  17461. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17462. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17463. sizeof(pthread_t),
  17464. ctx);
  17465. if (ctx->worker_threadids == NULL) {
  17466. const char *err_msg = "Not enough memory for worker thread ID array";
  17467. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17468. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17469. mg_snprintf(NULL,
  17470. NULL, /* No truncation check for error buffers */
  17471. error->text,
  17472. error->text_buffer_size,
  17473. "%s",
  17474. err_msg);
  17475. }
  17476. free_context(ctx);
  17477. pthread_setspecific(sTlsKey, NULL);
  17478. return NULL;
  17479. }
  17480. ctx->worker_connections =
  17481. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17482. sizeof(struct mg_connection),
  17483. ctx);
  17484. if (ctx->worker_connections == NULL) {
  17485. const char *err_msg =
  17486. "Not enough memory for worker thread connection array";
  17487. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17488. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17489. mg_snprintf(NULL,
  17490. NULL, /* No truncation check for error buffers */
  17491. error->text,
  17492. error->text_buffer_size,
  17493. "%s",
  17494. err_msg);
  17495. }
  17496. free_context(ctx);
  17497. pthread_setspecific(sTlsKey, NULL);
  17498. return NULL;
  17499. }
  17500. #if defined(ALTERNATIVE_QUEUE)
  17501. ctx->client_wait_events =
  17502. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17503. sizeof(ctx->client_wait_events[0]),
  17504. ctx);
  17505. if (ctx->client_wait_events == NULL) {
  17506. const char *err_msg = "Not enough memory for worker event array";
  17507. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17508. mg_free(ctx->worker_threadids);
  17509. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17510. mg_snprintf(NULL,
  17511. NULL, /* No truncation check for error buffers */
  17512. error->text,
  17513. error->text_buffer_size,
  17514. "%s",
  17515. err_msg);
  17516. }
  17517. free_context(ctx);
  17518. pthread_setspecific(sTlsKey, NULL);
  17519. return NULL;
  17520. }
  17521. ctx->client_socks =
  17522. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17523. sizeof(ctx->client_socks[0]),
  17524. ctx);
  17525. if (ctx->client_socks == NULL) {
  17526. const char *err_msg = "Not enough memory for worker socket array";
  17527. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17528. mg_free(ctx->client_wait_events);
  17529. mg_free(ctx->worker_threadids);
  17530. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17531. mg_snprintf(NULL,
  17532. NULL, /* No truncation check for error buffers */
  17533. error->text,
  17534. error->text_buffer_size,
  17535. "%s",
  17536. err_msg);
  17537. }
  17538. free_context(ctx);
  17539. pthread_setspecific(sTlsKey, NULL);
  17540. return NULL;
  17541. }
  17542. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17543. ctx->client_wait_events[i] = event_create();
  17544. if (ctx->client_wait_events[i] == 0) {
  17545. const char *err_msg = "Error creating worker event %i";
  17546. mg_cry_ctx_internal(ctx, err_msg, i);
  17547. while (i > 0) {
  17548. i--;
  17549. event_destroy(ctx->client_wait_events[i]);
  17550. }
  17551. mg_free(ctx->client_socks);
  17552. mg_free(ctx->client_wait_events);
  17553. mg_free(ctx->worker_threadids);
  17554. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17555. mg_snprintf(NULL,
  17556. NULL, /* No truncation check for error buffers */
  17557. error->text,
  17558. error->text_buffer_size,
  17559. err_msg,
  17560. i);
  17561. }
  17562. free_context(ctx);
  17563. pthread_setspecific(sTlsKey, NULL);
  17564. return NULL;
  17565. }
  17566. }
  17567. #endif
  17568. #if defined(USE_TIMERS)
  17569. if (timers_init(ctx) != 0) {
  17570. const char *err_msg = "Error creating timers";
  17571. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17572. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17573. mg_snprintf(NULL,
  17574. NULL, /* No truncation check for error buffers */
  17575. error->text,
  17576. error->text_buffer_size,
  17577. "%s",
  17578. err_msg);
  17579. }
  17580. free_context(ctx);
  17581. pthread_setspecific(sTlsKey, NULL);
  17582. return NULL;
  17583. }
  17584. #endif
  17585. /* Context has been created - init user libraries */
  17586. if (ctx->callbacks.init_context) {
  17587. ctx->callbacks.init_context(ctx);
  17588. }
  17589. /* From now, the context is successfully created.
  17590. * When it is destroyed, the exit callback should be called. */
  17591. ctx->callbacks.exit_context = exit_callback;
  17592. ctx->context_type = CONTEXT_SERVER; /* server context */
  17593. /* Start worker threads */
  17594. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17595. /* worker_thread sets up the other fields */
  17596. ctx->worker_connections[i].phys_ctx = ctx;
  17597. if (mg_start_thread_with_id(worker_thread,
  17598. &ctx->worker_connections[i],
  17599. &ctx->worker_threadids[i])
  17600. != 0) {
  17601. long error_no = (long)ERRNO;
  17602. /* thread was not created */
  17603. if (i > 0) {
  17604. /* If the second, third, ... thread cannot be created, set a
  17605. * warning, but keep running. */
  17606. mg_cry_ctx_internal(ctx,
  17607. "Cannot start worker thread %i: error %ld",
  17608. i + 1,
  17609. error_no);
  17610. /* If the server initialization should stop here, all
  17611. * threads that have already been created must be stopped
  17612. * first, before any free_context(ctx) call.
  17613. */
  17614. } else {
  17615. /* If the first worker thread cannot be created, stop
  17616. * initialization and free the entire server context. */
  17617. mg_cry_ctx_internal(ctx,
  17618. "Cannot create threads: error %ld",
  17619. error_no);
  17620. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17621. mg_snprintf(
  17622. NULL,
  17623. NULL, /* No truncation check for error buffers */
  17624. error->text,
  17625. error->text_buffer_size,
  17626. "Cannot create first worker thread: error %ld",
  17627. error_no);
  17628. }
  17629. free_context(ctx);
  17630. pthread_setspecific(sTlsKey, NULL);
  17631. return NULL;
  17632. }
  17633. break;
  17634. }
  17635. }
  17636. /* Start master (listening) thread */
  17637. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17638. pthread_setspecific(sTlsKey, NULL);
  17639. return ctx;
  17640. }
  17641. struct mg_context *
  17642. mg_start(const struct mg_callbacks *callbacks,
  17643. void *user_data,
  17644. const char **options)
  17645. {
  17646. struct mg_init_data init = {0};
  17647. init.callbacks = callbacks;
  17648. init.user_data = user_data;
  17649. init.configuration_options = options;
  17650. return mg_start2(&init, NULL);
  17651. }
  17652. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17653. /* Add an additional domain to an already running web server. */
  17654. int
  17655. mg_start_domain2(struct mg_context *ctx,
  17656. const char **options,
  17657. struct mg_error_data *error)
  17658. {
  17659. const char *name;
  17660. const char *value;
  17661. const char *default_value;
  17662. struct mg_domain_context *new_dom;
  17663. struct mg_domain_context *dom;
  17664. int idx, i;
  17665. if (error != NULL) {
  17666. error->code = 0;
  17667. if (error->text_buffer_size > 0) {
  17668. *error->text = 0;
  17669. }
  17670. }
  17671. if ((ctx == NULL) || (options == NULL)) {
  17672. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17673. mg_snprintf(NULL,
  17674. NULL, /* No truncation check for error buffers */
  17675. error->text,
  17676. error->text_buffer_size,
  17677. "%s",
  17678. "Invalid parameters");
  17679. }
  17680. return -1;
  17681. }
  17682. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17683. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17684. mg_snprintf(NULL,
  17685. NULL, /* No truncation check for error buffers */
  17686. error->text,
  17687. error->text_buffer_size,
  17688. "%s",
  17689. "Server already stopped");
  17690. }
  17691. return -1;
  17692. }
  17693. new_dom = (struct mg_domain_context *)
  17694. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17695. if (!new_dom) {
  17696. /* Out of memory */
  17697. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17698. mg_snprintf(NULL,
  17699. NULL, /* No truncation check for error buffers */
  17700. error->text,
  17701. error->text_buffer_size,
  17702. "%s",
  17703. "Out or memory");
  17704. }
  17705. return -6;
  17706. }
  17707. /* Store options - TODO: unite duplicate code */
  17708. while (options && (name = *options++) != NULL) {
  17709. if ((idx = get_option_index(name)) == -1) {
  17710. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17711. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17712. mg_snprintf(NULL,
  17713. NULL, /* No truncation check for error buffers */
  17714. error->text,
  17715. error->text_buffer_size,
  17716. "Invalid option: %s",
  17717. name);
  17718. }
  17719. mg_free(new_dom);
  17720. return -2;
  17721. } else if ((value = *options++) == NULL) {
  17722. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17723. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17724. mg_snprintf(NULL,
  17725. NULL, /* No truncation check for error buffers */
  17726. error->text,
  17727. error->text_buffer_size,
  17728. "Invalid option value: %s",
  17729. name);
  17730. }
  17731. mg_free(new_dom);
  17732. return -2;
  17733. }
  17734. if (new_dom->config[idx] != NULL) {
  17735. /* Duplicate option: Later values overwrite earlier ones. */
  17736. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17737. mg_free(new_dom->config[idx]);
  17738. }
  17739. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17740. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17741. }
  17742. /* Authentication domain is mandatory */
  17743. /* TODO: Maybe use a new option hostname? */
  17744. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17745. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17746. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17747. mg_snprintf(NULL,
  17748. NULL, /* No truncation check for error buffers */
  17749. error->text,
  17750. error->text_buffer_size,
  17751. "Mandatory option %s missing",
  17752. config_options[AUTHENTICATION_DOMAIN].name);
  17753. }
  17754. mg_free(new_dom);
  17755. return -4;
  17756. }
  17757. /* Set default value if needed. Take the config value from
  17758. * ctx as a default value. */
  17759. for (i = 0; config_options[i].name != NULL; i++) {
  17760. default_value = ctx->dd.config[i];
  17761. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17762. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17763. }
  17764. }
  17765. new_dom->handlers = NULL;
  17766. new_dom->next = NULL;
  17767. new_dom->nonce_count = 0;
  17768. new_dom->auth_nonce_mask =
  17769. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17770. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17771. new_dom->shared_lua_websockets = NULL;
  17772. #endif
  17773. #if !defined(NO_SSL)
  17774. if (!init_ssl_ctx(ctx, new_dom)) {
  17775. /* Init SSL failed */
  17776. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17777. mg_snprintf(NULL,
  17778. NULL, /* No truncation check for error buffers */
  17779. error->text,
  17780. error->text_buffer_size,
  17781. "%s",
  17782. "Initializing SSL context failed");
  17783. }
  17784. mg_free(new_dom);
  17785. return -3;
  17786. }
  17787. #endif
  17788. /* Add element to linked list. */
  17789. mg_lock_context(ctx);
  17790. idx = 0;
  17791. dom = &(ctx->dd);
  17792. for (;;) {
  17793. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17794. dom->config[AUTHENTICATION_DOMAIN])) {
  17795. /* Domain collision */
  17796. mg_cry_ctx_internal(ctx,
  17797. "domain %s already in use",
  17798. new_dom->config[AUTHENTICATION_DOMAIN]);
  17799. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17800. mg_snprintf(NULL,
  17801. NULL, /* No truncation check for error buffers */
  17802. error->text,
  17803. error->text_buffer_size,
  17804. "Domain %s specified by %s is already in use",
  17805. new_dom->config[AUTHENTICATION_DOMAIN],
  17806. config_options[AUTHENTICATION_DOMAIN].name);
  17807. }
  17808. mg_free(new_dom);
  17809. mg_unlock_context(ctx);
  17810. return -5;
  17811. }
  17812. /* Count number of domains */
  17813. idx++;
  17814. if (dom->next == NULL) {
  17815. dom->next = new_dom;
  17816. break;
  17817. }
  17818. dom = dom->next;
  17819. }
  17820. mg_unlock_context(ctx);
  17821. /* Return domain number */
  17822. return idx;
  17823. }
  17824. int
  17825. mg_start_domain(struct mg_context *ctx, const char **options)
  17826. {
  17827. return mg_start_domain2(ctx, options, NULL);
  17828. }
  17829. #endif
  17830. /* Feature check API function */
  17831. unsigned
  17832. mg_check_feature(unsigned feature)
  17833. {
  17834. static const unsigned feature_set = 0
  17835. /* Set bits for available features according to API documentation.
  17836. * This bit mask is created at compile time, according to the active
  17837. * preprocessor defines. It is a single const value at runtime. */
  17838. #if !defined(NO_FILES)
  17839. | MG_FEATURES_FILES
  17840. #endif
  17841. #if !defined(NO_SSL)
  17842. | MG_FEATURES_SSL
  17843. #endif
  17844. #if !defined(NO_CGI)
  17845. | MG_FEATURES_CGI
  17846. #endif
  17847. #if defined(USE_IPV6)
  17848. | MG_FEATURES_IPV6
  17849. #endif
  17850. #if defined(USE_WEBSOCKET)
  17851. | MG_FEATURES_WEBSOCKET
  17852. #endif
  17853. #if defined(USE_LUA)
  17854. | MG_FEATURES_LUA
  17855. #endif
  17856. #if defined(USE_DUKTAPE)
  17857. | MG_FEATURES_SSJS
  17858. #endif
  17859. #if !defined(NO_CACHING)
  17860. | MG_FEATURES_CACHE
  17861. #endif
  17862. #if defined(USE_SERVER_STATS)
  17863. | MG_FEATURES_STATS
  17864. #endif
  17865. #if defined(USE_ZLIB)
  17866. | MG_FEATURES_COMPRESSION
  17867. #endif
  17868. #if defined(USE_HTTP2)
  17869. | MG_FEATURES_HTTP2
  17870. #endif
  17871. #if defined(USE_X_DOM_SOCKET)
  17872. | MG_FEATURES_X_DOMAIN_SOCKET
  17873. #endif
  17874. /* Set some extra bits not defined in the API documentation.
  17875. * These bits may change without further notice. */
  17876. #if defined(MG_LEGACY_INTERFACE)
  17877. | 0x80000000u
  17878. #endif
  17879. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17880. | 0x40000000u
  17881. #endif
  17882. #if !defined(NO_RESPONSE_BUFFERING)
  17883. | 0x20000000u
  17884. #endif
  17885. #if defined(MEMORY_DEBUGGING)
  17886. | 0x10000000u
  17887. #endif
  17888. ;
  17889. return (feature & feature_set);
  17890. }
  17891. static size_t
  17892. mg_str_append(char **dst, char *end, const char *src)
  17893. {
  17894. size_t len = strlen(src);
  17895. if (*dst != end) {
  17896. /* Append src if enough space, or close dst. */
  17897. if ((size_t)(end - *dst) > len) {
  17898. strcpy(*dst, src);
  17899. *dst += len;
  17900. } else {
  17901. *dst = end;
  17902. }
  17903. }
  17904. return len;
  17905. }
  17906. /* Get system information. It can be printed or stored by the caller.
  17907. * Return the size of available information. */
  17908. int
  17909. mg_get_system_info(char *buffer, int buflen)
  17910. {
  17911. char *end, *append_eoobj = NULL, block[256];
  17912. size_t system_info_length = 0;
  17913. #if defined(_WIN32)
  17914. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17915. #else
  17916. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17917. #endif
  17918. if ((buffer == NULL) || (buflen < 1)) {
  17919. buflen = 0;
  17920. end = buffer;
  17921. } else {
  17922. *buffer = 0;
  17923. end = buffer + buflen;
  17924. }
  17925. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17926. /* has enough space to append eoobj */
  17927. append_eoobj = buffer;
  17928. if (end) {
  17929. end -= sizeof(eoobj) - 1;
  17930. }
  17931. }
  17932. system_info_length += mg_str_append(&buffer, end, "{");
  17933. /* Server version */
  17934. {
  17935. const char *version = mg_version();
  17936. mg_snprintf(NULL,
  17937. NULL,
  17938. block,
  17939. sizeof(block),
  17940. "%s\"version\" : \"%s\"",
  17941. eol,
  17942. version);
  17943. system_info_length += mg_str_append(&buffer, end, block);
  17944. }
  17945. /* System info */
  17946. {
  17947. #if defined(_WIN32)
  17948. DWORD dwVersion = 0;
  17949. DWORD dwMajorVersion = 0;
  17950. DWORD dwMinorVersion = 0;
  17951. SYSTEM_INFO si;
  17952. GetSystemInfo(&si);
  17953. #if defined(_MSC_VER)
  17954. #pragma warning(push)
  17955. /* GetVersion was declared deprecated */
  17956. #pragma warning(disable : 4996)
  17957. #endif
  17958. dwVersion = GetVersion();
  17959. #if defined(_MSC_VER)
  17960. #pragma warning(pop)
  17961. #endif
  17962. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17963. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17964. mg_snprintf(NULL,
  17965. NULL,
  17966. block,
  17967. sizeof(block),
  17968. ",%s\"os\" : \"Windows %u.%u\"",
  17969. eol,
  17970. (unsigned)dwMajorVersion,
  17971. (unsigned)dwMinorVersion);
  17972. system_info_length += mg_str_append(&buffer, end, block);
  17973. mg_snprintf(NULL,
  17974. NULL,
  17975. block,
  17976. sizeof(block),
  17977. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17978. eol,
  17979. (unsigned)si.wProcessorArchitecture,
  17980. (unsigned)si.dwNumberOfProcessors,
  17981. (unsigned)si.dwActiveProcessorMask);
  17982. system_info_length += mg_str_append(&buffer, end, block);
  17983. #elif defined(__ZEPHYR__)
  17984. mg_snprintf(NULL,
  17985. NULL,
  17986. block,
  17987. sizeof(block),
  17988. ",%s\"os\" : \"%s %s\"",
  17989. eol,
  17990. "Zephyr OS",
  17991. ZEPHYR_VERSION);
  17992. system_info_length += mg_str_append(&buffer, end, block);
  17993. #else
  17994. struct utsname name;
  17995. memset(&name, 0, sizeof(name));
  17996. uname(&name);
  17997. mg_snprintf(NULL,
  17998. NULL,
  17999. block,
  18000. sizeof(block),
  18001. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18002. eol,
  18003. name.sysname,
  18004. name.version,
  18005. name.release,
  18006. name.machine);
  18007. system_info_length += mg_str_append(&buffer, end, block);
  18008. #endif
  18009. }
  18010. /* Features */
  18011. {
  18012. mg_snprintf(NULL,
  18013. NULL,
  18014. block,
  18015. sizeof(block),
  18016. ",%s\"features\" : %lu"
  18017. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18018. eol,
  18019. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18020. eol,
  18021. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18022. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18023. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18024. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18025. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18026. : "",
  18027. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18028. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18029. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18030. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18031. system_info_length += mg_str_append(&buffer, end, block);
  18032. #if defined(USE_LUA)
  18033. mg_snprintf(NULL,
  18034. NULL,
  18035. block,
  18036. sizeof(block),
  18037. ",%s\"lua_version\" : \"%u (%s)\"",
  18038. eol,
  18039. (unsigned)LUA_VERSION_NUM,
  18040. LUA_RELEASE);
  18041. system_info_length += mg_str_append(&buffer, end, block);
  18042. #endif
  18043. #if defined(USE_DUKTAPE)
  18044. mg_snprintf(NULL,
  18045. NULL,
  18046. block,
  18047. sizeof(block),
  18048. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18049. eol,
  18050. (unsigned)DUK_VERSION / 10000,
  18051. ((unsigned)DUK_VERSION / 100) % 100,
  18052. (unsigned)DUK_VERSION % 100);
  18053. system_info_length += mg_str_append(&buffer, end, block);
  18054. #endif
  18055. }
  18056. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18057. {
  18058. #if defined(BUILD_DATE)
  18059. const char *bd = BUILD_DATE;
  18060. #else
  18061. #if defined(GCC_DIAGNOSTIC)
  18062. #if GCC_VERSION >= 40900
  18063. #pragma GCC diagnostic push
  18064. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18065. * does not work in some versions. If "BUILD_DATE" is defined to some
  18066. * string, it is used instead of __DATE__. */
  18067. #pragma GCC diagnostic ignored "-Wdate-time"
  18068. #endif
  18069. #endif
  18070. const char *bd = __DATE__;
  18071. #if defined(GCC_DIAGNOSTIC)
  18072. #if GCC_VERSION >= 40900
  18073. #pragma GCC diagnostic pop
  18074. #endif
  18075. #endif
  18076. #endif
  18077. mg_snprintf(
  18078. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18079. system_info_length += mg_str_append(&buffer, end, block);
  18080. }
  18081. /* Compiler information */
  18082. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18083. {
  18084. #if defined(_MSC_VER)
  18085. mg_snprintf(NULL,
  18086. NULL,
  18087. block,
  18088. sizeof(block),
  18089. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18090. eol,
  18091. (unsigned)_MSC_VER,
  18092. (unsigned)_MSC_FULL_VER);
  18093. system_info_length += mg_str_append(&buffer, end, block);
  18094. #elif defined(__MINGW64__)
  18095. mg_snprintf(NULL,
  18096. NULL,
  18097. block,
  18098. sizeof(block),
  18099. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18100. eol,
  18101. (unsigned)__MINGW64_VERSION_MAJOR,
  18102. (unsigned)__MINGW64_VERSION_MINOR);
  18103. system_info_length += mg_str_append(&buffer, end, block);
  18104. mg_snprintf(NULL,
  18105. NULL,
  18106. block,
  18107. sizeof(block),
  18108. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18109. eol,
  18110. (unsigned)__MINGW32_MAJOR_VERSION,
  18111. (unsigned)__MINGW32_MINOR_VERSION);
  18112. system_info_length += mg_str_append(&buffer, end, block);
  18113. #elif defined(__MINGW32__)
  18114. mg_snprintf(NULL,
  18115. NULL,
  18116. block,
  18117. sizeof(block),
  18118. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18119. eol,
  18120. (unsigned)__MINGW32_MAJOR_VERSION,
  18121. (unsigned)__MINGW32_MINOR_VERSION);
  18122. system_info_length += mg_str_append(&buffer, end, block);
  18123. #elif defined(__clang__)
  18124. mg_snprintf(NULL,
  18125. NULL,
  18126. block,
  18127. sizeof(block),
  18128. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18129. eol,
  18130. __clang_major__,
  18131. __clang_minor__,
  18132. __clang_patchlevel__,
  18133. __clang_version__);
  18134. system_info_length += mg_str_append(&buffer, end, block);
  18135. #elif defined(__GNUC__)
  18136. mg_snprintf(NULL,
  18137. NULL,
  18138. block,
  18139. sizeof(block),
  18140. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18141. eol,
  18142. (unsigned)__GNUC__,
  18143. (unsigned)__GNUC_MINOR__,
  18144. (unsigned)__GNUC_PATCHLEVEL__);
  18145. system_info_length += mg_str_append(&buffer, end, block);
  18146. #elif defined(__INTEL_COMPILER)
  18147. mg_snprintf(NULL,
  18148. NULL,
  18149. block,
  18150. sizeof(block),
  18151. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18152. eol,
  18153. (unsigned)__INTEL_COMPILER);
  18154. system_info_length += mg_str_append(&buffer, end, block);
  18155. #elif defined(__BORLANDC__)
  18156. mg_snprintf(NULL,
  18157. NULL,
  18158. block,
  18159. sizeof(block),
  18160. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18161. eol,
  18162. (unsigned)__BORLANDC__);
  18163. system_info_length += mg_str_append(&buffer, end, block);
  18164. #elif defined(__SUNPRO_C)
  18165. mg_snprintf(NULL,
  18166. NULL,
  18167. block,
  18168. sizeof(block),
  18169. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18170. eol,
  18171. (unsigned)__SUNPRO_C);
  18172. system_info_length += mg_str_append(&buffer, end, block);
  18173. #else
  18174. mg_snprintf(NULL,
  18175. NULL,
  18176. block,
  18177. sizeof(block),
  18178. ",%s\"compiler\" : \"other\"",
  18179. eol);
  18180. system_info_length += mg_str_append(&buffer, end, block);
  18181. #endif
  18182. }
  18183. /* Determine 32/64 bit data mode.
  18184. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18185. {
  18186. mg_snprintf(NULL,
  18187. NULL,
  18188. block,
  18189. sizeof(block),
  18190. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18191. "char:%u/%u, "
  18192. "ptr:%u, size:%u, time:%u\"",
  18193. eol,
  18194. (unsigned)sizeof(short),
  18195. (unsigned)sizeof(int),
  18196. (unsigned)sizeof(long),
  18197. (unsigned)sizeof(long long),
  18198. (unsigned)sizeof(float),
  18199. (unsigned)sizeof(double),
  18200. (unsigned)sizeof(long double),
  18201. (unsigned)sizeof(char),
  18202. (unsigned)sizeof(wchar_t),
  18203. (unsigned)sizeof(void *),
  18204. (unsigned)sizeof(size_t),
  18205. (unsigned)sizeof(time_t));
  18206. system_info_length += mg_str_append(&buffer, end, block);
  18207. }
  18208. /* Terminate string */
  18209. if (append_eoobj) {
  18210. strcat(append_eoobj, eoobj);
  18211. }
  18212. system_info_length += sizeof(eoobj) - 1;
  18213. return (int)system_info_length;
  18214. }
  18215. /* Get context information. It can be printed or stored by the caller.
  18216. * Return the size of available information. */
  18217. int
  18218. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18219. {
  18220. #if defined(USE_SERVER_STATS)
  18221. char *end, *append_eoobj = NULL, block[256];
  18222. size_t context_info_length = 0;
  18223. #if defined(_WIN32)
  18224. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18225. #else
  18226. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18227. #endif
  18228. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18229. if ((buffer == NULL) || (buflen < 1)) {
  18230. buflen = 0;
  18231. end = buffer;
  18232. } else {
  18233. *buffer = 0;
  18234. end = buffer + buflen;
  18235. }
  18236. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18237. /* has enough space to append eoobj */
  18238. append_eoobj = buffer;
  18239. end -= sizeof(eoobj) - 1;
  18240. }
  18241. context_info_length += mg_str_append(&buffer, end, "{");
  18242. if (ms) { /* <-- should be always true */
  18243. /* Memory information */
  18244. int blockCount = (int)ms->blockCount;
  18245. int64_t totalMemUsed = ms->totalMemUsed;
  18246. int64_t maxMemUsed = ms->maxMemUsed;
  18247. if (totalMemUsed > maxMemUsed) {
  18248. maxMemUsed = totalMemUsed;
  18249. }
  18250. mg_snprintf(NULL,
  18251. NULL,
  18252. block,
  18253. sizeof(block),
  18254. "%s\"memory\" : {%s"
  18255. "\"blocks\" : %i,%s"
  18256. "\"used\" : %" INT64_FMT ",%s"
  18257. "\"maxUsed\" : %" INT64_FMT "%s"
  18258. "}",
  18259. eol,
  18260. eol,
  18261. blockCount,
  18262. eol,
  18263. totalMemUsed,
  18264. eol,
  18265. maxMemUsed,
  18266. eol);
  18267. context_info_length += mg_str_append(&buffer, end, block);
  18268. }
  18269. if (ctx) {
  18270. /* Declare all variables at begin of the block, to comply
  18271. * with old C standards. */
  18272. char start_time_str[64] = {0};
  18273. char now_str[64] = {0};
  18274. time_t start_time = ctx->start_time;
  18275. time_t now = time(NULL);
  18276. int64_t total_data_read, total_data_written;
  18277. int active_connections = (int)ctx->active_connections;
  18278. int max_active_connections = (int)ctx->max_active_connections;
  18279. int total_connections = (int)ctx->total_connections;
  18280. if (active_connections > max_active_connections) {
  18281. max_active_connections = active_connections;
  18282. }
  18283. if (active_connections > total_connections) {
  18284. total_connections = active_connections;
  18285. }
  18286. /* Connections information */
  18287. mg_snprintf(NULL,
  18288. NULL,
  18289. block,
  18290. sizeof(block),
  18291. ",%s\"connections\" : {%s"
  18292. "\"active\" : %i,%s"
  18293. "\"maxActive\" : %i,%s"
  18294. "\"total\" : %i%s"
  18295. "}",
  18296. eol,
  18297. eol,
  18298. active_connections,
  18299. eol,
  18300. max_active_connections,
  18301. eol,
  18302. total_connections,
  18303. eol);
  18304. context_info_length += mg_str_append(&buffer, end, block);
  18305. /* Queue information */
  18306. #if !defined(ALTERNATIVE_QUEUE)
  18307. mg_snprintf(NULL,
  18308. NULL,
  18309. block,
  18310. sizeof(block),
  18311. ",%s\"queue\" : {%s"
  18312. "\"length\" : %i,%s"
  18313. "\"filled\" : %i,%s"
  18314. "\"maxFilled\" : %i,%s"
  18315. "\"full\" : %s%s"
  18316. "}",
  18317. eol,
  18318. eol,
  18319. ctx->sq_size,
  18320. eol,
  18321. ctx->sq_head - ctx->sq_tail,
  18322. eol,
  18323. ctx->sq_max_fill,
  18324. eol,
  18325. (ctx->sq_blocked ? "true" : "false"),
  18326. eol);
  18327. context_info_length += mg_str_append(&buffer, end, block);
  18328. #endif
  18329. /* Requests information */
  18330. mg_snprintf(NULL,
  18331. NULL,
  18332. block,
  18333. sizeof(block),
  18334. ",%s\"requests\" : {%s"
  18335. "\"total\" : %lu%s"
  18336. "}",
  18337. eol,
  18338. eol,
  18339. (unsigned long)ctx->total_requests,
  18340. eol);
  18341. context_info_length += mg_str_append(&buffer, end, block);
  18342. /* Data information */
  18343. total_data_read =
  18344. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18345. total_data_written =
  18346. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18347. mg_snprintf(NULL,
  18348. NULL,
  18349. block,
  18350. sizeof(block),
  18351. ",%s\"data\" : {%s"
  18352. "\"read\" : %" INT64_FMT ",%s"
  18353. "\"written\" : %" INT64_FMT "%s"
  18354. "}",
  18355. eol,
  18356. eol,
  18357. total_data_read,
  18358. eol,
  18359. total_data_written,
  18360. eol);
  18361. context_info_length += mg_str_append(&buffer, end, block);
  18362. /* Execution time information */
  18363. gmt_time_string(start_time_str,
  18364. sizeof(start_time_str) - 1,
  18365. &start_time);
  18366. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18367. mg_snprintf(NULL,
  18368. NULL,
  18369. block,
  18370. sizeof(block),
  18371. ",%s\"time\" : {%s"
  18372. "\"uptime\" : %.0f,%s"
  18373. "\"start\" : \"%s\",%s"
  18374. "\"now\" : \"%s\"%s"
  18375. "}",
  18376. eol,
  18377. eol,
  18378. difftime(now, start_time),
  18379. eol,
  18380. start_time_str,
  18381. eol,
  18382. now_str,
  18383. eol);
  18384. context_info_length += mg_str_append(&buffer, end, block);
  18385. }
  18386. /* Terminate string */
  18387. if (append_eoobj) {
  18388. strcat(append_eoobj, eoobj);
  18389. }
  18390. context_info_length += sizeof(eoobj) - 1;
  18391. return (int)context_info_length;
  18392. #else
  18393. (void)ctx;
  18394. if ((buffer != NULL) && (buflen > 0)) {
  18395. *buffer = 0;
  18396. }
  18397. return 0;
  18398. #endif
  18399. }
  18400. void
  18401. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18402. {
  18403. /* https://github.com/civetweb/civetweb/issues/727 */
  18404. if (conn != NULL) {
  18405. conn->must_close = 1;
  18406. }
  18407. }
  18408. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18409. /* Get connection information. It can be printed or stored by the caller.
  18410. * Return the size of available information. */
  18411. int
  18412. mg_get_connection_info(const struct mg_context *ctx,
  18413. int idx,
  18414. char *buffer,
  18415. int buflen)
  18416. {
  18417. const struct mg_connection *conn;
  18418. const struct mg_request_info *ri;
  18419. char *end, *append_eoobj = NULL, block[256];
  18420. size_t connection_info_length = 0;
  18421. int state = 0;
  18422. const char *state_str = "unknown";
  18423. #if defined(_WIN32)
  18424. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18425. #else
  18426. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18427. #endif
  18428. if ((buffer == NULL) || (buflen < 1)) {
  18429. buflen = 0;
  18430. end = buffer;
  18431. } else {
  18432. *buffer = 0;
  18433. end = buffer + buflen;
  18434. }
  18435. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18436. /* has enough space to append eoobj */
  18437. append_eoobj = buffer;
  18438. end -= sizeof(eoobj) - 1;
  18439. }
  18440. if ((ctx == NULL) || (idx < 0)) {
  18441. /* Parameter error */
  18442. return 0;
  18443. }
  18444. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18445. /* Out of range */
  18446. return 0;
  18447. }
  18448. /* Take connection [idx]. This connection is not locked in
  18449. * any way, so some other thread might use it. */
  18450. conn = (ctx->worker_connections) + idx;
  18451. /* Initialize output string */
  18452. connection_info_length += mg_str_append(&buffer, end, "{");
  18453. /* Init variables */
  18454. ri = &(conn->request_info);
  18455. #if defined(USE_SERVER_STATS)
  18456. state = conn->conn_state;
  18457. /* State as string */
  18458. switch (state) {
  18459. case 0:
  18460. state_str = "undefined";
  18461. break;
  18462. case 1:
  18463. state_str = "not used";
  18464. break;
  18465. case 2:
  18466. state_str = "init";
  18467. break;
  18468. case 3:
  18469. state_str = "ready";
  18470. break;
  18471. case 4:
  18472. state_str = "processing";
  18473. break;
  18474. case 5:
  18475. state_str = "processed";
  18476. break;
  18477. case 6:
  18478. state_str = "to close";
  18479. break;
  18480. case 7:
  18481. state_str = "closing";
  18482. break;
  18483. case 8:
  18484. state_str = "closed";
  18485. break;
  18486. case 9:
  18487. state_str = "done";
  18488. break;
  18489. }
  18490. #endif
  18491. /* Connection info */
  18492. if ((state >= 3) && (state < 9)) {
  18493. mg_snprintf(NULL,
  18494. NULL,
  18495. block,
  18496. sizeof(block),
  18497. "%s\"connection\" : {%s"
  18498. "\"remote\" : {%s"
  18499. "\"protocol\" : \"%s\",%s"
  18500. "\"addr\" : \"%s\",%s"
  18501. "\"port\" : %u%s"
  18502. "},%s"
  18503. "\"handled_requests\" : %u%s"
  18504. "}",
  18505. eol,
  18506. eol,
  18507. eol,
  18508. get_proto_name(conn),
  18509. eol,
  18510. ri->remote_addr,
  18511. eol,
  18512. ri->remote_port,
  18513. eol,
  18514. eol,
  18515. conn->handled_requests,
  18516. eol);
  18517. connection_info_length += mg_str_append(&buffer, end, block);
  18518. }
  18519. /* Request info */
  18520. if ((state >= 4) && (state < 6)) {
  18521. mg_snprintf(NULL,
  18522. NULL,
  18523. block,
  18524. sizeof(block),
  18525. "%s%s\"request_info\" : {%s"
  18526. "\"method\" : \"%s\",%s"
  18527. "\"uri\" : \"%s\",%s"
  18528. "\"query\" : %s%s%s%s"
  18529. "}",
  18530. (connection_info_length > 1 ? "," : ""),
  18531. eol,
  18532. eol,
  18533. ri->request_method,
  18534. eol,
  18535. ri->request_uri,
  18536. eol,
  18537. ri->query_string ? "\"" : "",
  18538. ri->query_string ? ri->query_string : "null",
  18539. ri->query_string ? "\"" : "",
  18540. eol);
  18541. connection_info_length += mg_str_append(&buffer, end, block);
  18542. }
  18543. /* Execution time information */
  18544. if ((state >= 2) && (state < 9)) {
  18545. char start_time_str[64] = {0};
  18546. char close_time_str[64] = {0};
  18547. time_t start_time = conn->conn_birth_time;
  18548. time_t close_time = 0;
  18549. double time_diff;
  18550. gmt_time_string(start_time_str,
  18551. sizeof(start_time_str) - 1,
  18552. &start_time);
  18553. #if defined(USE_SERVER_STATS)
  18554. close_time = conn->conn_close_time;
  18555. #endif
  18556. if (close_time != 0) {
  18557. time_diff = difftime(close_time, start_time);
  18558. gmt_time_string(close_time_str,
  18559. sizeof(close_time_str) - 1,
  18560. &close_time);
  18561. } else {
  18562. time_t now = time(NULL);
  18563. time_diff = difftime(now, start_time);
  18564. close_time_str[0] = 0; /* or use "now" ? */
  18565. }
  18566. mg_snprintf(NULL,
  18567. NULL,
  18568. block,
  18569. sizeof(block),
  18570. "%s%s\"time\" : {%s"
  18571. "\"uptime\" : %.0f,%s"
  18572. "\"start\" : \"%s\",%s"
  18573. "\"closed\" : \"%s\"%s"
  18574. "}",
  18575. (connection_info_length > 1 ? "," : ""),
  18576. eol,
  18577. eol,
  18578. time_diff,
  18579. eol,
  18580. start_time_str,
  18581. eol,
  18582. close_time_str,
  18583. eol);
  18584. connection_info_length += mg_str_append(&buffer, end, block);
  18585. }
  18586. /* Remote user name */
  18587. if ((ri->remote_user) && (state < 9)) {
  18588. mg_snprintf(NULL,
  18589. NULL,
  18590. block,
  18591. sizeof(block),
  18592. "%s%s\"user\" : {%s"
  18593. "\"name\" : \"%s\",%s"
  18594. "}",
  18595. (connection_info_length > 1 ? "," : ""),
  18596. eol,
  18597. eol,
  18598. ri->remote_user,
  18599. eol);
  18600. connection_info_length += mg_str_append(&buffer, end, block);
  18601. }
  18602. /* Data block */
  18603. if (state >= 3) {
  18604. mg_snprintf(NULL,
  18605. NULL,
  18606. block,
  18607. sizeof(block),
  18608. "%s%s\"data\" : {%s"
  18609. "\"read\" : %" INT64_FMT ",%s"
  18610. "\"written\" : %" INT64_FMT "%s"
  18611. "}",
  18612. (connection_info_length > 1 ? "," : ""),
  18613. eol,
  18614. eol,
  18615. conn->consumed_content,
  18616. eol,
  18617. conn->num_bytes_sent,
  18618. eol);
  18619. connection_info_length += mg_str_append(&buffer, end, block);
  18620. }
  18621. /* State */
  18622. mg_snprintf(NULL,
  18623. NULL,
  18624. block,
  18625. sizeof(block),
  18626. "%s%s\"state\" : \"%s\"",
  18627. (connection_info_length > 1 ? "," : ""),
  18628. eol,
  18629. state_str);
  18630. connection_info_length += mg_str_append(&buffer, end, block);
  18631. /* Terminate string */
  18632. if (append_eoobj) {
  18633. strcat(append_eoobj, eoobj);
  18634. }
  18635. connection_info_length += sizeof(eoobj) - 1;
  18636. return (int)connection_info_length;
  18637. }
  18638. #endif
  18639. /* Initialize this library. This function does not need to be thread safe.
  18640. */
  18641. unsigned
  18642. mg_init_library(unsigned features)
  18643. {
  18644. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18645. unsigned features_inited = features_to_init;
  18646. if (mg_init_library_called <= 0) {
  18647. /* Not initialized yet */
  18648. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18649. return 0;
  18650. }
  18651. }
  18652. mg_global_lock();
  18653. if (mg_init_library_called <= 0) {
  18654. #if defined(_WIN32)
  18655. int file_mutex_init = 1;
  18656. int wsa = 1;
  18657. #else
  18658. int mutexattr_init = 1;
  18659. #endif
  18660. int failed = 1;
  18661. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18662. if (key_create == 0) {
  18663. #if defined(_WIN32)
  18664. file_mutex_init =
  18665. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18666. if (file_mutex_init == 0) {
  18667. /* Start WinSock */
  18668. WSADATA data;
  18669. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18670. }
  18671. #else
  18672. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18673. if (mutexattr_init == 0) {
  18674. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18675. PTHREAD_MUTEX_RECURSIVE);
  18676. }
  18677. #endif
  18678. }
  18679. if (failed) {
  18680. #if defined(_WIN32)
  18681. if (wsa == 0) {
  18682. (void)WSACleanup();
  18683. }
  18684. if (file_mutex_init == 0) {
  18685. (void)pthread_mutex_destroy(&global_log_file_lock);
  18686. }
  18687. #else
  18688. if (mutexattr_init == 0) {
  18689. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18690. }
  18691. #endif
  18692. if (key_create == 0) {
  18693. (void)pthread_key_delete(sTlsKey);
  18694. }
  18695. mg_global_unlock();
  18696. (void)pthread_mutex_destroy(&global_lock_mutex);
  18697. return 0;
  18698. }
  18699. #if defined(USE_LUA)
  18700. lua_init_optional_libraries();
  18701. #endif
  18702. }
  18703. mg_global_unlock();
  18704. #if !defined(NO_SSL)
  18705. if (features_to_init & MG_FEATURES_SSL) {
  18706. if (!mg_ssl_initialized) {
  18707. char ebuf[128];
  18708. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18709. mg_ssl_initialized = 1;
  18710. } else {
  18711. (void)ebuf;
  18712. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18713. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18714. }
  18715. } else {
  18716. /* ssl already initialized */
  18717. }
  18718. }
  18719. #endif
  18720. mg_global_lock();
  18721. if (mg_init_library_called <= 0) {
  18722. mg_init_library_called = 1;
  18723. } else {
  18724. mg_init_library_called++;
  18725. }
  18726. mg_global_unlock();
  18727. return features_inited;
  18728. }
  18729. /* Un-initialize this library. */
  18730. unsigned
  18731. mg_exit_library(void)
  18732. {
  18733. if (mg_init_library_called <= 0) {
  18734. return 0;
  18735. }
  18736. mg_global_lock();
  18737. mg_init_library_called--;
  18738. if (mg_init_library_called == 0) {
  18739. #if !defined(NO_SSL)
  18740. if (mg_ssl_initialized) {
  18741. uninitialize_ssl();
  18742. mg_ssl_initialized = 0;
  18743. }
  18744. #endif
  18745. #if defined(_WIN32)
  18746. (void)WSACleanup();
  18747. (void)pthread_mutex_destroy(&global_log_file_lock);
  18748. #else
  18749. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18750. #endif
  18751. (void)pthread_key_delete(sTlsKey);
  18752. #if defined(USE_LUA)
  18753. lua_exit_optional_libraries();
  18754. #endif
  18755. mg_global_unlock();
  18756. (void)pthread_mutex_destroy(&global_lock_mutex);
  18757. return 1;
  18758. }
  18759. mg_global_unlock();
  18760. return 1;
  18761. }
  18762. /* End of civetweb.c */