civetweb.c 583 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620
  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. /* For a detailed description of these *_PATH_MAX defines, see
  441. * https://github.com/civetweb/civetweb/issues/937. */
  442. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  443. * null termination, rounded up to the next 4 bytes boundary */
  444. #define UTF8_PATH_MAX (3 * 260)
  445. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  446. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  447. #define UTF16_PATH_MAX (260)
  448. #if !defined(_IN_PORT_T)
  449. #if !defined(in_port_t)
  450. #define in_port_t u_short
  451. #endif
  452. #endif
  453. #if !defined(_WIN32_WCE)
  454. #include <direct.h>
  455. #include <io.h>
  456. #include <process.h>
  457. #else /* _WIN32_WCE */
  458. #define NO_CGI /* WinCE has no pipes */
  459. #define NO_POPEN /* WinCE has no popen */
  460. typedef long off_t;
  461. #define errno ((int)(GetLastError()))
  462. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  463. #endif /* _WIN32_WCE */
  464. #define MAKEUQUAD(lo, hi) \
  465. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  466. #define RATE_DIFF (10000000) /* 100 nsecs */
  467. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  468. #define SYS2UNIX_TIME(lo, hi) \
  469. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  470. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  471. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  472. * Also use _strtoui64 on modern M$ compilers */
  473. #if defined(_MSC_VER)
  474. #if (_MSC_VER < 1300)
  475. #define STRX(x) #x
  476. #define STR(x) STRX(x)
  477. #define __func__ __FILE__ ":" STR(__LINE__)
  478. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  479. #define strtoll(x, y, z) (_atoi64(x))
  480. #else
  481. #define __func__ __FUNCTION__
  482. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  483. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  484. #endif
  485. #endif /* _MSC_VER */
  486. #define ERRNO ((int)(GetLastError()))
  487. #define NO_SOCKLEN_T
  488. #if defined(_WIN64) || defined(__MINGW64__)
  489. #if !defined(SSL_LIB)
  490. #if defined(OPENSSL_API_1_1)
  491. #define SSL_LIB "libssl-1_1-x64.dll"
  492. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  493. #endif /* OPENSSL_API_1_1 */
  494. #if defined(OPENSSL_API_1_0)
  495. #define SSL_LIB "ssleay64.dll"
  496. #define CRYPTO_LIB "libeay64.dll"
  497. #endif /* OPENSSL_API_1_0 */
  498. #endif
  499. #else /* defined(_WIN64) || defined(__MINGW64__) */
  500. #if !defined(SSL_LIB)
  501. #if defined(OPENSSL_API_1_1)
  502. #define SSL_LIB "libssl-1_1.dll"
  503. #define CRYPTO_LIB "libcrypto-1_1.dll"
  504. #endif /* OPENSSL_API_1_1 */
  505. #if defined(OPENSSL_API_1_0)
  506. #define SSL_LIB "ssleay32.dll"
  507. #define CRYPTO_LIB "libeay32.dll"
  508. #endif /* OPENSSL_API_1_0 */
  509. #endif /* SSL_LIB */
  510. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  511. #define O_NONBLOCK (0)
  512. #if !defined(W_OK)
  513. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  514. #endif
  515. #define _POSIX_
  516. #define INT64_FMT "I64d"
  517. #define UINT64_FMT "I64u"
  518. #define WINCDECL __cdecl
  519. #define vsnprintf_impl _vsnprintf
  520. #define access _access
  521. #define mg_sleep(x) (Sleep(x))
  522. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  523. #if !defined(popen)
  524. #define popen(x, y) (_popen(x, y))
  525. #endif
  526. #if !defined(pclose)
  527. #define pclose(x) (_pclose(x))
  528. #endif
  529. #define close(x) (_close(x))
  530. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  531. #define RTLD_LAZY (0)
  532. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  533. #define fdopen(x, y) (_fdopen((x), (y)))
  534. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  535. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  536. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  537. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  538. #define sleep(x) (Sleep((x)*1000))
  539. #define rmdir(x) (_rmdir(x))
  540. #if defined(_WIN64) || !defined(__MINGW32__)
  541. /* Only MinGW 32 bit is missing this function */
  542. #define timegm(x) (_mkgmtime(x))
  543. #else
  544. time_t timegm(struct tm *tm);
  545. #define NEED_TIMEGM
  546. #endif
  547. #if !defined(fileno)
  548. #define fileno(x) (_fileno(x))
  549. #endif /* !fileno MINGW #defines fileno */
  550. typedef struct {
  551. CRITICAL_SECTION sec; /* Immovable */
  552. } pthread_mutex_t;
  553. typedef DWORD pthread_key_t;
  554. typedef HANDLE pthread_t;
  555. typedef struct {
  556. pthread_mutex_t threadIdSec;
  557. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  558. } pthread_cond_t;
  559. #if !defined(__clockid_t_defined)
  560. typedef DWORD clockid_t;
  561. #endif
  562. #if !defined(CLOCK_MONOTONIC)
  563. #define CLOCK_MONOTONIC (1)
  564. #endif
  565. #if !defined(CLOCK_REALTIME)
  566. #define CLOCK_REALTIME (2)
  567. #endif
  568. #if !defined(CLOCK_THREAD)
  569. #define CLOCK_THREAD (3)
  570. #endif
  571. #if !defined(CLOCK_PROCESS)
  572. #define CLOCK_PROCESS (4)
  573. #endif
  574. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  575. #define _TIMESPEC_DEFINED
  576. #endif
  577. #if !defined(_TIMESPEC_DEFINED)
  578. struct timespec {
  579. time_t tv_sec; /* seconds */
  580. long tv_nsec; /* nanoseconds */
  581. };
  582. #endif
  583. #if !defined(WIN_PTHREADS_TIME_H)
  584. #define MUST_IMPLEMENT_CLOCK_GETTIME
  585. #endif
  586. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  587. #define clock_gettime mg_clock_gettime
  588. static int
  589. clock_gettime(clockid_t clk_id, struct timespec *tp)
  590. {
  591. FILETIME ft;
  592. ULARGE_INTEGER li, li2;
  593. BOOL ok = FALSE;
  594. double d;
  595. static double perfcnt_per_sec = 0.0;
  596. static BOOL initialized = FALSE;
  597. if (!initialized) {
  598. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  599. perfcnt_per_sec = 1.0 / li.QuadPart;
  600. initialized = TRUE;
  601. }
  602. if (tp) {
  603. memset(tp, 0, sizeof(*tp));
  604. if (clk_id == CLOCK_REALTIME) {
  605. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  606. GetSystemTimeAsFileTime(&ft);
  607. li.LowPart = ft.dwLowDateTime;
  608. li.HighPart = ft.dwHighDateTime;
  609. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  610. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  611. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  612. ok = TRUE;
  613. /* END: CLOCK_REALTIME */
  614. } else if (clk_id == CLOCK_MONOTONIC) {
  615. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  616. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  617. d = li.QuadPart * perfcnt_per_sec;
  618. tp->tv_sec = (time_t)d;
  619. d -= (double)tp->tv_sec;
  620. tp->tv_nsec = (long)(d * 1.0E9);
  621. ok = TRUE;
  622. /* END: CLOCK_MONOTONIC */
  623. } else if (clk_id == CLOCK_THREAD) {
  624. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  625. FILETIME t_create, t_exit, t_kernel, t_user;
  626. if (GetThreadTimes(GetCurrentThread(),
  627. &t_create,
  628. &t_exit,
  629. &t_kernel,
  630. &t_user)) {
  631. li.LowPart = t_user.dwLowDateTime;
  632. li.HighPart = t_user.dwHighDateTime;
  633. li2.LowPart = t_kernel.dwLowDateTime;
  634. li2.HighPart = t_kernel.dwHighDateTime;
  635. li.QuadPart += li2.QuadPart;
  636. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  637. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  638. ok = TRUE;
  639. }
  640. /* END: CLOCK_THREAD */
  641. } else if (clk_id == CLOCK_PROCESS) {
  642. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  643. FILETIME t_create, t_exit, t_kernel, t_user;
  644. if (GetProcessTimes(GetCurrentProcess(),
  645. &t_create,
  646. &t_exit,
  647. &t_kernel,
  648. &t_user)) {
  649. li.LowPart = t_user.dwLowDateTime;
  650. li.HighPart = t_user.dwHighDateTime;
  651. li2.LowPart = t_kernel.dwLowDateTime;
  652. li2.HighPart = t_kernel.dwHighDateTime;
  653. li.QuadPart += li2.QuadPart;
  654. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  655. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  656. ok = TRUE;
  657. }
  658. /* END: CLOCK_PROCESS */
  659. } else {
  660. /* BEGIN: unknown clock */
  661. /* ok = FALSE; already set by init */
  662. /* END: unknown clock */
  663. }
  664. }
  665. return ok ? 0 : -1;
  666. }
  667. #endif
  668. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  669. static int pthread_mutex_lock(pthread_mutex_t *);
  670. static int pthread_mutex_unlock(pthread_mutex_t *);
  671. static void path_to_unicode(const struct mg_connection *conn,
  672. const char *path,
  673. wchar_t *wbuf,
  674. size_t wbuf_len);
  675. /* All file operations need to be rewritten to solve #246. */
  676. struct mg_file;
  677. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  678. /* POSIX dirent interface */
  679. struct dirent {
  680. char d_name[UTF8_PATH_MAX];
  681. };
  682. typedef struct DIR {
  683. HANDLE handle;
  684. WIN32_FIND_DATAW info;
  685. struct dirent result;
  686. } DIR;
  687. #if defined(HAVE_POLL)
  688. #define mg_pollfd pollfd
  689. #else
  690. struct mg_pollfd {
  691. SOCKET fd;
  692. short events;
  693. short revents;
  694. };
  695. #endif
  696. /* Mark required libraries */
  697. #if defined(_MSC_VER)
  698. #pragma comment(lib, "Ws2_32.lib")
  699. #endif
  700. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  701. #include <inttypes.h>
  702. /* Linux & co. internally use UTF8 */
  703. #define UTF8_PATH_MAX (PATH_MAX)
  704. typedef const void *SOCK_OPT_TYPE;
  705. #if defined(ANDROID)
  706. typedef unsigned short int in_port_t;
  707. #endif
  708. #if !defined(__ZEPHYR__)
  709. #include <arpa/inet.h>
  710. #include <ctype.h>
  711. #include <dirent.h>
  712. #include <grp.h>
  713. #include <limits.h>
  714. #include <netdb.h>
  715. #include <netinet/in.h>
  716. #include <netinet/tcp.h>
  717. #include <pthread.h>
  718. #include <pwd.h>
  719. #include <stdarg.h>
  720. #include <stddef.h>
  721. #include <stdio.h>
  722. #include <stdlib.h>
  723. #include <string.h>
  724. #include <sys/poll.h>
  725. #include <sys/socket.h>
  726. #include <sys/time.h>
  727. #include <sys/utsname.h>
  728. #include <sys/wait.h>
  729. #include <time.h>
  730. #include <unistd.h>
  731. #if defined(USE_X_DOM_SOCKET)
  732. #include <sys/un.h>
  733. #endif
  734. #endif
  735. #define vsnprintf_impl vsnprintf
  736. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  737. #include <dlfcn.h>
  738. #endif
  739. #if defined(__MACH__)
  740. #define SSL_LIB "libssl.dylib"
  741. #define CRYPTO_LIB "libcrypto.dylib"
  742. #else
  743. #if !defined(SSL_LIB)
  744. #define SSL_LIB "libssl.so"
  745. #endif
  746. #if !defined(CRYPTO_LIB)
  747. #define CRYPTO_LIB "libcrypto.so"
  748. #endif
  749. #endif
  750. #if !defined(O_BINARY)
  751. #define O_BINARY (0)
  752. #endif /* O_BINARY */
  753. #define closesocket(a) (close(a))
  754. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  755. #define mg_remove(conn, x) (remove(x))
  756. #define mg_sleep(x) (usleep((x)*1000))
  757. #define mg_opendir(conn, x) (opendir(x))
  758. #define mg_closedir(x) (closedir(x))
  759. #define mg_readdir(x) (readdir(x))
  760. #define ERRNO (errno)
  761. #define INVALID_SOCKET (-1)
  762. #define INT64_FMT PRId64
  763. #define UINT64_FMT PRIu64
  764. typedef int SOCKET;
  765. #define WINCDECL
  766. #if defined(__hpux)
  767. /* HPUX 11 does not have monotonic, fall back to realtime */
  768. #if !defined(CLOCK_MONOTONIC)
  769. #define CLOCK_MONOTONIC CLOCK_REALTIME
  770. #endif
  771. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  772. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  773. * the prototypes use int* rather than socklen_t* which matches the
  774. * actual library expectation. When called with the wrong size arg
  775. * accept() returns a zero client inet addr and check_acl() always
  776. * fails. Since socklen_t is widely used below, just force replace
  777. * their typedef with int. - DTL
  778. */
  779. #define socklen_t int
  780. #endif /* hpux */
  781. #define mg_pollfd pollfd
  782. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  783. /* In case our C library is missing "timegm", provide an implementation */
  784. #if defined(NEED_TIMEGM)
  785. static inline int
  786. is_leap(int y)
  787. {
  788. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  789. }
  790. static inline int
  791. count_leap(int y)
  792. {
  793. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  794. }
  795. time_t
  796. timegm(struct tm *tm)
  797. {
  798. static const unsigned short ydays[] = {
  799. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  800. int year = tm->tm_year + 1900;
  801. int mon = tm->tm_mon;
  802. int mday = tm->tm_mday - 1;
  803. int hour = tm->tm_hour;
  804. int min = tm->tm_min;
  805. int sec = tm->tm_sec;
  806. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  807. || (mday >= ydays[mon + 1] - ydays[mon]
  808. + (mon == 1 && is_leap(year) ? 1 : 0))
  809. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  810. return -1;
  811. time_t res = year - 1970;
  812. res *= 365;
  813. res += mday;
  814. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  815. res += count_leap(year);
  816. res *= 24;
  817. res += hour;
  818. res *= 60;
  819. res += min;
  820. res *= 60;
  821. res += sec;
  822. return res;
  823. }
  824. #endif /* NEED_TIMEGM */
  825. /* va_copy should always be a macro, C99 and C++11 - DTL */
  826. #if !defined(va_copy)
  827. #define va_copy(x, y) ((x) = (y))
  828. #endif
  829. #if defined(_WIN32)
  830. /* Create substitutes for POSIX functions in Win32. */
  831. #if defined(GCC_DIAGNOSTIC)
  832. /* Show no warning in case system functions are not used. */
  833. #pragma GCC diagnostic push
  834. #pragma GCC diagnostic ignored "-Wunused-function"
  835. #endif
  836. static pthread_mutex_t global_log_file_lock;
  837. FUNCTION_MAY_BE_UNUSED
  838. static DWORD
  839. pthread_self(void)
  840. {
  841. return GetCurrentThreadId();
  842. }
  843. FUNCTION_MAY_BE_UNUSED
  844. static int
  845. pthread_key_create(
  846. pthread_key_t *key,
  847. void (*_ignored)(void *) /* destructor not supported for Windows */
  848. )
  849. {
  850. (void)_ignored;
  851. if ((key != 0)) {
  852. *key = TlsAlloc();
  853. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  854. }
  855. return -2;
  856. }
  857. FUNCTION_MAY_BE_UNUSED
  858. static int
  859. pthread_key_delete(pthread_key_t key)
  860. {
  861. return TlsFree(key) ? 0 : 1;
  862. }
  863. FUNCTION_MAY_BE_UNUSED
  864. static int
  865. pthread_setspecific(pthread_key_t key, void *value)
  866. {
  867. return TlsSetValue(key, value) ? 0 : 1;
  868. }
  869. FUNCTION_MAY_BE_UNUSED
  870. static void *
  871. pthread_getspecific(pthread_key_t key)
  872. {
  873. return TlsGetValue(key);
  874. }
  875. #if defined(GCC_DIAGNOSTIC)
  876. /* Enable unused function warning again */
  877. #pragma GCC diagnostic pop
  878. #endif
  879. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  880. #else
  881. static pthread_mutexattr_t pthread_mutex_attr;
  882. #endif /* _WIN32 */
  883. #if defined(_WIN32_WCE)
  884. /* Create substitutes for POSIX functions in Win32. */
  885. #if defined(GCC_DIAGNOSTIC)
  886. /* Show no warning in case system functions are not used. */
  887. #pragma GCC diagnostic push
  888. #pragma GCC diagnostic ignored "-Wunused-function"
  889. #endif
  890. FUNCTION_MAY_BE_UNUSED
  891. static time_t
  892. time(time_t *ptime)
  893. {
  894. time_t t;
  895. SYSTEMTIME st;
  896. FILETIME ft;
  897. GetSystemTime(&st);
  898. SystemTimeToFileTime(&st, &ft);
  899. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  900. if (ptime != NULL) {
  901. *ptime = t;
  902. }
  903. return t;
  904. }
  905. FUNCTION_MAY_BE_UNUSED
  906. static struct tm *
  907. localtime_s(const time_t *ptime, struct tm *ptm)
  908. {
  909. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  910. FILETIME ft, lft;
  911. SYSTEMTIME st;
  912. TIME_ZONE_INFORMATION tzinfo;
  913. if (ptm == NULL) {
  914. return NULL;
  915. }
  916. *(int64_t *)&ft = t;
  917. FileTimeToLocalFileTime(&ft, &lft);
  918. FileTimeToSystemTime(&lft, &st);
  919. ptm->tm_year = st.wYear - 1900;
  920. ptm->tm_mon = st.wMonth - 1;
  921. ptm->tm_wday = st.wDayOfWeek;
  922. ptm->tm_mday = st.wDay;
  923. ptm->tm_hour = st.wHour;
  924. ptm->tm_min = st.wMinute;
  925. ptm->tm_sec = st.wSecond;
  926. ptm->tm_yday = 0; /* hope nobody uses this */
  927. ptm->tm_isdst =
  928. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  929. return ptm;
  930. }
  931. FUNCTION_MAY_BE_UNUSED
  932. static struct tm *
  933. gmtime_s(const time_t *ptime, struct tm *ptm)
  934. {
  935. /* FIXME(lsm): fix this. */
  936. return localtime_s(ptime, ptm);
  937. }
  938. static ptrdiff_t mg_atomic_inc(volatile ptrdiff_t *addr);
  939. static struct tm tm_array[MAX_WORKER_THREADS]; /* Must be 2^n */
  940. static volatile ptrdiff_t tm_index = 0;
  941. FUNCTION_MAY_BE_UNUSED
  942. static struct tm *
  943. localtime(const time_t *ptime)
  944. {
  945. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  946. return localtime_s(ptime, tm_array + i);
  947. }
  948. FUNCTION_MAY_BE_UNUSED
  949. static struct tm *
  950. gmtime(const time_t *ptime)
  951. {
  952. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  953. return gmtime_s(ptime, tm_array + i);
  954. }
  955. FUNCTION_MAY_BE_UNUSED
  956. static size_t
  957. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  958. {
  959. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  960. * for WinCE"); */
  961. return 0;
  962. }
  963. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  964. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  965. #define remove(f) mg_remove(NULL, f)
  966. FUNCTION_MAY_BE_UNUSED
  967. static int
  968. rename(const char *a, const char *b)
  969. {
  970. wchar_t wa[UTF16_PATH_MAX];
  971. wchar_t wb[UTF16_PATH_MAX];
  972. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  973. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  974. return MoveFileW(wa, wb) ? 0 : -1;
  975. }
  976. struct stat {
  977. int64_t st_size;
  978. time_t st_mtime;
  979. };
  980. FUNCTION_MAY_BE_UNUSED
  981. static int
  982. stat(const char *name, struct stat *st)
  983. {
  984. wchar_t wbuf[UTF16_PATH_MAX];
  985. WIN32_FILE_ATTRIBUTE_DATA attr;
  986. time_t creation_time, write_time;
  987. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  988. memset(&attr, 0, sizeof(attr));
  989. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  990. st->st_size =
  991. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  992. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  993. attr.ftLastWriteTime.dwHighDateTime);
  994. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  995. attr.ftCreationTime.dwHighDateTime);
  996. if (creation_time > write_time) {
  997. st->st_mtime = creation_time;
  998. } else {
  999. st->st_mtime = write_time;
  1000. }
  1001. return 0;
  1002. }
  1003. #define access(x, a) 1 /* not required anyway */
  1004. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  1005. /* Values from errno.h in Windows SDK (Visual Studio). */
  1006. #define EEXIST 17
  1007. #define EACCES 13
  1008. #define ENOENT 2
  1009. #if defined(GCC_DIAGNOSTIC)
  1010. /* Enable unused function warning again */
  1011. #pragma GCC diagnostic pop
  1012. #endif
  1013. #endif /* defined(_WIN32_WCE) */
  1014. #if defined(GCC_DIAGNOSTIC)
  1015. /* Show no warning in case system functions are not used. */
  1016. #pragma GCC diagnostic push
  1017. #pragma GCC diagnostic ignored "-Wunused-function"
  1018. #endif /* defined(GCC_DIAGNOSTIC) */
  1019. #if defined(__clang__)
  1020. /* Show no warning in case system functions are not used. */
  1021. #pragma clang diagnostic push
  1022. #pragma clang diagnostic ignored "-Wunused-function"
  1023. #endif
  1024. static pthread_mutex_t global_lock_mutex;
  1025. FUNCTION_MAY_BE_UNUSED
  1026. static void
  1027. mg_global_lock(void)
  1028. {
  1029. (void)pthread_mutex_lock(&global_lock_mutex);
  1030. }
  1031. FUNCTION_MAY_BE_UNUSED
  1032. static void
  1033. mg_global_unlock(void)
  1034. {
  1035. (void)pthread_mutex_unlock(&global_lock_mutex);
  1036. }
  1037. #if defined(_WIN64)
  1038. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  1039. #elif defined(_WIN32)
  1040. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  1041. #endif
  1042. /* Atomic functions working on ptrdiff_t ("signed size_t").
  1043. * Operations: Increment, Decrement, Add, Maximum.
  1044. * Up to size_t, they do not an atomic "load" operation.
  1045. */
  1046. FUNCTION_MAY_BE_UNUSED
  1047. static ptrdiff_t
  1048. mg_atomic_inc(volatile ptrdiff_t *addr)
  1049. {
  1050. ptrdiff_t ret;
  1051. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1052. ret = InterlockedIncrement64(addr);
  1053. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1054. ret = InterlockedIncrement(addr);
  1055. #elif defined(__GNUC__) \
  1056. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1057. && !defined(NO_ATOMICS)
  1058. ret = __sync_add_and_fetch(addr, 1);
  1059. #else
  1060. mg_global_lock();
  1061. ret = (++(*addr));
  1062. mg_global_unlock();
  1063. #endif
  1064. return ret;
  1065. }
  1066. FUNCTION_MAY_BE_UNUSED
  1067. static ptrdiff_t
  1068. mg_atomic_dec(volatile ptrdiff_t *addr)
  1069. {
  1070. ptrdiff_t ret;
  1071. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1072. ret = InterlockedDecrement64(addr);
  1073. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1074. ret = InterlockedDecrement(addr);
  1075. #elif defined(__GNUC__) \
  1076. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1077. && !defined(NO_ATOMICS)
  1078. ret = __sync_sub_and_fetch(addr, 1);
  1079. #else
  1080. mg_global_lock();
  1081. ret = (--(*addr));
  1082. mg_global_unlock();
  1083. #endif
  1084. return ret;
  1085. }
  1086. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  1087. static ptrdiff_t
  1088. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1089. {
  1090. ptrdiff_t ret;
  1091. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1092. ret = InterlockedAdd64(addr, value);
  1093. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1094. ret = InterlockedExchangeAdd(addr, value) + value;
  1095. #elif defined(__GNUC__) \
  1096. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1097. && !defined(NO_ATOMICS)
  1098. ret = __sync_add_and_fetch(addr, value);
  1099. #else
  1100. mg_global_lock();
  1101. *addr += value;
  1102. ret = (*addr);
  1103. mg_global_unlock();
  1104. #endif
  1105. return ret;
  1106. }
  1107. FUNCTION_MAY_BE_UNUSED
  1108. static ptrdiff_t
  1109. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1110. ptrdiff_t oldval,
  1111. ptrdiff_t newval)
  1112. {
  1113. ptrdiff_t ret;
  1114. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1115. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1116. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1117. ret = InterlockedCompareExchange(addr, newval, oldval);
  1118. #elif defined(__GNUC__) \
  1119. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1120. && !defined(NO_ATOMICS)
  1121. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1122. #else
  1123. mg_global_lock();
  1124. ret = *addr;
  1125. if ((ret != newval) && (ret == oldval)) {
  1126. *addr = newval;
  1127. }
  1128. mg_global_unlock();
  1129. #endif
  1130. return ret;
  1131. }
  1132. static void
  1133. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1134. {
  1135. register ptrdiff_t tmp = *addr;
  1136. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1137. while (tmp < value) {
  1138. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1139. }
  1140. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1141. while (tmp < value) {
  1142. tmp = InterlockedCompareExchange(addr, value, tmp);
  1143. }
  1144. #elif defined(__GNUC__) \
  1145. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1146. && !defined(NO_ATOMICS)
  1147. while (tmp < value) {
  1148. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1149. }
  1150. #else
  1151. mg_global_lock();
  1152. if (*addr < value) {
  1153. *addr = value;
  1154. }
  1155. mg_global_unlock();
  1156. #endif
  1157. }
  1158. static int64_t
  1159. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1160. {
  1161. int64_t ret;
  1162. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1163. ret = InterlockedAdd64(addr, value);
  1164. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1165. ret = InterlockedExchangeAdd64(addr, value) + value;
  1166. #elif defined(__GNUC__) \
  1167. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1168. && !defined(NO_ATOMICS)
  1169. ret = __sync_add_and_fetch(addr, value);
  1170. #else
  1171. mg_global_lock();
  1172. *addr += value;
  1173. ret = (*addr);
  1174. mg_global_unlock();
  1175. #endif
  1176. return ret;
  1177. }
  1178. #endif
  1179. #if defined(GCC_DIAGNOSTIC)
  1180. /* Show no warning in case system functions are not used. */
  1181. #pragma GCC diagnostic pop
  1182. #endif /* defined(GCC_DIAGNOSTIC) */
  1183. #if defined(__clang__)
  1184. /* Show no warning in case system functions are not used. */
  1185. #pragma clang diagnostic pop
  1186. #endif
  1187. #if defined(USE_SERVER_STATS)
  1188. struct mg_memory_stat {
  1189. volatile ptrdiff_t totalMemUsed;
  1190. volatile ptrdiff_t maxMemUsed;
  1191. volatile ptrdiff_t blockCount;
  1192. };
  1193. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1194. static void *
  1195. mg_malloc_ex(size_t size,
  1196. struct mg_context *ctx,
  1197. const char *file,
  1198. unsigned line)
  1199. {
  1200. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1201. void *memory = 0;
  1202. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1203. #if defined(MEMORY_DEBUGGING)
  1204. char mallocStr[256];
  1205. #else
  1206. (void)file;
  1207. (void)line;
  1208. #endif
  1209. if (data) {
  1210. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1211. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1212. mg_atomic_inc(&mstat->blockCount);
  1213. ((uintptr_t *)data)[0] = size;
  1214. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1215. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1216. }
  1217. #if defined(MEMORY_DEBUGGING)
  1218. sprintf(mallocStr,
  1219. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1220. memory,
  1221. (unsigned long)size,
  1222. (unsigned long)mstat->totalMemUsed,
  1223. (unsigned long)mstat->blockCount,
  1224. file,
  1225. line);
  1226. DEBUG_TRACE("%s", mallocStr);
  1227. #endif
  1228. return memory;
  1229. }
  1230. static void *
  1231. mg_calloc_ex(size_t count,
  1232. size_t size,
  1233. struct mg_context *ctx,
  1234. const char *file,
  1235. unsigned line)
  1236. {
  1237. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1238. if (data) {
  1239. memset(data, 0, size * count);
  1240. }
  1241. return data;
  1242. }
  1243. static void
  1244. mg_free_ex(void *memory, const char *file, unsigned line)
  1245. {
  1246. #if defined(MEMORY_DEBUGGING)
  1247. char mallocStr[256];
  1248. #else
  1249. (void)file;
  1250. (void)line;
  1251. #endif
  1252. if (memory) {
  1253. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1254. uintptr_t size = ((uintptr_t *)data)[0];
  1255. struct mg_memory_stat *mstat =
  1256. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1257. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1258. mg_atomic_dec(&mstat->blockCount);
  1259. #if defined(MEMORY_DEBUGGING)
  1260. sprintf(mallocStr,
  1261. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1262. memory,
  1263. (unsigned long)size,
  1264. (unsigned long)mstat->totalMemUsed,
  1265. (unsigned long)mstat->blockCount,
  1266. file,
  1267. line);
  1268. DEBUG_TRACE("%s", mallocStr);
  1269. #endif
  1270. free(data);
  1271. }
  1272. }
  1273. static void *
  1274. mg_realloc_ex(void *memory,
  1275. size_t newsize,
  1276. struct mg_context *ctx,
  1277. const char *file,
  1278. unsigned line)
  1279. {
  1280. void *data;
  1281. void *_realloc;
  1282. uintptr_t oldsize;
  1283. #if defined(MEMORY_DEBUGGING)
  1284. char mallocStr[256];
  1285. #else
  1286. (void)file;
  1287. (void)line;
  1288. #endif
  1289. if (newsize) {
  1290. if (memory) {
  1291. /* Reallocate existing block */
  1292. struct mg_memory_stat *mstat;
  1293. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1294. oldsize = ((uintptr_t *)data)[0];
  1295. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1296. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1297. if (_realloc) {
  1298. data = _realloc;
  1299. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1300. #if defined(MEMORY_DEBUGGING)
  1301. sprintf(mallocStr,
  1302. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1303. memory,
  1304. (unsigned long)oldsize,
  1305. (unsigned long)mstat->totalMemUsed,
  1306. (unsigned long)mstat->blockCount,
  1307. file,
  1308. line);
  1309. DEBUG_TRACE("%s", mallocStr);
  1310. #endif
  1311. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1312. #if defined(MEMORY_DEBUGGING)
  1313. sprintf(mallocStr,
  1314. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1315. memory,
  1316. (unsigned long)newsize,
  1317. (unsigned long)mstat->totalMemUsed,
  1318. (unsigned long)mstat->blockCount,
  1319. file,
  1320. line);
  1321. DEBUG_TRACE("%s", mallocStr);
  1322. #endif
  1323. *(uintptr_t *)data = newsize;
  1324. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1325. } else {
  1326. #if defined(MEMORY_DEBUGGING)
  1327. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1328. #endif
  1329. return _realloc;
  1330. }
  1331. } else {
  1332. /* Allocate new block */
  1333. data = mg_malloc_ex(newsize, ctx, file, line);
  1334. }
  1335. } else {
  1336. /* Free existing block */
  1337. data = 0;
  1338. mg_free_ex(memory, file, line);
  1339. }
  1340. return data;
  1341. }
  1342. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1343. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1344. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1345. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1346. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1347. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1348. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1349. #else /* USE_SERVER_STATS */
  1350. static __inline void *
  1351. mg_malloc(size_t a)
  1352. {
  1353. return malloc(a);
  1354. }
  1355. static __inline void *
  1356. mg_calloc(size_t a, size_t b)
  1357. {
  1358. return calloc(a, b);
  1359. }
  1360. static __inline void *
  1361. mg_realloc(void *a, size_t b)
  1362. {
  1363. return realloc(a, b);
  1364. }
  1365. static __inline void
  1366. mg_free(void *a)
  1367. {
  1368. free(a);
  1369. }
  1370. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1371. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1372. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1373. #define mg_free_ctx(a, c) mg_free(a)
  1374. #endif /* USE_SERVER_STATS */
  1375. static void mg_vsnprintf(const struct mg_connection *conn,
  1376. int *truncated,
  1377. char *buf,
  1378. size_t buflen,
  1379. const char *fmt,
  1380. va_list ap);
  1381. static void mg_snprintf(const struct mg_connection *conn,
  1382. int *truncated,
  1383. char *buf,
  1384. size_t buflen,
  1385. PRINTF_FORMAT_STRING(const char *fmt),
  1386. ...) PRINTF_ARGS(5, 6);
  1387. /* This following lines are just meant as a reminder to use the mg-functions
  1388. * for memory management */
  1389. #if defined(malloc)
  1390. #undef malloc
  1391. #endif
  1392. #if defined(calloc)
  1393. #undef calloc
  1394. #endif
  1395. #if defined(realloc)
  1396. #undef realloc
  1397. #endif
  1398. #if defined(free)
  1399. #undef free
  1400. #endif
  1401. #if defined(snprintf)
  1402. #undef snprintf
  1403. #endif
  1404. #if defined(vsnprintf)
  1405. #undef vsnprintf
  1406. #endif
  1407. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1408. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1409. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1410. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1411. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1412. #if defined(_WIN32)
  1413. /* vsnprintf must not be used in any system,
  1414. * but this define only works well for Windows. */
  1415. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1416. #endif
  1417. /* mg_init_library counter */
  1418. static int mg_init_library_called = 0;
  1419. #if !defined(NO_SSL)
  1420. static int mg_ssl_initialized = 0;
  1421. /* TODO: Selection of SSL library and version */
  1422. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1)
  1423. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1424. #endif
  1425. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1426. #error "Multiple OPENSSL_API versions defined"
  1427. #endif
  1428. #endif /* NO_SSL */
  1429. static pthread_key_t sTlsKey; /* Thread local storage index */
  1430. static volatile ptrdiff_t thread_idx_max = 0;
  1431. #if defined(MG_LEGACY_INTERFACE)
  1432. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1433. #endif
  1434. struct mg_workerTLS {
  1435. int is_master;
  1436. unsigned long thread_idx;
  1437. void *user_ptr;
  1438. #if defined(_WIN32)
  1439. HANDLE pthread_cond_helper_mutex;
  1440. struct mg_workerTLS *next_waiting_thread;
  1441. #endif
  1442. const char *alpn_proto;
  1443. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1444. char txtbuf[4];
  1445. #endif
  1446. };
  1447. #if defined(GCC_DIAGNOSTIC)
  1448. /* Show no warning in case system functions are not used. */
  1449. #pragma GCC diagnostic push
  1450. #pragma GCC diagnostic ignored "-Wunused-function"
  1451. #endif /* defined(GCC_DIAGNOSTIC) */
  1452. #if defined(__clang__)
  1453. /* Show no warning in case system functions are not used. */
  1454. #pragma clang diagnostic push
  1455. #pragma clang diagnostic ignored "-Wunused-function"
  1456. #endif
  1457. /* Get a unique thread ID as unsigned long, independent from the data type
  1458. * of thread IDs defined by the operating system API.
  1459. * If two calls to mg_current_thread_id return the same value, they calls
  1460. * are done from the same thread. If they return different values, they are
  1461. * done from different threads. (Provided this function is used in the same
  1462. * process context and threads are not repeatedly created and deleted, but
  1463. * CivetWeb does not do that).
  1464. * This function must match the signature required for SSL id callbacks:
  1465. * CRYPTO_set_id_callback
  1466. */
  1467. FUNCTION_MAY_BE_UNUSED
  1468. static unsigned long
  1469. mg_current_thread_id(void)
  1470. {
  1471. #if defined(_WIN32)
  1472. return GetCurrentThreadId();
  1473. #else
  1474. #if defined(__clang__)
  1475. #pragma clang diagnostic push
  1476. #pragma clang diagnostic ignored "-Wunreachable-code"
  1477. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1478. * or not, so one of the two conditions will be unreachable by construction.
  1479. * Unfortunately the C standard does not define a way to check this at
  1480. * compile time, since the #if preprocessor conditions can not use the sizeof
  1481. * operator as an argument. */
  1482. #endif
  1483. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1484. /* This is the problematic case for CRYPTO_set_id_callback:
  1485. * The OS pthread_t can not be cast to unsigned long. */
  1486. struct mg_workerTLS *tls =
  1487. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1488. if (tls == NULL) {
  1489. /* SSL called from an unknown thread: Create some thread index.
  1490. */
  1491. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1492. tls->is_master = -2; /* -2 means "3rd party thread" */
  1493. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1494. pthread_setspecific(sTlsKey, tls);
  1495. }
  1496. return tls->thread_idx;
  1497. } else {
  1498. /* pthread_t may be any data type, so a simple cast to unsigned long
  1499. * can rise a warning/error, depending on the platform.
  1500. * Here memcpy is used as an anything-to-anything cast. */
  1501. unsigned long ret = 0;
  1502. pthread_t t = pthread_self();
  1503. memcpy(&ret, &t, sizeof(pthread_t));
  1504. return ret;
  1505. }
  1506. #if defined(__clang__)
  1507. #pragma clang diagnostic pop
  1508. #endif
  1509. #endif
  1510. }
  1511. FUNCTION_MAY_BE_UNUSED
  1512. static uint64_t
  1513. mg_get_current_time_ns(void)
  1514. {
  1515. struct timespec tsnow;
  1516. clock_gettime(CLOCK_REALTIME, &tsnow);
  1517. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1518. }
  1519. #if defined(GCC_DIAGNOSTIC)
  1520. /* Show no warning in case system functions are not used. */
  1521. #pragma GCC diagnostic pop
  1522. #endif /* defined(GCC_DIAGNOSTIC) */
  1523. #if defined(__clang__)
  1524. /* Show no warning in case system functions are not used. */
  1525. #pragma clang diagnostic pop
  1526. #endif
  1527. #if defined(NEED_DEBUG_TRACE_FUNC)
  1528. static void
  1529. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1530. {
  1531. va_list args;
  1532. struct timespec tsnow;
  1533. /* Get some operating system independent thread id */
  1534. unsigned long thread_id = mg_current_thread_id();
  1535. clock_gettime(CLOCK_REALTIME, &tsnow);
  1536. flockfile(DEBUG_TRACE_STREAM);
  1537. fprintf(DEBUG_TRACE_STREAM,
  1538. "*** %lu.%09lu %lu %s:%u: ",
  1539. (unsigned long)tsnow.tv_sec,
  1540. (unsigned long)tsnow.tv_nsec,
  1541. thread_id,
  1542. func,
  1543. line);
  1544. va_start(args, fmt);
  1545. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1546. va_end(args);
  1547. putc('\n', DEBUG_TRACE_STREAM);
  1548. fflush(DEBUG_TRACE_STREAM);
  1549. funlockfile(DEBUG_TRACE_STREAM);
  1550. }
  1551. #endif /* NEED_DEBUG_TRACE_FUNC */
  1552. #define MD5_STATIC static
  1553. #include "md5.inl"
  1554. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1555. #if defined(NO_SOCKLEN_T)
  1556. typedef int socklen_t;
  1557. #endif /* NO_SOCKLEN_T */
  1558. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1559. #if !defined(MSG_NOSIGNAL)
  1560. #define MSG_NOSIGNAL (0)
  1561. #endif
  1562. #if defined(NO_SSL)
  1563. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1564. typedef struct SSL_CTX SSL_CTX;
  1565. #else
  1566. #if defined(NO_SSL_DL)
  1567. #include <openssl/bn.h>
  1568. #include <openssl/conf.h>
  1569. #include <openssl/crypto.h>
  1570. #include <openssl/dh.h>
  1571. #include <openssl/engine.h>
  1572. #include <openssl/err.h>
  1573. #include <openssl/opensslv.h>
  1574. #include <openssl/pem.h>
  1575. #include <openssl/ssl.h>
  1576. #include <openssl/tls1.h>
  1577. #include <openssl/x509.h>
  1578. #if defined(WOLFSSL_VERSION)
  1579. /* Additional defines for WolfSSL, see
  1580. * https://github.com/civetweb/civetweb/issues/583 */
  1581. #include "wolfssl_extras.inl"
  1582. #endif
  1583. #if defined(OPENSSL_IS_BORINGSSL)
  1584. /* From boringssl/src/include/openssl/mem.h:
  1585. *
  1586. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1587. * However, that was written in a time before Valgrind and ASAN. Since we now
  1588. * have those tools, the OpenSSL allocation functions are simply macros around
  1589. * the standard memory functions.
  1590. *
  1591. * #define OPENSSL_free free */
  1592. #define free free
  1593. // disable for boringssl
  1594. #define CONF_modules_unload(a) ((void)0)
  1595. #define ENGINE_cleanup() ((void)0)
  1596. #endif
  1597. /* If OpenSSL headers are included, automatically select the API version */
  1598. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1599. #if !defined(OPENSSL_API_1_1)
  1600. #define OPENSSL_API_1_1
  1601. #endif
  1602. #define OPENSSL_REMOVE_THREAD_STATE()
  1603. #else
  1604. #if !defined(OPENSSL_API_1_0)
  1605. #define OPENSSL_API_1_0
  1606. #endif
  1607. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1608. #endif
  1609. #else
  1610. /* SSL loaded dynamically from DLL.
  1611. * I put the prototypes here to be independent from OpenSSL source
  1612. * installation. */
  1613. typedef struct ssl_st SSL;
  1614. typedef struct ssl_method_st SSL_METHOD;
  1615. typedef struct ssl_ctx_st SSL_CTX;
  1616. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1617. typedef struct x509_name X509_NAME;
  1618. typedef struct asn1_integer ASN1_INTEGER;
  1619. typedef struct bignum BIGNUM;
  1620. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1621. typedef struct evp_md EVP_MD;
  1622. typedef struct x509 X509;
  1623. #define SSL_CTRL_OPTIONS (32)
  1624. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1625. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1626. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1627. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1628. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1629. #define SSL_VERIFY_NONE (0)
  1630. #define SSL_VERIFY_PEER (1)
  1631. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1632. #define SSL_VERIFY_CLIENT_ONCE (4)
  1633. #define SSL_OP_ALL (0x80000BFFul)
  1634. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1635. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1636. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1637. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1638. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1639. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1640. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1641. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1642. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1643. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1644. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1645. #define SSL_CB_HANDSHAKE_START (0x10)
  1646. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1647. #define SSL_ERROR_NONE (0)
  1648. #define SSL_ERROR_SSL (1)
  1649. #define SSL_ERROR_WANT_READ (2)
  1650. #define SSL_ERROR_WANT_WRITE (3)
  1651. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1652. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1653. #define SSL_ERROR_ZERO_RETURN (6)
  1654. #define SSL_ERROR_WANT_CONNECT (7)
  1655. #define SSL_ERROR_WANT_ACCEPT (8)
  1656. #define TLSEXT_TYPE_server_name (0)
  1657. #define TLSEXT_NAMETYPE_host_name (0)
  1658. #define SSL_TLSEXT_ERR_OK (0)
  1659. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1660. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1661. #define SSL_TLSEXT_ERR_NOACK (3)
  1662. #define SSL_SESS_CACHE_BOTH (3)
  1663. enum ssl_func_category {
  1664. TLS_Mandatory, /* required for HTTPS */
  1665. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1666. TLS_END_OF_LIST
  1667. };
  1668. /* Check if all TLS functions/features are available */
  1669. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1670. struct ssl_func {
  1671. const char *name; /* SSL function name */
  1672. enum ssl_func_category required; /* Mandatory or optional */
  1673. void (*ptr)(void); /* Function pointer */
  1674. };
  1675. #if defined(OPENSSL_API_1_1)
  1676. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1677. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1678. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1679. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1680. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1681. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1682. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1683. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1684. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1685. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1686. #define OPENSSL_init_ssl \
  1687. (*(int (*)(uint64_t opts, \
  1688. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1689. .ptr)
  1690. #define SSL_CTX_use_PrivateKey_file \
  1691. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1692. #define SSL_CTX_use_certificate_file \
  1693. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1694. #define SSL_CTX_set_default_passwd_cb \
  1695. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1696. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1697. #define SSL_CTX_use_certificate_chain_file \
  1698. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1699. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1700. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1701. #define SSL_CTX_set_verify \
  1702. (*(void (*)(SSL_CTX *, \
  1703. int, \
  1704. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1705. .ptr)
  1706. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1707. #define SSL_CTX_load_verify_locations \
  1708. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1709. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1710. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1711. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1712. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1713. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1714. #define SSL_CIPHER_get_name \
  1715. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1716. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1717. #define SSL_CTX_set_session_id_context \
  1718. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1719. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1720. #define SSL_CTX_set_cipher_list \
  1721. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1722. #define SSL_CTX_set_options \
  1723. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1724. #define SSL_CTX_set_info_callback \
  1725. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1726. ssl_sw[32] \
  1727. .ptr)
  1728. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1729. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1730. #define SSL_CTX_callback_ctrl \
  1731. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1732. #define SSL_get_servername \
  1733. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1734. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1735. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1736. #define SSL_CTX_set_alpn_protos \
  1737. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1738. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1739. const unsigned char **out,
  1740. unsigned char *outlen,
  1741. const unsigned char *in,
  1742. unsigned int inlen,
  1743. void *arg);
  1744. #define SSL_CTX_set_alpn_select_cb \
  1745. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1746. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1747. const unsigned char **out,
  1748. unsigned int *outlen,
  1749. void *arg);
  1750. #define SSL_CTX_set_next_protos_advertised_cb \
  1751. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1752. .ptr)
  1753. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1754. #define SSL_CTX_clear_options(ctx, op) \
  1755. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1756. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1757. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1758. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1759. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1760. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1761. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1762. SSL_CTX_callback_ctrl(ctx, \
  1763. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1764. (void (*)(void))cb)
  1765. #define SSL_set_tlsext_host_name(ctx, arg) \
  1766. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1767. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1768. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1769. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1770. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1771. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1772. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1773. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1774. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1775. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1776. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1777. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1778. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1779. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1780. #define X509_NAME_oneline \
  1781. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1782. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1783. #define EVP_get_digestbyname \
  1784. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1785. #define EVP_Digest \
  1786. (*(int (*)( \
  1787. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1788. crypto_sw[9] \
  1789. .ptr)
  1790. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1791. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1792. #define ASN1_INTEGER_to_BN \
  1793. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1794. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1795. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1796. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1797. #define OPENSSL_free(a) CRYPTO_free(a)
  1798. #define OPENSSL_REMOVE_THREAD_STATE()
  1799. /* init_ssl_ctx() function updates this array.
  1800. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1801. * of respective functions. The macros above (like SSL_connect()) are really
  1802. * just calling these functions indirectly via the pointer. */
  1803. static struct ssl_func ssl_sw[] = {
  1804. {"SSL_free", TLS_Mandatory, NULL},
  1805. {"SSL_accept", TLS_Mandatory, NULL},
  1806. {"SSL_connect", TLS_Mandatory, NULL},
  1807. {"SSL_read", TLS_Mandatory, NULL},
  1808. {"SSL_write", TLS_Mandatory, NULL},
  1809. {"SSL_get_error", TLS_Mandatory, NULL},
  1810. {"SSL_set_fd", TLS_Mandatory, NULL},
  1811. {"SSL_new", TLS_Mandatory, NULL},
  1812. {"SSL_CTX_new", TLS_Mandatory, NULL},
  1813. {"TLS_server_method", TLS_Mandatory, NULL},
  1814. {"OPENSSL_init_ssl", TLS_Mandatory, NULL},
  1815. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  1816. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  1817. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  1818. {"SSL_CTX_free", TLS_Mandatory, NULL},
  1819. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  1820. {"TLS_client_method", TLS_Mandatory, NULL},
  1821. {"SSL_pending", TLS_Mandatory, NULL},
  1822. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  1823. {"SSL_shutdown", TLS_Mandatory, NULL},
  1824. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  1825. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  1826. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  1827. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  1828. {"SSL_get_version", TLS_Mandatory, NULL},
  1829. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  1830. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  1831. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  1832. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  1833. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  1834. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  1835. {"SSL_CTX_set_options", TLS_Mandatory, NULL},
  1836. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  1837. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  1838. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  1839. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  1840. {"SSL_get_servername", TLS_Mandatory, NULL},
  1841. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  1842. {"SSL_ctrl", TLS_Mandatory, NULL},
  1843. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  1844. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  1845. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  1846. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  1847. {NULL, TLS_END_OF_LIST, NULL}};
  1848. /* Similar array as ssl_sw. These functions could be located in different
  1849. * lib. */
  1850. static struct ssl_func crypto_sw[] = {
  1851. {"ERR_get_error", TLS_Mandatory, NULL},
  1852. {"ERR_error_string", TLS_Mandatory, NULL},
  1853. {"CONF_modules_unload", TLS_Mandatory, NULL},
  1854. {"X509_free", TLS_Mandatory, NULL},
  1855. {"X509_get_subject_name", TLS_Mandatory, NULL},
  1856. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  1857. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  1858. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  1859. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  1860. {"EVP_Digest", TLS_Mandatory, NULL},
  1861. {"i2d_X509", TLS_Mandatory, NULL},
  1862. {"BN_bn2hex", TLS_Mandatory, NULL},
  1863. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  1864. {"BN_free", TLS_Mandatory, NULL},
  1865. {"CRYPTO_free", TLS_Mandatory, NULL},
  1866. {"ERR_clear_error", TLS_Mandatory, NULL},
  1867. {NULL, TLS_END_OF_LIST, NULL}};
  1868. #else
  1869. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1870. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1871. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1872. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1873. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1874. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1875. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1876. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1877. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1878. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1879. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1880. #define SSL_CTX_use_PrivateKey_file \
  1881. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1882. #define SSL_CTX_use_certificate_file \
  1883. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1884. #define SSL_CTX_set_default_passwd_cb \
  1885. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1886. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1887. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1888. #define SSL_CTX_use_certificate_chain_file \
  1889. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1890. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1891. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1892. #define SSL_CTX_set_verify \
  1893. (*(void (*)(SSL_CTX *, \
  1894. int, \
  1895. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1896. .ptr)
  1897. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1898. #define SSL_CTX_load_verify_locations \
  1899. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1900. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1901. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1902. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1903. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1904. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1905. #define SSL_CIPHER_get_name \
  1906. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1907. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1908. #define SSL_CTX_set_session_id_context \
  1909. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1910. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1911. #define SSL_CTX_set_cipher_list \
  1912. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1913. #define SSL_CTX_set_info_callback \
  1914. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1915. .ptr)
  1916. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1917. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1918. #define SSL_CTX_callback_ctrl \
  1919. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1920. #define SSL_get_servername \
  1921. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1922. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1923. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1924. #define SSL_CTX_set_alpn_protos \
  1925. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1926. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1927. const unsigned char **out,
  1928. unsigned char *outlen,
  1929. const unsigned char *in,
  1930. unsigned int inlen,
  1931. void *arg);
  1932. #define SSL_CTX_set_alpn_select_cb \
  1933. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1934. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1935. const unsigned char **out,
  1936. unsigned int *outlen,
  1937. void *arg);
  1938. #define SSL_CTX_set_next_protos_advertised_cb \
  1939. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1940. .ptr)
  1941. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1942. #define SSL_CTX_set_options(ctx, op) \
  1943. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1944. #define SSL_CTX_clear_options(ctx, op) \
  1945. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1946. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1947. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1948. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1949. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1950. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1951. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1952. SSL_CTX_callback_ctrl(ctx, \
  1953. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1954. (void (*)(void))cb)
  1955. #define SSL_set_tlsext_host_name(ctx, arg) \
  1956. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1957. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1958. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1959. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1960. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1961. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1962. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1963. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1964. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1965. #define CRYPTO_set_locking_callback \
  1966. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1967. #define CRYPTO_set_id_callback \
  1968. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1969. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1970. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1971. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1972. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1973. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1974. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1975. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1976. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1977. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1978. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1979. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1980. #define X509_NAME_oneline \
  1981. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1982. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1983. #define i2c_ASN1_INTEGER \
  1984. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1985. #define EVP_get_digestbyname \
  1986. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1987. #define EVP_Digest \
  1988. (*(int (*)( \
  1989. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1990. crypto_sw[18] \
  1991. .ptr)
  1992. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1993. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1994. #define ASN1_INTEGER_to_BN \
  1995. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1996. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1997. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1998. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1999. #define OPENSSL_free(a) CRYPTO_free(a)
  2000. /* use here ERR_remove_state,
  2001. * while on some platforms function is not included into library due to
  2002. * deprication */
  2003. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  2004. /* init_ssl_ctx() function updates this array.
  2005. * It loads SSL library dynamically and changes NULLs to the actual addresses
  2006. * of respective functions. The macros above (like SSL_connect()) are really
  2007. * just calling these functions indirectly via the pointer. */
  2008. static struct ssl_func ssl_sw[] = {
  2009. {"SSL_free", TLS_Mandatory, NULL},
  2010. {"SSL_accept", TLS_Mandatory, NULL},
  2011. {"SSL_connect", TLS_Mandatory, NULL},
  2012. {"SSL_read", TLS_Mandatory, NULL},
  2013. {"SSL_write", TLS_Mandatory, NULL},
  2014. {"SSL_get_error", TLS_Mandatory, NULL},
  2015. {"SSL_set_fd", TLS_Mandatory, NULL},
  2016. {"SSL_new", TLS_Mandatory, NULL},
  2017. {"SSL_CTX_new", TLS_Mandatory, NULL},
  2018. {"SSLv23_server_method", TLS_Mandatory, NULL},
  2019. {"SSL_library_init", TLS_Mandatory, NULL},
  2020. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  2021. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  2022. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  2023. {"SSL_CTX_free", TLS_Mandatory, NULL},
  2024. {"SSL_load_error_strings", TLS_Mandatory, NULL},
  2025. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  2026. {"SSLv23_client_method", TLS_Mandatory, NULL},
  2027. {"SSL_pending", TLS_Mandatory, NULL},
  2028. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  2029. {"SSL_shutdown", TLS_Mandatory, NULL},
  2030. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  2031. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  2032. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  2033. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  2034. {"SSL_get_version", TLS_Mandatory, NULL},
  2035. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  2036. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  2037. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  2038. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  2039. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  2040. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  2041. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  2042. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  2043. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  2044. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  2045. {"SSL_get_servername", TLS_Mandatory, NULL},
  2046. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  2047. {"SSL_ctrl", TLS_Mandatory, NULL},
  2048. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  2049. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  2050. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  2051. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  2052. {NULL, TLS_END_OF_LIST, NULL}};
  2053. /* Similar array as ssl_sw. These functions could be located in different
  2054. * lib. */
  2055. static struct ssl_func crypto_sw[] = {
  2056. {"CRYPTO_num_locks", TLS_Mandatory, NULL},
  2057. {"CRYPTO_set_locking_callback", TLS_Mandatory, NULL},
  2058. {"CRYPTO_set_id_callback", TLS_Mandatory, NULL},
  2059. {"ERR_get_error", TLS_Mandatory, NULL},
  2060. {"ERR_error_string", TLS_Mandatory, NULL},
  2061. {"ERR_remove_state", TLS_Mandatory, NULL},
  2062. {"ERR_free_strings", TLS_Mandatory, NULL},
  2063. {"ENGINE_cleanup", TLS_Mandatory, NULL},
  2064. {"CONF_modules_unload", TLS_Mandatory, NULL},
  2065. {"CRYPTO_cleanup_all_ex_data", TLS_Mandatory, NULL},
  2066. {"EVP_cleanup", TLS_Mandatory, NULL},
  2067. {"X509_free", TLS_Mandatory, NULL},
  2068. {"X509_get_subject_name", TLS_Mandatory, NULL},
  2069. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  2070. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  2071. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  2072. {"i2c_ASN1_INTEGER", TLS_Mandatory, NULL},
  2073. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  2074. {"EVP_Digest", TLS_Mandatory, NULL},
  2075. {"i2d_X509", TLS_Mandatory, NULL},
  2076. {"BN_bn2hex", TLS_Mandatory, NULL},
  2077. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  2078. {"BN_free", TLS_Mandatory, NULL},
  2079. {"CRYPTO_free", TLS_Mandatory, NULL},
  2080. {"ERR_clear_error", TLS_Mandatory, NULL},
  2081. {NULL, TLS_END_OF_LIST, NULL}};
  2082. #endif /* OPENSSL_API_1_1 */
  2083. #endif /* NO_SSL_DL */
  2084. #endif /* NO_SSL */
  2085. #if !defined(NO_CACHING)
  2086. static const char month_names[][4] = {"Jan",
  2087. "Feb",
  2088. "Mar",
  2089. "Apr",
  2090. "May",
  2091. "Jun",
  2092. "Jul",
  2093. "Aug",
  2094. "Sep",
  2095. "Oct",
  2096. "Nov",
  2097. "Dec"};
  2098. #endif /* !NO_CACHING */
  2099. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2100. * the union u. */
  2101. union usa {
  2102. struct sockaddr sa;
  2103. struct sockaddr_in sin;
  2104. #if defined(USE_IPV6)
  2105. struct sockaddr_in6 sin6;
  2106. #endif
  2107. #if defined(USE_X_DOM_SOCKET)
  2108. struct sockaddr_un sun;
  2109. #endif
  2110. };
  2111. #if defined(USE_X_DOM_SOCKET)
  2112. static unsigned short
  2113. USA_IN_PORT_UNSAFE(union usa *s)
  2114. {
  2115. if (s->sa.sa_family == AF_INET)
  2116. return s->sin.sin_port;
  2117. #if defined(USE_IPV6)
  2118. if (s->sa.sa_family == AF_INET6)
  2119. return s->sin6.sin6_port;
  2120. #endif
  2121. return 0;
  2122. }
  2123. #endif
  2124. #if defined(USE_IPV6)
  2125. #define USA_IN_PORT_UNSAFE(s) \
  2126. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  2127. #else
  2128. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  2129. #endif
  2130. /* Describes a string (chunk of memory). */
  2131. struct vec {
  2132. const char *ptr;
  2133. size_t len;
  2134. };
  2135. struct mg_file_stat {
  2136. /* File properties filled by mg_stat: */
  2137. uint64_t size;
  2138. time_t last_modified;
  2139. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2140. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2141. * case we need a "Content-Eencoding: gzip" header */
  2142. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2143. };
  2144. struct mg_file_access {
  2145. /* File properties filled by mg_fopen: */
  2146. FILE *fp;
  2147. };
  2148. struct mg_file {
  2149. struct mg_file_stat stat;
  2150. struct mg_file_access access;
  2151. };
  2152. #define STRUCT_FILE_INITIALIZER \
  2153. { \
  2154. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2155. { \
  2156. (FILE *)NULL \
  2157. } \
  2158. }
  2159. /* Describes listening socket, or socket which was accept()-ed by the master
  2160. * thread and queued for future handling by the worker thread. */
  2161. struct socket {
  2162. SOCKET sock; /* Listening socket */
  2163. union usa lsa; /* Local socket address */
  2164. union usa rsa; /* Remote socket address */
  2165. unsigned char is_ssl; /* Is port SSL-ed */
  2166. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2167. * port */
  2168. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2169. };
  2170. /* Enum const for all options must be in sync with
  2171. * static struct mg_option config_options[]
  2172. * This is tested in the unit test (test/private.c)
  2173. * "Private Config Options"
  2174. */
  2175. enum {
  2176. /* Once for each server */
  2177. LISTENING_PORTS,
  2178. NUM_THREADS,
  2179. RUN_AS_USER,
  2180. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2181. * socket option typedef TCP_NODELAY. */
  2182. MAX_REQUEST_SIZE,
  2183. LINGER_TIMEOUT,
  2184. CONNECTION_QUEUE_SIZE,
  2185. LISTEN_BACKLOG_SIZE,
  2186. #if defined(__linux__)
  2187. ALLOW_SENDFILE_CALL,
  2188. #endif
  2189. #if defined(_WIN32)
  2190. CASE_SENSITIVE_FILES,
  2191. #endif
  2192. THROTTLE,
  2193. ACCESS_LOG_FILE,
  2194. ERROR_LOG_FILE,
  2195. ENABLE_KEEP_ALIVE,
  2196. REQUEST_TIMEOUT,
  2197. KEEP_ALIVE_TIMEOUT,
  2198. #if defined(USE_WEBSOCKET)
  2199. WEBSOCKET_TIMEOUT,
  2200. ENABLE_WEBSOCKET_PING_PONG,
  2201. #endif
  2202. DECODE_URL,
  2203. #if defined(USE_LUA)
  2204. LUA_BACKGROUND_SCRIPT,
  2205. LUA_BACKGROUND_SCRIPT_PARAMS,
  2206. #endif
  2207. #if defined(USE_HTTP2)
  2208. ENABLE_HTTP2,
  2209. #endif
  2210. /* Once for each domain */
  2211. DOCUMENT_ROOT,
  2212. CGI_EXTENSIONS,
  2213. CGI2_EXTENSIONS,
  2214. CGI_ENVIRONMENT,
  2215. CGI2_ENVIRONMENT,
  2216. CGI_INTERPRETER,
  2217. CGI2_INTERPRETER,
  2218. CGI_INTERPRETER_ARGS,
  2219. CGI2_INTERPRETER_ARGS,
  2220. #if defined(USE_TIMERS)
  2221. CGI_TIMEOUT,
  2222. CGI2_TIMEOUT,
  2223. #endif
  2224. PUT_DELETE_PASSWORDS_FILE,
  2225. PROTECT_URI,
  2226. AUTHENTICATION_DOMAIN,
  2227. ENABLE_AUTH_DOMAIN_CHECK,
  2228. SSI_EXTENSIONS,
  2229. ENABLE_DIRECTORY_LISTING,
  2230. GLOBAL_PASSWORDS_FILE,
  2231. INDEX_FILES,
  2232. ACCESS_CONTROL_LIST,
  2233. EXTRA_MIME_TYPES,
  2234. SSL_CERTIFICATE,
  2235. SSL_CERTIFICATE_CHAIN,
  2236. URL_REWRITE_PATTERN,
  2237. HIDE_FILES,
  2238. SSL_DO_VERIFY_PEER,
  2239. SSL_CACHE_TIMEOUT,
  2240. SSL_CA_PATH,
  2241. SSL_CA_FILE,
  2242. SSL_VERIFY_DEPTH,
  2243. SSL_DEFAULT_VERIFY_PATHS,
  2244. SSL_CIPHER_LIST,
  2245. SSL_PROTOCOL_VERSION,
  2246. SSL_SHORT_TRUST,
  2247. #if defined(USE_LUA)
  2248. LUA_PRELOAD_FILE,
  2249. LUA_SCRIPT_EXTENSIONS,
  2250. LUA_SERVER_PAGE_EXTENSIONS,
  2251. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2252. LUA_DEBUG_PARAMS,
  2253. #endif
  2254. #endif
  2255. #if defined(USE_DUKTAPE)
  2256. DUKTAPE_SCRIPT_EXTENSIONS,
  2257. #endif
  2258. #if defined(USE_WEBSOCKET)
  2259. WEBSOCKET_ROOT,
  2260. #endif
  2261. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2262. LUA_WEBSOCKET_EXTENSIONS,
  2263. #endif
  2264. ACCESS_CONTROL_ALLOW_ORIGIN,
  2265. ACCESS_CONTROL_ALLOW_METHODS,
  2266. ACCESS_CONTROL_ALLOW_HEADERS,
  2267. ERROR_PAGES,
  2268. #if !defined(NO_CACHING)
  2269. STATIC_FILE_MAX_AGE,
  2270. STATIC_FILE_CACHE_CONTROL,
  2271. #endif
  2272. #if !defined(NO_SSL)
  2273. STRICT_HTTPS_MAX_AGE,
  2274. #endif
  2275. ADDITIONAL_HEADER,
  2276. ALLOW_INDEX_SCRIPT_SUB_RES,
  2277. #if defined(DAEMONIZE)
  2278. ENABLE_DAEMONIZE,
  2279. #endif
  2280. NUM_OPTIONS
  2281. };
  2282. /* Config option name, config types, default value.
  2283. * Must be in the same order as the enum const above.
  2284. */
  2285. static const struct mg_option config_options[] = {
  2286. /* Once for each server */
  2287. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2288. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2289. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2290. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2291. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2292. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2293. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2294. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2295. #if defined(__linux__)
  2296. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2297. #endif
  2298. #if defined(_WIN32)
  2299. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2300. #endif
  2301. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2302. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2303. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2304. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2305. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2306. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2307. #if defined(USE_WEBSOCKET)
  2308. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2309. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2310. #endif
  2311. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2312. #if defined(USE_LUA)
  2313. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2314. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2315. #endif
  2316. #if defined(USE_HTTP2)
  2317. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2318. #endif
  2319. /* Once for each domain */
  2320. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2321. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2322. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2323. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2324. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2325. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2326. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2327. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2328. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2329. #if defined(USE_TIMERS)
  2330. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2331. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2332. #endif
  2333. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2334. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2335. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2336. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2337. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2338. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2339. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2340. {"index_files",
  2341. MG_CONFIG_TYPE_STRING_LIST,
  2342. #if defined(USE_LUA)
  2343. "index.xhtml,index.html,index.htm,"
  2344. "index.lp,index.lsp,index.lua,index.cgi,"
  2345. "index.shtml,index.php"},
  2346. #else
  2347. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2348. #endif
  2349. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2350. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2351. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2352. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2353. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2354. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2355. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2356. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  2357. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2358. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2359. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2360. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2361. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2362. #if defined(USE_HTTP2)
  2363. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  2364. * as a minimum in 2020 */
  2365. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  2366. #else
  2367. /* Keep the default (compatibility) */
  2368. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2369. #endif /* defined(USE_HTTP2) */
  2370. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2371. #if defined(USE_LUA)
  2372. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2373. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2374. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2375. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2376. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2377. #endif
  2378. #endif
  2379. #if defined(USE_DUKTAPE)
  2380. /* The support for duktape is still in alpha version state.
  2381. * The name of this config option might change. */
  2382. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2383. #endif
  2384. #if defined(USE_WEBSOCKET)
  2385. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2386. #endif
  2387. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2388. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2389. #endif
  2390. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2391. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2392. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2393. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2394. #if !defined(NO_CACHING)
  2395. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2396. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2397. #endif
  2398. #if !defined(NO_SSL)
  2399. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2400. #endif
  2401. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2402. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2403. #if defined(DAEMONIZE)
  2404. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2405. #endif
  2406. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2407. /* Check if the config_options and the corresponding enum have compatible
  2408. * sizes. */
  2409. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2410. == (NUM_OPTIONS + 1),
  2411. "config_options and enum not sync");
  2412. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2413. struct mg_handler_info {
  2414. /* Name/Pattern of the URI. */
  2415. char *uri;
  2416. size_t uri_len;
  2417. /* handler type */
  2418. int handler_type;
  2419. /* Handler for http/https or authorization requests. */
  2420. mg_request_handler handler;
  2421. unsigned int refcount;
  2422. int removing;
  2423. /* Handler for ws/wss (websocket) requests. */
  2424. mg_websocket_connect_handler connect_handler;
  2425. mg_websocket_ready_handler ready_handler;
  2426. mg_websocket_data_handler data_handler;
  2427. mg_websocket_close_handler close_handler;
  2428. /* accepted subprotocols for ws/wss requests. */
  2429. struct mg_websocket_subprotocols *subprotocols;
  2430. /* Handler for authorization requests */
  2431. mg_authorization_handler auth_handler;
  2432. /* User supplied argument for the handler function. */
  2433. void *cbdata;
  2434. /* next handler in a linked list */
  2435. struct mg_handler_info *next;
  2436. };
  2437. enum {
  2438. CONTEXT_INVALID,
  2439. CONTEXT_SERVER,
  2440. CONTEXT_HTTP_CLIENT,
  2441. CONTEXT_WS_CLIENT
  2442. };
  2443. struct mg_domain_context {
  2444. SSL_CTX *ssl_ctx; /* SSL context */
  2445. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2446. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2447. int64_t ssl_cert_last_mtime;
  2448. /* Server nonce */
  2449. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2450. unsigned long nonce_count; /* Used nonces, used for authentication */
  2451. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2452. /* linked list of shared lua websockets */
  2453. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2454. #endif
  2455. /* Linked list of domains */
  2456. struct mg_domain_context *next;
  2457. };
  2458. /* Stop flag can be "volatile" or require a lock.
  2459. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  2460. * states a read operation for int is always atomic. */
  2461. #if defined(STOP_FLAG_NEEDS_LOCK)
  2462. typedef ptrdiff_t volatile stop_flag_t;
  2463. static int
  2464. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2465. {
  2466. stop_flag_t sf = mg_atomic_add(f, 0);
  2467. return (sf == 0);
  2468. }
  2469. static int
  2470. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2471. {
  2472. stop_flag_t sf = mg_atomic_add(f, 0);
  2473. return (sf == 2);
  2474. }
  2475. static void
  2476. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2477. {
  2478. stop_flag_t sf;
  2479. do {
  2480. sf = mg_atomic_compare_and_swap(f, *f, v);
  2481. } while (sf != v);
  2482. }
  2483. #else /* STOP_FLAG_NEEDS_LOCK */
  2484. typedef int volatile stop_flag_t;
  2485. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2486. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2487. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2488. #endif /* STOP_FLAG_NEEDS_LOCK */
  2489. struct mg_context {
  2490. /* Part 1 - Physical context:
  2491. * This holds threads, ports, timeouts, ...
  2492. * set for the entire server, independent from the
  2493. * addressed hostname.
  2494. */
  2495. /* Connection related */
  2496. int context_type; /* See CONTEXT_* above */
  2497. struct socket *listening_sockets;
  2498. struct mg_pollfd *listening_socket_fds;
  2499. unsigned int num_listening_sockets;
  2500. struct mg_connection *worker_connections; /* The connection struct, pre-
  2501. * allocated for each worker */
  2502. #if defined(USE_SERVER_STATS)
  2503. volatile ptrdiff_t active_connections;
  2504. volatile ptrdiff_t max_active_connections;
  2505. volatile ptrdiff_t total_connections;
  2506. volatile ptrdiff_t total_requests;
  2507. volatile int64_t total_data_read;
  2508. volatile int64_t total_data_written;
  2509. #endif
  2510. /* Thread related */
  2511. stop_flag_t stop_flag; /* Should we stop event loop */
  2512. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2513. pthread_t masterthreadid; /* The master thread ID */
  2514. unsigned int
  2515. cfg_worker_threads; /* The number of configured worker threads. */
  2516. pthread_t *worker_threadids; /* The worker thread IDs */
  2517. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2518. /* Connection to thread dispatching */
  2519. #if defined(ALTERNATIVE_QUEUE)
  2520. struct socket *client_socks;
  2521. void **client_wait_events;
  2522. #else
  2523. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2524. worker thread */
  2525. volatile int sq_head; /* Head of the socket queue */
  2526. volatile int sq_tail; /* Tail of the socket queue */
  2527. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2528. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2529. volatile int sq_blocked; /* Status information: sq is full */
  2530. int sq_size; /* No of elements in socket queue */
  2531. #if defined(USE_SERVER_STATS)
  2532. int sq_max_fill;
  2533. #endif /* USE_SERVER_STATS */
  2534. #endif /* ALTERNATIVE_QUEUE */
  2535. /* Memory related */
  2536. unsigned int max_request_size; /* The max request size */
  2537. #if defined(USE_SERVER_STATS)
  2538. struct mg_memory_stat ctx_memory;
  2539. #endif
  2540. /* Operating system related */
  2541. char *systemName; /* What operating system is running */
  2542. time_t start_time; /* Server start time, used for authentication
  2543. * and for diagnstics. */
  2544. #if defined(USE_TIMERS)
  2545. struct ttimers *timers;
  2546. #endif
  2547. /* Lua specific: Background operations and shared websockets */
  2548. #if defined(USE_LUA)
  2549. void *lua_background_state;
  2550. #endif
  2551. /* Server nonce */
  2552. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2553. * ssl_cert_last_mtime, nonce_count, and
  2554. * next (linked list) */
  2555. /* Server callbacks */
  2556. struct mg_callbacks callbacks; /* User-defined callback function */
  2557. void *user_data; /* User-defined data */
  2558. /* Part 2 - Logical domain:
  2559. * This holds hostname, TLS certificate, document root, ...
  2560. * set for a domain hosted at the server.
  2561. * There may be multiple domains hosted at one physical server.
  2562. * The default domain "dd" is the first element of a list of
  2563. * domains.
  2564. */
  2565. struct mg_domain_context dd; /* default domain */
  2566. };
  2567. #if defined(USE_SERVER_STATS)
  2568. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2569. static struct mg_memory_stat *
  2570. get_memory_stat(struct mg_context *ctx)
  2571. {
  2572. if (ctx) {
  2573. return &(ctx->ctx_memory);
  2574. }
  2575. return &mg_common_memory;
  2576. }
  2577. #endif
  2578. enum {
  2579. CONNECTION_TYPE_INVALID = 0,
  2580. CONNECTION_TYPE_REQUEST = 1,
  2581. CONNECTION_TYPE_RESPONSE = 2
  2582. };
  2583. enum {
  2584. PROTOCOL_TYPE_HTTP1 = 0,
  2585. PROTOCOL_TYPE_WEBSOCKET = 1,
  2586. PROTOCOL_TYPE_HTTP2 = 2
  2587. };
  2588. #if defined(USE_HTTP2)
  2589. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2590. #define HTTP2_DYN_TABLE_SIZE (256)
  2591. #endif
  2592. struct mg_http2_connection {
  2593. uint32_t stream_id;
  2594. uint32_t dyn_table_size;
  2595. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2596. };
  2597. #endif
  2598. struct mg_connection {
  2599. int connection_type; /* see CONNECTION_TYPE_* above */
  2600. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2601. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2602. fully sent */
  2603. #if defined(USE_HTTP2)
  2604. struct mg_http2_connection http2;
  2605. #endif
  2606. struct mg_request_info request_info;
  2607. struct mg_response_info response_info;
  2608. struct mg_context *phys_ctx;
  2609. struct mg_domain_context *dom_ctx;
  2610. #if defined(USE_SERVER_STATS)
  2611. int conn_state; /* 0 = undef, numerical value may change in different
  2612. * versions. For the current definition, see
  2613. * mg_get_connection_info_impl */
  2614. #endif
  2615. SSL *ssl; /* SSL descriptor */
  2616. struct socket client; /* Connected client */
  2617. time_t conn_birth_time; /* Time (wall clock) when connection was
  2618. * established */
  2619. #if defined(USE_SERVER_STATS)
  2620. time_t conn_close_time; /* Time (wall clock) when connection was
  2621. * closed (or 0 if still open) */
  2622. #endif
  2623. struct timespec req_time; /* Time (since system start) when the request
  2624. * was received */
  2625. int64_t num_bytes_sent; /* Total bytes sent to client */
  2626. int64_t content_len; /* How many bytes of content can be read
  2627. * !is_chunked: Content-Length header value
  2628. * or -1 (until connection closed,
  2629. * not allowed for a request)
  2630. * is_chunked: >= 0, appended gradually
  2631. */
  2632. int64_t consumed_content; /* How many bytes of content have been read */
  2633. int is_chunked; /* Transfer-Encoding is chunked:
  2634. * 0 = not chunked,
  2635. * 1 = chunked, not yet, or some data read,
  2636. * 2 = chunked, has error,
  2637. * 3 = chunked, all data read except trailer,
  2638. * 4 = chunked, all data read
  2639. */
  2640. char *buf; /* Buffer for received data */
  2641. char *path_info; /* PATH_INFO part of the URL */
  2642. int must_close; /* 1 if connection must be closed */
  2643. int accept_gzip; /* 1 if gzip encoding is accepted */
  2644. int in_error_handler; /* 1 if in handler for user defined error
  2645. * pages */
  2646. #if defined(USE_WEBSOCKET)
  2647. int in_websocket_handling; /* 1 if in read_websocket */
  2648. #endif
  2649. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2650. && defined(MG_EXPERIMENTAL_INTERFACES)
  2651. /* Parameters for websocket data compression according to rfc7692 */
  2652. int websocket_deflate_server_max_windows_bits;
  2653. int websocket_deflate_client_max_windows_bits;
  2654. int websocket_deflate_server_no_context_takeover;
  2655. int websocket_deflate_client_no_context_takeover;
  2656. int websocket_deflate_initialized;
  2657. int websocket_deflate_flush;
  2658. z_stream websocket_deflate_state;
  2659. z_stream websocket_inflate_state;
  2660. #endif
  2661. int handled_requests; /* Number of requests handled by this connection
  2662. */
  2663. int buf_size; /* Buffer size */
  2664. int request_len; /* Size of the request + headers in a buffer */
  2665. int data_len; /* Total size of data in a buffer */
  2666. int status_code; /* HTTP reply status code, e.g. 200 */
  2667. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2668. * throttle */
  2669. time_t last_throttle_time; /* Last time throttled data was sent */
  2670. int last_throttle_bytes; /* Bytes sent this second */
  2671. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2672. * atomic transmissions for websockets */
  2673. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2674. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2675. #endif
  2676. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2677. * for quick access */
  2678. };
  2679. /* Directory entry */
  2680. struct de {
  2681. struct mg_connection *conn;
  2682. char *file_name;
  2683. struct mg_file_stat file;
  2684. };
  2685. #define mg_cry_internal(conn, fmt, ...) \
  2686. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2687. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2688. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2689. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2690. struct mg_context *ctx,
  2691. const char *func,
  2692. unsigned line,
  2693. const char *fmt,
  2694. ...) PRINTF_ARGS(5, 6);
  2695. #if !defined(NO_THREAD_NAME)
  2696. #if defined(_WIN32) && defined(_MSC_VER)
  2697. /* Set the thread name for debugging purposes in Visual Studio
  2698. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2699. */
  2700. #pragma pack(push, 8)
  2701. typedef struct tagTHREADNAME_INFO {
  2702. DWORD dwType; /* Must be 0x1000. */
  2703. LPCSTR szName; /* Pointer to name (in user addr space). */
  2704. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2705. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2706. } THREADNAME_INFO;
  2707. #pragma pack(pop)
  2708. #elif defined(__linux__)
  2709. #include <sys/prctl.h>
  2710. #include <sys/sendfile.h>
  2711. #if defined(ALTERNATIVE_QUEUE)
  2712. #include <sys/eventfd.h>
  2713. #endif /* ALTERNATIVE_QUEUE */
  2714. #if defined(ALTERNATIVE_QUEUE)
  2715. static void *
  2716. event_create(void)
  2717. {
  2718. int evhdl = eventfd(0, EFD_CLOEXEC);
  2719. int *ret;
  2720. if (evhdl == -1) {
  2721. /* Linux uses -1 on error, Windows NULL. */
  2722. /* However, Linux does not return 0 on success either. */
  2723. return 0;
  2724. }
  2725. ret = (int *)mg_malloc(sizeof(int));
  2726. if (ret) {
  2727. *ret = evhdl;
  2728. } else {
  2729. (void)close(evhdl);
  2730. }
  2731. return (void *)ret;
  2732. }
  2733. static int
  2734. event_wait(void *eventhdl)
  2735. {
  2736. uint64_t u;
  2737. int evhdl, s;
  2738. if (!eventhdl) {
  2739. /* error */
  2740. return 0;
  2741. }
  2742. evhdl = *(int *)eventhdl;
  2743. s = (int)read(evhdl, &u, sizeof(u));
  2744. if (s != sizeof(u)) {
  2745. /* error */
  2746. return 0;
  2747. }
  2748. (void)u; /* the value is not required */
  2749. return 1;
  2750. }
  2751. static int
  2752. event_signal(void *eventhdl)
  2753. {
  2754. uint64_t u = 1;
  2755. int evhdl, s;
  2756. if (!eventhdl) {
  2757. /* error */
  2758. return 0;
  2759. }
  2760. evhdl = *(int *)eventhdl;
  2761. s = (int)write(evhdl, &u, sizeof(u));
  2762. if (s != sizeof(u)) {
  2763. /* error */
  2764. return 0;
  2765. }
  2766. return 1;
  2767. }
  2768. static void
  2769. event_destroy(void *eventhdl)
  2770. {
  2771. int evhdl;
  2772. if (!eventhdl) {
  2773. /* error */
  2774. return;
  2775. }
  2776. evhdl = *(int *)eventhdl;
  2777. close(evhdl);
  2778. mg_free(eventhdl);
  2779. }
  2780. #endif
  2781. #endif
  2782. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2783. struct posix_event {
  2784. pthread_mutex_t mutex;
  2785. pthread_cond_t cond;
  2786. int signaled;
  2787. };
  2788. static void *
  2789. event_create(void)
  2790. {
  2791. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2792. if (ret == 0) {
  2793. /* out of memory */
  2794. return 0;
  2795. }
  2796. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2797. /* pthread mutex not available */
  2798. mg_free(ret);
  2799. return 0;
  2800. }
  2801. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2802. /* pthread cond not available */
  2803. pthread_mutex_destroy(&(ret->mutex));
  2804. mg_free(ret);
  2805. return 0;
  2806. }
  2807. ret->signaled = 0;
  2808. return (void *)ret;
  2809. }
  2810. static int
  2811. event_wait(void *eventhdl)
  2812. {
  2813. struct posix_event *ev = (struct posix_event *)eventhdl;
  2814. pthread_mutex_lock(&(ev->mutex));
  2815. while (!ev->signaled) {
  2816. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2817. }
  2818. ev->signaled = 0;
  2819. pthread_mutex_unlock(&(ev->mutex));
  2820. return 1;
  2821. }
  2822. static int
  2823. event_signal(void *eventhdl)
  2824. {
  2825. struct posix_event *ev = (struct posix_event *)eventhdl;
  2826. pthread_mutex_lock(&(ev->mutex));
  2827. pthread_cond_signal(&(ev->cond));
  2828. ev->signaled = 1;
  2829. pthread_mutex_unlock(&(ev->mutex));
  2830. return 1;
  2831. }
  2832. static void
  2833. event_destroy(void *eventhdl)
  2834. {
  2835. struct posix_event *ev = (struct posix_event *)eventhdl;
  2836. pthread_cond_destroy(&(ev->cond));
  2837. pthread_mutex_destroy(&(ev->mutex));
  2838. mg_free(ev);
  2839. }
  2840. #endif
  2841. static void
  2842. mg_set_thread_name(const char *name)
  2843. {
  2844. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2845. mg_snprintf(
  2846. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2847. #if defined(_WIN32)
  2848. #if defined(_MSC_VER)
  2849. /* Windows and Visual Studio Compiler */
  2850. __try {
  2851. THREADNAME_INFO info;
  2852. info.dwType = 0x1000;
  2853. info.szName = threadName;
  2854. info.dwThreadID = ~0U;
  2855. info.dwFlags = 0;
  2856. RaiseException(0x406D1388,
  2857. 0,
  2858. sizeof(info) / sizeof(ULONG_PTR),
  2859. (ULONG_PTR *)&info);
  2860. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2861. }
  2862. #elif defined(__MINGW32__)
  2863. /* No option known to set thread name for MinGW known */
  2864. #endif
  2865. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2866. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2867. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2868. #if defined(__MACH__)
  2869. /* OS X only current thread name can be changed */
  2870. (void)pthread_setname_np(threadName);
  2871. #else
  2872. (void)pthread_setname_np(pthread_self(), threadName);
  2873. #endif
  2874. #elif defined(__linux__)
  2875. /* On Linux we can use the prctl function.
  2876. * When building for Linux Standard Base (LSB) use
  2877. * NO_THREAD_NAME. However, thread names are a big
  2878. * help for debugging, so the stadard is to set them.
  2879. */
  2880. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2881. #endif
  2882. }
  2883. #else /* !defined(NO_THREAD_NAME) */
  2884. void
  2885. mg_set_thread_name(const char *threadName)
  2886. {
  2887. }
  2888. #endif
  2889. const struct mg_option *
  2890. mg_get_valid_options(void)
  2891. {
  2892. return config_options;
  2893. }
  2894. /* Do not open file (unused) */
  2895. #define MG_FOPEN_MODE_NONE (0)
  2896. /* Open file for read only access */
  2897. #define MG_FOPEN_MODE_READ (1)
  2898. /* Open file for writing, create and overwrite */
  2899. #define MG_FOPEN_MODE_WRITE (2)
  2900. /* Open file for writing, create and append */
  2901. #define MG_FOPEN_MODE_APPEND (4)
  2902. static int
  2903. is_file_opened(const struct mg_file_access *fileacc)
  2904. {
  2905. if (!fileacc) {
  2906. return 0;
  2907. }
  2908. return (fileacc->fp != NULL);
  2909. }
  2910. #if !defined(NO_FILESYSTEMS)
  2911. static int mg_stat(const struct mg_connection *conn,
  2912. const char *path,
  2913. struct mg_file_stat *filep);
  2914. /* Reject files with special characters (for Windows) */
  2915. static int
  2916. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2917. {
  2918. const uint8_t *c = (const uint8_t *)path;
  2919. (void)conn; /* not used */
  2920. if ((c == NULL) || (c[0] == 0)) {
  2921. /* Null pointer or empty path --> suspicious */
  2922. return 1;
  2923. }
  2924. #if defined(_WIN32)
  2925. while (*c) {
  2926. if (*c <= 32) {
  2927. /* Control character or space */
  2928. return 1;
  2929. }
  2930. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2931. /* stdin/stdout redirection character */
  2932. return 1;
  2933. }
  2934. if (*c == '\\') {
  2935. /* Windows backslash */
  2936. return 1;
  2937. }
  2938. if (*c == ':') {
  2939. /* Windows drive letter */
  2940. return 1;
  2941. }
  2942. if ((*c == '*') || (*c == '?')) {
  2943. /* Wildcard character */
  2944. return 1;
  2945. }
  2946. if (*c == '"') {
  2947. /* Windows drive letter */
  2948. return 1;
  2949. }
  2950. c++;
  2951. }
  2952. #endif
  2953. /* Nothing suspicious found */
  2954. return 0;
  2955. }
  2956. /* mg_fopen will open a file either in memory or on the disk.
  2957. * The input parameter path is a string in UTF-8 encoding.
  2958. * The input parameter mode is MG_FOPEN_MODE_*
  2959. * On success, fp will be set in the output struct mg_file.
  2960. * All status members will also be set.
  2961. * The function returns 1 on success, 0 on error. */
  2962. static int
  2963. mg_fopen(const struct mg_connection *conn,
  2964. const char *path,
  2965. int mode,
  2966. struct mg_file *filep)
  2967. {
  2968. int found;
  2969. if (!filep) {
  2970. return 0;
  2971. }
  2972. filep->access.fp = NULL;
  2973. if (mg_path_suspicious(conn, path)) {
  2974. return 0;
  2975. }
  2976. /* filep is initialized in mg_stat: all fields with memset to,
  2977. * some fields like size and modification date with values */
  2978. found = mg_stat(conn, path, &(filep->stat));
  2979. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2980. /* file does not exist and will not be created */
  2981. return 0;
  2982. }
  2983. #if defined(_WIN32)
  2984. {
  2985. wchar_t wbuf[UTF16_PATH_MAX];
  2986. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2987. switch (mode) {
  2988. case MG_FOPEN_MODE_READ:
  2989. filep->access.fp = _wfopen(wbuf, L"rb");
  2990. break;
  2991. case MG_FOPEN_MODE_WRITE:
  2992. filep->access.fp = _wfopen(wbuf, L"wb");
  2993. break;
  2994. case MG_FOPEN_MODE_APPEND:
  2995. filep->access.fp = _wfopen(wbuf, L"ab");
  2996. break;
  2997. }
  2998. }
  2999. #else
  3000. /* Linux et al already use unicode. No need to convert. */
  3001. switch (mode) {
  3002. case MG_FOPEN_MODE_READ:
  3003. filep->access.fp = fopen(path, "r");
  3004. break;
  3005. case MG_FOPEN_MODE_WRITE:
  3006. filep->access.fp = fopen(path, "w");
  3007. break;
  3008. case MG_FOPEN_MODE_APPEND:
  3009. filep->access.fp = fopen(path, "a");
  3010. break;
  3011. }
  3012. #endif
  3013. if (!found) {
  3014. /* File did not exist before fopen was called.
  3015. * Maybe it has been created now. Get stat info
  3016. * like creation time now. */
  3017. found = mg_stat(conn, path, &(filep->stat));
  3018. (void)found;
  3019. }
  3020. /* return OK if file is opened */
  3021. return (filep->access.fp != NULL);
  3022. }
  3023. /* return 0 on success, just like fclose */
  3024. static int
  3025. mg_fclose(struct mg_file_access *fileacc)
  3026. {
  3027. int ret = -1;
  3028. if (fileacc != NULL) {
  3029. if (fileacc->fp != NULL) {
  3030. ret = fclose(fileacc->fp);
  3031. }
  3032. /* reset all members of fileacc */
  3033. memset(fileacc, 0, sizeof(*fileacc));
  3034. }
  3035. return ret;
  3036. }
  3037. #endif /* NO_FILESYSTEMS */
  3038. static void
  3039. mg_strlcpy(register char *dst, register const char *src, size_t n)
  3040. {
  3041. for (; *src != '\0' && n > 1; n--) {
  3042. *dst++ = *src++;
  3043. }
  3044. *dst = '\0';
  3045. }
  3046. static int
  3047. lowercase(const char *s)
  3048. {
  3049. return tolower((unsigned char)*s);
  3050. }
  3051. int
  3052. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  3053. {
  3054. int diff = 0;
  3055. if (len > 0) {
  3056. do {
  3057. diff = lowercase(s1++) - lowercase(s2++);
  3058. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  3059. }
  3060. return diff;
  3061. }
  3062. int
  3063. mg_strcasecmp(const char *s1, const char *s2)
  3064. {
  3065. int diff;
  3066. do {
  3067. diff = lowercase(s1++) - lowercase(s2++);
  3068. } while (diff == 0 && s1[-1] != '\0');
  3069. return diff;
  3070. }
  3071. static char *
  3072. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3073. {
  3074. char *p;
  3075. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3076. * defined */
  3077. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3078. mg_strlcpy(p, ptr, len + 1);
  3079. }
  3080. return p;
  3081. }
  3082. static char *
  3083. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3084. {
  3085. return mg_strndup_ctx(str, strlen(str), ctx);
  3086. }
  3087. static char *
  3088. mg_strdup(const char *str)
  3089. {
  3090. return mg_strndup_ctx(str, strlen(str), NULL);
  3091. }
  3092. static const char *
  3093. mg_strcasestr(const char *big_str, const char *small_str)
  3094. {
  3095. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3096. if (big_len >= small_len) {
  3097. for (i = 0; i <= (big_len - small_len); i++) {
  3098. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3099. return big_str + i;
  3100. }
  3101. }
  3102. }
  3103. return NULL;
  3104. }
  3105. /* Return null terminated string of given maximum length.
  3106. * Report errors if length is exceeded. */
  3107. static void
  3108. mg_vsnprintf(const struct mg_connection *conn,
  3109. int *truncated,
  3110. char *buf,
  3111. size_t buflen,
  3112. const char *fmt,
  3113. va_list ap)
  3114. {
  3115. int n, ok;
  3116. if (buflen == 0) {
  3117. if (truncated) {
  3118. *truncated = 1;
  3119. }
  3120. return;
  3121. }
  3122. #if defined(__clang__)
  3123. #pragma clang diagnostic push
  3124. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3125. /* Using fmt as a non-literal is intended here, since it is mostly called
  3126. * indirectly by mg_snprintf */
  3127. #endif
  3128. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3129. ok = (n >= 0) && ((size_t)n < buflen);
  3130. #if defined(__clang__)
  3131. #pragma clang diagnostic pop
  3132. #endif
  3133. if (ok) {
  3134. if (truncated) {
  3135. *truncated = 0;
  3136. }
  3137. } else {
  3138. if (truncated) {
  3139. *truncated = 1;
  3140. }
  3141. mg_cry_internal(conn,
  3142. "truncating vsnprintf buffer: [%.*s]",
  3143. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3144. buf);
  3145. n = (int)buflen - 1;
  3146. }
  3147. buf[n] = '\0';
  3148. }
  3149. static void
  3150. mg_snprintf(const struct mg_connection *conn,
  3151. int *truncated,
  3152. char *buf,
  3153. size_t buflen,
  3154. const char *fmt,
  3155. ...)
  3156. {
  3157. va_list ap;
  3158. va_start(ap, fmt);
  3159. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3160. va_end(ap);
  3161. }
  3162. static int
  3163. get_option_index(const char *name)
  3164. {
  3165. int i;
  3166. for (i = 0; config_options[i].name != NULL; i++) {
  3167. if (strcmp(config_options[i].name, name) == 0) {
  3168. return i;
  3169. }
  3170. }
  3171. return -1;
  3172. }
  3173. const char *
  3174. mg_get_option(const struct mg_context *ctx, const char *name)
  3175. {
  3176. int i;
  3177. if ((i = get_option_index(name)) == -1) {
  3178. return NULL;
  3179. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3180. return "";
  3181. } else {
  3182. return ctx->dd.config[i];
  3183. }
  3184. }
  3185. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3186. struct mg_context *
  3187. mg_get_context(const struct mg_connection *conn)
  3188. {
  3189. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3190. }
  3191. void *
  3192. mg_get_user_data(const struct mg_context *ctx)
  3193. {
  3194. return (ctx == NULL) ? NULL : ctx->user_data;
  3195. }
  3196. void *
  3197. mg_get_user_context_data(const struct mg_connection *conn)
  3198. {
  3199. return mg_get_user_data(mg_get_context(conn));
  3200. }
  3201. void *
  3202. mg_get_thread_pointer(const struct mg_connection *conn)
  3203. {
  3204. /* both methods should return the same pointer */
  3205. if (conn) {
  3206. /* quick access, in case conn is known */
  3207. return conn->tls_user_ptr;
  3208. } else {
  3209. /* otherwise get pointer from thread local storage (TLS) */
  3210. struct mg_workerTLS *tls =
  3211. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3212. return tls->user_ptr;
  3213. }
  3214. }
  3215. void
  3216. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  3217. {
  3218. if (const_conn != NULL) {
  3219. /* Const cast, since "const struct mg_connection *" does not mean
  3220. * the connection object is not modified. Here "const" is used,
  3221. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  3222. struct mg_connection *conn = (struct mg_connection *)const_conn;
  3223. conn->request_info.conn_data = data;
  3224. }
  3225. }
  3226. void *
  3227. mg_get_user_connection_data(const struct mg_connection *conn)
  3228. {
  3229. if (conn != NULL) {
  3230. return conn->request_info.conn_data;
  3231. }
  3232. return NULL;
  3233. }
  3234. #if defined(MG_LEGACY_INTERFACE)
  3235. /* Deprecated: Use mg_get_server_ports instead. */
  3236. size_t
  3237. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3238. {
  3239. size_t i;
  3240. if (!ctx) {
  3241. return 0;
  3242. }
  3243. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3244. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3245. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3246. }
  3247. return i;
  3248. }
  3249. #endif
  3250. int
  3251. mg_get_server_ports(const struct mg_context *ctx,
  3252. int size,
  3253. struct mg_server_port *ports)
  3254. {
  3255. int i, cnt = 0;
  3256. if (size <= 0) {
  3257. return -1;
  3258. }
  3259. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3260. if (!ctx) {
  3261. return -1;
  3262. }
  3263. if (!ctx->listening_sockets) {
  3264. return -1;
  3265. }
  3266. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3267. ports[cnt].port =
  3268. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3269. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3270. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3271. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3272. /* IPv4 */
  3273. ports[cnt].protocol = 1;
  3274. cnt++;
  3275. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3276. /* IPv6 */
  3277. ports[cnt].protocol = 3;
  3278. cnt++;
  3279. }
  3280. }
  3281. return cnt;
  3282. }
  3283. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  3284. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  3285. #endif
  3286. static void
  3287. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3288. {
  3289. buf[0] = '\0';
  3290. if (!usa) {
  3291. return;
  3292. }
  3293. if (usa->sa.sa_family == AF_INET) {
  3294. getnameinfo(&usa->sa,
  3295. sizeof(usa->sin),
  3296. buf,
  3297. (unsigned)len,
  3298. NULL,
  3299. 0,
  3300. NI_NUMERICHOST);
  3301. }
  3302. #if defined(USE_IPV6)
  3303. else if (usa->sa.sa_family == AF_INET6) {
  3304. getnameinfo(&usa->sa,
  3305. sizeof(usa->sin6),
  3306. buf,
  3307. (unsigned)len,
  3308. NULL,
  3309. 0,
  3310. NI_NUMERICHOST);
  3311. }
  3312. #endif
  3313. #if defined(USE_X_DOM_SOCKET)
  3314. else if (usa->sa.sa_family == AF_UNIX) {
  3315. /* TODO: Define a remote address for unix domain sockets.
  3316. * This code will always return "localhost", identical to http+tcp:
  3317. getnameinfo(&usa->sa,
  3318. sizeof(usa->sun),
  3319. buf,
  3320. (unsigned)len,
  3321. NULL,
  3322. 0,
  3323. NI_NUMERICHOST);
  3324. */
  3325. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  3326. buf[len] = 0;
  3327. }
  3328. #endif
  3329. }
  3330. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3331. * included in all responses other than 100, 101, 5xx. */
  3332. static void
  3333. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3334. {
  3335. #if !defined(REENTRANT_TIME)
  3336. struct tm *tm;
  3337. tm = ((t != NULL) ? gmtime(t) : NULL);
  3338. if (tm != NULL) {
  3339. #else
  3340. struct tm _tm;
  3341. struct tm *tm = &_tm;
  3342. if (t != NULL) {
  3343. gmtime_r(t, tm);
  3344. #endif
  3345. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3346. } else {
  3347. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3348. buf[buf_len - 1] = '\0';
  3349. }
  3350. }
  3351. /* difftime for struct timespec. Return value is in seconds. */
  3352. static double
  3353. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3354. {
  3355. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3356. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3357. }
  3358. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3359. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3360. const char *func,
  3361. unsigned line,
  3362. const char *fmt,
  3363. va_list ap);
  3364. #include "external_mg_cry_internal_impl.inl"
  3365. #elif !defined(NO_FILESYSTEMS)
  3366. /* Print error message to the opened error log stream. */
  3367. static void
  3368. mg_cry_internal_impl(const struct mg_connection *conn,
  3369. const char *func,
  3370. unsigned line,
  3371. const char *fmt,
  3372. va_list ap)
  3373. {
  3374. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3375. struct mg_file fi;
  3376. time_t timestamp;
  3377. /* Unused, in the RELEASE build */
  3378. (void)func;
  3379. (void)line;
  3380. #if defined(GCC_DIAGNOSTIC)
  3381. #pragma GCC diagnostic push
  3382. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3383. #endif
  3384. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3385. #if defined(GCC_DIAGNOSTIC)
  3386. #pragma GCC diagnostic pop
  3387. #endif
  3388. buf[sizeof(buf) - 1] = 0;
  3389. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3390. if (!conn) {
  3391. puts(buf);
  3392. return;
  3393. }
  3394. /* Do not lock when getting the callback value, here and below.
  3395. * I suppose this is fine, since function cannot disappear in the
  3396. * same way string option can. */
  3397. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3398. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3399. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3400. if (mg_fopen(conn,
  3401. conn->dom_ctx->config[ERROR_LOG_FILE],
  3402. MG_FOPEN_MODE_APPEND,
  3403. &fi)
  3404. == 0) {
  3405. fi.access.fp = NULL;
  3406. }
  3407. } else {
  3408. fi.access.fp = NULL;
  3409. }
  3410. if (fi.access.fp != NULL) {
  3411. flockfile(fi.access.fp);
  3412. timestamp = time(NULL);
  3413. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3414. fprintf(fi.access.fp,
  3415. "[%010lu] [error] [client %s] ",
  3416. (unsigned long)timestamp,
  3417. src_addr);
  3418. if (conn->request_info.request_method != NULL) {
  3419. fprintf(fi.access.fp,
  3420. "%s %s: ",
  3421. conn->request_info.request_method,
  3422. conn->request_info.request_uri
  3423. ? conn->request_info.request_uri
  3424. : "");
  3425. }
  3426. fprintf(fi.access.fp, "%s", buf);
  3427. fputc('\n', fi.access.fp);
  3428. fflush(fi.access.fp);
  3429. funlockfile(fi.access.fp);
  3430. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3431. * mg_cry here anyway ;-) */
  3432. }
  3433. }
  3434. }
  3435. #else
  3436. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3437. #endif /* Externally provided function */
  3438. /* Construct fake connection structure. Used for logging, if connection
  3439. * is not applicable at the moment of logging. */
  3440. static struct mg_connection *
  3441. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3442. {
  3443. static const struct mg_connection conn_zero = {0};
  3444. *fc = conn_zero;
  3445. fc->phys_ctx = ctx;
  3446. fc->dom_ctx = &(ctx->dd);
  3447. return fc;
  3448. }
  3449. static void
  3450. mg_cry_internal_wrap(const struct mg_connection *conn,
  3451. struct mg_context *ctx,
  3452. const char *func,
  3453. unsigned line,
  3454. const char *fmt,
  3455. ...)
  3456. {
  3457. va_list ap;
  3458. va_start(ap, fmt);
  3459. if (!conn && ctx) {
  3460. struct mg_connection fc;
  3461. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3462. } else {
  3463. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3464. }
  3465. va_end(ap);
  3466. }
  3467. void
  3468. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3469. {
  3470. va_list ap;
  3471. va_start(ap, fmt);
  3472. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3473. va_end(ap);
  3474. }
  3475. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3476. const char *
  3477. mg_version(void)
  3478. {
  3479. return CIVETWEB_VERSION;
  3480. }
  3481. const struct mg_request_info *
  3482. mg_get_request_info(const struct mg_connection *conn)
  3483. {
  3484. if (!conn) {
  3485. return NULL;
  3486. }
  3487. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3488. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3489. char txt[16];
  3490. struct mg_workerTLS *tls =
  3491. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3492. sprintf(txt, "%03i", conn->response_info.status_code);
  3493. if (strlen(txt) == 3) {
  3494. memcpy(tls->txtbuf, txt, 4);
  3495. } else {
  3496. strcpy(tls->txtbuf, "ERR");
  3497. }
  3498. ((struct mg_connection *)conn)->request_info.local_uri =
  3499. ((struct mg_connection *)conn)->request_info.request_uri =
  3500. tls->txtbuf; /* use thread safe buffer */
  3501. ((struct mg_connection *)conn)->request_info.num_headers =
  3502. conn->response_info.num_headers;
  3503. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3504. conn->response_info.http_headers,
  3505. sizeof(conn->response_info.http_headers));
  3506. } else
  3507. #endif
  3508. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3509. return NULL;
  3510. }
  3511. return &conn->request_info;
  3512. }
  3513. const struct mg_response_info *
  3514. mg_get_response_info(const struct mg_connection *conn)
  3515. {
  3516. if (!conn) {
  3517. return NULL;
  3518. }
  3519. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3520. return NULL;
  3521. }
  3522. return &conn->response_info;
  3523. }
  3524. static const char *
  3525. get_proto_name(const struct mg_connection *conn)
  3526. {
  3527. #if defined(__clang__)
  3528. #pragma clang diagnostic push
  3529. #pragma clang diagnostic ignored "-Wunreachable-code"
  3530. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3531. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3532. * unreachable, but splitting into four different #ifdef clauses here is more
  3533. * complicated.
  3534. */
  3535. #endif
  3536. const struct mg_request_info *ri = &conn->request_info;
  3537. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3538. ? (ri->is_ssl ? "wss" : "ws")
  3539. : (ri->is_ssl ? "https" : "http"));
  3540. return proto;
  3541. #if defined(__clang__)
  3542. #pragma clang diagnostic pop
  3543. #endif
  3544. }
  3545. static int
  3546. mg_construct_local_link(const struct mg_connection *conn,
  3547. char *buf,
  3548. size_t buflen,
  3549. const char *define_proto,
  3550. int define_port,
  3551. const char *define_uri)
  3552. {
  3553. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3554. return -1;
  3555. } else {
  3556. int truncated = 0;
  3557. const struct mg_request_info *ri = &conn->request_info;
  3558. const char *proto =
  3559. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3560. const char *uri =
  3561. (define_uri != NULL)
  3562. ? define_uri
  3563. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3564. int port = (define_port > 0) ? define_port : ri->server_port;
  3565. int default_port = 80;
  3566. if (uri == NULL) {
  3567. return -1;
  3568. }
  3569. #if defined(USE_X_DOM_SOCKET)
  3570. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3571. /* TODO: Define and document a link for UNIX domain sockets. */
  3572. /* There seems to be no official standard for this.
  3573. * Common uses seem to be "httpunix://", "http.unix://" or
  3574. * "http+unix://" as a protocol definition string, followed by
  3575. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3576. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3577. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3578. * "" (completely skipping the server name part). In any case, the
  3579. * last part is the server local path. */
  3580. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3581. mg_snprintf(conn,
  3582. &truncated,
  3583. buf,
  3584. buflen,
  3585. "%s.unix://%s%s",
  3586. proto,
  3587. server_name,
  3588. ri->local_uri);
  3589. default_port = 0;
  3590. return 0;
  3591. }
  3592. #endif
  3593. if (define_proto) {
  3594. /* If we got a protocol name, use the default port accordingly. */
  3595. if ((0 == strcmp(define_proto, "https"))
  3596. || (0 == strcmp(define_proto, "wss"))) {
  3597. default_port = 443;
  3598. }
  3599. } else if (ri->is_ssl) {
  3600. /* If we did not get a protocol name, use TLS as default if it is
  3601. * already used. */
  3602. default_port = 443;
  3603. }
  3604. {
  3605. #if defined(USE_IPV6)
  3606. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3607. #endif
  3608. int auth_domain_check_enabled =
  3609. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3610. && (!mg_strcasecmp(
  3611. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3612. const char *server_domain =
  3613. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3614. char portstr[16];
  3615. char server_ip[48];
  3616. if (port != default_port) {
  3617. sprintf(portstr, ":%u", (unsigned)port);
  3618. } else {
  3619. portstr[0] = 0;
  3620. }
  3621. if (!auth_domain_check_enabled || !server_domain) {
  3622. sockaddr_to_string(server_ip,
  3623. sizeof(server_ip),
  3624. &conn->client.lsa);
  3625. server_domain = server_ip;
  3626. }
  3627. mg_snprintf(conn,
  3628. &truncated,
  3629. buf,
  3630. buflen,
  3631. #if defined(USE_IPV6)
  3632. "%s://%s%s%s%s%s",
  3633. proto,
  3634. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3635. server_domain,
  3636. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3637. #else
  3638. "%s://%s%s%s",
  3639. proto,
  3640. server_domain,
  3641. #endif
  3642. portstr,
  3643. ri->local_uri);
  3644. if (truncated) {
  3645. return -1;
  3646. }
  3647. return 0;
  3648. }
  3649. }
  3650. }
  3651. int
  3652. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3653. {
  3654. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3655. }
  3656. /* Skip the characters until one of the delimiters characters found.
  3657. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3658. * Advance pointer to buffer to the next word. Return found 0-terminated
  3659. * word.
  3660. * Delimiters can be quoted with quotechar. */
  3661. static char *
  3662. skip_quoted(char **buf,
  3663. const char *delimiters,
  3664. const char *whitespace,
  3665. char quotechar)
  3666. {
  3667. char *p, *begin_word, *end_word, *end_whitespace;
  3668. begin_word = *buf;
  3669. end_word = begin_word + strcspn(begin_word, delimiters);
  3670. /* Check for quotechar */
  3671. if (end_word > begin_word) {
  3672. p = end_word - 1;
  3673. while (*p == quotechar) {
  3674. /* While the delimiter is quoted, look for the next delimiter.
  3675. */
  3676. /* This happens, e.g., in calls from parse_auth_header,
  3677. * if the user name contains a " character. */
  3678. /* If there is anything beyond end_word, copy it. */
  3679. if (*end_word != '\0') {
  3680. size_t end_off = strcspn(end_word + 1, delimiters);
  3681. memmove(p, end_word, end_off + 1);
  3682. p += end_off; /* p must correspond to end_word - 1 */
  3683. end_word += end_off + 1;
  3684. } else {
  3685. *p = '\0';
  3686. break;
  3687. }
  3688. }
  3689. for (p++; p < end_word; p++) {
  3690. *p = '\0';
  3691. }
  3692. }
  3693. if (*end_word == '\0') {
  3694. *buf = end_word;
  3695. } else {
  3696. #if defined(GCC_DIAGNOSTIC)
  3697. /* Disable spurious conversion warning for GCC */
  3698. #pragma GCC diagnostic push
  3699. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3700. #endif /* defined(GCC_DIAGNOSTIC) */
  3701. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3702. #if defined(GCC_DIAGNOSTIC)
  3703. #pragma GCC diagnostic pop
  3704. #endif /* defined(GCC_DIAGNOSTIC) */
  3705. for (p = end_word; p < end_whitespace; p++) {
  3706. *p = '\0';
  3707. }
  3708. *buf = end_whitespace;
  3709. }
  3710. return begin_word;
  3711. }
  3712. /* Return HTTP header value, or NULL if not found. */
  3713. static const char *
  3714. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3715. {
  3716. int i;
  3717. for (i = 0; i < num_hdr; i++) {
  3718. if (!mg_strcasecmp(name, hdr[i].name)) {
  3719. return hdr[i].value;
  3720. }
  3721. }
  3722. return NULL;
  3723. }
  3724. #if defined(USE_WEBSOCKET)
  3725. /* Retrieve requested HTTP header multiple values, and return the number of
  3726. * found occurrences */
  3727. static int
  3728. get_req_headers(const struct mg_request_info *ri,
  3729. const char *name,
  3730. const char **output,
  3731. int output_max_size)
  3732. {
  3733. int i;
  3734. int cnt = 0;
  3735. if (ri) {
  3736. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3737. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3738. output[cnt++] = ri->http_headers[i].value;
  3739. }
  3740. }
  3741. }
  3742. return cnt;
  3743. }
  3744. #endif
  3745. const char *
  3746. mg_get_header(const struct mg_connection *conn, const char *name)
  3747. {
  3748. if (!conn) {
  3749. return NULL;
  3750. }
  3751. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3752. return get_header(conn->request_info.http_headers,
  3753. conn->request_info.num_headers,
  3754. name);
  3755. }
  3756. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3757. return get_header(conn->response_info.http_headers,
  3758. conn->response_info.num_headers,
  3759. name);
  3760. }
  3761. return NULL;
  3762. }
  3763. static const char *
  3764. get_http_version(const struct mg_connection *conn)
  3765. {
  3766. if (!conn) {
  3767. return NULL;
  3768. }
  3769. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3770. return conn->request_info.http_version;
  3771. }
  3772. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3773. return conn->response_info.http_version;
  3774. }
  3775. return NULL;
  3776. }
  3777. /* A helper function for traversing a comma separated list of values.
  3778. * It returns a list pointer shifted to the next value, or NULL if the end
  3779. * of the list found.
  3780. * Value is stored in val vector. If value has form "x=y", then eq_val
  3781. * vector is initialized to point to the "y" part, and val vector length
  3782. * is adjusted to point only to "x". */
  3783. static const char *
  3784. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3785. {
  3786. int end;
  3787. reparse:
  3788. if (val == NULL || list == NULL || *list == '\0') {
  3789. /* End of the list */
  3790. return NULL;
  3791. }
  3792. /* Skip over leading LWS */
  3793. while (*list == ' ' || *list == '\t')
  3794. list++;
  3795. val->ptr = list;
  3796. if ((list = strchr(val->ptr, ',')) != NULL) {
  3797. /* Comma found. Store length and shift the list ptr */
  3798. val->len = ((size_t)(list - val->ptr));
  3799. list++;
  3800. } else {
  3801. /* This value is the last one */
  3802. list = val->ptr + strlen(val->ptr);
  3803. val->len = ((size_t)(list - val->ptr));
  3804. }
  3805. /* Adjust length for trailing LWS */
  3806. end = (int)val->len - 1;
  3807. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3808. end--;
  3809. val->len = (size_t)(end) + (size_t)(1);
  3810. if (val->len == 0) {
  3811. /* Ignore any empty entries. */
  3812. goto reparse;
  3813. }
  3814. if (eq_val != NULL) {
  3815. /* Value has form "x=y", adjust pointers and lengths
  3816. * so that val points to "x", and eq_val points to "y". */
  3817. eq_val->len = 0;
  3818. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3819. if (eq_val->ptr != NULL) {
  3820. eq_val->ptr++; /* Skip over '=' character */
  3821. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3822. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3823. }
  3824. }
  3825. return list;
  3826. }
  3827. /* A helper function for checking if a comma separated list of values
  3828. * contains
  3829. * the given option (case insensitvely).
  3830. * 'header' can be NULL, in which case false is returned. */
  3831. static int
  3832. header_has_option(const char *header, const char *option)
  3833. {
  3834. struct vec opt_vec;
  3835. struct vec eq_vec;
  3836. DEBUG_ASSERT(option != NULL);
  3837. DEBUG_ASSERT(option[0] != '\0');
  3838. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3839. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3840. return 1;
  3841. }
  3842. return 0;
  3843. }
  3844. /* Perform case-insensitive match of string against pattern */
  3845. static ptrdiff_t
  3846. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3847. {
  3848. const char *or_str;
  3849. ptrdiff_t i, j, len, res;
  3850. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3851. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3852. return (res > 0) ? res
  3853. : match_prefix(or_str + 1,
  3854. (size_t)((pattern + pattern_len)
  3855. - (or_str + 1)),
  3856. str);
  3857. }
  3858. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3859. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3860. continue;
  3861. } else if (pattern[i] == '$') {
  3862. return (str[j] == '\0') ? j : -1;
  3863. } else if (pattern[i] == '*') {
  3864. i++;
  3865. if (pattern[i] == '*') {
  3866. i++;
  3867. len = (ptrdiff_t)strlen(str + j);
  3868. } else {
  3869. len = (ptrdiff_t)strcspn(str + j, "/");
  3870. }
  3871. if (i == (ptrdiff_t)pattern_len) {
  3872. return j + len;
  3873. }
  3874. do {
  3875. res = match_prefix(pattern + i,
  3876. (pattern_len - (size_t)i),
  3877. str + j + len);
  3878. } while (res == -1 && len-- > 0);
  3879. return (res == -1) ? -1 : j + res + len;
  3880. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3881. return -1;
  3882. }
  3883. }
  3884. return (ptrdiff_t)j;
  3885. }
  3886. static ptrdiff_t
  3887. match_prefix_strlen(const char *pattern, const char *str)
  3888. {
  3889. if (pattern == NULL) {
  3890. return -1;
  3891. }
  3892. return match_prefix(pattern, strlen(pattern), str);
  3893. }
  3894. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3895. * This function must tolerate situations when connection info is not
  3896. * set up, for example if request parsing failed. */
  3897. static int
  3898. should_keep_alive(const struct mg_connection *conn)
  3899. {
  3900. const char *http_version;
  3901. const char *header;
  3902. /* First satisfy needs of the server */
  3903. if ((conn == NULL) || conn->must_close) {
  3904. /* Close, if civetweb framework needs to close */
  3905. return 0;
  3906. }
  3907. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3908. /* Close, if keep alive is not enabled */
  3909. return 0;
  3910. }
  3911. /* Check explicit wish of the client */
  3912. header = mg_get_header(conn, "Connection");
  3913. if (header) {
  3914. /* If there is a connection header from the client, obey */
  3915. if (header_has_option(header, "keep-alive")) {
  3916. return 1;
  3917. }
  3918. return 0;
  3919. }
  3920. /* Use default of the standard */
  3921. http_version = get_http_version(conn);
  3922. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3923. /* HTTP 1.1 default is keep alive */
  3924. return 1;
  3925. }
  3926. /* HTTP 1.0 (and earlier) default is to close the connection */
  3927. return 0;
  3928. }
  3929. static int
  3930. should_decode_url(const struct mg_connection *conn)
  3931. {
  3932. if (!conn || !conn->dom_ctx) {
  3933. return 0;
  3934. }
  3935. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3936. }
  3937. static const char *
  3938. suggest_connection_header(const struct mg_connection *conn)
  3939. {
  3940. return should_keep_alive(conn) ? "keep-alive" : "close";
  3941. }
  3942. #include "response.inl"
  3943. static void
  3944. send_no_cache_header(struct mg_connection *conn)
  3945. {
  3946. /* Send all current and obsolete cache opt-out directives. */
  3947. mg_response_header_add(conn,
  3948. "Cache-Control",
  3949. "no-cache, no-store, "
  3950. "must-revalidate, private, max-age=0",
  3951. -1);
  3952. mg_response_header_add(conn, "Expires", "0", -1);
  3953. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3954. /* Obsolete, but still send it for HTTP/1.0 */
  3955. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3956. }
  3957. }
  3958. static void
  3959. send_static_cache_header(struct mg_connection *conn)
  3960. {
  3961. #if !defined(NO_CACHING)
  3962. int max_age;
  3963. char val[64];
  3964. const char *cache_control =
  3965. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3966. /* If there is a full cache-control option configured,0 use it */
  3967. if (cache_control != NULL) {
  3968. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3969. return;
  3970. }
  3971. /* Read the server config to check how long a file may be cached.
  3972. * The configuration is in seconds. */
  3973. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3974. if (max_age <= 0) {
  3975. /* 0 means "do not cache". All values <0 are reserved
  3976. * and may be used differently in the future. */
  3977. /* If a file should not be cached, do not only send
  3978. * max-age=0, but also pragmas and Expires headers. */
  3979. send_no_cache_header(conn);
  3980. return;
  3981. }
  3982. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3983. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3984. /* See also https://www.mnot.net/cache_docs/ */
  3985. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3986. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3987. * leap
  3988. * year to 31622400 seconds. For the moment, we just send whatever has
  3989. * been configured, still the behavior for >1 year should be considered
  3990. * as undefined. */
  3991. mg_snprintf(
  3992. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3993. mg_response_header_add(conn, "Cache-Control", val, -1);
  3994. #else /* NO_CACHING */
  3995. send_no_cache_header(conn);
  3996. #endif /* !NO_CACHING */
  3997. }
  3998. static void
  3999. send_additional_header(struct mg_connection *conn)
  4000. {
  4001. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  4002. #if !defined(NO_SSL)
  4003. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  4004. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  4005. if (max_age >= 0) {
  4006. char val[64];
  4007. mg_snprintf(conn,
  4008. NULL,
  4009. val,
  4010. sizeof(val),
  4011. "max-age=%lu",
  4012. (unsigned long)max_age);
  4013. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  4014. }
  4015. }
  4016. #endif
  4017. if (header && header[0]) {
  4018. mg_response_header_add_lines(conn, header);
  4019. }
  4020. }
  4021. #if !defined(NO_FILESYSTEMS)
  4022. static void handle_file_based_request(struct mg_connection *conn,
  4023. const char *path,
  4024. struct mg_file *filep);
  4025. #endif /* NO_FILESYSTEMS */
  4026. const char *
  4027. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  4028. {
  4029. /* See IANA HTTP status code assignment:
  4030. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  4031. */
  4032. switch (response_code) {
  4033. /* RFC2616 Section 10.1 - Informational 1xx */
  4034. case 100:
  4035. return "Continue"; /* RFC2616 Section 10.1.1 */
  4036. case 101:
  4037. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  4038. case 102:
  4039. return "Processing"; /* RFC2518 Section 10.1 */
  4040. /* RFC2616 Section 10.2 - Successful 2xx */
  4041. case 200:
  4042. return "OK"; /* RFC2616 Section 10.2.1 */
  4043. case 201:
  4044. return "Created"; /* RFC2616 Section 10.2.2 */
  4045. case 202:
  4046. return "Accepted"; /* RFC2616 Section 10.2.3 */
  4047. case 203:
  4048. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  4049. case 204:
  4050. return "No Content"; /* RFC2616 Section 10.2.5 */
  4051. case 205:
  4052. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  4053. case 206:
  4054. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  4055. case 207:
  4056. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  4057. */
  4058. case 208:
  4059. return "Already Reported"; /* RFC5842 Section 7.1 */
  4060. case 226:
  4061. return "IM used"; /* RFC3229 Section 10.4.1 */
  4062. /* RFC2616 Section 10.3 - Redirection 3xx */
  4063. case 300:
  4064. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  4065. case 301:
  4066. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  4067. case 302:
  4068. return "Found"; /* RFC2616 Section 10.3.3 */
  4069. case 303:
  4070. return "See Other"; /* RFC2616 Section 10.3.4 */
  4071. case 304:
  4072. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  4073. case 305:
  4074. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  4075. case 307:
  4076. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  4077. case 308:
  4078. return "Permanent Redirect"; /* RFC7238 Section 3 */
  4079. /* RFC2616 Section 10.4 - Client Error 4xx */
  4080. case 400:
  4081. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  4082. case 401:
  4083. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  4084. case 402:
  4085. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  4086. case 403:
  4087. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  4088. case 404:
  4089. return "Not Found"; /* RFC2616 Section 10.4.5 */
  4090. case 405:
  4091. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  4092. case 406:
  4093. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  4094. case 407:
  4095. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  4096. case 408:
  4097. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  4098. case 409:
  4099. return "Conflict"; /* RFC2616 Section 10.4.10 */
  4100. case 410:
  4101. return "Gone"; /* RFC2616 Section 10.4.11 */
  4102. case 411:
  4103. return "Length Required"; /* RFC2616 Section 10.4.12 */
  4104. case 412:
  4105. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  4106. case 413:
  4107. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  4108. case 414:
  4109. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  4110. case 415:
  4111. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  4112. case 416:
  4113. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  4114. */
  4115. case 417:
  4116. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  4117. case 421:
  4118. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  4119. case 422:
  4120. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  4121. * Section 11.2 */
  4122. case 423:
  4123. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  4124. case 424:
  4125. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  4126. * Section 11.4 */
  4127. case 426:
  4128. return "Upgrade Required"; /* RFC 2817 Section 4 */
  4129. case 428:
  4130. return "Precondition Required"; /* RFC 6585, Section 3 */
  4131. case 429:
  4132. return "Too Many Requests"; /* RFC 6585, Section 4 */
  4133. case 431:
  4134. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  4135. case 451:
  4136. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  4137. * Section 3 */
  4138. /* RFC2616 Section 10.5 - Server Error 5xx */
  4139. case 500:
  4140. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  4141. case 501:
  4142. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  4143. case 502:
  4144. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4145. case 503:
  4146. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4147. case 504:
  4148. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4149. case 505:
  4150. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4151. case 506:
  4152. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4153. case 507:
  4154. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4155. * Section 11.5 */
  4156. case 508:
  4157. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4158. case 510:
  4159. return "Not Extended"; /* RFC 2774, Section 7 */
  4160. case 511:
  4161. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4162. /* Other status codes, not shown in the IANA HTTP status code
  4163. * assignment.
  4164. * E.g., "de facto" standards due to common use, ... */
  4165. case 418:
  4166. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4167. case 419:
  4168. return "Authentication Timeout"; /* common use */
  4169. case 420:
  4170. return "Enhance Your Calm"; /* common use */
  4171. case 440:
  4172. return "Login Timeout"; /* common use */
  4173. case 509:
  4174. return "Bandwidth Limit Exceeded"; /* common use */
  4175. default:
  4176. /* This error code is unknown. This should not happen. */
  4177. if (conn) {
  4178. mg_cry_internal(conn,
  4179. "Unknown HTTP response code: %u",
  4180. response_code);
  4181. }
  4182. /* Return at least a category according to RFC 2616 Section 10. */
  4183. if (response_code >= 100 && response_code < 200) {
  4184. /* Unknown informational status code */
  4185. return "Information";
  4186. }
  4187. if (response_code >= 200 && response_code < 300) {
  4188. /* Unknown success code */
  4189. return "Success";
  4190. }
  4191. if (response_code >= 300 && response_code < 400) {
  4192. /* Unknown redirection code */
  4193. return "Redirection";
  4194. }
  4195. if (response_code >= 400 && response_code < 500) {
  4196. /* Unknown request error code */
  4197. return "Client Error";
  4198. }
  4199. if (response_code >= 500 && response_code < 600) {
  4200. /* Unknown server error code */
  4201. return "Server Error";
  4202. }
  4203. /* Response code not even within reasonable range */
  4204. return "";
  4205. }
  4206. }
  4207. static int
  4208. mg_send_http_error_impl(struct mg_connection *conn,
  4209. int status,
  4210. const char *fmt,
  4211. va_list args)
  4212. {
  4213. char errmsg_buf[MG_BUF_LEN];
  4214. va_list ap;
  4215. int has_body;
  4216. #if !defined(NO_FILESYSTEMS)
  4217. char path_buf[UTF8_PATH_MAX];
  4218. int len, i, page_handler_found, scope, truncated;
  4219. const char *error_handler = NULL;
  4220. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4221. const char *error_page_file_ext, *tstr;
  4222. #endif /* NO_FILESYSTEMS */
  4223. int handled_by_callback = 0;
  4224. if ((conn == NULL) || (fmt == NULL)) {
  4225. return -2;
  4226. }
  4227. /* Set status (for log) */
  4228. conn->status_code = status;
  4229. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4230. has_body = ((status > 199) && (status != 204) && (status != 304));
  4231. /* Prepare message in buf, if required */
  4232. if (has_body
  4233. || (!conn->in_error_handler
  4234. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4235. /* Store error message in errmsg_buf */
  4236. va_copy(ap, args);
  4237. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4238. va_end(ap);
  4239. /* In a debug build, print all html errors */
  4240. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4241. }
  4242. /* If there is a http_error callback, call it.
  4243. * But don't do it recursively, if callback calls mg_send_http_error again.
  4244. */
  4245. if (!conn->in_error_handler
  4246. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4247. /* Mark in_error_handler to avoid recursion and call user callback. */
  4248. conn->in_error_handler = 1;
  4249. handled_by_callback =
  4250. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4251. == 0);
  4252. conn->in_error_handler = 0;
  4253. }
  4254. if (!handled_by_callback) {
  4255. /* Check for recursion */
  4256. if (conn->in_error_handler) {
  4257. DEBUG_TRACE(
  4258. "Recursion when handling error %u - fall back to default",
  4259. status);
  4260. #if !defined(NO_FILESYSTEMS)
  4261. } else {
  4262. /* Send user defined error pages, if defined */
  4263. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4264. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4265. page_handler_found = 0;
  4266. if (error_handler != NULL) {
  4267. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4268. switch (scope) {
  4269. case 1: /* Handler for specific error, e.g. 404 error */
  4270. mg_snprintf(conn,
  4271. &truncated,
  4272. path_buf,
  4273. sizeof(path_buf) - 32,
  4274. "%serror%03u.",
  4275. error_handler,
  4276. status);
  4277. break;
  4278. case 2: /* Handler for error group, e.g., 5xx error
  4279. * handler
  4280. * for all server errors (500-599) */
  4281. mg_snprintf(conn,
  4282. &truncated,
  4283. path_buf,
  4284. sizeof(path_buf) - 32,
  4285. "%serror%01uxx.",
  4286. error_handler,
  4287. status / 100);
  4288. break;
  4289. default: /* Handler for all errors */
  4290. mg_snprintf(conn,
  4291. &truncated,
  4292. path_buf,
  4293. sizeof(path_buf) - 32,
  4294. "%serror.",
  4295. error_handler);
  4296. break;
  4297. }
  4298. /* String truncation in buf may only occur if
  4299. * error_handler is too long. This string is
  4300. * from the config, not from a client. */
  4301. (void)truncated;
  4302. /* The following code is redundant, but it should avoid
  4303. * false positives in static source code analyzers and
  4304. * vulnerability scanners.
  4305. */
  4306. path_buf[sizeof(path_buf) - 32] = 0;
  4307. len = (int)strlen(path_buf);
  4308. if (len > (int)sizeof(path_buf) - 32) {
  4309. len = (int)sizeof(path_buf) - 32;
  4310. }
  4311. /* Start with the file extenstion from the configuration. */
  4312. tstr = strchr(error_page_file_ext, '.');
  4313. while (tstr) {
  4314. for (i = 1;
  4315. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4316. i++) {
  4317. /* buffer overrun is not possible here, since
  4318. * (i < 32) && (len < sizeof(path_buf) - 32)
  4319. * ==> (i + len) < sizeof(path_buf) */
  4320. path_buf[len + i - 1] = tstr[i];
  4321. }
  4322. /* buffer overrun is not possible here, since
  4323. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4324. * ==> (i + len) <= sizeof(path_buf) */
  4325. path_buf[len + i - 1] = 0;
  4326. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4327. DEBUG_TRACE("Check error page %s - found",
  4328. path_buf);
  4329. page_handler_found = 1;
  4330. break;
  4331. }
  4332. DEBUG_TRACE("Check error page %s - not found",
  4333. path_buf);
  4334. /* Continue with the next file extenstion from the
  4335. * configuration (if there is a next one). */
  4336. tstr = strchr(tstr + i, '.');
  4337. }
  4338. }
  4339. }
  4340. if (page_handler_found) {
  4341. conn->in_error_handler = 1;
  4342. handle_file_based_request(conn, path_buf, &error_page_file);
  4343. conn->in_error_handler = 0;
  4344. return 0;
  4345. }
  4346. #endif /* NO_FILESYSTEMS */
  4347. }
  4348. /* No custom error page. Send default error page. */
  4349. conn->must_close = 1;
  4350. mg_response_header_start(conn, status);
  4351. send_no_cache_header(conn);
  4352. send_additional_header(conn);
  4353. if (has_body) {
  4354. mg_response_header_add(conn,
  4355. "Content-Type",
  4356. "text/plain; charset=utf-8",
  4357. -1);
  4358. }
  4359. mg_response_header_send(conn);
  4360. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4361. if (has_body) {
  4362. /* For other errors, send a generic error message. */
  4363. const char *status_text = mg_get_response_code_text(conn, status);
  4364. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4365. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4366. } else {
  4367. /* No body allowed. Close the connection. */
  4368. DEBUG_TRACE("Error %i", status);
  4369. }
  4370. }
  4371. return 0;
  4372. }
  4373. int
  4374. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4375. {
  4376. va_list ap;
  4377. int ret;
  4378. va_start(ap, fmt);
  4379. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4380. va_end(ap);
  4381. return ret;
  4382. }
  4383. int
  4384. mg_send_http_ok(struct mg_connection *conn,
  4385. const char *mime_type,
  4386. long long content_length)
  4387. {
  4388. if ((mime_type == NULL) || (*mime_type == 0)) {
  4389. /* No content type defined: default to text/html */
  4390. mime_type = "text/html";
  4391. }
  4392. mg_response_header_start(conn, 200);
  4393. send_no_cache_header(conn);
  4394. send_additional_header(conn);
  4395. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  4396. if (content_length < 0) {
  4397. /* Size not known. Use chunked encoding (HTTP/1.x) */
  4398. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  4399. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  4400. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  4401. }
  4402. } else {
  4403. char len[32];
  4404. int trunc = 0;
  4405. mg_snprintf(conn,
  4406. &trunc,
  4407. len,
  4408. sizeof(len),
  4409. "%" UINT64_FMT,
  4410. (uint64_t)content_length);
  4411. if (!trunc) {
  4412. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  4413. * !trunc is always true */
  4414. mg_response_header_add(conn, "Content-Length", len, -1);
  4415. }
  4416. }
  4417. mg_response_header_send(conn);
  4418. return 0;
  4419. }
  4420. int
  4421. mg_send_http_redirect(struct mg_connection *conn,
  4422. const char *target_url,
  4423. int redirect_code)
  4424. {
  4425. /* Send a 30x redirect response.
  4426. *
  4427. * Redirect types (status codes):
  4428. *
  4429. * Status | Perm/Temp | Method | Version
  4430. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4431. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4432. * 303 | temporary | always use GET | HTTP/1.1
  4433. * 307 | temporary | always keep method | HTTP/1.1
  4434. * 308 | permanent | always keep method | HTTP/1.1
  4435. */
  4436. const char *redirect_text;
  4437. int ret;
  4438. size_t content_len = 0;
  4439. #if defined(MG_SEND_REDIRECT_BODY)
  4440. char reply[MG_BUF_LEN];
  4441. #endif
  4442. /* In case redirect_code=0, use 307. */
  4443. if (redirect_code == 0) {
  4444. redirect_code = 307;
  4445. }
  4446. /* In case redirect_code is none of the above, return error. */
  4447. if ((redirect_code != 301) && (redirect_code != 302)
  4448. && (redirect_code != 303) && (redirect_code != 307)
  4449. && (redirect_code != 308)) {
  4450. /* Parameter error */
  4451. return -2;
  4452. }
  4453. /* Get proper text for response code */
  4454. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4455. /* If target_url is not defined, redirect to "/". */
  4456. if ((target_url == NULL) || (*target_url == 0)) {
  4457. target_url = "/";
  4458. }
  4459. #if defined(MG_SEND_REDIRECT_BODY)
  4460. /* TODO: condition name? */
  4461. /* Prepare a response body with a hyperlink.
  4462. *
  4463. * According to RFC2616 (and RFC1945 before):
  4464. * Unless the request method was HEAD, the entity of the
  4465. * response SHOULD contain a short hypertext note with a hyperlink to
  4466. * the new URI(s).
  4467. *
  4468. * However, this response body is not useful in M2M communication.
  4469. * Probably the original reason in the RFC was, clients not supporting
  4470. * a 30x HTTP redirect could still show the HTML page and let the user
  4471. * press the link. Since current browsers support 30x HTTP, the additional
  4472. * HTML body does not seem to make sense anymore.
  4473. *
  4474. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4475. * but it only notes:
  4476. * The server's response payload usually contains a short
  4477. * hypertext note with a hyperlink to the new URI(s).
  4478. *
  4479. * Deactivated by default. If you need the 30x body, set the define.
  4480. */
  4481. mg_snprintf(
  4482. conn,
  4483. NULL /* ignore truncation */,
  4484. reply,
  4485. sizeof(reply),
  4486. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4487. redirect_text,
  4488. target_url,
  4489. target_url);
  4490. content_len = strlen(reply);
  4491. #endif
  4492. /* Do not send any additional header. For all other options,
  4493. * including caching, there are suitable defaults. */
  4494. ret = mg_printf(conn,
  4495. "HTTP/1.1 %i %s\r\n"
  4496. "Location: %s\r\n"
  4497. "Content-Length: %u\r\n"
  4498. "Connection: %s\r\n\r\n",
  4499. redirect_code,
  4500. redirect_text,
  4501. target_url,
  4502. (unsigned int)content_len,
  4503. suggest_connection_header(conn));
  4504. #if defined(MG_SEND_REDIRECT_BODY)
  4505. /* Send response body */
  4506. if (ret > 0) {
  4507. /* ... unless it is a HEAD request */
  4508. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4509. ret = mg_write(conn, reply, content_len);
  4510. }
  4511. }
  4512. #endif
  4513. return (ret > 0) ? ret : -1;
  4514. }
  4515. #if defined(_WIN32)
  4516. /* Create substitutes for POSIX functions in Win32. */
  4517. #if defined(GCC_DIAGNOSTIC)
  4518. /* Show no warning in case system functions are not used. */
  4519. #pragma GCC diagnostic push
  4520. #pragma GCC diagnostic ignored "-Wunused-function"
  4521. #endif
  4522. static int
  4523. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4524. {
  4525. (void)unused;
  4526. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4527. InitializeCriticalSection(&mutex->sec);
  4528. return 0;
  4529. }
  4530. static int
  4531. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4532. {
  4533. DeleteCriticalSection(&mutex->sec);
  4534. return 0;
  4535. }
  4536. static int
  4537. pthread_mutex_lock(pthread_mutex_t *mutex)
  4538. {
  4539. EnterCriticalSection(&mutex->sec);
  4540. return 0;
  4541. }
  4542. static int
  4543. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4544. {
  4545. LeaveCriticalSection(&mutex->sec);
  4546. return 0;
  4547. }
  4548. FUNCTION_MAY_BE_UNUSED
  4549. static int
  4550. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4551. {
  4552. (void)unused;
  4553. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4554. cv->waiting_thread = NULL;
  4555. return 0;
  4556. }
  4557. FUNCTION_MAY_BE_UNUSED
  4558. static int
  4559. pthread_cond_timedwait(pthread_cond_t *cv,
  4560. pthread_mutex_t *mutex,
  4561. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4562. {
  4563. struct mg_workerTLS **ptls,
  4564. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4565. int ok;
  4566. uint64_t nsnow, nswaitabs;
  4567. int64_t nswaitrel;
  4568. DWORD mswaitrel;
  4569. pthread_mutex_lock(&cv->threadIdSec);
  4570. /* Add this thread to cv's waiting list */
  4571. ptls = &cv->waiting_thread;
  4572. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4573. ;
  4574. tls->next_waiting_thread = NULL;
  4575. *ptls = tls;
  4576. pthread_mutex_unlock(&cv->threadIdSec);
  4577. if (abstime) {
  4578. nsnow = mg_get_current_time_ns();
  4579. nswaitabs =
  4580. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4581. nswaitrel = nswaitabs - nsnow;
  4582. if (nswaitrel < 0) {
  4583. nswaitrel = 0;
  4584. }
  4585. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4586. } else {
  4587. mswaitrel = (DWORD)INFINITE;
  4588. }
  4589. pthread_mutex_unlock(mutex);
  4590. ok = (WAIT_OBJECT_0
  4591. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4592. if (!ok) {
  4593. ok = 1;
  4594. pthread_mutex_lock(&cv->threadIdSec);
  4595. ptls = &cv->waiting_thread;
  4596. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4597. if (*ptls == tls) {
  4598. *ptls = tls->next_waiting_thread;
  4599. ok = 0;
  4600. break;
  4601. }
  4602. }
  4603. pthread_mutex_unlock(&cv->threadIdSec);
  4604. if (ok) {
  4605. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4606. (DWORD)INFINITE);
  4607. }
  4608. }
  4609. /* This thread has been removed from cv's waiting list */
  4610. pthread_mutex_lock(mutex);
  4611. return ok ? 0 : -1;
  4612. }
  4613. FUNCTION_MAY_BE_UNUSED
  4614. static int
  4615. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4616. {
  4617. return pthread_cond_timedwait(cv, mutex, NULL);
  4618. }
  4619. FUNCTION_MAY_BE_UNUSED
  4620. static int
  4621. pthread_cond_signal(pthread_cond_t *cv)
  4622. {
  4623. HANDLE wkup = NULL;
  4624. BOOL ok = FALSE;
  4625. pthread_mutex_lock(&cv->threadIdSec);
  4626. if (cv->waiting_thread) {
  4627. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4628. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4629. ok = SetEvent(wkup);
  4630. DEBUG_ASSERT(ok);
  4631. }
  4632. pthread_mutex_unlock(&cv->threadIdSec);
  4633. return ok ? 0 : 1;
  4634. }
  4635. FUNCTION_MAY_BE_UNUSED
  4636. static int
  4637. pthread_cond_broadcast(pthread_cond_t *cv)
  4638. {
  4639. pthread_mutex_lock(&cv->threadIdSec);
  4640. while (cv->waiting_thread) {
  4641. pthread_cond_signal(cv);
  4642. }
  4643. pthread_mutex_unlock(&cv->threadIdSec);
  4644. return 0;
  4645. }
  4646. FUNCTION_MAY_BE_UNUSED
  4647. static int
  4648. pthread_cond_destroy(pthread_cond_t *cv)
  4649. {
  4650. pthread_mutex_lock(&cv->threadIdSec);
  4651. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4652. pthread_mutex_unlock(&cv->threadIdSec);
  4653. pthread_mutex_destroy(&cv->threadIdSec);
  4654. return 0;
  4655. }
  4656. #if defined(ALTERNATIVE_QUEUE)
  4657. FUNCTION_MAY_BE_UNUSED
  4658. static void *
  4659. event_create(void)
  4660. {
  4661. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4662. }
  4663. FUNCTION_MAY_BE_UNUSED
  4664. static int
  4665. event_wait(void *eventhdl)
  4666. {
  4667. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4668. return (res == WAIT_OBJECT_0);
  4669. }
  4670. FUNCTION_MAY_BE_UNUSED
  4671. static int
  4672. event_signal(void *eventhdl)
  4673. {
  4674. return (int)SetEvent((HANDLE)eventhdl);
  4675. }
  4676. FUNCTION_MAY_BE_UNUSED
  4677. static void
  4678. event_destroy(void *eventhdl)
  4679. {
  4680. CloseHandle((HANDLE)eventhdl);
  4681. }
  4682. #endif
  4683. #if defined(GCC_DIAGNOSTIC)
  4684. /* Enable unused function warning again */
  4685. #pragma GCC diagnostic pop
  4686. #endif
  4687. /* For Windows, change all slashes to backslashes in path names. */
  4688. static void
  4689. change_slashes_to_backslashes(char *path)
  4690. {
  4691. int i;
  4692. for (i = 0; path[i] != '\0'; i++) {
  4693. if (path[i] == '/') {
  4694. path[i] = '\\';
  4695. }
  4696. /* remove double backslash (check i > 0 to preserve UNC paths,
  4697. * like \\server\file.txt) */
  4698. if ((i > 0) && (path[i] == '\\')) {
  4699. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4700. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4701. }
  4702. }
  4703. }
  4704. }
  4705. static int
  4706. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4707. {
  4708. int diff;
  4709. do {
  4710. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4711. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4712. s1++;
  4713. s2++;
  4714. } while ((diff == 0) && (s1[-1] != L'\0'));
  4715. return diff;
  4716. }
  4717. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4718. * wbuf and wbuf_len is a target buffer and its length. */
  4719. static void
  4720. path_to_unicode(const struct mg_connection *conn,
  4721. const char *path,
  4722. wchar_t *wbuf,
  4723. size_t wbuf_len)
  4724. {
  4725. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4726. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4727. DWORD long_len, err;
  4728. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4729. mg_strlcpy(buf, path, sizeof(buf));
  4730. change_slashes_to_backslashes(buf);
  4731. /* Convert to Unicode and back. If doubly-converted string does not
  4732. * match the original, something is fishy, reject. */
  4733. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4734. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4735. WideCharToMultiByte(
  4736. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4737. if (strcmp(buf, buf2) != 0) {
  4738. wbuf[0] = L'\0';
  4739. }
  4740. /* Windows file systems are not case sensitive, but you can still use
  4741. * uppercase and lowercase letters (on all modern file systems).
  4742. * The server can check if the URI uses the same upper/lowercase
  4743. * letters an the file system, effectively making Windows servers
  4744. * case sensitive (like Linux servers are). It is still not possible
  4745. * to use two files with the same name in different cases on Windows
  4746. * (like /a and /A) - this would be possible in Linux.
  4747. * As a default, Windows is not case sensitive, but the case sensitive
  4748. * file name check can be activated by an additional configuration. */
  4749. if (conn) {
  4750. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4751. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4752. "yes")) {
  4753. /* Use case sensitive compare function */
  4754. fcompare = wcscmp;
  4755. }
  4756. }
  4757. (void)conn; /* conn is currently unused */
  4758. #if !defined(_WIN32_WCE)
  4759. /* Only accept a full file path, not a Windows short (8.3) path. */
  4760. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4761. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4762. if (long_len == 0) {
  4763. err = GetLastError();
  4764. if (err == ERROR_FILE_NOT_FOUND) {
  4765. /* File does not exist. This is not always a problem here. */
  4766. return;
  4767. }
  4768. }
  4769. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4770. /* Short name is used. */
  4771. wbuf[0] = L'\0';
  4772. }
  4773. #else
  4774. (void)long_len;
  4775. (void)wbuf2;
  4776. (void)err;
  4777. if (strchr(path, '~')) {
  4778. wbuf[0] = L'\0';
  4779. }
  4780. #endif
  4781. }
  4782. #if !defined(NO_FILESYSTEMS)
  4783. /* Get file information, return 1 if file exists, 0 if not */
  4784. static int
  4785. mg_stat(const struct mg_connection *conn,
  4786. const char *path,
  4787. struct mg_file_stat *filep)
  4788. {
  4789. wchar_t wbuf[UTF16_PATH_MAX];
  4790. WIN32_FILE_ATTRIBUTE_DATA info;
  4791. time_t creation_time;
  4792. size_t len;
  4793. if (!filep) {
  4794. return 0;
  4795. }
  4796. memset(filep, 0, sizeof(*filep));
  4797. if (mg_path_suspicious(conn, path)) {
  4798. return 0;
  4799. }
  4800. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4801. /* Windows happily opens files with some garbage at the end of file name.
  4802. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4803. * "a.cgi", despite one would expect an error back. */
  4804. len = strlen(path);
  4805. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4806. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4807. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4808. filep->last_modified =
  4809. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4810. info.ftLastWriteTime.dwHighDateTime);
  4811. /* On Windows, the file creation time can be higher than the
  4812. * modification time, e.g. when a file is copied.
  4813. * Since the Last-Modified timestamp is used for caching
  4814. * it should be based on the most recent timestamp. */
  4815. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4816. info.ftCreationTime.dwHighDateTime);
  4817. if (creation_time > filep->last_modified) {
  4818. filep->last_modified = creation_time;
  4819. }
  4820. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4821. return 1;
  4822. }
  4823. return 0;
  4824. }
  4825. #endif
  4826. static int
  4827. mg_remove(const struct mg_connection *conn, const char *path)
  4828. {
  4829. wchar_t wbuf[UTF16_PATH_MAX];
  4830. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4831. return DeleteFileW(wbuf) ? 0 : -1;
  4832. }
  4833. static int
  4834. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4835. {
  4836. wchar_t wbuf[UTF16_PATH_MAX];
  4837. (void)mode;
  4838. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4839. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4840. }
  4841. /* Create substitutes for POSIX functions in Win32. */
  4842. #if defined(GCC_DIAGNOSTIC)
  4843. /* Show no warning in case system functions are not used. */
  4844. #pragma GCC diagnostic push
  4845. #pragma GCC diagnostic ignored "-Wunused-function"
  4846. #endif
  4847. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4848. FUNCTION_MAY_BE_UNUSED
  4849. static DIR *
  4850. mg_opendir(const struct mg_connection *conn, const char *name)
  4851. {
  4852. DIR *dir = NULL;
  4853. wchar_t wpath[UTF16_PATH_MAX];
  4854. DWORD attrs;
  4855. if (name == NULL) {
  4856. SetLastError(ERROR_BAD_ARGUMENTS);
  4857. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4858. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4859. } else {
  4860. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4861. attrs = GetFileAttributesW(wpath);
  4862. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4863. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4864. (void)wcscat(wpath, L"\\*");
  4865. dir->handle = FindFirstFileW(wpath, &dir->info);
  4866. dir->result.d_name[0] = '\0';
  4867. } else {
  4868. mg_free(dir);
  4869. dir = NULL;
  4870. }
  4871. }
  4872. return dir;
  4873. }
  4874. FUNCTION_MAY_BE_UNUSED
  4875. static int
  4876. mg_closedir(DIR *dir)
  4877. {
  4878. int result = 0;
  4879. if (dir != NULL) {
  4880. if (dir->handle != INVALID_HANDLE_VALUE)
  4881. result = FindClose(dir->handle) ? 0 : -1;
  4882. mg_free(dir);
  4883. } else {
  4884. result = -1;
  4885. SetLastError(ERROR_BAD_ARGUMENTS);
  4886. }
  4887. return result;
  4888. }
  4889. FUNCTION_MAY_BE_UNUSED
  4890. static struct dirent *
  4891. mg_readdir(DIR *dir)
  4892. {
  4893. struct dirent *result = 0;
  4894. if (dir) {
  4895. if (dir->handle != INVALID_HANDLE_VALUE) {
  4896. result = &dir->result;
  4897. (void)WideCharToMultiByte(CP_UTF8,
  4898. 0,
  4899. dir->info.cFileName,
  4900. -1,
  4901. result->d_name,
  4902. sizeof(result->d_name),
  4903. NULL,
  4904. NULL);
  4905. if (!FindNextFileW(dir->handle, &dir->info)) {
  4906. (void)FindClose(dir->handle);
  4907. dir->handle = INVALID_HANDLE_VALUE;
  4908. }
  4909. } else {
  4910. SetLastError(ERROR_FILE_NOT_FOUND);
  4911. }
  4912. } else {
  4913. SetLastError(ERROR_BAD_ARGUMENTS);
  4914. }
  4915. return result;
  4916. }
  4917. #if !defined(HAVE_POLL)
  4918. #undef POLLIN
  4919. #undef POLLPRI
  4920. #undef POLLOUT
  4921. #define POLLIN (1) /* Data ready - read will not block. */
  4922. #define POLLPRI (2) /* Priority data ready. */
  4923. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4924. FUNCTION_MAY_BE_UNUSED
  4925. static int
  4926. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4927. {
  4928. struct timeval tv;
  4929. fd_set rset;
  4930. fd_set wset;
  4931. unsigned int i;
  4932. int result;
  4933. SOCKET maxfd = 0;
  4934. memset(&tv, 0, sizeof(tv));
  4935. tv.tv_sec = milliseconds / 1000;
  4936. tv.tv_usec = (milliseconds % 1000) * 1000;
  4937. FD_ZERO(&rset);
  4938. FD_ZERO(&wset);
  4939. for (i = 0; i < n; i++) {
  4940. if (pfd[i].events & POLLIN) {
  4941. FD_SET(pfd[i].fd, &rset);
  4942. }
  4943. if (pfd[i].events & POLLOUT) {
  4944. FD_SET(pfd[i].fd, &wset);
  4945. }
  4946. pfd[i].revents = 0;
  4947. if (pfd[i].fd > maxfd) {
  4948. maxfd = pfd[i].fd;
  4949. }
  4950. }
  4951. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4952. for (i = 0; i < n; i++) {
  4953. if (FD_ISSET(pfd[i].fd, &rset)) {
  4954. pfd[i].revents |= POLLIN;
  4955. }
  4956. if (FD_ISSET(pfd[i].fd, &wset)) {
  4957. pfd[i].revents |= POLLOUT;
  4958. }
  4959. }
  4960. }
  4961. /* We should subtract the time used in select from remaining
  4962. * "milliseconds", in particular if called from mg_poll with a
  4963. * timeout quantum.
  4964. * Unfortunately, the remaining time is not stored in "tv" in all
  4965. * implementations, so the result in "tv" must be considered undefined.
  4966. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4967. return result;
  4968. }
  4969. #endif /* HAVE_POLL */
  4970. #if defined(GCC_DIAGNOSTIC)
  4971. /* Enable unused function warning again */
  4972. #pragma GCC diagnostic pop
  4973. #endif
  4974. static void
  4975. set_close_on_exec(SOCKET sock,
  4976. const struct mg_connection *conn /* may be null */,
  4977. struct mg_context *ctx /* may be null */)
  4978. {
  4979. (void)conn; /* Unused. */
  4980. (void)ctx;
  4981. #if defined(_WIN32_WCE)
  4982. (void)sock;
  4983. #else
  4984. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4985. #endif
  4986. }
  4987. int
  4988. mg_start_thread(mg_thread_func_t f, void *p)
  4989. {
  4990. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4991. /* Compile-time option to control stack size, e.g.
  4992. * -DUSE_STACK_SIZE=16384
  4993. */
  4994. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4995. == ((uintptr_t)(-1L)))
  4996. ? -1
  4997. : 0);
  4998. #else
  4999. return (
  5000. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  5001. ? -1
  5002. : 0);
  5003. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5004. }
  5005. /* Start a thread storing the thread context. */
  5006. static int
  5007. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  5008. void *p,
  5009. pthread_t *threadidptr)
  5010. {
  5011. uintptr_t uip;
  5012. HANDLE threadhandle;
  5013. int result = -1;
  5014. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  5015. threadhandle = (HANDLE)uip;
  5016. if ((uip != 0) && (threadidptr != NULL)) {
  5017. *threadidptr = threadhandle;
  5018. result = 0;
  5019. }
  5020. return result;
  5021. }
  5022. /* Wait for a thread to finish. */
  5023. static int
  5024. mg_join_thread(pthread_t threadid)
  5025. {
  5026. int result;
  5027. DWORD dwevent;
  5028. result = -1;
  5029. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  5030. if (dwevent == WAIT_FAILED) {
  5031. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  5032. } else {
  5033. if (dwevent == WAIT_OBJECT_0) {
  5034. CloseHandle(threadid);
  5035. result = 0;
  5036. }
  5037. }
  5038. return result;
  5039. }
  5040. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  5041. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  5042. /* Create substitutes for POSIX functions in Win32. */
  5043. #if defined(GCC_DIAGNOSTIC)
  5044. /* Show no warning in case system functions are not used. */
  5045. #pragma GCC diagnostic push
  5046. #pragma GCC diagnostic ignored "-Wunused-function"
  5047. #endif
  5048. FUNCTION_MAY_BE_UNUSED
  5049. static HANDLE
  5050. dlopen(const char *dll_name, int flags)
  5051. {
  5052. wchar_t wbuf[UTF16_PATH_MAX];
  5053. (void)flags;
  5054. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  5055. return LoadLibraryW(wbuf);
  5056. }
  5057. FUNCTION_MAY_BE_UNUSED
  5058. static int
  5059. dlclose(void *handle)
  5060. {
  5061. int result;
  5062. if (FreeLibrary((HMODULE)handle) != 0) {
  5063. result = 0;
  5064. } else {
  5065. result = -1;
  5066. }
  5067. return result;
  5068. }
  5069. #if defined(GCC_DIAGNOSTIC)
  5070. /* Enable unused function warning again */
  5071. #pragma GCC diagnostic pop
  5072. #endif
  5073. #endif
  5074. #if !defined(NO_CGI)
  5075. #define SIGKILL (0)
  5076. static int
  5077. kill(pid_t pid, int sig_num)
  5078. {
  5079. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  5080. (void)CloseHandle((HANDLE)pid);
  5081. return 0;
  5082. }
  5083. #if !defined(WNOHANG)
  5084. #define WNOHANG (1)
  5085. #endif
  5086. static pid_t
  5087. waitpid(pid_t pid, int *status, int flags)
  5088. {
  5089. DWORD timeout = INFINITE;
  5090. DWORD waitres;
  5091. (void)status; /* Currently not used by any client here */
  5092. if ((flags | WNOHANG) == WNOHANG) {
  5093. timeout = 0;
  5094. }
  5095. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  5096. if (waitres == WAIT_OBJECT_0) {
  5097. return pid;
  5098. }
  5099. if (waitres == WAIT_TIMEOUT) {
  5100. return 0;
  5101. }
  5102. return (pid_t)-1;
  5103. }
  5104. static void
  5105. trim_trailing_whitespaces(char *s)
  5106. {
  5107. char *e = s + strlen(s);
  5108. while ((e > s) && isspace((unsigned char)e[-1])) {
  5109. *(--e) = '\0';
  5110. }
  5111. }
  5112. static pid_t
  5113. spawn_process(struct mg_connection *conn,
  5114. const char *prog,
  5115. char *envblk,
  5116. char *envp[],
  5117. int fdin[2],
  5118. int fdout[2],
  5119. int fderr[2],
  5120. const char *dir)
  5121. {
  5122. HANDLE me;
  5123. char *interp;
  5124. char *interp_arg = 0;
  5125. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  5126. int truncated;
  5127. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5128. STARTUPINFOA si;
  5129. PROCESS_INFORMATION pi = {0};
  5130. (void)envp;
  5131. memset(&si, 0, sizeof(si));
  5132. si.cb = sizeof(si);
  5133. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5134. si.wShowWindow = SW_HIDE;
  5135. me = GetCurrentProcess();
  5136. DuplicateHandle(me,
  5137. (HANDLE)_get_osfhandle(fdin[0]),
  5138. me,
  5139. &si.hStdInput,
  5140. 0,
  5141. TRUE,
  5142. DUPLICATE_SAME_ACCESS);
  5143. DuplicateHandle(me,
  5144. (HANDLE)_get_osfhandle(fdout[1]),
  5145. me,
  5146. &si.hStdOutput,
  5147. 0,
  5148. TRUE,
  5149. DUPLICATE_SAME_ACCESS);
  5150. DuplicateHandle(me,
  5151. (HANDLE)_get_osfhandle(fderr[1]),
  5152. me,
  5153. &si.hStdError,
  5154. 0,
  5155. TRUE,
  5156. DUPLICATE_SAME_ACCESS);
  5157. /* Mark handles that should not be inherited. See
  5158. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5159. */
  5160. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5161. HANDLE_FLAG_INHERIT,
  5162. 0);
  5163. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5164. HANDLE_FLAG_INHERIT,
  5165. 0);
  5166. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5167. HANDLE_FLAG_INHERIT,
  5168. 0);
  5169. /* First check, if there is a CGI interpreter configured for all CGI
  5170. * scripts. */
  5171. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5172. if (interp != NULL) {
  5173. /* If there is a configured interpreter, check for additional arguments
  5174. */
  5175. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5176. } else {
  5177. /* Otherwise, the interpreter must be stated in the first line of the
  5178. * CGI script file, after a #! (shebang) mark. */
  5179. buf[0] = buf[1] = '\0';
  5180. /* Get the full script path */
  5181. mg_snprintf(
  5182. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5183. if (truncated) {
  5184. pi.hProcess = (pid_t)-1;
  5185. goto spawn_cleanup;
  5186. }
  5187. /* Open the script file, to read the first line */
  5188. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5189. /* Read the first line of the script into the buffer */
  5190. mg_fgets(buf, sizeof(buf), &file);
  5191. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5192. buf[sizeof(buf) - 1] = '\0';
  5193. }
  5194. if ((buf[0] == '#') && (buf[1] == '!')) {
  5195. trim_trailing_whitespaces(buf + 2);
  5196. } else {
  5197. buf[2] = '\0';
  5198. }
  5199. interp = buf + 2;
  5200. }
  5201. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5202. if (interp[0] != '\0') {
  5203. /* This is an interpreted script file. We must call the interpreter. */
  5204. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5205. mg_snprintf(conn,
  5206. &truncated,
  5207. cmdline,
  5208. sizeof(cmdline),
  5209. "\"%s\" %s \"%s\\%s\"",
  5210. interp,
  5211. interp_arg,
  5212. full_dir,
  5213. prog);
  5214. } else {
  5215. mg_snprintf(conn,
  5216. &truncated,
  5217. cmdline,
  5218. sizeof(cmdline),
  5219. "\"%s\" \"%s\\%s\"",
  5220. interp,
  5221. full_dir,
  5222. prog);
  5223. }
  5224. } else {
  5225. /* This is (probably) a compiled program. We call it directly. */
  5226. mg_snprintf(conn,
  5227. &truncated,
  5228. cmdline,
  5229. sizeof(cmdline),
  5230. "\"%s\\%s\"",
  5231. full_dir,
  5232. prog);
  5233. }
  5234. if (truncated) {
  5235. pi.hProcess = (pid_t)-1;
  5236. goto spawn_cleanup;
  5237. }
  5238. DEBUG_TRACE("Running [%s]", cmdline);
  5239. if (CreateProcessA(NULL,
  5240. cmdline,
  5241. NULL,
  5242. NULL,
  5243. TRUE,
  5244. CREATE_NEW_PROCESS_GROUP,
  5245. envblk,
  5246. NULL,
  5247. &si,
  5248. &pi)
  5249. == 0) {
  5250. mg_cry_internal(
  5251. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5252. pi.hProcess = (pid_t)-1;
  5253. /* goto spawn_cleanup; */
  5254. }
  5255. spawn_cleanup:
  5256. (void)CloseHandle(si.hStdOutput);
  5257. (void)CloseHandle(si.hStdError);
  5258. (void)CloseHandle(si.hStdInput);
  5259. if (pi.hThread != NULL) {
  5260. (void)CloseHandle(pi.hThread);
  5261. }
  5262. return (pid_t)pi.hProcess;
  5263. }
  5264. #endif /* !NO_CGI */
  5265. static int
  5266. set_blocking_mode(SOCKET sock)
  5267. {
  5268. unsigned long non_blocking = 0;
  5269. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5270. }
  5271. static int
  5272. set_non_blocking_mode(SOCKET sock)
  5273. {
  5274. unsigned long non_blocking = 1;
  5275. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5276. }
  5277. #else
  5278. #if !defined(NO_FILESYSTEMS)
  5279. static int
  5280. mg_stat(const struct mg_connection *conn,
  5281. const char *path,
  5282. struct mg_file_stat *filep)
  5283. {
  5284. struct stat st;
  5285. if (!filep) {
  5286. return 0;
  5287. }
  5288. memset(filep, 0, sizeof(*filep));
  5289. if (mg_path_suspicious(conn, path)) {
  5290. return 0;
  5291. }
  5292. if (0 == stat(path, &st)) {
  5293. filep->size = (uint64_t)(st.st_size);
  5294. filep->last_modified = st.st_mtime;
  5295. filep->is_directory = S_ISDIR(st.st_mode);
  5296. return 1;
  5297. }
  5298. return 0;
  5299. }
  5300. #endif /* NO_FILESYSTEMS */
  5301. static void
  5302. set_close_on_exec(int fd,
  5303. const struct mg_connection *conn /* may be null */,
  5304. struct mg_context *ctx /* may be null */)
  5305. {
  5306. #if defined(__ZEPHYR__)
  5307. (void)fd;
  5308. (void)conn;
  5309. (void)ctx;
  5310. #else
  5311. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5312. if (conn || ctx) {
  5313. struct mg_connection fc;
  5314. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5315. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5316. __func__,
  5317. strerror(ERRNO));
  5318. }
  5319. }
  5320. #endif
  5321. }
  5322. int
  5323. mg_start_thread(mg_thread_func_t func, void *param)
  5324. {
  5325. pthread_t thread_id;
  5326. pthread_attr_t attr;
  5327. int result;
  5328. (void)pthread_attr_init(&attr);
  5329. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5330. #if defined(__ZEPHYR__)
  5331. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5332. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5333. /* Compile-time option to control stack size,
  5334. * e.g. -DUSE_STACK_SIZE=16384 */
  5335. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5336. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5337. result = pthread_create(&thread_id, &attr, func, param);
  5338. pthread_attr_destroy(&attr);
  5339. return result;
  5340. }
  5341. /* Start a thread storing the thread context. */
  5342. static int
  5343. mg_start_thread_with_id(mg_thread_func_t func,
  5344. void *param,
  5345. pthread_t *threadidptr)
  5346. {
  5347. pthread_t thread_id;
  5348. pthread_attr_t attr;
  5349. int result;
  5350. (void)pthread_attr_init(&attr);
  5351. #if defined(__ZEPHYR__)
  5352. pthread_attr_setstack(&attr,
  5353. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5354. ZEPHYR_STACK_SIZE);
  5355. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5356. /* Compile-time option to control stack size,
  5357. * e.g. -DUSE_STACK_SIZE=16384 */
  5358. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5359. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5360. result = pthread_create(&thread_id, &attr, func, param);
  5361. pthread_attr_destroy(&attr);
  5362. if ((result == 0) && (threadidptr != NULL)) {
  5363. *threadidptr = thread_id;
  5364. }
  5365. return result;
  5366. }
  5367. /* Wait for a thread to finish. */
  5368. static int
  5369. mg_join_thread(pthread_t threadid)
  5370. {
  5371. int result;
  5372. result = pthread_join(threadid, NULL);
  5373. return result;
  5374. }
  5375. #if !defined(NO_CGI)
  5376. static pid_t
  5377. spawn_process(struct mg_connection *conn,
  5378. const char *prog,
  5379. char *envblk,
  5380. char *envp[],
  5381. int fdin[2],
  5382. int fdout[2],
  5383. int fderr[2],
  5384. const char *dir)
  5385. {
  5386. pid_t pid;
  5387. const char *interp;
  5388. (void)envblk;
  5389. if ((pid = fork()) == -1) {
  5390. /* Parent */
  5391. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5392. } else if (pid != 0) {
  5393. /* Make sure children close parent-side descriptors.
  5394. * The caller will close the child-side immediately. */
  5395. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5396. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5397. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5398. } else {
  5399. /* Child */
  5400. if (chdir(dir) != 0) {
  5401. mg_cry_internal(
  5402. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5403. } else if (dup2(fdin[0], 0) == -1) {
  5404. mg_cry_internal(conn,
  5405. "%s: dup2(%d, 0): %s",
  5406. __func__,
  5407. fdin[0],
  5408. strerror(ERRNO));
  5409. } else if (dup2(fdout[1], 1) == -1) {
  5410. mg_cry_internal(conn,
  5411. "%s: dup2(%d, 1): %s",
  5412. __func__,
  5413. fdout[1],
  5414. strerror(ERRNO));
  5415. } else if (dup2(fderr[1], 2) == -1) {
  5416. mg_cry_internal(conn,
  5417. "%s: dup2(%d, 2): %s",
  5418. __func__,
  5419. fderr[1],
  5420. strerror(ERRNO));
  5421. } else {
  5422. struct sigaction sa;
  5423. /* Keep stderr and stdout in two different pipes.
  5424. * Stdout will be sent back to the client,
  5425. * stderr should go into a server error log. */
  5426. (void)close(fdin[0]);
  5427. (void)close(fdout[1]);
  5428. (void)close(fderr[1]);
  5429. /* Close write end fdin and read end fdout and fderr */
  5430. (void)close(fdin[1]);
  5431. (void)close(fdout[0]);
  5432. (void)close(fderr[0]);
  5433. /* After exec, all signal handlers are restored to their default
  5434. * values, with one exception of SIGCHLD. According to
  5435. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5436. * will leave unchanged after exec if it was set to be ignored.
  5437. * Restore it to default action. */
  5438. memset(&sa, 0, sizeof(sa));
  5439. sa.sa_handler = SIG_DFL;
  5440. sigaction(SIGCHLD, &sa, NULL);
  5441. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5442. if (interp == NULL) {
  5443. /* no interpreter configured, call the programm directly */
  5444. (void)execle(prog, prog, NULL, envp);
  5445. mg_cry_internal(conn,
  5446. "%s: execle(%s): %s",
  5447. __func__,
  5448. prog,
  5449. strerror(ERRNO));
  5450. } else {
  5451. /* call the configured interpreter */
  5452. const char *interp_args =
  5453. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5454. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5455. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5456. } else {
  5457. (void)execle(interp, interp, prog, NULL, envp);
  5458. }
  5459. mg_cry_internal(conn,
  5460. "%s: execle(%s %s): %s",
  5461. __func__,
  5462. interp,
  5463. prog,
  5464. strerror(ERRNO));
  5465. }
  5466. }
  5467. exit(EXIT_FAILURE);
  5468. }
  5469. return pid;
  5470. }
  5471. #endif /* !NO_CGI */
  5472. static int
  5473. set_non_blocking_mode(SOCKET sock)
  5474. {
  5475. int flags = fcntl(sock, F_GETFL, 0);
  5476. if (flags < 0) {
  5477. return -1;
  5478. }
  5479. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5480. return -1;
  5481. }
  5482. return 0;
  5483. }
  5484. static int
  5485. set_blocking_mode(SOCKET sock)
  5486. {
  5487. int flags = fcntl(sock, F_GETFL, 0);
  5488. if (flags < 0) {
  5489. return -1;
  5490. }
  5491. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5492. return -1;
  5493. }
  5494. return 0;
  5495. }
  5496. #endif /* _WIN32 / else */
  5497. /* End of initial operating system specific define block. */
  5498. /* Get a random number (independent of C rand function) */
  5499. static uint64_t
  5500. get_random(void)
  5501. {
  5502. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5503. static uint64_t lcg = 0; /* Linear congruential generator */
  5504. uint64_t now = mg_get_current_time_ns();
  5505. if (lfsr == 0) {
  5506. /* lfsr will be only 0 if has not been initialized,
  5507. * so this code is called only once. */
  5508. lfsr = mg_get_current_time_ns();
  5509. lcg = mg_get_current_time_ns();
  5510. } else {
  5511. /* Get the next step of both random number generators. */
  5512. lfsr = (lfsr >> 1)
  5513. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5514. << 63);
  5515. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5516. }
  5517. /* Combining two pseudo-random number generators and a high resolution
  5518. * part
  5519. * of the current server time will make it hard (impossible?) to guess
  5520. * the
  5521. * next number. */
  5522. return (lfsr ^ lcg ^ now);
  5523. }
  5524. static int
  5525. mg_poll(struct mg_pollfd *pfd,
  5526. unsigned int n,
  5527. int milliseconds,
  5528. stop_flag_t *stop_flag)
  5529. {
  5530. /* Call poll, but only for a maximum time of a few seconds.
  5531. * This will allow to stop the server after some seconds, instead
  5532. * of having to wait for a long socket timeout. */
  5533. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5534. do {
  5535. int result;
  5536. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5537. /* Shut down signal */
  5538. return -2;
  5539. }
  5540. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5541. ms_now = milliseconds;
  5542. }
  5543. result = poll(pfd, n, ms_now);
  5544. if (result != 0) {
  5545. /* Poll returned either success (1) or error (-1).
  5546. * Forward both to the caller. */
  5547. return result;
  5548. }
  5549. /* Poll returned timeout (0). */
  5550. if (milliseconds > 0) {
  5551. milliseconds -= ms_now;
  5552. }
  5553. } while (milliseconds > 0);
  5554. /* timeout: return 0 */
  5555. return 0;
  5556. }
  5557. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5558. * descriptor.
  5559. * Return value:
  5560. * >=0 .. number of bytes successfully written
  5561. * -1 .. timeout
  5562. * -2 .. error
  5563. */
  5564. static int
  5565. push_inner(struct mg_context *ctx,
  5566. FILE *fp,
  5567. SOCKET sock,
  5568. SSL *ssl,
  5569. const char *buf,
  5570. int len,
  5571. double timeout)
  5572. {
  5573. uint64_t start = 0, now = 0, timeout_ns = 0;
  5574. int n, err;
  5575. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5576. #if defined(_WIN32)
  5577. typedef int len_t;
  5578. #else
  5579. typedef size_t len_t;
  5580. #endif
  5581. if (timeout > 0) {
  5582. now = mg_get_current_time_ns();
  5583. start = now;
  5584. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5585. }
  5586. if (ctx == NULL) {
  5587. return -2;
  5588. }
  5589. #if defined(NO_SSL)
  5590. if (ssl) {
  5591. return -2;
  5592. }
  5593. #endif
  5594. /* Try to read until it succeeds, fails, times out, or the server
  5595. * shuts down. */
  5596. for (;;) {
  5597. #if !defined(NO_SSL)
  5598. if (ssl != NULL) {
  5599. ERR_clear_error();
  5600. n = SSL_write(ssl, buf, len);
  5601. if (n <= 0) {
  5602. err = SSL_get_error(ssl, n);
  5603. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5604. err = ERRNO;
  5605. } else if ((err == SSL_ERROR_WANT_READ)
  5606. || (err == SSL_ERROR_WANT_WRITE)) {
  5607. n = 0;
  5608. } else {
  5609. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5610. ERR_clear_error();
  5611. return -2;
  5612. }
  5613. ERR_clear_error();
  5614. } else {
  5615. err = 0;
  5616. }
  5617. } else
  5618. #endif
  5619. if (fp != NULL) {
  5620. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5621. if (ferror(fp)) {
  5622. n = -1;
  5623. err = ERRNO;
  5624. } else {
  5625. err = 0;
  5626. }
  5627. } else {
  5628. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5629. err = (n < 0) ? ERRNO : 0;
  5630. #if defined(_WIN32)
  5631. if (err == WSAEWOULDBLOCK) {
  5632. err = 0;
  5633. n = 0;
  5634. }
  5635. #else
  5636. if (ERROR_TRY_AGAIN(err)) {
  5637. err = 0;
  5638. n = 0;
  5639. }
  5640. #endif
  5641. if (n < 0) {
  5642. /* shutdown of the socket at client side */
  5643. return -2;
  5644. }
  5645. }
  5646. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5647. return -2;
  5648. }
  5649. if ((n > 0) || ((n == 0) && (len == 0))) {
  5650. /* some data has been read, or no data was requested */
  5651. return n;
  5652. }
  5653. if (n < 0) {
  5654. /* socket error - check errno */
  5655. DEBUG_TRACE("send() failed, error %d", err);
  5656. /* TODO (mid): error handling depending on the error code.
  5657. * These codes are different between Windows and Linux.
  5658. * Currently there is no problem with failing send calls,
  5659. * if there is a reproducible situation, it should be
  5660. * investigated in detail.
  5661. */
  5662. return -2;
  5663. }
  5664. /* Only in case n=0 (timeout), repeat calling the write function */
  5665. /* If send failed, wait before retry */
  5666. if (fp != NULL) {
  5667. /* For files, just wait a fixed time.
  5668. * Maybe it helps, maybe not. */
  5669. mg_sleep(5);
  5670. } else {
  5671. /* For sockets, wait for the socket using poll */
  5672. struct mg_pollfd pfd[1];
  5673. int pollres;
  5674. pfd[0].fd = sock;
  5675. pfd[0].events = POLLOUT;
  5676. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5677. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5678. return -2;
  5679. }
  5680. if (pollres > 0) {
  5681. continue;
  5682. }
  5683. }
  5684. if (timeout > 0) {
  5685. now = mg_get_current_time_ns();
  5686. if ((now - start) > timeout_ns) {
  5687. /* Timeout */
  5688. break;
  5689. }
  5690. }
  5691. }
  5692. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5693. used */
  5694. return -1;
  5695. }
  5696. static int
  5697. push_all(struct mg_context *ctx,
  5698. FILE *fp,
  5699. SOCKET sock,
  5700. SSL *ssl,
  5701. const char *buf,
  5702. int len)
  5703. {
  5704. double timeout = -1.0;
  5705. int n, nwritten = 0;
  5706. if (ctx == NULL) {
  5707. return -1;
  5708. }
  5709. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5710. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5711. }
  5712. if (timeout <= 0.0) {
  5713. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5714. }
  5715. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5716. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5717. if (n < 0) {
  5718. if (nwritten == 0) {
  5719. nwritten = -1; /* Propagate the error */
  5720. }
  5721. break;
  5722. } else if (n == 0) {
  5723. break; /* No more data to write */
  5724. } else {
  5725. nwritten += n;
  5726. len -= n;
  5727. }
  5728. }
  5729. return nwritten;
  5730. }
  5731. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5732. * Return value:
  5733. * >=0 .. number of bytes successfully read
  5734. * -1 .. timeout
  5735. * -2 .. error
  5736. */
  5737. static int
  5738. pull_inner(FILE *fp,
  5739. struct mg_connection *conn,
  5740. char *buf,
  5741. int len,
  5742. double timeout)
  5743. {
  5744. int nread, err = 0;
  5745. #if defined(_WIN32)
  5746. typedef int len_t;
  5747. #else
  5748. typedef size_t len_t;
  5749. #endif
  5750. /* We need an additional wait loop around this, because in some cases
  5751. * with TLSwe may get data from the socket but not from SSL_read.
  5752. * In this case we need to repeat at least once.
  5753. */
  5754. if (fp != NULL) {
  5755. #if !defined(_WIN32_WCE)
  5756. /* Use read() instead of fread(), because if we're reading from the
  5757. * CGI pipe, fread() may block until IO buffer is filled up. We
  5758. * cannot afford to block and must pass all read bytes immediately
  5759. * to the client. */
  5760. nread = (int)read(fileno(fp), buf, (size_t)len);
  5761. #else
  5762. /* WinCE does not support CGI pipes */
  5763. nread = (int)fread(buf, 1, (size_t)len, fp);
  5764. #endif
  5765. err = (nread < 0) ? ERRNO : 0;
  5766. if ((nread == 0) && (len > 0)) {
  5767. /* Should get data, but got EOL */
  5768. return -2;
  5769. }
  5770. #if !defined(NO_SSL)
  5771. } else if (conn->ssl != NULL) {
  5772. int ssl_pending;
  5773. struct mg_pollfd pfd[1];
  5774. int pollres;
  5775. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5776. /* We already know there is no more data buffered in conn->buf
  5777. * but there is more available in the SSL layer. So don't poll
  5778. * conn->client.sock yet. */
  5779. if (ssl_pending > len) {
  5780. ssl_pending = len;
  5781. }
  5782. pollres = 1;
  5783. } else {
  5784. pfd[0].fd = conn->client.sock;
  5785. pfd[0].events = POLLIN;
  5786. pollres = mg_poll(pfd,
  5787. 1,
  5788. (int)(timeout * 1000.0),
  5789. &(conn->phys_ctx->stop_flag));
  5790. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5791. return -2;
  5792. }
  5793. }
  5794. if (pollres > 0) {
  5795. ERR_clear_error();
  5796. nread =
  5797. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5798. if (nread <= 0) {
  5799. err = SSL_get_error(conn->ssl, nread);
  5800. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5801. err = ERRNO;
  5802. } else if ((err == SSL_ERROR_WANT_READ)
  5803. || (err == SSL_ERROR_WANT_WRITE)) {
  5804. nread = 0;
  5805. } else {
  5806. /* All errors should return -2 */
  5807. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5808. ERR_clear_error();
  5809. return -2;
  5810. }
  5811. ERR_clear_error();
  5812. } else {
  5813. err = 0;
  5814. }
  5815. } else if (pollres < 0) {
  5816. /* Error */
  5817. return -2;
  5818. } else {
  5819. /* pollres = 0 means timeout */
  5820. nread = 0;
  5821. }
  5822. #endif
  5823. } else {
  5824. struct mg_pollfd pfd[1];
  5825. int pollres;
  5826. pfd[0].fd = conn->client.sock;
  5827. pfd[0].events = POLLIN;
  5828. pollres = mg_poll(pfd,
  5829. 1,
  5830. (int)(timeout * 1000.0),
  5831. &(conn->phys_ctx->stop_flag));
  5832. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5833. return -2;
  5834. }
  5835. if (pollres > 0) {
  5836. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5837. err = (nread < 0) ? ERRNO : 0;
  5838. if (nread <= 0) {
  5839. /* shutdown of the socket at client side */
  5840. return -2;
  5841. }
  5842. } else if (pollres < 0) {
  5843. /* error callint poll */
  5844. return -2;
  5845. } else {
  5846. /* pollres = 0 means timeout */
  5847. nread = 0;
  5848. }
  5849. }
  5850. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5851. return -2;
  5852. }
  5853. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5854. /* some data has been read, or no data was requested */
  5855. return nread;
  5856. }
  5857. if (nread < 0) {
  5858. /* socket error - check errno */
  5859. #if defined(_WIN32)
  5860. if (err == WSAEWOULDBLOCK) {
  5861. /* TODO (low): check if this is still required */
  5862. /* standard case if called from close_socket_gracefully */
  5863. return -2;
  5864. } else if (err == WSAETIMEDOUT) {
  5865. /* TODO (low): check if this is still required */
  5866. /* timeout is handled by the while loop */
  5867. return 0;
  5868. } else if (err == WSAECONNABORTED) {
  5869. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5870. return -2;
  5871. } else {
  5872. DEBUG_TRACE("recv() failed, error %d", err);
  5873. return -2;
  5874. }
  5875. #else
  5876. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5877. * if the timeout is reached and if the socket was set to non-
  5878. * blocking in close_socket_gracefully, so we can not distinguish
  5879. * here. We have to wait for the timeout in both cases for now.
  5880. */
  5881. if (ERROR_TRY_AGAIN(err)) {
  5882. /* TODO (low): check if this is still required */
  5883. /* EAGAIN/EWOULDBLOCK:
  5884. * standard case if called from close_socket_gracefully
  5885. * => should return -1 */
  5886. /* or timeout occurred
  5887. * => the code must stay in the while loop */
  5888. /* EINTR can be generated on a socket with a timeout set even
  5889. * when SA_RESTART is effective for all relevant signals
  5890. * (see signal(7)).
  5891. * => stay in the while loop */
  5892. } else {
  5893. DEBUG_TRACE("recv() failed, error %d", err);
  5894. return -2;
  5895. }
  5896. #endif
  5897. }
  5898. /* Timeout occurred, but no data available. */
  5899. return -1;
  5900. }
  5901. static int
  5902. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5903. {
  5904. int n, nread = 0;
  5905. double timeout = -1.0;
  5906. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5907. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5908. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5909. }
  5910. if (timeout <= 0.0) {
  5911. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5912. }
  5913. start_time = mg_get_current_time_ns();
  5914. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5915. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5916. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5917. if (n == -2) {
  5918. if (nread == 0) {
  5919. nread = -1; /* Propagate the error */
  5920. }
  5921. break;
  5922. } else if (n == -1) {
  5923. /* timeout */
  5924. if (timeout >= 0.0) {
  5925. now = mg_get_current_time_ns();
  5926. if ((now - start_time) <= timeout_ns) {
  5927. continue;
  5928. }
  5929. }
  5930. break;
  5931. } else if (n == 0) {
  5932. break; /* No more data to read */
  5933. } else {
  5934. nread += n;
  5935. len -= n;
  5936. }
  5937. }
  5938. return nread;
  5939. }
  5940. static void
  5941. discard_unread_request_data(struct mg_connection *conn)
  5942. {
  5943. char buf[MG_BUF_LEN];
  5944. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5945. ;
  5946. }
  5947. static int
  5948. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5949. {
  5950. int64_t content_len, n, buffered_len, nread;
  5951. int64_t len64 =
  5952. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5953. * int, we may not read more
  5954. * bytes */
  5955. const char *body;
  5956. if (conn == NULL) {
  5957. return 0;
  5958. }
  5959. /* If Content-Length is not set for a response with body data,
  5960. * we do not know in advance how much data should be read. */
  5961. content_len = conn->content_len;
  5962. if (content_len < 0) {
  5963. /* The body data is completed when the connection is closed. */
  5964. content_len = INT64_MAX;
  5965. }
  5966. nread = 0;
  5967. if (conn->consumed_content < content_len) {
  5968. /* Adjust number of bytes to read. */
  5969. int64_t left_to_read = content_len - conn->consumed_content;
  5970. if (left_to_read < len64) {
  5971. /* Do not read more than the total content length of the
  5972. * request.
  5973. */
  5974. len64 = left_to_read;
  5975. }
  5976. /* Return buffered data */
  5977. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5978. - conn->consumed_content;
  5979. if (buffered_len > 0) {
  5980. if (len64 < buffered_len) {
  5981. buffered_len = len64;
  5982. }
  5983. body = conn->buf + conn->request_len + conn->consumed_content;
  5984. memcpy(buf, body, (size_t)buffered_len);
  5985. len64 -= buffered_len;
  5986. conn->consumed_content += buffered_len;
  5987. nread += buffered_len;
  5988. buf = (char *)buf + buffered_len;
  5989. }
  5990. /* We have returned all buffered data. Read new data from the remote
  5991. * socket.
  5992. */
  5993. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5994. conn->consumed_content += n;
  5995. nread += n;
  5996. } else {
  5997. nread = ((nread > 0) ? nread : n);
  5998. }
  5999. }
  6000. return (int)nread;
  6001. }
  6002. /* Forward declarations */
  6003. static void handle_request(struct mg_connection *);
  6004. #if defined(USE_HTTP2)
  6005. #if defined(NO_SSL)
  6006. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  6007. #endif
  6008. #define USE_ALPN
  6009. #include "mod_http2.inl"
  6010. /* Not supported with HTTP/2 */
  6011. #define HTTP1_only \
  6012. { \
  6013. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  6014. http2_must_use_http1(conn); \
  6015. return; \
  6016. } \
  6017. }
  6018. #else
  6019. #define HTTP1_only
  6020. #endif
  6021. int
  6022. mg_read(struct mg_connection *conn, void *buf, size_t len)
  6023. {
  6024. if (len > INT_MAX) {
  6025. len = INT_MAX;
  6026. }
  6027. if (conn == NULL) {
  6028. return 0;
  6029. }
  6030. if (conn->is_chunked) {
  6031. size_t all_read = 0;
  6032. while (len > 0) {
  6033. if (conn->is_chunked >= 3) {
  6034. /* No more data left to read */
  6035. return 0;
  6036. }
  6037. if (conn->is_chunked != 1) {
  6038. /* Has error */
  6039. return -1;
  6040. }
  6041. if (conn->consumed_content != conn->content_len) {
  6042. /* copy from the current chunk */
  6043. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  6044. if (read_ret < 1) {
  6045. /* read error */
  6046. conn->is_chunked = 2;
  6047. return -1;
  6048. }
  6049. all_read += (size_t)read_ret;
  6050. len -= (size_t)read_ret;
  6051. if (conn->consumed_content == conn->content_len) {
  6052. /* Add data bytes in the current chunk have been read,
  6053. * so we are expecting \r\n now. */
  6054. char x[2];
  6055. conn->content_len += 2;
  6056. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  6057. || (x[1] != '\n')) {
  6058. /* Protocol violation */
  6059. conn->is_chunked = 2;
  6060. return -1;
  6061. }
  6062. }
  6063. } else {
  6064. /* fetch a new chunk */
  6065. size_t i;
  6066. char lenbuf[64];
  6067. char *end = NULL;
  6068. unsigned long chunkSize = 0;
  6069. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  6070. conn->content_len++;
  6071. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  6072. lenbuf[i] = 0;
  6073. }
  6074. if ((i > 0) && (lenbuf[i] == '\r')
  6075. && (lenbuf[i - 1] != '\r')) {
  6076. continue;
  6077. }
  6078. if ((i > 1) && (lenbuf[i] == '\n')
  6079. && (lenbuf[i - 1] == '\r')) {
  6080. lenbuf[i + 1] = 0;
  6081. chunkSize = strtoul(lenbuf, &end, 16);
  6082. if (chunkSize == 0) {
  6083. /* regular end of content */
  6084. conn->is_chunked = 3;
  6085. }
  6086. break;
  6087. }
  6088. if (!isxdigit((unsigned char)lenbuf[i])) {
  6089. /* illegal character for chunk length */
  6090. conn->is_chunked = 2;
  6091. return -1;
  6092. }
  6093. }
  6094. if ((end == NULL) || (*end != '\r')) {
  6095. /* chunksize not set correctly */
  6096. conn->is_chunked = 2;
  6097. return -1;
  6098. }
  6099. if (chunkSize == 0) {
  6100. /* try discarding trailer for keep-alive */
  6101. conn->content_len += 2;
  6102. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  6103. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  6104. conn->is_chunked = 4;
  6105. }
  6106. break;
  6107. }
  6108. /* append a new chunk */
  6109. conn->content_len += (int64_t)chunkSize;
  6110. }
  6111. }
  6112. return (int)all_read;
  6113. }
  6114. return mg_read_inner(conn, buf, len);
  6115. }
  6116. int
  6117. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  6118. {
  6119. time_t now;
  6120. int n, total, allowed;
  6121. if (conn == NULL) {
  6122. return 0;
  6123. }
  6124. if (len > INT_MAX) {
  6125. return -1;
  6126. }
  6127. /* Mark connection as "data sent" */
  6128. conn->request_state = 10;
  6129. #if defined(USE_HTTP2)
  6130. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  6131. http2_data_frame_head(conn, len, 0);
  6132. }
  6133. #endif
  6134. if (conn->throttle > 0) {
  6135. if ((now = time(NULL)) != conn->last_throttle_time) {
  6136. conn->last_throttle_time = now;
  6137. conn->last_throttle_bytes = 0;
  6138. }
  6139. allowed = conn->throttle - conn->last_throttle_bytes;
  6140. if (allowed > (int)len) {
  6141. allowed = (int)len;
  6142. }
  6143. total = push_all(conn->phys_ctx,
  6144. NULL,
  6145. conn->client.sock,
  6146. conn->ssl,
  6147. (const char *)buf,
  6148. allowed);
  6149. if (total == allowed) {
  6150. buf = (const char *)buf + total;
  6151. conn->last_throttle_bytes += total;
  6152. while ((total < (int)len)
  6153. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6154. allowed = (conn->throttle > ((int)len - total))
  6155. ? (int)len - total
  6156. : conn->throttle;
  6157. n = push_all(conn->phys_ctx,
  6158. NULL,
  6159. conn->client.sock,
  6160. conn->ssl,
  6161. (const char *)buf,
  6162. allowed);
  6163. if (n != allowed) {
  6164. break;
  6165. }
  6166. sleep(1);
  6167. conn->last_throttle_bytes = allowed;
  6168. conn->last_throttle_time = time(NULL);
  6169. buf = (const char *)buf + n;
  6170. total += n;
  6171. }
  6172. }
  6173. } else {
  6174. total = push_all(conn->phys_ctx,
  6175. NULL,
  6176. conn->client.sock,
  6177. conn->ssl,
  6178. (const char *)buf,
  6179. (int)len);
  6180. }
  6181. if (total > 0) {
  6182. conn->num_bytes_sent += total;
  6183. }
  6184. return total;
  6185. }
  6186. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6187. int
  6188. mg_send_chunk(struct mg_connection *conn,
  6189. const char *chunk,
  6190. unsigned int chunk_len)
  6191. {
  6192. char lenbuf[16];
  6193. size_t lenbuf_len;
  6194. int ret;
  6195. int t;
  6196. /* First store the length information in a text buffer. */
  6197. sprintf(lenbuf, "%x\r\n", chunk_len);
  6198. lenbuf_len = strlen(lenbuf);
  6199. /* Then send length information, chunk and terminating \r\n. */
  6200. ret = mg_write(conn, lenbuf, lenbuf_len);
  6201. if (ret != (int)lenbuf_len) {
  6202. return -1;
  6203. }
  6204. t = ret;
  6205. ret = mg_write(conn, chunk, chunk_len);
  6206. if (ret != (int)chunk_len) {
  6207. return -1;
  6208. }
  6209. t += ret;
  6210. ret = mg_write(conn, "\r\n", 2);
  6211. if (ret != 2) {
  6212. return -1;
  6213. }
  6214. t += ret;
  6215. return t;
  6216. }
  6217. #if defined(GCC_DIAGNOSTIC)
  6218. /* This block forwards format strings to printf implementations,
  6219. * so we need to disable the format-nonliteral warning. */
  6220. #pragma GCC diagnostic push
  6221. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6222. #endif
  6223. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6224. static int
  6225. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6226. {
  6227. va_list ap_copy;
  6228. size_t size = MG_BUF_LEN / 4;
  6229. int len = -1;
  6230. *buf = NULL;
  6231. while (len < 0) {
  6232. if (*buf) {
  6233. mg_free(*buf);
  6234. }
  6235. size *= 4;
  6236. *buf = (char *)mg_malloc(size);
  6237. if (!*buf) {
  6238. break;
  6239. }
  6240. va_copy(ap_copy, ap);
  6241. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6242. va_end(ap_copy);
  6243. (*buf)[size - 1] = 0;
  6244. }
  6245. return len;
  6246. }
  6247. /* Print message to buffer. If buffer is large enough to hold the message,
  6248. * return buffer. If buffer is to small, allocate large enough buffer on
  6249. * heap,
  6250. * and return allocated buffer. */
  6251. static int
  6252. alloc_vprintf(char **out_buf,
  6253. char *prealloc_buf,
  6254. size_t prealloc_size,
  6255. const char *fmt,
  6256. va_list ap)
  6257. {
  6258. va_list ap_copy;
  6259. int len;
  6260. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6261. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6262. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6263. * Therefore, we make two passes: on first pass, get required message
  6264. * length.
  6265. * On second pass, actually print the message. */
  6266. va_copy(ap_copy, ap);
  6267. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6268. va_end(ap_copy);
  6269. if (len < 0) {
  6270. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6271. * Switch to alternative code path that uses incremental
  6272. * allocations.
  6273. */
  6274. va_copy(ap_copy, ap);
  6275. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6276. va_end(ap_copy);
  6277. } else if ((size_t)(len) >= prealloc_size) {
  6278. /* The pre-allocated buffer not large enough. */
  6279. /* Allocate a new buffer. */
  6280. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6281. if (!*out_buf) {
  6282. /* Allocation failed. Return -1 as "out of memory" error. */
  6283. return -1;
  6284. }
  6285. /* Buffer allocation successful. Store the string there. */
  6286. va_copy(ap_copy, ap);
  6287. IGNORE_UNUSED_RESULT(
  6288. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6289. va_end(ap_copy);
  6290. } else {
  6291. /* The pre-allocated buffer is large enough.
  6292. * Use it to store the string and return the address. */
  6293. va_copy(ap_copy, ap);
  6294. IGNORE_UNUSED_RESULT(
  6295. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6296. va_end(ap_copy);
  6297. *out_buf = prealloc_buf;
  6298. }
  6299. return len;
  6300. }
  6301. #if defined(GCC_DIAGNOSTIC)
  6302. /* Enable format-nonliteral warning again. */
  6303. #pragma GCC diagnostic pop
  6304. #endif
  6305. static int
  6306. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6307. {
  6308. char mem[MG_BUF_LEN];
  6309. char *buf = NULL;
  6310. int len;
  6311. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6312. len = mg_write(conn, buf, (size_t)len);
  6313. }
  6314. if (buf != mem) {
  6315. mg_free(buf);
  6316. }
  6317. return len;
  6318. }
  6319. int
  6320. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6321. {
  6322. va_list ap;
  6323. int result;
  6324. va_start(ap, fmt);
  6325. result = mg_vprintf(conn, fmt, ap);
  6326. va_end(ap);
  6327. return result;
  6328. }
  6329. int
  6330. mg_url_decode(const char *src,
  6331. int src_len,
  6332. char *dst,
  6333. int dst_len,
  6334. int is_form_url_encoded)
  6335. {
  6336. int i, j, a, b;
  6337. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6338. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6339. if ((i < src_len - 2) && (src[i] == '%')
  6340. && isxdigit((unsigned char)src[i + 1])
  6341. && isxdigit((unsigned char)src[i + 2])) {
  6342. a = tolower((unsigned char)src[i + 1]);
  6343. b = tolower((unsigned char)src[i + 2]);
  6344. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6345. i += 2;
  6346. } else if (is_form_url_encoded && (src[i] == '+')) {
  6347. dst[j] = ' ';
  6348. } else {
  6349. dst[j] = src[i];
  6350. }
  6351. }
  6352. dst[j] = '\0'; /* Null-terminate the destination */
  6353. return (i >= src_len) ? j : -1;
  6354. }
  6355. /* form url decoding of an entire string */
  6356. static void
  6357. url_decode_in_place(char *buf)
  6358. {
  6359. int len = (int)strlen(buf);
  6360. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6361. }
  6362. int
  6363. mg_get_var(const char *data,
  6364. size_t data_len,
  6365. const char *name,
  6366. char *dst,
  6367. size_t dst_len)
  6368. {
  6369. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6370. }
  6371. int
  6372. mg_get_var2(const char *data,
  6373. size_t data_len,
  6374. const char *name,
  6375. char *dst,
  6376. size_t dst_len,
  6377. size_t occurrence)
  6378. {
  6379. const char *p, *e, *s;
  6380. size_t name_len;
  6381. int len;
  6382. if ((dst == NULL) || (dst_len == 0)) {
  6383. len = -2;
  6384. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6385. len = -1;
  6386. dst[0] = '\0';
  6387. } else {
  6388. name_len = strlen(name);
  6389. e = data + data_len;
  6390. len = -1;
  6391. dst[0] = '\0';
  6392. /* data is "var1=val1&var2=val2...". Find variable first */
  6393. for (p = data; p + name_len < e; p++) {
  6394. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6395. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6396. /* Point p to variable value */
  6397. p += name_len + 1;
  6398. /* Point s to the end of the value */
  6399. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6400. if (s == NULL) {
  6401. s = e;
  6402. }
  6403. DEBUG_ASSERT(s >= p);
  6404. if (s < p) {
  6405. return -3;
  6406. }
  6407. /* Decode variable into destination buffer */
  6408. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6409. /* Redirect error code from -1 to -2 (destination buffer too
  6410. * small). */
  6411. if (len == -1) {
  6412. len = -2;
  6413. }
  6414. break;
  6415. }
  6416. }
  6417. }
  6418. return len;
  6419. }
  6420. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6421. int
  6422. mg_split_form_urlencoded(char *data,
  6423. struct mg_header *form_fields,
  6424. unsigned num_form_fields)
  6425. {
  6426. char *b;
  6427. int i;
  6428. int num = 0;
  6429. if (data == NULL) {
  6430. /* parameter error */
  6431. return -1;
  6432. }
  6433. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6434. /* determine the number of expected fields */
  6435. if (data[0] == 0) {
  6436. return 0;
  6437. }
  6438. /* count number of & to return the number of key-value-pairs */
  6439. num = 1;
  6440. while (*data) {
  6441. if (*data == '&') {
  6442. num++;
  6443. }
  6444. data++;
  6445. }
  6446. return num;
  6447. }
  6448. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6449. /* parameter error */
  6450. return -1;
  6451. }
  6452. for (i = 0; i < (int)num_form_fields; i++) {
  6453. /* extract key-value pairs from input data */
  6454. while ((*data == ' ') || (*data == '\t')) {
  6455. /* skip initial spaces */
  6456. data++;
  6457. }
  6458. if (*data == 0) {
  6459. /* end of string reached */
  6460. break;
  6461. }
  6462. form_fields[num].name = data;
  6463. /* find & or = */
  6464. b = data;
  6465. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6466. b++;
  6467. }
  6468. if (*b == 0) {
  6469. /* last key without value */
  6470. form_fields[num].value = NULL;
  6471. } else if (*b == '&') {
  6472. /* mid key without value */
  6473. form_fields[num].value = NULL;
  6474. } else {
  6475. /* terminate string */
  6476. *b = 0;
  6477. /* value starts after '=' */
  6478. data = b + 1;
  6479. form_fields[num].value = data;
  6480. }
  6481. /* new field is stored */
  6482. num++;
  6483. /* find a next key */
  6484. b = strchr(data, '&');
  6485. if (b == 0) {
  6486. /* no more data */
  6487. break;
  6488. } else {
  6489. /* terminate value of last field at '&' */
  6490. *b = 0;
  6491. /* next key-value-pairs starts after '&' */
  6492. data = b + 1;
  6493. }
  6494. }
  6495. /* Decode all values */
  6496. for (i = 0; i < num; i++) {
  6497. if (form_fields[i].name) {
  6498. url_decode_in_place((char *)form_fields[i].name);
  6499. }
  6500. if (form_fields[i].value) {
  6501. url_decode_in_place((char *)form_fields[i].value);
  6502. }
  6503. }
  6504. /* return number of fields found */
  6505. return num;
  6506. }
  6507. /* HCP24: some changes to compare hole var_name */
  6508. int
  6509. mg_get_cookie(const char *cookie_header,
  6510. const char *var_name,
  6511. char *dst,
  6512. size_t dst_size)
  6513. {
  6514. const char *s, *p, *end;
  6515. int name_len, len = -1;
  6516. if ((dst == NULL) || (dst_size == 0)) {
  6517. return -2;
  6518. }
  6519. dst[0] = '\0';
  6520. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6521. return -1;
  6522. }
  6523. name_len = (int)strlen(var_name);
  6524. end = s + strlen(s);
  6525. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6526. if (s[name_len] == '=') {
  6527. /* HCP24: now check is it a substring or a full cookie name */
  6528. if ((s == cookie_header) || (s[-1] == ' ')) {
  6529. s += name_len + 1;
  6530. if ((p = strchr(s, ' ')) == NULL) {
  6531. p = end;
  6532. }
  6533. if (p[-1] == ';') {
  6534. p--;
  6535. }
  6536. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6537. s++;
  6538. p--;
  6539. }
  6540. if ((size_t)(p - s) < dst_size) {
  6541. len = (int)(p - s);
  6542. mg_strlcpy(dst, s, (size_t)len + 1);
  6543. } else {
  6544. len = -3;
  6545. }
  6546. break;
  6547. }
  6548. }
  6549. }
  6550. return len;
  6551. }
  6552. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6553. static void
  6554. base64_encode(const unsigned char *src, int src_len, char *dst)
  6555. {
  6556. static const char *b64 =
  6557. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6558. int i, j, a, b, c;
  6559. for (i = j = 0; i < src_len; i += 3) {
  6560. a = src[i];
  6561. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6562. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6563. dst[j++] = b64[a >> 2];
  6564. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6565. if (i + 1 < src_len) {
  6566. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6567. }
  6568. if (i + 2 < src_len) {
  6569. dst[j++] = b64[c & 63];
  6570. }
  6571. }
  6572. while (j % 4 != 0) {
  6573. dst[j++] = '=';
  6574. }
  6575. dst[j++] = '\0';
  6576. }
  6577. #endif
  6578. #if defined(USE_LUA)
  6579. static unsigned char
  6580. b64reverse(char letter)
  6581. {
  6582. if ((letter >= 'A') && (letter <= 'Z')) {
  6583. return letter - 'A';
  6584. }
  6585. if ((letter >= 'a') && (letter <= 'z')) {
  6586. return letter - 'a' + 26;
  6587. }
  6588. if ((letter >= '0') && (letter <= '9')) {
  6589. return letter - '0' + 52;
  6590. }
  6591. if (letter == '+') {
  6592. return 62;
  6593. }
  6594. if (letter == '/') {
  6595. return 63;
  6596. }
  6597. if (letter == '=') {
  6598. return 255; /* normal end */
  6599. }
  6600. return 254; /* error */
  6601. }
  6602. static int
  6603. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6604. {
  6605. int i;
  6606. unsigned char a, b, c, d;
  6607. *dst_len = 0;
  6608. for (i = 0; i < src_len; i += 4) {
  6609. a = b64reverse(src[i]);
  6610. if (a >= 254) {
  6611. return i;
  6612. }
  6613. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6614. if (b >= 254) {
  6615. return i + 1;
  6616. }
  6617. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6618. if (c == 254) {
  6619. return i + 2;
  6620. }
  6621. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6622. if (d == 254) {
  6623. return i + 3;
  6624. }
  6625. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6626. if (c != 255) {
  6627. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6628. if (d != 255) {
  6629. dst[(*dst_len)++] = (c << 6) + d;
  6630. }
  6631. }
  6632. }
  6633. return -1;
  6634. }
  6635. #endif
  6636. static int
  6637. is_put_or_delete_method(const struct mg_connection *conn)
  6638. {
  6639. if (conn) {
  6640. const char *s = conn->request_info.request_method;
  6641. return (s != NULL)
  6642. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6643. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6644. }
  6645. return 0;
  6646. }
  6647. #if !defined(NO_FILES)
  6648. static int
  6649. extention_matches_script(
  6650. struct mg_connection *conn, /* in: request (must be valid) */
  6651. const char *filename /* in: filename (must be valid) */
  6652. )
  6653. {
  6654. #if !defined(NO_CGI)
  6655. if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], filename)
  6656. > 0) {
  6657. return 1;
  6658. }
  6659. if (match_prefix_strlen(conn->dom_ctx->config[CGI2_EXTENSIONS], filename)
  6660. > 0) {
  6661. return 1;
  6662. }
  6663. #endif
  6664. #if defined(USE_LUA)
  6665. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6666. filename)
  6667. > 0) {
  6668. return 1;
  6669. }
  6670. #endif
  6671. #if defined(USE_DUKTAPE)
  6672. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6673. filename)
  6674. > 0) {
  6675. return 1;
  6676. }
  6677. #endif
  6678. /* filename and conn could be unused, if all preocessor conditions
  6679. * are false (no script language supported). */
  6680. (void)filename;
  6681. (void)conn;
  6682. return 0;
  6683. }
  6684. static int
  6685. extention_matches_template_text(
  6686. struct mg_connection *conn, /* in: request (must be valid) */
  6687. const char *filename /* in: filename (must be valid) */
  6688. )
  6689. {
  6690. #if defined(USE_LUA)
  6691. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6692. filename)
  6693. > 0) {
  6694. return 1;
  6695. }
  6696. #endif
  6697. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6698. > 0) {
  6699. return 1;
  6700. }
  6701. return 0;
  6702. }
  6703. /* For given directory path, substitute it to valid index file.
  6704. * Return 1 if index file has been found, 0 if not found.
  6705. * If the file is found, it's stats is returned in stp. */
  6706. static int
  6707. substitute_index_file(struct mg_connection *conn,
  6708. char *path,
  6709. size_t path_len,
  6710. struct mg_file_stat *filestat)
  6711. {
  6712. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6713. struct vec filename_vec;
  6714. size_t n = strlen(path);
  6715. int found = 0;
  6716. /* The 'path' given to us points to the directory. Remove all trailing
  6717. * directory separator characters from the end of the path, and
  6718. * then append single directory separator character. */
  6719. while ((n > 0) && (path[n - 1] == '/')) {
  6720. n--;
  6721. }
  6722. path[n] = '/';
  6723. /* Traverse index files list. For each entry, append it to the given
  6724. * path and see if the file exists. If it exists, break the loop */
  6725. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6726. /* Ignore too long entries that may overflow path buffer */
  6727. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6728. continue;
  6729. }
  6730. /* Prepare full path to the index file */
  6731. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6732. /* Does it exist? */
  6733. if (mg_stat(conn, path, filestat)) {
  6734. /* Yes it does, break the loop */
  6735. found = 1;
  6736. break;
  6737. }
  6738. }
  6739. /* If no index file exists, restore directory path */
  6740. if (!found) {
  6741. path[n] = '\0';
  6742. }
  6743. return found;
  6744. }
  6745. #endif
  6746. static void
  6747. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6748. char *filename, /* out: filename */
  6749. size_t filename_buf_len, /* in: size of filename buffer */
  6750. struct mg_file_stat *filestat, /* out: file status structure */
  6751. int *is_found, /* out: file found (directly) */
  6752. int *is_script_resource, /* out: handled by a script? */
  6753. int *is_websocket_request, /* out: websocket connetion? */
  6754. int *is_put_or_delete_request, /* out: put/delete a file? */
  6755. int *is_template_text /* out: SSI file or LSP file? */
  6756. )
  6757. {
  6758. char const *accept_encoding;
  6759. #if !defined(NO_FILES)
  6760. const char *uri = conn->request_info.local_uri;
  6761. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6762. const char *rewrite;
  6763. struct vec a, b;
  6764. ptrdiff_t match_len;
  6765. char gz_path[UTF8_PATH_MAX];
  6766. int truncated;
  6767. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6768. char *tmp_str;
  6769. size_t tmp_str_len, sep_pos;
  6770. int allow_substitute_script_subresources;
  6771. #endif
  6772. #else
  6773. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6774. #endif
  6775. /* Step 1: Set all initially unknown outputs to zero */
  6776. memset(filestat, 0, sizeof(*filestat));
  6777. *filename = 0;
  6778. *is_found = 0;
  6779. *is_script_resource = 0;
  6780. *is_template_text = 0;
  6781. /* Step 2: Check if the request attempts to modify the file system */
  6782. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6783. /* Step 3: Check if it is a websocket request, and modify the document
  6784. * root if required */
  6785. #if defined(USE_WEBSOCKET)
  6786. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6787. #if !defined(NO_FILES)
  6788. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6789. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6790. }
  6791. #endif /* !NO_FILES */
  6792. #else /* USE_WEBSOCKET */
  6793. *is_websocket_request = 0;
  6794. #endif /* USE_WEBSOCKET */
  6795. /* Step 4: Check if gzip encoded response is allowed */
  6796. conn->accept_gzip = 0;
  6797. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6798. if (strstr(accept_encoding, "gzip") != NULL) {
  6799. conn->accept_gzip = 1;
  6800. }
  6801. }
  6802. #if !defined(NO_FILES)
  6803. /* Step 5: If there is no root directory, don't look for files. */
  6804. /* Note that root == NULL is a regular use case here. This occurs,
  6805. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6806. * config is not required. */
  6807. if (root == NULL) {
  6808. /* all file related outputs have already been set to 0, just return
  6809. */
  6810. return;
  6811. }
  6812. /* Step 6: Determine the local file path from the root path and the
  6813. * request uri. */
  6814. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6815. * part of the path one byte on the right. */
  6816. truncated = 0;
  6817. mg_snprintf(
  6818. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6819. if (truncated) {
  6820. goto interpret_cleanup;
  6821. }
  6822. /* Step 7: URI rewriting */
  6823. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6824. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6825. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6826. mg_snprintf(conn,
  6827. &truncated,
  6828. filename,
  6829. filename_buf_len - 1,
  6830. "%.*s%s",
  6831. (int)b.len,
  6832. b.ptr,
  6833. uri + match_len);
  6834. break;
  6835. }
  6836. }
  6837. if (truncated) {
  6838. goto interpret_cleanup;
  6839. }
  6840. /* Step 8: Check if the file exists at the server */
  6841. /* Local file path and name, corresponding to requested URI
  6842. * is now stored in "filename" variable. */
  6843. if (mg_stat(conn, filename, filestat)) {
  6844. int uri_len = (int)strlen(uri);
  6845. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6846. /* 8.1: File exists. */
  6847. *is_found = 1;
  6848. /* 8.2: Check if it is a script type. */
  6849. if (extention_matches_script(conn, filename)) {
  6850. /* The request addresses a CGI resource, Lua script or
  6851. * server-side javascript.
  6852. * The URI corresponds to the script itself (like
  6853. * /path/script.cgi), and there is no additional resource
  6854. * path (like /path/script.cgi/something).
  6855. * Requests that modify (replace or delete) a resource, like
  6856. * PUT and DELETE requests, should replace/delete the script
  6857. * file.
  6858. * Requests that read or write from/to a resource, like GET and
  6859. * POST requests, should call the script and return the
  6860. * generated response. */
  6861. *is_script_resource = (!*is_put_or_delete_request);
  6862. }
  6863. /* 8.3: Check for SSI and LSP files */
  6864. if (extention_matches_template_text(conn, filename)) {
  6865. /* Same as above, but for *.lsp and *.shtml files. */
  6866. /* A "template text" is a file delivered directly to the client,
  6867. * but with some text tags replaced by dynamic content.
  6868. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6869. * (LP, LSP) file. */
  6870. *is_template_text = (!*is_put_or_delete_request);
  6871. }
  6872. /* 8.4: If the request target is a directory, there could be
  6873. * a substitute file (index.html, index.cgi, ...). */
  6874. if (filestat->is_directory && is_uri_end_slash) {
  6875. /* Use a local copy here, since substitute_index_file will
  6876. * change the content of the file status */
  6877. struct mg_file_stat tmp_filestat;
  6878. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6879. if (substitute_index_file(
  6880. conn, filename, filename_buf_len, &tmp_filestat)) {
  6881. /* Substitute file found. Copy stat to the output, then
  6882. * check if the file is a script file */
  6883. *filestat = tmp_filestat;
  6884. if (extention_matches_script(conn, filename)) {
  6885. /* Substitute file is a script file */
  6886. *is_script_resource = 1;
  6887. } else if (extention_matches_template_text(conn, filename)) {
  6888. /* Substitute file is a LSP or SSI file */
  6889. *is_template_text = 1;
  6890. } else {
  6891. /* Substitute file is a regular file */
  6892. *is_script_resource = 0;
  6893. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6894. }
  6895. }
  6896. /* If there is no substitute file, the server could return
  6897. * a directory listing in a later step */
  6898. }
  6899. return;
  6900. }
  6901. /* Step 9: Check for zipped files: */
  6902. /* If we can't find the actual file, look for the file
  6903. * with the same name but a .gz extension. If we find it,
  6904. * use that and set the gzipped flag in the file struct
  6905. * to indicate that the response need to have the content-
  6906. * encoding: gzip header.
  6907. * We can only do this if the browser declares support. */
  6908. if (conn->accept_gzip) {
  6909. mg_snprintf(
  6910. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6911. if (truncated) {
  6912. goto interpret_cleanup;
  6913. }
  6914. if (mg_stat(conn, gz_path, filestat)) {
  6915. if (filestat) {
  6916. filestat->is_gzipped = 1;
  6917. *is_found = 1;
  6918. }
  6919. /* Currently gz files can not be scripts. */
  6920. return;
  6921. }
  6922. }
  6923. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6924. /* Step 10: Script resources may handle sub-resources */
  6925. /* Support PATH_INFO for CGI scripts. */
  6926. tmp_str_len = strlen(filename);
  6927. tmp_str =
  6928. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6929. if (!tmp_str) {
  6930. /* Out of memory */
  6931. goto interpret_cleanup;
  6932. }
  6933. memcpy(tmp_str, filename, tmp_str_len + 1);
  6934. /* Check config, if index scripts may have sub-resources */
  6935. allow_substitute_script_subresources =
  6936. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6937. "yes");
  6938. sep_pos = tmp_str_len;
  6939. while (sep_pos > 0) {
  6940. sep_pos--;
  6941. if (tmp_str[sep_pos] == '/') {
  6942. int is_script = 0, does_exist = 0;
  6943. tmp_str[sep_pos] = 0;
  6944. if (tmp_str[0]) {
  6945. is_script = extention_matches_script(conn, tmp_str);
  6946. does_exist = mg_stat(conn, tmp_str, filestat);
  6947. }
  6948. if (does_exist && is_script) {
  6949. filename[sep_pos] = 0;
  6950. memmove(filename + sep_pos + 2,
  6951. filename + sep_pos + 1,
  6952. strlen(filename + sep_pos + 1) + 1);
  6953. conn->path_info = filename + sep_pos + 1;
  6954. filename[sep_pos + 1] = '/';
  6955. *is_script_resource = 1;
  6956. *is_found = 1;
  6957. break;
  6958. }
  6959. if (allow_substitute_script_subresources) {
  6960. if (substitute_index_file(
  6961. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6962. /* some intermediate directory has an index file */
  6963. if (extention_matches_script(conn, tmp_str)) {
  6964. size_t script_name_len = strlen(tmp_str);
  6965. /* subres_name read before this memory locatio will be
  6966. overwritten */
  6967. char *subres_name = filename + sep_pos;
  6968. size_t subres_name_len = strlen(subres_name);
  6969. DEBUG_TRACE("Substitute script %s serving path %s",
  6970. tmp_str,
  6971. filename);
  6972. /* this index file is a script */
  6973. if ((script_name_len + subres_name_len + 2)
  6974. >= filename_buf_len) {
  6975. mg_free(tmp_str);
  6976. goto interpret_cleanup;
  6977. }
  6978. conn->path_info =
  6979. filename + script_name_len + 1; /* new target */
  6980. memmove(conn->path_info, subres_name, subres_name_len);
  6981. conn->path_info[subres_name_len] = 0;
  6982. memcpy(filename, tmp_str, script_name_len + 1);
  6983. *is_script_resource = 1;
  6984. *is_found = 1;
  6985. break;
  6986. } else {
  6987. DEBUG_TRACE("Substitute file %s serving path %s",
  6988. tmp_str,
  6989. filename);
  6990. /* non-script files will not have sub-resources */
  6991. filename[sep_pos] = 0;
  6992. conn->path_info = 0;
  6993. *is_script_resource = 0;
  6994. *is_found = 0;
  6995. break;
  6996. }
  6997. }
  6998. }
  6999. tmp_str[sep_pos] = '/';
  7000. }
  7001. }
  7002. mg_free(tmp_str);
  7003. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  7004. #endif /* !defined(NO_FILES) */
  7005. return;
  7006. #if !defined(NO_FILES)
  7007. /* Reset all outputs */
  7008. interpret_cleanup:
  7009. memset(filestat, 0, sizeof(*filestat));
  7010. *filename = 0;
  7011. *is_found = 0;
  7012. *is_script_resource = 0;
  7013. *is_websocket_request = 0;
  7014. *is_put_or_delete_request = 0;
  7015. #endif /* !defined(NO_FILES) */
  7016. }
  7017. /* Check whether full request is buffered. Return:
  7018. * -1 if request or response is malformed
  7019. * 0 if request or response is not yet fully buffered
  7020. * >0 actual request length, including last \r\n\r\n */
  7021. static int
  7022. get_http_header_len(const char *buf, int buflen)
  7023. {
  7024. int i;
  7025. for (i = 0; i < buflen; i++) {
  7026. /* Do an unsigned comparison in some conditions below */
  7027. const unsigned char c = (unsigned char)buf[i];
  7028. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7029. && !isprint(c)) {
  7030. /* abort scan as soon as one malformed character is found */
  7031. return -1;
  7032. }
  7033. if (i < buflen - 1) {
  7034. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7035. /* Two newline, no carriage return - not standard compliant,
  7036. * but it should be accepted */
  7037. return i + 2;
  7038. }
  7039. }
  7040. if (i < buflen - 3) {
  7041. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7042. && (buf[i + 3] == '\n')) {
  7043. /* Two \r\n - standard compliant */
  7044. return i + 4;
  7045. }
  7046. }
  7047. }
  7048. return 0;
  7049. }
  7050. #if !defined(NO_CACHING)
  7051. /* Convert month to the month number. Return -1 on error, or month number */
  7052. static int
  7053. get_month_index(const char *s)
  7054. {
  7055. size_t i;
  7056. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7057. if (!strcmp(s, month_names[i])) {
  7058. return (int)i;
  7059. }
  7060. }
  7061. return -1;
  7062. }
  7063. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7064. static time_t
  7065. parse_date_string(const char *datetime)
  7066. {
  7067. char month_str[32] = {0};
  7068. int second, minute, hour, day, month, year;
  7069. time_t result = (time_t)0;
  7070. struct tm tm;
  7071. if ((sscanf(datetime,
  7072. "%d/%3s/%d %d:%d:%d",
  7073. &day,
  7074. month_str,
  7075. &year,
  7076. &hour,
  7077. &minute,
  7078. &second)
  7079. == 6)
  7080. || (sscanf(datetime,
  7081. "%d %3s %d %d:%d:%d",
  7082. &day,
  7083. month_str,
  7084. &year,
  7085. &hour,
  7086. &minute,
  7087. &second)
  7088. == 6)
  7089. || (sscanf(datetime,
  7090. "%*3s, %d %3s %d %d:%d:%d",
  7091. &day,
  7092. month_str,
  7093. &year,
  7094. &hour,
  7095. &minute,
  7096. &second)
  7097. == 6)
  7098. || (sscanf(datetime,
  7099. "%d-%3s-%d %d:%d:%d",
  7100. &day,
  7101. month_str,
  7102. &year,
  7103. &hour,
  7104. &minute,
  7105. &second)
  7106. == 6)) {
  7107. month = get_month_index(month_str);
  7108. if ((month >= 0) && (year >= 1970)) {
  7109. memset(&tm, 0, sizeof(tm));
  7110. tm.tm_year = year - 1900;
  7111. tm.tm_mon = month;
  7112. tm.tm_mday = day;
  7113. tm.tm_hour = hour;
  7114. tm.tm_min = minute;
  7115. tm.tm_sec = second;
  7116. result = timegm(&tm);
  7117. }
  7118. }
  7119. return result;
  7120. }
  7121. #endif /* !NO_CACHING */
  7122. /* Pre-process URIs according to RFC + protect against directory disclosure
  7123. * attacks by removing '..', excessive '/' and '\' characters */
  7124. static void
  7125. remove_dot_segments(char *inout)
  7126. {
  7127. /* Windows backend protection
  7128. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7129. * in URI by slash */
  7130. char *out_end = inout;
  7131. char *in = inout;
  7132. if (!in) {
  7133. /* Param error. */
  7134. return;
  7135. }
  7136. while (*in) {
  7137. if (*in == '\\') {
  7138. *in = '/';
  7139. }
  7140. in++;
  7141. }
  7142. /* Algorithm "remove_dot_segments" from
  7143. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7144. /* Step 1:
  7145. * The input buffer is initialized.
  7146. * The output buffer is initialized to the empty string.
  7147. */
  7148. in = inout;
  7149. /* Step 2:
  7150. * While the input buffer is not empty, loop as follows:
  7151. */
  7152. /* Less than out_end of the inout buffer is used as output, so keep
  7153. * condition: out_end <= in */
  7154. while (*in) {
  7155. /* Step 2a:
  7156. * If the input buffer begins with a prefix of "../" or "./",
  7157. * then remove that prefix from the input buffer;
  7158. */
  7159. if (!strncmp(in, "../", 3)) {
  7160. in += 3;
  7161. } else if (!strncmp(in, "./", 2)) {
  7162. in += 2;
  7163. }
  7164. /* otherwise */
  7165. /* Step 2b:
  7166. * if the input buffer begins with a prefix of "/./" or "/.",
  7167. * where "." is a complete path segment, then replace that
  7168. * prefix with "/" in the input buffer;
  7169. */
  7170. else if (!strncmp(in, "/./", 3)) {
  7171. in += 2;
  7172. } else if (!strcmp(in, "/.")) {
  7173. in[1] = 0;
  7174. }
  7175. /* otherwise */
  7176. /* Step 2c:
  7177. * if the input buffer begins with a prefix of "/../" or "/..",
  7178. * where ".." is a complete path segment, then replace that
  7179. * prefix with "/" in the input buffer and remove the last
  7180. * segment and its preceding "/" (if any) from the output
  7181. * buffer;
  7182. */
  7183. else if (!strncmp(in, "/../", 4)) {
  7184. in += 3;
  7185. if (inout != out_end) {
  7186. /* remove last segment */
  7187. do {
  7188. out_end--;
  7189. } while ((inout != out_end) && (*out_end != '/'));
  7190. }
  7191. } else if (!strcmp(in, "/..")) {
  7192. in[1] = 0;
  7193. if (inout != out_end) {
  7194. /* remove last segment */
  7195. do {
  7196. out_end--;
  7197. } while ((inout != out_end) && (*out_end != '/'));
  7198. }
  7199. }
  7200. /* otherwise */
  7201. /* Step 2d:
  7202. * if the input buffer consists only of "." or "..", then remove
  7203. * that from the input buffer;
  7204. */
  7205. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7206. *in = 0;
  7207. }
  7208. /* otherwise */
  7209. /* Step 2e:
  7210. * move the first path segment in the input buffer to the end of
  7211. * the output buffer, including the initial "/" character (if
  7212. * any) and any subsequent characters up to, but not including,
  7213. * the next "/" character or the end of the input buffer.
  7214. */
  7215. else {
  7216. do {
  7217. *out_end = *in;
  7218. out_end++;
  7219. in++;
  7220. } while ((*in != 0) && (*in != '/'));
  7221. }
  7222. }
  7223. /* Step 3:
  7224. * Finally, the output buffer is returned as the result of
  7225. * remove_dot_segments.
  7226. */
  7227. /* Terminate output */
  7228. *out_end = 0;
  7229. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7230. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7231. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7232. * or "//" anymore.
  7233. */
  7234. out_end = in = inout;
  7235. while (*in) {
  7236. if (*in == '.') {
  7237. /* remove . at the end or preceding of / */
  7238. char *in_ahead = in;
  7239. do {
  7240. in_ahead++;
  7241. } while (*in_ahead == '.');
  7242. if (*in_ahead == '/') {
  7243. in = in_ahead;
  7244. if ((out_end != inout) && (out_end[-1] == '/')) {
  7245. /* remove generated // */
  7246. out_end--;
  7247. }
  7248. } else if (*in_ahead == 0) {
  7249. in = in_ahead;
  7250. } else {
  7251. do {
  7252. *out_end++ = '.';
  7253. in++;
  7254. } while (in != in_ahead);
  7255. }
  7256. } else if (*in == '/') {
  7257. /* replace // by / */
  7258. *out_end++ = '/';
  7259. do {
  7260. in++;
  7261. } while (*in == '/');
  7262. } else {
  7263. *out_end++ = *in;
  7264. in++;
  7265. }
  7266. }
  7267. *out_end = 0;
  7268. }
  7269. static const struct {
  7270. const char *extension;
  7271. size_t ext_len;
  7272. const char *mime_type;
  7273. } builtin_mime_types[] = {
  7274. /* IANA registered MIME types
  7275. * (http://www.iana.org/assignments/media-types)
  7276. * application types */
  7277. {".doc", 4, "application/msword"},
  7278. {".eps", 4, "application/postscript"},
  7279. {".exe", 4, "application/octet-stream"},
  7280. {".js", 3, "application/javascript"},
  7281. {".json", 5, "application/json"},
  7282. {".pdf", 4, "application/pdf"},
  7283. {".ps", 3, "application/postscript"},
  7284. {".rtf", 4, "application/rtf"},
  7285. {".xhtml", 6, "application/xhtml+xml"},
  7286. {".xsl", 4, "application/xml"},
  7287. {".xslt", 5, "application/xml"},
  7288. /* fonts */
  7289. {".ttf", 4, "application/font-sfnt"},
  7290. {".cff", 4, "application/font-sfnt"},
  7291. {".otf", 4, "application/font-sfnt"},
  7292. {".aat", 4, "application/font-sfnt"},
  7293. {".sil", 4, "application/font-sfnt"},
  7294. {".pfr", 4, "application/font-tdpfr"},
  7295. {".woff", 5, "application/font-woff"},
  7296. /* audio */
  7297. {".mp3", 4, "audio/mpeg"},
  7298. {".oga", 4, "audio/ogg"},
  7299. {".ogg", 4, "audio/ogg"},
  7300. /* image */
  7301. {".gif", 4, "image/gif"},
  7302. {".ief", 4, "image/ief"},
  7303. {".jpeg", 5, "image/jpeg"},
  7304. {".jpg", 4, "image/jpeg"},
  7305. {".jpm", 4, "image/jpm"},
  7306. {".jpx", 4, "image/jpx"},
  7307. {".png", 4, "image/png"},
  7308. {".svg", 4, "image/svg+xml"},
  7309. {".tif", 4, "image/tiff"},
  7310. {".tiff", 5, "image/tiff"},
  7311. /* model */
  7312. {".wrl", 4, "model/vrml"},
  7313. /* text */
  7314. {".css", 4, "text/css"},
  7315. {".csv", 4, "text/csv"},
  7316. {".htm", 4, "text/html"},
  7317. {".html", 5, "text/html"},
  7318. {".sgm", 4, "text/sgml"},
  7319. {".shtm", 5, "text/html"},
  7320. {".shtml", 6, "text/html"},
  7321. {".txt", 4, "text/plain"},
  7322. {".xml", 4, "text/xml"},
  7323. /* video */
  7324. {".mov", 4, "video/quicktime"},
  7325. {".mp4", 4, "video/mp4"},
  7326. {".mpeg", 5, "video/mpeg"},
  7327. {".mpg", 4, "video/mpeg"},
  7328. {".ogv", 4, "video/ogg"},
  7329. {".qt", 3, "video/quicktime"},
  7330. /* not registered types
  7331. * (http://reference.sitepoint.com/html/mime-types-full,
  7332. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7333. {".arj", 4, "application/x-arj-compressed"},
  7334. {".gz", 3, "application/x-gunzip"},
  7335. {".rar", 4, "application/x-arj-compressed"},
  7336. {".swf", 4, "application/x-shockwave-flash"},
  7337. {".tar", 4, "application/x-tar"},
  7338. {".tgz", 4, "application/x-tar-gz"},
  7339. {".torrent", 8, "application/x-bittorrent"},
  7340. {".ppt", 4, "application/x-mspowerpoint"},
  7341. {".xls", 4, "application/x-msexcel"},
  7342. {".zip", 4, "application/x-zip-compressed"},
  7343. {".aac",
  7344. 4,
  7345. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7346. {".aif", 4, "audio/x-aif"},
  7347. {".m3u", 4, "audio/x-mpegurl"},
  7348. {".mid", 4, "audio/x-midi"},
  7349. {".ra", 3, "audio/x-pn-realaudio"},
  7350. {".ram", 4, "audio/x-pn-realaudio"},
  7351. {".wav", 4, "audio/x-wav"},
  7352. {".bmp", 4, "image/bmp"},
  7353. {".ico", 4, "image/x-icon"},
  7354. {".pct", 4, "image/x-pct"},
  7355. {".pict", 5, "image/pict"},
  7356. {".rgb", 4, "image/x-rgb"},
  7357. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7358. {".asf", 4, "video/x-ms-asf"},
  7359. {".avi", 4, "video/x-msvideo"},
  7360. {".m4v", 4, "video/x-m4v"},
  7361. {NULL, 0, NULL}};
  7362. const char *
  7363. mg_get_builtin_mime_type(const char *path)
  7364. {
  7365. const char *ext;
  7366. size_t i, path_len;
  7367. path_len = strlen(path);
  7368. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7369. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7370. if ((path_len > builtin_mime_types[i].ext_len)
  7371. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7372. return builtin_mime_types[i].mime_type;
  7373. }
  7374. }
  7375. return "text/plain";
  7376. }
  7377. /* Look at the "path" extension and figure what mime type it has.
  7378. * Store mime type in the vector. */
  7379. static void
  7380. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7381. {
  7382. struct vec ext_vec, mime_vec;
  7383. const char *list, *ext;
  7384. size_t path_len;
  7385. path_len = strlen(path);
  7386. if ((conn == NULL) || (vec == NULL)) {
  7387. if (vec != NULL) {
  7388. memset(vec, '\0', sizeof(struct vec));
  7389. }
  7390. return;
  7391. }
  7392. /* Scan user-defined mime types first, in case user wants to
  7393. * override default mime types. */
  7394. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7395. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7396. /* ext now points to the path suffix */
  7397. ext = path + path_len - ext_vec.len;
  7398. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7399. *vec = mime_vec;
  7400. return;
  7401. }
  7402. }
  7403. vec->ptr = mg_get_builtin_mime_type(path);
  7404. vec->len = strlen(vec->ptr);
  7405. }
  7406. /* Stringify binary data. Output buffer must be twice as big as input,
  7407. * because each byte takes 2 bytes in string representation */
  7408. static void
  7409. bin2str(char *to, const unsigned char *p, size_t len)
  7410. {
  7411. static const char *hex = "0123456789abcdef";
  7412. for (; len--; p++) {
  7413. *to++ = hex[p[0] >> 4];
  7414. *to++ = hex[p[0] & 0x0f];
  7415. }
  7416. *to = '\0';
  7417. }
  7418. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7419. */
  7420. char *
  7421. mg_md5(char buf[33], ...)
  7422. {
  7423. md5_byte_t hash[16];
  7424. const char *p;
  7425. va_list ap;
  7426. md5_state_t ctx;
  7427. md5_init(&ctx);
  7428. va_start(ap, buf);
  7429. while ((p = va_arg(ap, const char *)) != NULL) {
  7430. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7431. }
  7432. va_end(ap);
  7433. md5_finish(&ctx, hash);
  7434. bin2str(buf, hash, sizeof(hash));
  7435. return buf;
  7436. }
  7437. /* Check the user's password, return 1 if OK */
  7438. static int
  7439. check_password(const char *method,
  7440. const char *ha1,
  7441. const char *uri,
  7442. const char *nonce,
  7443. const char *nc,
  7444. const char *cnonce,
  7445. const char *qop,
  7446. const char *response)
  7447. {
  7448. char ha2[32 + 1], expected_response[32 + 1];
  7449. /* Some of the parameters may be NULL */
  7450. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7451. || (qop == NULL) || (response == NULL)) {
  7452. return 0;
  7453. }
  7454. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7455. if (strlen(response) != 32) {
  7456. return 0;
  7457. }
  7458. mg_md5(ha2, method, ":", uri, NULL);
  7459. mg_md5(expected_response,
  7460. ha1,
  7461. ":",
  7462. nonce,
  7463. ":",
  7464. nc,
  7465. ":",
  7466. cnonce,
  7467. ":",
  7468. qop,
  7469. ":",
  7470. ha2,
  7471. NULL);
  7472. return mg_strcasecmp(response, expected_response) == 0;
  7473. }
  7474. #if !defined(NO_FILESYSTEMS)
  7475. /* Use the global passwords file, if specified by auth_gpass option,
  7476. * or search for .htpasswd in the requested directory. */
  7477. static void
  7478. open_auth_file(struct mg_connection *conn,
  7479. const char *path,
  7480. struct mg_file *filep)
  7481. {
  7482. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7483. char name[UTF8_PATH_MAX];
  7484. const char *p, *e,
  7485. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7486. int truncated;
  7487. if (gpass != NULL) {
  7488. /* Use global passwords file */
  7489. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7490. #if defined(DEBUG)
  7491. /* Use mg_cry_internal here, since gpass has been
  7492. * configured. */
  7493. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7494. #endif
  7495. }
  7496. /* Important: using local struct mg_file to test path for
  7497. * is_directory flag. If filep is used, mg_stat() makes it
  7498. * appear as if auth file was opened.
  7499. * TODO(mid): Check if this is still required after rewriting
  7500. * mg_stat */
  7501. } else if (mg_stat(conn, path, &filep->stat)
  7502. && filep->stat.is_directory) {
  7503. mg_snprintf(conn,
  7504. &truncated,
  7505. name,
  7506. sizeof(name),
  7507. "%s/%s",
  7508. path,
  7509. PASSWORDS_FILE_NAME);
  7510. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7511. #if defined(DEBUG)
  7512. /* Don't use mg_cry_internal here, but only a trace, since
  7513. * this is a typical case. It will occur for every directory
  7514. * without a password file. */
  7515. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7516. #endif
  7517. }
  7518. } else {
  7519. /* Try to find .htpasswd in requested directory. */
  7520. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7521. if (e[0] == '/') {
  7522. break;
  7523. }
  7524. }
  7525. mg_snprintf(conn,
  7526. &truncated,
  7527. name,
  7528. sizeof(name),
  7529. "%.*s/%s",
  7530. (int)(e - p),
  7531. p,
  7532. PASSWORDS_FILE_NAME);
  7533. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7534. #if defined(DEBUG)
  7535. /* Don't use mg_cry_internal here, but only a trace, since
  7536. * this is a typical case. It will occur for every directory
  7537. * without a password file. */
  7538. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7539. #endif
  7540. }
  7541. }
  7542. }
  7543. }
  7544. #endif /* NO_FILESYSTEMS */
  7545. /* Parsed Authorization header */
  7546. struct ah {
  7547. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7548. };
  7549. /* Return 1 on success. Always initializes the ah structure. */
  7550. static int
  7551. parse_auth_header(struct mg_connection *conn,
  7552. char *buf,
  7553. size_t buf_size,
  7554. struct ah *ah)
  7555. {
  7556. char *name, *value, *s;
  7557. const char *auth_header;
  7558. uint64_t nonce;
  7559. if (!ah || !conn) {
  7560. return 0;
  7561. }
  7562. (void)memset(ah, 0, sizeof(*ah));
  7563. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7564. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7565. return 0;
  7566. }
  7567. /* Make modifiable copy of the auth header */
  7568. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7569. s = buf;
  7570. /* Parse authorization header */
  7571. for (;;) {
  7572. /* Gobble initial spaces */
  7573. while (isspace((unsigned char)*s)) {
  7574. s++;
  7575. }
  7576. name = skip_quoted(&s, "=", " ", 0);
  7577. /* Value is either quote-delimited, or ends at first comma or space.
  7578. */
  7579. if (s[0] == '\"') {
  7580. s++;
  7581. value = skip_quoted(&s, "\"", " ", '\\');
  7582. if (s[0] == ',') {
  7583. s++;
  7584. }
  7585. } else {
  7586. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7587. * uses spaces */
  7588. }
  7589. if (*name == '\0') {
  7590. break;
  7591. }
  7592. if (!strcmp(name, "username")) {
  7593. ah->user = value;
  7594. } else if (!strcmp(name, "cnonce")) {
  7595. ah->cnonce = value;
  7596. } else if (!strcmp(name, "response")) {
  7597. ah->response = value;
  7598. } else if (!strcmp(name, "uri")) {
  7599. ah->uri = value;
  7600. } else if (!strcmp(name, "qop")) {
  7601. ah->qop = value;
  7602. } else if (!strcmp(name, "nc")) {
  7603. ah->nc = value;
  7604. } else if (!strcmp(name, "nonce")) {
  7605. ah->nonce = value;
  7606. }
  7607. }
  7608. #if !defined(NO_NONCE_CHECK)
  7609. /* Read the nonce from the response. */
  7610. if (ah->nonce == NULL) {
  7611. return 0;
  7612. }
  7613. s = NULL;
  7614. nonce = strtoull(ah->nonce, &s, 10);
  7615. if ((s == NULL) || (*s != 0)) {
  7616. return 0;
  7617. }
  7618. /* Convert the nonce from the client to a number. */
  7619. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7620. /* The converted number corresponds to the time the nounce has been
  7621. * created. This should not be earlier than the server start. */
  7622. /* Server side nonce check is valuable in all situations but one:
  7623. * if the server restarts frequently, but the client should not see
  7624. * that, so the server should accept nonces from previous starts. */
  7625. /* However, the reasonable default is to not accept a nonce from a
  7626. * previous start, so if anyone changed the access rights between
  7627. * two restarts, a new login is required. */
  7628. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7629. /* nonce is from a previous start of the server and no longer valid
  7630. * (replay attack?) */
  7631. return 0;
  7632. }
  7633. /* Check if the nonce is too high, so it has not (yet) been used by the
  7634. * server. */
  7635. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7636. + conn->dom_ctx->nonce_count)) {
  7637. return 0;
  7638. }
  7639. #else
  7640. (void)nonce;
  7641. #endif
  7642. /* CGI needs it as REMOTE_USER */
  7643. if (ah->user != NULL) {
  7644. conn->request_info.remote_user =
  7645. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7646. } else {
  7647. return 0;
  7648. }
  7649. return 1;
  7650. }
  7651. static const char *
  7652. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7653. {
  7654. if (!filep) {
  7655. return NULL;
  7656. }
  7657. if (filep->access.fp != NULL) {
  7658. return fgets(buf, (int)size, filep->access.fp);
  7659. } else {
  7660. return NULL;
  7661. }
  7662. }
  7663. /* Define the initial recursion depth for procesesing htpasswd files that
  7664. * include other htpasswd
  7665. * (or even the same) files. It is not difficult to provide a file or files
  7666. * s.t. they force civetweb
  7667. * to infinitely recurse and then crash.
  7668. */
  7669. #define INITIAL_DEPTH 9
  7670. #if INITIAL_DEPTH <= 0
  7671. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7672. #endif
  7673. #if !defined(NO_FILESYSTEMS)
  7674. struct read_auth_file_struct {
  7675. struct mg_connection *conn;
  7676. struct ah ah;
  7677. const char *domain;
  7678. char buf[256 + 256 + 40];
  7679. const char *f_user;
  7680. const char *f_domain;
  7681. const char *f_ha1;
  7682. };
  7683. static int
  7684. read_auth_file(struct mg_file *filep,
  7685. struct read_auth_file_struct *workdata,
  7686. int depth)
  7687. {
  7688. int is_authorized = 0;
  7689. struct mg_file fp;
  7690. size_t l;
  7691. if (!filep || !workdata || (0 == depth)) {
  7692. return 0;
  7693. }
  7694. /* Loop over passwords file */
  7695. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7696. l = strlen(workdata->buf);
  7697. while (l > 0) {
  7698. if (isspace((unsigned char)workdata->buf[l - 1])
  7699. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7700. l--;
  7701. workdata->buf[l] = 0;
  7702. } else
  7703. break;
  7704. }
  7705. if (l < 1) {
  7706. continue;
  7707. }
  7708. workdata->f_user = workdata->buf;
  7709. if (workdata->f_user[0] == ':') {
  7710. /* user names may not contain a ':' and may not be empty,
  7711. * so lines starting with ':' may be used for a special purpose
  7712. */
  7713. if (workdata->f_user[1] == '#') {
  7714. /* :# is a comment */
  7715. continue;
  7716. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7717. if (mg_fopen(workdata->conn,
  7718. workdata->f_user + 9,
  7719. MG_FOPEN_MODE_READ,
  7720. &fp)) {
  7721. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7722. (void)mg_fclose(
  7723. &fp.access); /* ignore error on read only file */
  7724. /* No need to continue processing files once we have a
  7725. * match, since nothing will reset it back
  7726. * to 0.
  7727. */
  7728. if (is_authorized) {
  7729. return is_authorized;
  7730. }
  7731. } else {
  7732. mg_cry_internal(workdata->conn,
  7733. "%s: cannot open authorization file: %s",
  7734. __func__,
  7735. workdata->buf);
  7736. }
  7737. continue;
  7738. }
  7739. /* everything is invalid for the moment (might change in the
  7740. * future) */
  7741. mg_cry_internal(workdata->conn,
  7742. "%s: syntax error in authorization file: %s",
  7743. __func__,
  7744. workdata->buf);
  7745. continue;
  7746. }
  7747. workdata->f_domain = strchr(workdata->f_user, ':');
  7748. if (workdata->f_domain == NULL) {
  7749. mg_cry_internal(workdata->conn,
  7750. "%s: syntax error in authorization file: %s",
  7751. __func__,
  7752. workdata->buf);
  7753. continue;
  7754. }
  7755. *(char *)(workdata->f_domain) = 0;
  7756. (workdata->f_domain)++;
  7757. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7758. if (workdata->f_ha1 == NULL) {
  7759. mg_cry_internal(workdata->conn,
  7760. "%s: syntax error in authorization file: %s",
  7761. __func__,
  7762. workdata->buf);
  7763. continue;
  7764. }
  7765. *(char *)(workdata->f_ha1) = 0;
  7766. (workdata->f_ha1)++;
  7767. if (!strcmp(workdata->ah.user, workdata->f_user)
  7768. && !strcmp(workdata->domain, workdata->f_domain)) {
  7769. return check_password(workdata->conn->request_info.request_method,
  7770. workdata->f_ha1,
  7771. workdata->ah.uri,
  7772. workdata->ah.nonce,
  7773. workdata->ah.nc,
  7774. workdata->ah.cnonce,
  7775. workdata->ah.qop,
  7776. workdata->ah.response);
  7777. }
  7778. }
  7779. return is_authorized;
  7780. }
  7781. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7782. static int
  7783. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7784. {
  7785. struct read_auth_file_struct workdata;
  7786. char buf[MG_BUF_LEN];
  7787. if (!conn || !conn->dom_ctx) {
  7788. return 0;
  7789. }
  7790. memset(&workdata, 0, sizeof(workdata));
  7791. workdata.conn = conn;
  7792. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7793. return 0;
  7794. }
  7795. if (realm) {
  7796. workdata.domain = realm;
  7797. } else {
  7798. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7799. }
  7800. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7801. }
  7802. /* Public function to check http digest authentication header */
  7803. int
  7804. mg_check_digest_access_authentication(struct mg_connection *conn,
  7805. const char *realm,
  7806. const char *filename)
  7807. {
  7808. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7809. int auth;
  7810. if (!conn || !filename) {
  7811. return -1;
  7812. }
  7813. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7814. return -2;
  7815. }
  7816. auth = authorize(conn, &file, realm);
  7817. mg_fclose(&file.access);
  7818. return auth;
  7819. }
  7820. #endif /* NO_FILESYSTEMS */
  7821. /* Return 1 if request is authorised, 0 otherwise. */
  7822. static int
  7823. check_authorization(struct mg_connection *conn, const char *path)
  7824. {
  7825. #if !defined(NO_FILESYSTEMS)
  7826. char fname[UTF8_PATH_MAX];
  7827. struct vec uri_vec, filename_vec;
  7828. const char *list;
  7829. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7830. int authorized = 1, truncated;
  7831. if (!conn || !conn->dom_ctx) {
  7832. return 0;
  7833. }
  7834. list = conn->dom_ctx->config[PROTECT_URI];
  7835. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7836. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7837. mg_snprintf(conn,
  7838. &truncated,
  7839. fname,
  7840. sizeof(fname),
  7841. "%.*s",
  7842. (int)filename_vec.len,
  7843. filename_vec.ptr);
  7844. if (truncated
  7845. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7846. mg_cry_internal(conn,
  7847. "%s: cannot open %s: %s",
  7848. __func__,
  7849. fname,
  7850. strerror(errno));
  7851. }
  7852. break;
  7853. }
  7854. }
  7855. if (!is_file_opened(&file.access)) {
  7856. open_auth_file(conn, path, &file);
  7857. }
  7858. if (is_file_opened(&file.access)) {
  7859. authorized = authorize(conn, &file, NULL);
  7860. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7861. }
  7862. return authorized;
  7863. #else
  7864. (void)conn;
  7865. (void)path;
  7866. return 1;
  7867. #endif /* NO_FILESYSTEMS */
  7868. }
  7869. /* Internal function. Assumes conn is valid */
  7870. static void
  7871. send_authorization_request(struct mg_connection *conn, const char *realm)
  7872. {
  7873. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7874. int trunc = 0;
  7875. char buf[128];
  7876. if (!realm) {
  7877. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7878. }
  7879. mg_lock_context(conn->phys_ctx);
  7880. nonce += conn->dom_ctx->nonce_count;
  7881. ++conn->dom_ctx->nonce_count;
  7882. mg_unlock_context(conn->phys_ctx);
  7883. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7884. conn->must_close = 1;
  7885. /* Create 401 response */
  7886. mg_response_header_start(conn, 401);
  7887. send_no_cache_header(conn);
  7888. send_additional_header(conn);
  7889. mg_response_header_add(conn, "Content-Length", "0", -1);
  7890. /* Content for "WWW-Authenticate" header */
  7891. mg_snprintf(conn,
  7892. &trunc,
  7893. buf,
  7894. sizeof(buf),
  7895. "Digest qop=\"auth\", realm=\"%s\", "
  7896. "nonce=\"%" UINT64_FMT "\"",
  7897. realm,
  7898. nonce);
  7899. if (!trunc) {
  7900. /* !trunc should always be true */
  7901. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7902. }
  7903. /* Send all headers */
  7904. mg_response_header_send(conn);
  7905. }
  7906. /* Interface function. Parameters are provided by the user, so do
  7907. * at least some basic checks.
  7908. */
  7909. int
  7910. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7911. const char *realm)
  7912. {
  7913. if (conn && conn->dom_ctx) {
  7914. send_authorization_request(conn, realm);
  7915. return 0;
  7916. }
  7917. return -1;
  7918. }
  7919. #if !defined(NO_FILES)
  7920. static int
  7921. is_authorized_for_put(struct mg_connection *conn)
  7922. {
  7923. if (conn) {
  7924. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7925. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7926. int ret = 0;
  7927. if (passfile != NULL
  7928. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7929. ret = authorize(conn, &file, NULL);
  7930. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7931. }
  7932. return ret;
  7933. }
  7934. return 0;
  7935. }
  7936. #endif
  7937. int
  7938. mg_modify_passwords_file(const char *fname,
  7939. const char *domain,
  7940. const char *user,
  7941. const char *pass)
  7942. {
  7943. int found, i;
  7944. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[UTF8_PATH_MAX + 8];
  7945. FILE *fp, *fp2;
  7946. found = 0;
  7947. fp = fp2 = NULL;
  7948. /* Regard empty password as no password - remove user record. */
  7949. if ((pass != NULL) && (pass[0] == '\0')) {
  7950. pass = NULL;
  7951. }
  7952. /* Other arguments must not be empty */
  7953. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7954. return 0;
  7955. }
  7956. /* Using the given file format, user name and domain must not contain
  7957. * ':'
  7958. */
  7959. if (strchr(user, ':') != NULL) {
  7960. return 0;
  7961. }
  7962. if (strchr(domain, ':') != NULL) {
  7963. return 0;
  7964. }
  7965. /* Do not allow control characters like newline in user name and domain.
  7966. * Do not allow excessively long names either. */
  7967. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7968. if (iscntrl((unsigned char)user[i])) {
  7969. return 0;
  7970. }
  7971. }
  7972. if (user[i]) {
  7973. return 0;
  7974. }
  7975. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7976. if (iscntrl((unsigned char)domain[i])) {
  7977. return 0;
  7978. }
  7979. }
  7980. if (domain[i]) {
  7981. return 0;
  7982. }
  7983. /* The maximum length of the path to the password file is limited */
  7984. if ((strlen(fname) + 4) >= UTF8_PATH_MAX) {
  7985. return 0;
  7986. }
  7987. /* Create a temporary file name. Length has been checked before. */
  7988. strcpy(tmp, fname);
  7989. strcat(tmp, ".tmp");
  7990. /* Create the file if does not exist */
  7991. /* Use of fopen here is OK, since fname is only ASCII */
  7992. if ((fp = fopen(fname, "a+")) != NULL) {
  7993. (void)fclose(fp);
  7994. }
  7995. /* Open the given file and temporary file */
  7996. if ((fp = fopen(fname, "r")) == NULL) {
  7997. return 0;
  7998. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7999. fclose(fp);
  8000. return 0;
  8001. }
  8002. /* Copy the stuff to temporary file */
  8003. while (fgets(line, sizeof(line), fp) != NULL) {
  8004. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  8005. continue;
  8006. }
  8007. u[255] = 0;
  8008. d[255] = 0;
  8009. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8010. found++;
  8011. if (pass != NULL) {
  8012. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  8013. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  8014. }
  8015. } else {
  8016. fprintf(fp2, "%s", line);
  8017. }
  8018. }
  8019. /* If new user, just add it */
  8020. if (!found && (pass != NULL)) {
  8021. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  8022. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  8023. }
  8024. /* Close files */
  8025. fclose(fp);
  8026. fclose(fp2);
  8027. /* Put the temp file in place of real file */
  8028. IGNORE_UNUSED_RESULT(remove(fname));
  8029. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  8030. return 1;
  8031. }
  8032. static int
  8033. is_valid_port(unsigned long port)
  8034. {
  8035. return (port <= 0xffff);
  8036. }
  8037. static int
  8038. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8039. {
  8040. struct addrinfo hints, *res, *ressave;
  8041. int func_ret = 0;
  8042. int gai_ret;
  8043. memset(&hints, 0, sizeof(struct addrinfo));
  8044. hints.ai_family = af;
  8045. if (!resolve_src) {
  8046. hints.ai_flags = AI_NUMERICHOST;
  8047. }
  8048. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8049. if (gai_ret != 0) {
  8050. /* gai_strerror could be used to convert gai_ret to a string */
  8051. /* POSIX return values: see
  8052. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8053. */
  8054. /* Windows return values: see
  8055. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8056. */
  8057. return 0;
  8058. }
  8059. ressave = res;
  8060. while (res) {
  8061. if ((dstlen >= (size_t)res->ai_addrlen)
  8062. && (res->ai_addr->sa_family == af)) {
  8063. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8064. func_ret = 1;
  8065. }
  8066. res = res->ai_next;
  8067. }
  8068. freeaddrinfo(ressave);
  8069. return func_ret;
  8070. }
  8071. static int
  8072. connect_socket(struct mg_context *ctx /* may be NULL */,
  8073. const char *host,
  8074. int port,
  8075. int use_ssl,
  8076. char *ebuf,
  8077. size_t ebuf_len,
  8078. SOCKET *sock /* output: socket, must not be NULL */,
  8079. union usa *sa /* output: socket address, must not be NULL */
  8080. )
  8081. {
  8082. int ip_ver = 0;
  8083. int conn_ret = -1;
  8084. int sockerr = 0;
  8085. *sock = INVALID_SOCKET;
  8086. memset(sa, 0, sizeof(*sa));
  8087. if (ebuf_len > 0) {
  8088. *ebuf = 0;
  8089. }
  8090. if (host == NULL) {
  8091. mg_snprintf(NULL,
  8092. NULL, /* No truncation check for ebuf */
  8093. ebuf,
  8094. ebuf_len,
  8095. "%s",
  8096. "NULL host");
  8097. return 0;
  8098. }
  8099. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8100. mg_snprintf(NULL,
  8101. NULL, /* No truncation check for ebuf */
  8102. ebuf,
  8103. ebuf_len,
  8104. "%s",
  8105. "invalid port");
  8106. return 0;
  8107. }
  8108. #if !defined(NO_SSL)
  8109. #if !defined(NO_SSL_DL)
  8110. #if defined(OPENSSL_API_1_1)
  8111. if (use_ssl && (TLS_client_method == NULL)) {
  8112. mg_snprintf(NULL,
  8113. NULL, /* No truncation check for ebuf */
  8114. ebuf,
  8115. ebuf_len,
  8116. "%s",
  8117. "SSL is not initialized");
  8118. return 0;
  8119. }
  8120. #else
  8121. if (use_ssl && (SSLv23_client_method == NULL)) {
  8122. mg_snprintf(NULL,
  8123. NULL, /* No truncation check for ebuf */
  8124. ebuf,
  8125. ebuf_len,
  8126. "%s",
  8127. "SSL is not initialized");
  8128. return 0;
  8129. }
  8130. #endif /* OPENSSL_API_1_1 */
  8131. #else
  8132. (void)use_ssl;
  8133. #endif /* NO_SSL_DL */
  8134. #else
  8135. (void)use_ssl;
  8136. #endif /* !defined(NO_SSL) */
  8137. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8138. sa->sin.sin_port = htons((uint16_t)port);
  8139. ip_ver = 4;
  8140. #if defined(USE_IPV6)
  8141. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8142. sa->sin6.sin6_port = htons((uint16_t)port);
  8143. ip_ver = 6;
  8144. } else if (host[0] == '[') {
  8145. /* While getaddrinfo on Windows will work with [::1],
  8146. * getaddrinfo on Linux only works with ::1 (without []). */
  8147. size_t l = strlen(host + 1);
  8148. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8149. if (h) {
  8150. h[l - 1] = 0;
  8151. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8152. sa->sin6.sin6_port = htons((uint16_t)port);
  8153. ip_ver = 6;
  8154. }
  8155. mg_free(h);
  8156. }
  8157. #endif
  8158. }
  8159. if (ip_ver == 0) {
  8160. mg_snprintf(NULL,
  8161. NULL, /* No truncation check for ebuf */
  8162. ebuf,
  8163. ebuf_len,
  8164. "%s",
  8165. "host not found");
  8166. return 0;
  8167. }
  8168. if (ip_ver == 4) {
  8169. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8170. }
  8171. #if defined(USE_IPV6)
  8172. else if (ip_ver == 6) {
  8173. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8174. }
  8175. #endif
  8176. #if 0 /* Not available as client */
  8177. #if defined(USE_X_DOM_SOCKET)
  8178. else if (ip_ver == 99) {
  8179. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8180. }
  8181. #endif
  8182. #endif
  8183. if (*sock == INVALID_SOCKET) {
  8184. mg_snprintf(NULL,
  8185. NULL, /* No truncation check for ebuf */
  8186. ebuf,
  8187. ebuf_len,
  8188. "socket(): %s",
  8189. strerror(ERRNO));
  8190. return 0;
  8191. }
  8192. if (0 != set_non_blocking_mode(*sock)) {
  8193. mg_snprintf(NULL,
  8194. NULL, /* No truncation check for ebuf */
  8195. ebuf,
  8196. ebuf_len,
  8197. "Cannot set socket to non-blocking: %s",
  8198. strerror(ERRNO));
  8199. closesocket(*sock);
  8200. *sock = INVALID_SOCKET;
  8201. return 0;
  8202. }
  8203. set_close_on_exec(*sock, NULL, ctx);
  8204. if (ip_ver == 4) {
  8205. /* connected with IPv4 */
  8206. conn_ret = connect(*sock,
  8207. (struct sockaddr *)((void *)&sa->sin),
  8208. sizeof(sa->sin));
  8209. }
  8210. #if defined(USE_IPV6)
  8211. else if (ip_ver == 6) {
  8212. /* connected with IPv6 */
  8213. conn_ret = connect(*sock,
  8214. (struct sockaddr *)((void *)&sa->sin6),
  8215. sizeof(sa->sin6));
  8216. }
  8217. #endif
  8218. if (conn_ret != 0) {
  8219. sockerr = ERRNO;
  8220. }
  8221. #if defined(_WIN32)
  8222. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8223. #else
  8224. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8225. #endif
  8226. /* Data for getsockopt */
  8227. void *psockerr = &sockerr;
  8228. int ret;
  8229. #if defined(_WIN32)
  8230. int len = (int)sizeof(sockerr);
  8231. #else
  8232. socklen_t len = (socklen_t)sizeof(sockerr);
  8233. #endif
  8234. /* Data for poll */
  8235. struct mg_pollfd pfd[1];
  8236. int pollres;
  8237. int ms_wait = 10000; /* 10 second timeout */
  8238. stop_flag_t nonstop;
  8239. STOP_FLAG_ASSIGN(&nonstop, 0);
  8240. /* For a non-blocking socket, the connect sequence is:
  8241. * 1) call connect (will not block)
  8242. * 2) wait until the socket is ready for writing (select or poll)
  8243. * 3) check connection state with getsockopt
  8244. */
  8245. pfd[0].fd = *sock;
  8246. pfd[0].events = POLLOUT;
  8247. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8248. if (pollres != 1) {
  8249. /* Not connected */
  8250. mg_snprintf(NULL,
  8251. NULL, /* No truncation check for ebuf */
  8252. ebuf,
  8253. ebuf_len,
  8254. "connect(%s:%d): timeout",
  8255. host,
  8256. port);
  8257. closesocket(*sock);
  8258. *sock = INVALID_SOCKET;
  8259. return 0;
  8260. }
  8261. #if defined(_WIN32)
  8262. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8263. #else
  8264. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8265. #endif
  8266. if ((ret == 0) && (sockerr == 0)) {
  8267. conn_ret = 0;
  8268. }
  8269. }
  8270. if (conn_ret != 0) {
  8271. /* Not connected */
  8272. mg_snprintf(NULL,
  8273. NULL, /* No truncation check for ebuf */
  8274. ebuf,
  8275. ebuf_len,
  8276. "connect(%s:%d): error %s",
  8277. host,
  8278. port,
  8279. strerror(sockerr));
  8280. closesocket(*sock);
  8281. *sock = INVALID_SOCKET;
  8282. return 0;
  8283. }
  8284. return 1;
  8285. }
  8286. int
  8287. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8288. {
  8289. static const char *dont_escape = "._-$,;~()";
  8290. static const char *hex = "0123456789abcdef";
  8291. char *pos = dst;
  8292. const char *end = dst + dst_len - 1;
  8293. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8294. if (isalnum((unsigned char)*src)
  8295. || (strchr(dont_escape, *src) != NULL)) {
  8296. *pos = *src;
  8297. } else if (pos + 2 < end) {
  8298. pos[0] = '%';
  8299. pos[1] = hex[(unsigned char)*src >> 4];
  8300. pos[2] = hex[(unsigned char)*src & 0xf];
  8301. pos += 2;
  8302. } else {
  8303. break;
  8304. }
  8305. }
  8306. *pos = '\0';
  8307. return (*src == '\0') ? (int)(pos - dst) : -1;
  8308. }
  8309. /* Return 0 on success, non-zero if an error occurs. */
  8310. static int
  8311. print_dir_entry(struct de *de)
  8312. {
  8313. size_t namesize, escsize, i;
  8314. char *href, *esc, *p;
  8315. char size[64], mod[64];
  8316. #if defined(REENTRANT_TIME)
  8317. struct tm _tm;
  8318. struct tm *tm = &_tm;
  8319. #else
  8320. struct tm *tm;
  8321. #endif
  8322. /* Estimate worst case size for encoding and escaping */
  8323. namesize = strlen(de->file_name) + 1;
  8324. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8325. href = (char *)mg_malloc(namesize * 3 + escsize);
  8326. if (href == NULL) {
  8327. return -1;
  8328. }
  8329. mg_url_encode(de->file_name, href, namesize * 3);
  8330. esc = NULL;
  8331. if (escsize > 0) {
  8332. /* HTML escaping needed */
  8333. esc = href + namesize * 3;
  8334. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8335. mg_strlcpy(p, de->file_name + i, 2);
  8336. if (*p == '&') {
  8337. strcpy(p, "&amp;");
  8338. } else if (*p == '<') {
  8339. strcpy(p, "&lt;");
  8340. } else if (*p == '>') {
  8341. strcpy(p, "&gt;");
  8342. }
  8343. }
  8344. }
  8345. if (de->file.is_directory) {
  8346. mg_snprintf(de->conn,
  8347. NULL, /* Buffer is big enough */
  8348. size,
  8349. sizeof(size),
  8350. "%s",
  8351. "[DIRECTORY]");
  8352. } else {
  8353. /* We use (signed) cast below because MSVC 6 compiler cannot
  8354. * convert unsigned __int64 to double. Sigh. */
  8355. if (de->file.size < 1024) {
  8356. mg_snprintf(de->conn,
  8357. NULL, /* Buffer is big enough */
  8358. size,
  8359. sizeof(size),
  8360. "%d",
  8361. (int)de->file.size);
  8362. } else if (de->file.size < 0x100000) {
  8363. mg_snprintf(de->conn,
  8364. NULL, /* Buffer is big enough */
  8365. size,
  8366. sizeof(size),
  8367. "%.1fk",
  8368. (double)de->file.size / 1024.0);
  8369. } else if (de->file.size < 0x40000000) {
  8370. mg_snprintf(de->conn,
  8371. NULL, /* Buffer is big enough */
  8372. size,
  8373. sizeof(size),
  8374. "%.1fM",
  8375. (double)de->file.size / 1048576);
  8376. } else {
  8377. mg_snprintf(de->conn,
  8378. NULL, /* Buffer is big enough */
  8379. size,
  8380. sizeof(size),
  8381. "%.1fG",
  8382. (double)de->file.size / 1073741824);
  8383. }
  8384. }
  8385. /* Note: mg_snprintf will not cause a buffer overflow above.
  8386. * So, string truncation checks are not required here. */
  8387. #if defined(REENTRANT_TIME)
  8388. localtime_r(&de->file.last_modified, tm);
  8389. #else
  8390. tm = localtime(&de->file.last_modified);
  8391. #endif
  8392. if (tm != NULL) {
  8393. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8394. } else {
  8395. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8396. mod[sizeof(mod) - 1] = '\0';
  8397. }
  8398. mg_printf(de->conn,
  8399. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8400. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8401. href,
  8402. de->file.is_directory ? "/" : "",
  8403. esc ? esc : de->file_name,
  8404. de->file.is_directory ? "/" : "",
  8405. mod,
  8406. size);
  8407. mg_free(href);
  8408. return 0;
  8409. }
  8410. /* This function is called from send_directory() and used for
  8411. * sorting directory entries by size, or name, or modification time.
  8412. * On windows, __cdecl specification is needed in case if project is built
  8413. * with __stdcall convention. qsort always requires __cdels callback. */
  8414. static int WINCDECL
  8415. compare_dir_entries(const void *p1, const void *p2)
  8416. {
  8417. if (p1 && p2) {
  8418. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8419. const char *query_string = a->conn->request_info.query_string;
  8420. int cmp_result = 0;
  8421. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8422. query_string = "n";
  8423. }
  8424. if (a->file.is_directory && !b->file.is_directory) {
  8425. return -1; /* Always put directories on top */
  8426. } else if (!a->file.is_directory && b->file.is_directory) {
  8427. return 1; /* Always put directories on top */
  8428. } else if (*query_string == 'n') {
  8429. cmp_result = strcmp(a->file_name, b->file_name);
  8430. } else if (*query_string == 's') {
  8431. cmp_result = (a->file.size == b->file.size)
  8432. ? 0
  8433. : ((a->file.size > b->file.size) ? 1 : -1);
  8434. } else if (*query_string == 'd') {
  8435. cmp_result =
  8436. (a->file.last_modified == b->file.last_modified)
  8437. ? 0
  8438. : ((a->file.last_modified > b->file.last_modified) ? 1
  8439. : -1);
  8440. }
  8441. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8442. }
  8443. return 0;
  8444. }
  8445. static int
  8446. must_hide_file(struct mg_connection *conn, const char *path)
  8447. {
  8448. if (conn && conn->dom_ctx) {
  8449. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8450. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8451. return (match_prefix_strlen(pw_pattern, path) > 0)
  8452. || (match_prefix_strlen(pattern, path) > 0);
  8453. }
  8454. return 0;
  8455. }
  8456. #if !defined(NO_FILESYSTEMS)
  8457. static int
  8458. scan_directory(struct mg_connection *conn,
  8459. const char *dir,
  8460. void *data,
  8461. int (*cb)(struct de *, void *))
  8462. {
  8463. char path[UTF8_PATH_MAX];
  8464. struct dirent *dp;
  8465. DIR *dirp;
  8466. struct de de;
  8467. int truncated;
  8468. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8469. return 0;
  8470. } else {
  8471. de.conn = conn;
  8472. while ((dp = mg_readdir(dirp)) != NULL) {
  8473. /* Do not show current dir and hidden files */
  8474. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8475. || must_hide_file(conn, dp->d_name)) {
  8476. continue;
  8477. }
  8478. mg_snprintf(
  8479. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8480. /* If we don't memset stat structure to zero, mtime will have
  8481. * garbage and strftime() will segfault later on in
  8482. * print_dir_entry(). memset is required only if mg_stat()
  8483. * fails. For more details, see
  8484. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8485. memset(&de.file, 0, sizeof(de.file));
  8486. if (truncated) {
  8487. /* If the path is not complete, skip processing. */
  8488. continue;
  8489. }
  8490. if (!mg_stat(conn, path, &de.file)) {
  8491. mg_cry_internal(conn,
  8492. "%s: mg_stat(%s) failed: %s",
  8493. __func__,
  8494. path,
  8495. strerror(ERRNO));
  8496. }
  8497. de.file_name = dp->d_name;
  8498. if (cb(&de, data)) {
  8499. /* stopped */
  8500. break;
  8501. }
  8502. }
  8503. (void)mg_closedir(dirp);
  8504. }
  8505. return 1;
  8506. }
  8507. #endif /* NO_FILESYSTEMS */
  8508. #if !defined(NO_FILES)
  8509. static int
  8510. remove_directory(struct mg_connection *conn, const char *dir)
  8511. {
  8512. char path[UTF8_PATH_MAX];
  8513. struct dirent *dp;
  8514. DIR *dirp;
  8515. struct de de;
  8516. int truncated;
  8517. int ok = 1;
  8518. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8519. return 0;
  8520. } else {
  8521. de.conn = conn;
  8522. while ((dp = mg_readdir(dirp)) != NULL) {
  8523. /* Do not show current dir (but show hidden files as they will
  8524. * also be removed) */
  8525. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8526. continue;
  8527. }
  8528. mg_snprintf(
  8529. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8530. /* If we don't memset stat structure to zero, mtime will have
  8531. * garbage and strftime() will segfault later on in
  8532. * print_dir_entry(). memset is required only if mg_stat()
  8533. * fails. For more details, see
  8534. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8535. memset(&de.file, 0, sizeof(de.file));
  8536. if (truncated) {
  8537. /* Do not delete anything shorter */
  8538. ok = 0;
  8539. continue;
  8540. }
  8541. if (!mg_stat(conn, path, &de.file)) {
  8542. mg_cry_internal(conn,
  8543. "%s: mg_stat(%s) failed: %s",
  8544. __func__,
  8545. path,
  8546. strerror(ERRNO));
  8547. ok = 0;
  8548. }
  8549. if (de.file.is_directory) {
  8550. if (remove_directory(conn, path) == 0) {
  8551. ok = 0;
  8552. }
  8553. } else {
  8554. /* This will fail file is the file is in memory */
  8555. if (mg_remove(conn, path) == 0) {
  8556. ok = 0;
  8557. }
  8558. }
  8559. }
  8560. (void)mg_closedir(dirp);
  8561. IGNORE_UNUSED_RESULT(rmdir(dir));
  8562. }
  8563. return ok;
  8564. }
  8565. #endif
  8566. struct dir_scan_data {
  8567. struct de *entries;
  8568. size_t num_entries;
  8569. size_t arr_size;
  8570. };
  8571. #if !defined(NO_FILESYSTEMS)
  8572. static int
  8573. dir_scan_callback(struct de *de, void *data)
  8574. {
  8575. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8576. struct de *entries = dsd->entries;
  8577. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8578. /* Here "entries" is a temporary pointer and can be replaced,
  8579. * "dsd->entries" is the original pointer */
  8580. entries =
  8581. (struct de *)mg_realloc(entries,
  8582. dsd->arr_size * 2 * sizeof(entries[0]));
  8583. if (entries == NULL) {
  8584. /* stop scan */
  8585. return 1;
  8586. }
  8587. dsd->entries = entries;
  8588. dsd->arr_size *= 2;
  8589. }
  8590. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8591. if (entries[dsd->num_entries].file_name == NULL) {
  8592. /* stop scan */
  8593. return 1;
  8594. }
  8595. entries[dsd->num_entries].file = de->file;
  8596. entries[dsd->num_entries].conn = de->conn;
  8597. dsd->num_entries++;
  8598. return 0;
  8599. }
  8600. static void
  8601. handle_directory_request(struct mg_connection *conn, const char *dir)
  8602. {
  8603. size_t i;
  8604. int sort_direction;
  8605. struct dir_scan_data data = {NULL, 0, 128};
  8606. char date[64], *esc, *p;
  8607. const char *title;
  8608. time_t curtime = time(NULL);
  8609. if (!conn) {
  8610. return;
  8611. }
  8612. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8613. mg_send_http_error(conn,
  8614. 500,
  8615. "Error: Cannot open directory\nopendir(%s): %s",
  8616. dir,
  8617. strerror(ERRNO));
  8618. return;
  8619. }
  8620. gmt_time_string(date, sizeof(date), &curtime);
  8621. esc = NULL;
  8622. title = conn->request_info.local_uri;
  8623. if (title[strcspn(title, "&<>")]) {
  8624. /* HTML escaping needed */
  8625. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8626. if (esc) {
  8627. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8628. mg_strlcpy(p, title + i, 2);
  8629. if (*p == '&') {
  8630. strcpy(p, "&amp;");
  8631. } else if (*p == '<') {
  8632. strcpy(p, "&lt;");
  8633. } else if (*p == '>') {
  8634. strcpy(p, "&gt;");
  8635. }
  8636. }
  8637. } else {
  8638. title = "";
  8639. }
  8640. }
  8641. sort_direction = ((conn->request_info.query_string != NULL)
  8642. && (conn->request_info.query_string[0] != '\0')
  8643. && (conn->request_info.query_string[1] == 'd'))
  8644. ? 'a'
  8645. : 'd';
  8646. conn->must_close = 1;
  8647. /* Create 200 OK response */
  8648. mg_response_header_start(conn, 200);
  8649. send_static_cache_header(conn);
  8650. send_additional_header(conn);
  8651. mg_response_header_add(conn,
  8652. "Content-Type",
  8653. "text/html; charset=utf-8",
  8654. -1);
  8655. /* Send all headers */
  8656. mg_response_header_send(conn);
  8657. /* Body */
  8658. mg_printf(conn,
  8659. "<html><head><title>Index of %s</title>"
  8660. "<style>th {text-align: left;}</style></head>"
  8661. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8662. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8663. "<th><a href=\"?d%c\">Modified</a></th>"
  8664. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8665. "<tr><td colspan=\"3\"><hr></td></tr>",
  8666. esc ? esc : title,
  8667. esc ? esc : title,
  8668. sort_direction,
  8669. sort_direction,
  8670. sort_direction);
  8671. mg_free(esc);
  8672. /* Print first entry - link to a parent directory */
  8673. mg_printf(conn,
  8674. "<tr><td><a href=\"%s\">%s</a></td>"
  8675. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8676. "..",
  8677. "Parent directory",
  8678. "-",
  8679. "-");
  8680. /* Sort and print directory entries */
  8681. if (data.entries != NULL) {
  8682. qsort(data.entries,
  8683. data.num_entries,
  8684. sizeof(data.entries[0]),
  8685. compare_dir_entries);
  8686. for (i = 0; i < data.num_entries; i++) {
  8687. print_dir_entry(&data.entries[i]);
  8688. mg_free(data.entries[i].file_name);
  8689. }
  8690. mg_free(data.entries);
  8691. }
  8692. mg_printf(conn, "%s", "</table></pre></body></html>");
  8693. conn->status_code = 200;
  8694. }
  8695. #endif /* NO_FILESYSTEMS */
  8696. /* Send len bytes from the opened file to the client. */
  8697. static void
  8698. send_file_data(struct mg_connection *conn,
  8699. struct mg_file *filep,
  8700. int64_t offset,
  8701. int64_t len)
  8702. {
  8703. char buf[MG_BUF_LEN];
  8704. int to_read, num_read, num_written;
  8705. int64_t size;
  8706. if (!filep || !conn) {
  8707. return;
  8708. }
  8709. /* Sanity check the offset */
  8710. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8711. : (int64_t)(filep->stat.size);
  8712. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8713. if (len > 0 && filep->access.fp != NULL) {
  8714. /* file stored on disk */
  8715. #if defined(__linux__)
  8716. /* sendfile is only available for Linux */
  8717. if ((conn->ssl == 0) && (conn->throttle == 0)
  8718. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8719. "yes"))) {
  8720. off_t sf_offs = (off_t)offset;
  8721. ssize_t sf_sent;
  8722. int sf_file = fileno(filep->access.fp);
  8723. int loop_cnt = 0;
  8724. do {
  8725. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8726. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8727. size_t sf_tosend =
  8728. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8729. sf_sent =
  8730. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8731. if (sf_sent > 0) {
  8732. len -= sf_sent;
  8733. offset += sf_sent;
  8734. } else if (loop_cnt == 0) {
  8735. /* This file can not be sent using sendfile.
  8736. * This might be the case for pseudo-files in the
  8737. * /sys/ and /proc/ file system.
  8738. * Use the regular user mode copy code instead. */
  8739. break;
  8740. } else if (sf_sent == 0) {
  8741. /* No error, but 0 bytes sent. May be EOF? */
  8742. return;
  8743. }
  8744. loop_cnt++;
  8745. } while ((len > 0) && (sf_sent >= 0));
  8746. if (sf_sent > 0) {
  8747. return; /* OK */
  8748. }
  8749. /* sf_sent<0 means error, thus fall back to the classic way */
  8750. /* This is always the case, if sf_file is not a "normal" file,
  8751. * e.g., for sending data from the output of a CGI process. */
  8752. offset = (int64_t)sf_offs;
  8753. }
  8754. #endif
  8755. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8756. mg_cry_internal(conn,
  8757. "%s: fseeko() failed: %s",
  8758. __func__,
  8759. strerror(ERRNO));
  8760. mg_send_http_error(
  8761. conn,
  8762. 500,
  8763. "%s",
  8764. "Error: Unable to access file at requested position.");
  8765. } else {
  8766. while (len > 0) {
  8767. /* Calculate how much to read from the file in the buffer */
  8768. to_read = sizeof(buf);
  8769. if ((int64_t)to_read > len) {
  8770. to_read = (int)len;
  8771. }
  8772. /* Read from file, exit the loop on error */
  8773. if ((num_read =
  8774. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8775. <= 0) {
  8776. break;
  8777. }
  8778. /* Send read bytes to the client, exit the loop on error */
  8779. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8780. != num_read) {
  8781. break;
  8782. }
  8783. /* Both read and were successful, adjust counters */
  8784. len -= num_written;
  8785. }
  8786. }
  8787. }
  8788. }
  8789. static int
  8790. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8791. {
  8792. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8793. }
  8794. static void
  8795. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8796. {
  8797. if ((filestat != NULL) && (buf != NULL)) {
  8798. mg_snprintf(NULL,
  8799. NULL, /* All calls to construct_etag use 64 byte buffer */
  8800. buf,
  8801. buf_len,
  8802. "\"%lx.%" INT64_FMT "\"",
  8803. (unsigned long)filestat->last_modified,
  8804. filestat->size);
  8805. }
  8806. }
  8807. static void
  8808. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8809. {
  8810. if (filep != NULL && filep->fp != NULL) {
  8811. #if defined(_WIN32)
  8812. (void)conn; /* Unused. */
  8813. #else
  8814. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8815. mg_cry_internal(conn,
  8816. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8817. __func__,
  8818. strerror(ERRNO));
  8819. }
  8820. #endif
  8821. }
  8822. }
  8823. #if defined(USE_ZLIB)
  8824. #include "mod_zlib.inl"
  8825. #endif
  8826. #if !defined(NO_FILESYSTEMS)
  8827. static void
  8828. handle_static_file_request(struct mg_connection *conn,
  8829. const char *path,
  8830. struct mg_file *filep,
  8831. const char *mime_type,
  8832. const char *additional_headers)
  8833. {
  8834. char lm[64], etag[64];
  8835. char range[128]; /* large enough, so there will be no overflow */
  8836. const char *range_hdr;
  8837. int64_t cl, r1, r2;
  8838. struct vec mime_vec;
  8839. int n, truncated;
  8840. char gz_path[UTF8_PATH_MAX];
  8841. const char *encoding = 0;
  8842. const char *origin_hdr;
  8843. const char *cors_orig_cfg;
  8844. const char *cors1, *cors2;
  8845. int is_head_request;
  8846. #if defined(USE_ZLIB)
  8847. /* Compression is allowed, unless there is a reason not to use
  8848. * compression. If the file is already compressed, too small or a
  8849. * "range" request was made, on the fly compression is not possible. */
  8850. int allow_on_the_fly_compression = 1;
  8851. #endif
  8852. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8853. return;
  8854. }
  8855. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8856. if (mime_type == NULL) {
  8857. get_mime_type(conn, path, &mime_vec);
  8858. } else {
  8859. mime_vec.ptr = mime_type;
  8860. mime_vec.len = strlen(mime_type);
  8861. }
  8862. if (filep->stat.size > INT64_MAX) {
  8863. mg_send_http_error(conn,
  8864. 500,
  8865. "Error: File size is too large to send\n%" INT64_FMT,
  8866. filep->stat.size);
  8867. return;
  8868. }
  8869. cl = (int64_t)filep->stat.size;
  8870. conn->status_code = 200;
  8871. range[0] = '\0';
  8872. #if defined(USE_ZLIB)
  8873. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8874. * it's important to rewrite the filename after resolving
  8875. * the mime type from it, to preserve the actual file's type */
  8876. if (!conn->accept_gzip) {
  8877. allow_on_the_fly_compression = 0;
  8878. }
  8879. #endif
  8880. /* Check if there is a range header */
  8881. range_hdr = mg_get_header(conn, "Range");
  8882. /* For gzipped files, add *.gz */
  8883. if (filep->stat.is_gzipped) {
  8884. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8885. if (truncated) {
  8886. mg_send_http_error(conn,
  8887. 500,
  8888. "Error: Path of zipped file too long (%s)",
  8889. path);
  8890. return;
  8891. }
  8892. path = gz_path;
  8893. encoding = "gzip";
  8894. #if defined(USE_ZLIB)
  8895. /* File is already compressed. No "on the fly" compression. */
  8896. allow_on_the_fly_compression = 0;
  8897. #endif
  8898. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8899. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8900. struct mg_file_stat file_stat;
  8901. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8902. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8903. && !file_stat.is_directory) {
  8904. file_stat.is_gzipped = 1;
  8905. filep->stat = file_stat;
  8906. cl = (int64_t)filep->stat.size;
  8907. path = gz_path;
  8908. encoding = "gzip";
  8909. #if defined(USE_ZLIB)
  8910. /* File is already compressed. No "on the fly" compression. */
  8911. allow_on_the_fly_compression = 0;
  8912. #endif
  8913. }
  8914. }
  8915. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8916. mg_send_http_error(conn,
  8917. 500,
  8918. "Error: Cannot open file\nfopen(%s): %s",
  8919. path,
  8920. strerror(ERRNO));
  8921. return;
  8922. }
  8923. fclose_on_exec(&filep->access, conn);
  8924. /* If "Range" request was made: parse header, send only selected part
  8925. * of the file. */
  8926. r1 = r2 = 0;
  8927. if ((range_hdr != NULL)
  8928. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8929. && (r2 >= 0)) {
  8930. /* actually, range requests don't play well with a pre-gzipped
  8931. * file (since the range is specified in the uncompressed space) */
  8932. if (filep->stat.is_gzipped) {
  8933. mg_send_http_error(
  8934. conn,
  8935. 416, /* 416 = Range Not Satisfiable */
  8936. "%s",
  8937. "Error: Range requests in gzipped files are not supported");
  8938. (void)mg_fclose(
  8939. &filep->access); /* ignore error on read only file */
  8940. return;
  8941. }
  8942. conn->status_code = 206;
  8943. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8944. mg_snprintf(conn,
  8945. NULL, /* range buffer is big enough */
  8946. range,
  8947. sizeof(range),
  8948. "bytes "
  8949. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8950. r1,
  8951. r1 + cl - 1,
  8952. filep->stat.size);
  8953. #if defined(USE_ZLIB)
  8954. /* Do not compress ranges. */
  8955. allow_on_the_fly_compression = 0;
  8956. #endif
  8957. }
  8958. /* Do not compress small files. Small files do not benefit from file
  8959. * compression, but there is still some overhead. */
  8960. #if defined(USE_ZLIB)
  8961. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8962. /* File is below the size limit. */
  8963. allow_on_the_fly_compression = 0;
  8964. }
  8965. #endif
  8966. /* Standard CORS header */
  8967. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8968. origin_hdr = mg_get_header(conn, "Origin");
  8969. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8970. /* Cross-origin resource sharing (CORS), see
  8971. * http://www.html5rocks.com/en/tutorials/cors/,
  8972. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8973. * -
  8974. * preflight is not supported for files. */
  8975. cors1 = "Access-Control-Allow-Origin";
  8976. cors2 = cors_orig_cfg;
  8977. } else {
  8978. cors1 = cors2 = "";
  8979. }
  8980. /* Prepare Etag, and Last-Modified headers. */
  8981. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8982. construct_etag(etag, sizeof(etag), &filep->stat);
  8983. /* Create 2xx (200, 206) response */
  8984. mg_response_header_start(conn, conn->status_code);
  8985. send_static_cache_header(conn);
  8986. send_additional_header(conn);
  8987. mg_response_header_add(conn,
  8988. "Content-Type",
  8989. mime_vec.ptr,
  8990. (int)mime_vec.len);
  8991. if (cors1[0] != 0) {
  8992. mg_response_header_add(conn, cors1, cors2, -1);
  8993. }
  8994. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8995. mg_response_header_add(conn, "Etag", etag, -1);
  8996. #if defined(USE_ZLIB)
  8997. /* On the fly compression allowed */
  8998. if (allow_on_the_fly_compression) {
  8999. /* For on the fly compression, we don't know the content size in
  9000. * advance, so we have to use chunked encoding */
  9001. encoding = "gzip";
  9002. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9003. /* HTTP/2 is always using "chunks" (frames) */
  9004. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9005. }
  9006. } else
  9007. #endif
  9008. {
  9009. /* Without on-the-fly compression, we know the content-length
  9010. * and we can use ranges (with on-the-fly compression we cannot).
  9011. * So we send these response headers only in this case. */
  9012. char len[32];
  9013. int trunc = 0;
  9014. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9015. if (!trunc) {
  9016. mg_response_header_add(conn, "Content-Length", len, -1);
  9017. }
  9018. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9019. }
  9020. if (encoding) {
  9021. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9022. }
  9023. if (range[0] != 0) {
  9024. mg_response_header_add(conn, "Content-Range", range, -1);
  9025. }
  9026. /* The code above does not add any header starting with X- to make
  9027. * sure no one of the additional_headers is included twice */
  9028. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9029. mg_response_header_add_lines(conn, additional_headers);
  9030. }
  9031. /* Send all headers */
  9032. mg_response_header_send(conn);
  9033. if (!is_head_request) {
  9034. #if defined(USE_ZLIB)
  9035. if (allow_on_the_fly_compression) {
  9036. /* Compress and send */
  9037. send_compressed_data(conn, filep);
  9038. } else
  9039. #endif
  9040. {
  9041. /* Send file directly */
  9042. send_file_data(conn, filep, r1, cl);
  9043. }
  9044. }
  9045. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9046. }
  9047. int
  9048. mg_send_file_body(struct mg_connection *conn, const char *path)
  9049. {
  9050. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9051. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9052. return -1;
  9053. }
  9054. fclose_on_exec(&file.access, conn);
  9055. send_file_data(conn, &file, 0, INT64_MAX);
  9056. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9057. return 0; /* >= 0 for OK */
  9058. }
  9059. #endif /* NO_FILESYSTEMS */
  9060. #if !defined(NO_CACHING)
  9061. /* Return True if we should reply 304 Not Modified. */
  9062. static int
  9063. is_not_modified(const struct mg_connection *conn,
  9064. const struct mg_file_stat *filestat)
  9065. {
  9066. char etag[64];
  9067. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9068. const char *inm = mg_get_header(conn, "If-None-Match");
  9069. construct_etag(etag, sizeof(etag), filestat);
  9070. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9071. || ((ims != NULL)
  9072. && (filestat->last_modified <= parse_date_string(ims)));
  9073. }
  9074. static void
  9075. handle_not_modified_static_file_request(struct mg_connection *conn,
  9076. struct mg_file *filep)
  9077. {
  9078. char lm[64], etag[64];
  9079. if ((conn == NULL) || (filep == NULL)) {
  9080. return;
  9081. }
  9082. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9083. construct_etag(etag, sizeof(etag), &filep->stat);
  9084. /* Create 304 "not modified" response */
  9085. mg_response_header_start(conn, 304);
  9086. send_static_cache_header(conn);
  9087. send_additional_header(conn);
  9088. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9089. mg_response_header_add(conn, "Etag", etag, -1);
  9090. /* Send all headers */
  9091. mg_response_header_send(conn);
  9092. }
  9093. #endif
  9094. #if !defined(NO_FILESYSTEMS)
  9095. void
  9096. mg_send_file(struct mg_connection *conn, const char *path)
  9097. {
  9098. mg_send_mime_file2(conn, path, NULL, NULL);
  9099. }
  9100. void
  9101. mg_send_mime_file(struct mg_connection *conn,
  9102. const char *path,
  9103. const char *mime_type)
  9104. {
  9105. mg_send_mime_file2(conn, path, mime_type, NULL);
  9106. }
  9107. void
  9108. mg_send_mime_file2(struct mg_connection *conn,
  9109. const char *path,
  9110. const char *mime_type,
  9111. const char *additional_headers)
  9112. {
  9113. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9114. if (!conn) {
  9115. /* No conn */
  9116. return;
  9117. }
  9118. if (mg_stat(conn, path, &file.stat)) {
  9119. #if !defined(NO_CACHING)
  9120. if (is_not_modified(conn, &file.stat)) {
  9121. /* Send 304 "Not Modified" - this must not send any body data */
  9122. handle_not_modified_static_file_request(conn, &file);
  9123. } else
  9124. #endif /* NO_CACHING */
  9125. if (file.stat.is_directory) {
  9126. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9127. "yes")) {
  9128. handle_directory_request(conn, path);
  9129. } else {
  9130. mg_send_http_error(conn,
  9131. 403,
  9132. "%s",
  9133. "Error: Directory listing denied");
  9134. }
  9135. } else {
  9136. handle_static_file_request(
  9137. conn, path, &file, mime_type, additional_headers);
  9138. }
  9139. } else {
  9140. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9141. }
  9142. }
  9143. /* For a given PUT path, create all intermediate subdirectories.
  9144. * Return 0 if the path itself is a directory.
  9145. * Return 1 if the path leads to a file.
  9146. * Return -1 for if the path is too long.
  9147. * Return -2 if path can not be created.
  9148. */
  9149. static int
  9150. put_dir(struct mg_connection *conn, const char *path)
  9151. {
  9152. char buf[UTF8_PATH_MAX];
  9153. const char *s, *p;
  9154. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9155. size_t len;
  9156. int res = 1;
  9157. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9158. len = (size_t)(p - path);
  9159. if (len >= sizeof(buf)) {
  9160. /* path too long */
  9161. res = -1;
  9162. break;
  9163. }
  9164. memcpy(buf, path, len);
  9165. buf[len] = '\0';
  9166. /* Try to create intermediate directory */
  9167. DEBUG_TRACE("mkdir(%s)", buf);
  9168. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9169. /* path does not exixt and can not be created */
  9170. res = -2;
  9171. break;
  9172. }
  9173. /* Is path itself a directory? */
  9174. if (p[1] == '\0') {
  9175. res = 0;
  9176. }
  9177. }
  9178. return res;
  9179. }
  9180. static void
  9181. remove_bad_file(const struct mg_connection *conn, const char *path)
  9182. {
  9183. int r = mg_remove(conn, path);
  9184. if (r != 0) {
  9185. mg_cry_internal(conn,
  9186. "%s: Cannot remove invalid file %s",
  9187. __func__,
  9188. path);
  9189. }
  9190. }
  9191. long long
  9192. mg_store_body(struct mg_connection *conn, const char *path)
  9193. {
  9194. char buf[MG_BUF_LEN];
  9195. long long len = 0;
  9196. int ret, n;
  9197. struct mg_file fi;
  9198. if (conn->consumed_content != 0) {
  9199. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9200. return -11;
  9201. }
  9202. ret = put_dir(conn, path);
  9203. if (ret < 0) {
  9204. /* -1 for path too long,
  9205. * -2 for path can not be created. */
  9206. return ret;
  9207. }
  9208. if (ret != 1) {
  9209. /* Return 0 means, path itself is a directory. */
  9210. return 0;
  9211. }
  9212. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9213. return -12;
  9214. }
  9215. ret = mg_read(conn, buf, sizeof(buf));
  9216. while (ret > 0) {
  9217. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9218. if (n != ret) {
  9219. (void)mg_fclose(
  9220. &fi.access); /* File is bad and will be removed anyway. */
  9221. remove_bad_file(conn, path);
  9222. return -13;
  9223. }
  9224. len += ret;
  9225. ret = mg_read(conn, buf, sizeof(buf));
  9226. }
  9227. /* File is open for writing. If fclose fails, there was probably an
  9228. * error flushing the buffer to disk, so the file on disk might be
  9229. * broken. Delete it and return an error to the caller. */
  9230. if (mg_fclose(&fi.access) != 0) {
  9231. remove_bad_file(conn, path);
  9232. return -14;
  9233. }
  9234. return len;
  9235. }
  9236. #endif /* NO_FILESYSTEMS */
  9237. /* Parse a buffer:
  9238. * Forward the string pointer till the end of a word, then
  9239. * terminate it and forward till the begin of the next word.
  9240. */
  9241. static int
  9242. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9243. {
  9244. /* Forward until a space is found - use isgraph here */
  9245. /* See http://www.cplusplus.com/reference/cctype/ */
  9246. while (isgraph((unsigned char)**ppw)) {
  9247. (*ppw)++;
  9248. }
  9249. /* Check end of word */
  9250. if (eol) {
  9251. /* must be a end of line */
  9252. if ((**ppw != '\r') && (**ppw != '\n')) {
  9253. return -1;
  9254. }
  9255. } else {
  9256. /* must be a end of a word, but not a line */
  9257. if (**ppw != ' ') {
  9258. return -1;
  9259. }
  9260. }
  9261. /* Terminate and forward to the next word */
  9262. do {
  9263. **ppw = 0;
  9264. (*ppw)++;
  9265. } while (isspace((unsigned char)**ppw));
  9266. /* Check after term */
  9267. if (!eol) {
  9268. /* if it's not the end of line, there must be a next word */
  9269. if (!isgraph((unsigned char)**ppw)) {
  9270. return -1;
  9271. }
  9272. }
  9273. /* ok */
  9274. return 1;
  9275. }
  9276. /* Parse HTTP headers from the given buffer, advance buf pointer
  9277. * to the point where parsing stopped.
  9278. * All parameters must be valid pointers (not NULL).
  9279. * Return <0 on error. */
  9280. static int
  9281. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9282. {
  9283. int i;
  9284. int num_headers = 0;
  9285. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9286. char *dp = *buf;
  9287. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9288. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9289. dp++;
  9290. }
  9291. if (dp == *buf) {
  9292. /* End of headers reached. */
  9293. break;
  9294. }
  9295. /* Drop all spaces after header name before : */
  9296. while (*dp == ' ') {
  9297. *dp = 0;
  9298. dp++;
  9299. }
  9300. if (*dp != ':') {
  9301. /* This is not a valid field. */
  9302. return -1;
  9303. }
  9304. /* End of header key (*dp == ':') */
  9305. /* Truncate here and set the key name */
  9306. *dp = 0;
  9307. hdr[i].name = *buf;
  9308. /* Skip all spaces */
  9309. do {
  9310. dp++;
  9311. } while ((*dp == ' ') || (*dp == '\t'));
  9312. /* The rest of the line is the value */
  9313. hdr[i].value = dp;
  9314. /* Find end of line */
  9315. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9316. dp++;
  9317. };
  9318. /* eliminate \r */
  9319. if (*dp == '\r') {
  9320. *dp = 0;
  9321. dp++;
  9322. if (*dp != '\n') {
  9323. /* This is not a valid line. */
  9324. return -1;
  9325. }
  9326. }
  9327. /* here *dp is either 0 or '\n' */
  9328. /* in any case, we have a new header */
  9329. num_headers = i + 1;
  9330. if (*dp) {
  9331. *dp = 0;
  9332. dp++;
  9333. *buf = dp;
  9334. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9335. /* This is the end of the header */
  9336. break;
  9337. }
  9338. } else {
  9339. *buf = dp;
  9340. break;
  9341. }
  9342. }
  9343. return num_headers;
  9344. }
  9345. struct mg_http_method_info {
  9346. const char *name;
  9347. int request_has_body;
  9348. int response_has_body;
  9349. int is_safe;
  9350. int is_idempotent;
  9351. int is_cacheable;
  9352. };
  9353. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9354. static const struct mg_http_method_info http_methods[] = {
  9355. /* HTTP (RFC 2616) */
  9356. {"GET", 0, 1, 1, 1, 1},
  9357. {"POST", 1, 1, 0, 0, 0},
  9358. {"PUT", 1, 0, 0, 1, 0},
  9359. {"DELETE", 0, 0, 0, 1, 0},
  9360. {"HEAD", 0, 0, 1, 1, 1},
  9361. {"OPTIONS", 0, 0, 1, 1, 0},
  9362. {"CONNECT", 1, 1, 0, 0, 0},
  9363. /* TRACE method (RFC 2616) is not supported for security reasons */
  9364. /* PATCH method (RFC 5789) */
  9365. {"PATCH", 1, 0, 0, 0, 0},
  9366. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9367. /* WEBDAV (RFC 2518) */
  9368. {"PROPFIND", 0, 1, 1, 1, 0},
  9369. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9370. * Some PROPFIND results MAY be cached, with care,
  9371. * as there is no cache validation mechanism for
  9372. * most properties. This method is both safe and
  9373. * idempotent (see Section 9.1 of [RFC2616]). */
  9374. {"MKCOL", 0, 0, 0, 1, 0},
  9375. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9376. * When MKCOL is invoked without a request body,
  9377. * the newly created collection SHOULD have no
  9378. * members. A MKCOL request message may contain
  9379. * a message body. The precise behavior of a MKCOL
  9380. * request when the body is present is undefined,
  9381. * ... ==> We do not support MKCOL with body data.
  9382. * This method is idempotent, but not safe (see
  9383. * Section 9.1 of [RFC2616]). Responses to this
  9384. * method MUST NOT be cached. */
  9385. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9386. {"LOCK", 1, 1, 0, 0, 0},
  9387. {"UNLOCK", 1, 0, 0, 0, 0},
  9388. {"PROPPATCH", 1, 1, 0, 0, 0},
  9389. /* Unsupported WEBDAV Methods: */
  9390. /* COPY, MOVE (RFC 2518) */
  9391. /* + 11 methods from RFC 3253 */
  9392. /* ORDERPATCH (RFC 3648) */
  9393. /* ACL (RFC 3744) */
  9394. /* SEARCH (RFC 5323) */
  9395. /* + MicroSoft extensions
  9396. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9397. /* REPORT method (RFC 3253) */
  9398. {"REPORT", 1, 1, 1, 1, 1},
  9399. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9400. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9401. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9402. * to be useful for REST in case a "GET request with body" is
  9403. * required. */
  9404. {NULL, 0, 0, 0, 0, 0}
  9405. /* end of list */
  9406. };
  9407. static const struct mg_http_method_info *
  9408. get_http_method_info(const char *method)
  9409. {
  9410. /* Check if the method is known to the server. The list of all known
  9411. * HTTP methods can be found here at
  9412. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9413. */
  9414. const struct mg_http_method_info *m = http_methods;
  9415. while (m->name) {
  9416. if (!strcmp(m->name, method)) {
  9417. return m;
  9418. }
  9419. m++;
  9420. }
  9421. return NULL;
  9422. }
  9423. static int
  9424. is_valid_http_method(const char *method)
  9425. {
  9426. return (get_http_method_info(method) != NULL);
  9427. }
  9428. /* Parse HTTP request, fill in mg_request_info structure.
  9429. * This function modifies the buffer by NUL-terminating
  9430. * HTTP request components, header names and header values.
  9431. * Parameters:
  9432. * buf (in/out): pointer to the HTTP header to parse and split
  9433. * len (in): length of HTTP header buffer
  9434. * re (out): parsed header as mg_request_info
  9435. * buf and ri must be valid pointers (not NULL), len>0.
  9436. * Returns <0 on error. */
  9437. static int
  9438. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9439. {
  9440. int request_length;
  9441. int init_skip = 0;
  9442. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9443. * remote_port */
  9444. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9445. NULL;
  9446. ri->num_headers = 0;
  9447. /* RFC says that all initial whitespaces should be ingored */
  9448. /* This included all leading \r and \n (isspace) */
  9449. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9450. while ((len > 0) && isspace((unsigned char)*buf)) {
  9451. buf++;
  9452. len--;
  9453. init_skip++;
  9454. }
  9455. if (len == 0) {
  9456. /* Incomplete request */
  9457. return 0;
  9458. }
  9459. /* Control characters are not allowed, including zero */
  9460. if (iscntrl((unsigned char)*buf)) {
  9461. return -1;
  9462. }
  9463. /* Find end of HTTP header */
  9464. request_length = get_http_header_len(buf, len);
  9465. if (request_length <= 0) {
  9466. return request_length;
  9467. }
  9468. buf[request_length - 1] = '\0';
  9469. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9470. return -1;
  9471. }
  9472. /* The first word has to be the HTTP method */
  9473. ri->request_method = buf;
  9474. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9475. return -1;
  9476. }
  9477. /* Check for a valid http method */
  9478. if (!is_valid_http_method(ri->request_method)) {
  9479. return -1;
  9480. }
  9481. /* The second word is the URI */
  9482. ri->request_uri = buf;
  9483. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9484. return -1;
  9485. }
  9486. /* Next would be the HTTP version */
  9487. ri->http_version = buf;
  9488. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9489. return -1;
  9490. }
  9491. /* Check for a valid HTTP version key */
  9492. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9493. /* Invalid request */
  9494. return -1;
  9495. }
  9496. ri->http_version += 5;
  9497. /* Parse all HTTP headers */
  9498. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9499. if (ri->num_headers < 0) {
  9500. /* Error while parsing headers */
  9501. return -1;
  9502. }
  9503. return request_length + init_skip;
  9504. }
  9505. static int
  9506. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9507. {
  9508. int response_length;
  9509. int init_skip = 0;
  9510. char *tmp, *tmp2;
  9511. long l;
  9512. /* Initialize elements. */
  9513. ri->http_version = ri->status_text = NULL;
  9514. ri->num_headers = ri->status_code = 0;
  9515. /* RFC says that all initial whitespaces should be ingored */
  9516. /* This included all leading \r and \n (isspace) */
  9517. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9518. while ((len > 0) && isspace((unsigned char)*buf)) {
  9519. buf++;
  9520. len--;
  9521. init_skip++;
  9522. }
  9523. if (len == 0) {
  9524. /* Incomplete request */
  9525. return 0;
  9526. }
  9527. /* Control characters are not allowed, including zero */
  9528. if (iscntrl((unsigned char)*buf)) {
  9529. return -1;
  9530. }
  9531. /* Find end of HTTP header */
  9532. response_length = get_http_header_len(buf, len);
  9533. if (response_length <= 0) {
  9534. return response_length;
  9535. }
  9536. buf[response_length - 1] = '\0';
  9537. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9538. return -1;
  9539. }
  9540. /* The first word is the HTTP version */
  9541. /* Check for a valid HTTP version key */
  9542. if (strncmp(buf, "HTTP/", 5) != 0) {
  9543. /* Invalid request */
  9544. return -1;
  9545. }
  9546. buf += 5;
  9547. if (!isgraph((unsigned char)buf[0])) {
  9548. /* Invalid request */
  9549. return -1;
  9550. }
  9551. ri->http_version = buf;
  9552. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9553. return -1;
  9554. }
  9555. /* The second word is the status as a number */
  9556. tmp = buf;
  9557. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9558. return -1;
  9559. }
  9560. l = strtol(tmp, &tmp2, 10);
  9561. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9562. /* Everything else but a 3 digit code is invalid */
  9563. return -1;
  9564. }
  9565. ri->status_code = (int)l;
  9566. /* The rest of the line is the status text */
  9567. ri->status_text = buf;
  9568. /* Find end of status text */
  9569. /* isgraph or isspace = isprint */
  9570. while (isprint((unsigned char)*buf)) {
  9571. buf++;
  9572. }
  9573. if ((*buf != '\r') && (*buf != '\n')) {
  9574. return -1;
  9575. }
  9576. /* Terminate string and forward buf to next line */
  9577. do {
  9578. *buf = 0;
  9579. buf++;
  9580. } while (isspace((unsigned char)*buf));
  9581. /* Parse all HTTP headers */
  9582. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9583. if (ri->num_headers < 0) {
  9584. /* Error while parsing headers */
  9585. return -1;
  9586. }
  9587. return response_length + init_skip;
  9588. }
  9589. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9590. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9591. * buffer (which marks the end of HTTP request). Buffer buf may already
  9592. * have some data. The length of the data is stored in nread.
  9593. * Upon every read operation, increase nread by the number of bytes read. */
  9594. static int
  9595. read_message(FILE *fp,
  9596. struct mg_connection *conn,
  9597. char *buf,
  9598. int bufsiz,
  9599. int *nread)
  9600. {
  9601. int request_len, n = 0;
  9602. struct timespec last_action_time;
  9603. double request_timeout;
  9604. if (!conn) {
  9605. return 0;
  9606. }
  9607. memset(&last_action_time, 0, sizeof(last_action_time));
  9608. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9609. /* value of request_timeout is in seconds, config in milliseconds */
  9610. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9611. } else {
  9612. request_timeout =
  9613. atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  9614. }
  9615. if (conn->handled_requests > 0) {
  9616. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9617. request_timeout =
  9618. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9619. }
  9620. }
  9621. request_len = get_http_header_len(buf, *nread);
  9622. while (request_len == 0) {
  9623. /* Full request not yet received */
  9624. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9625. /* Server is to be stopped. */
  9626. return -1;
  9627. }
  9628. if (*nread >= bufsiz) {
  9629. /* Request too long */
  9630. return -2;
  9631. }
  9632. n = pull_inner(
  9633. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9634. if (n == -2) {
  9635. /* Receive error */
  9636. return -1;
  9637. }
  9638. /* update clock after every read request */
  9639. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9640. if (n > 0) {
  9641. *nread += n;
  9642. request_len = get_http_header_len(buf, *nread);
  9643. }
  9644. if ((request_len == 0) && (request_timeout >= 0)) {
  9645. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9646. > request_timeout) {
  9647. /* Timeout */
  9648. return -1;
  9649. }
  9650. }
  9651. }
  9652. return request_len;
  9653. }
  9654. #if !defined(NO_CGI) || !defined(NO_FILES)
  9655. static int
  9656. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9657. {
  9658. const char *expect;
  9659. char buf[MG_BUF_LEN];
  9660. int success = 0;
  9661. if (!conn) {
  9662. return 0;
  9663. }
  9664. expect = mg_get_header(conn, "Expect");
  9665. DEBUG_ASSERT(fp != NULL);
  9666. if (!fp) {
  9667. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9668. return 0;
  9669. }
  9670. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9671. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9672. */
  9673. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9674. } else {
  9675. if (expect != NULL) {
  9676. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9677. conn->status_code = 100;
  9678. } else {
  9679. conn->status_code = 200;
  9680. }
  9681. DEBUG_ASSERT(conn->consumed_content == 0);
  9682. if (conn->consumed_content != 0) {
  9683. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9684. return 0;
  9685. }
  9686. for (;;) {
  9687. int nread = mg_read(conn, buf, sizeof(buf));
  9688. if (nread <= 0) {
  9689. success = (nread == 0);
  9690. break;
  9691. }
  9692. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9693. break;
  9694. }
  9695. }
  9696. /* Each error code path in this function must send an error */
  9697. if (!success) {
  9698. /* NOTE: Maybe some data has already been sent. */
  9699. /* TODO (low): If some data has been sent, a correct error
  9700. * reply can no longer be sent, so just close the connection */
  9701. mg_send_http_error(conn, 500, "%s", "");
  9702. }
  9703. }
  9704. return success;
  9705. }
  9706. #endif
  9707. #if defined(USE_TIMERS)
  9708. #define TIMER_API static
  9709. #include "timer.inl"
  9710. #endif /* USE_TIMERS */
  9711. #if !defined(NO_CGI)
  9712. /* This structure helps to create an environment for the spawned CGI
  9713. * program.
  9714. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9715. * last element must be NULL.
  9716. * However, on Windows there is a requirement that all these
  9717. * VARIABLE=VALUE\0
  9718. * strings must reside in a contiguous buffer. The end of the buffer is
  9719. * marked by two '\0' characters.
  9720. * We satisfy both worlds: we create an envp array (which is vars), all
  9721. * entries are actually pointers inside buf. */
  9722. struct cgi_environment {
  9723. struct mg_connection *conn;
  9724. /* Data block */
  9725. char *buf; /* Environment buffer */
  9726. size_t buflen; /* Space available in buf */
  9727. size_t bufused; /* Space taken in buf */
  9728. /* Index block */
  9729. char **var; /* char **envp */
  9730. size_t varlen; /* Number of variables available in var */
  9731. size_t varused; /* Number of variables stored in var */
  9732. };
  9733. static void addenv(struct cgi_environment *env,
  9734. PRINTF_FORMAT_STRING(const char *fmt),
  9735. ...) PRINTF_ARGS(2, 3);
  9736. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9737. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9738. static void
  9739. addenv(struct cgi_environment *env, const char *fmt, ...)
  9740. {
  9741. size_t i, n, space;
  9742. int truncated = 0;
  9743. char *added;
  9744. va_list ap;
  9745. if ((env->varlen - env->varused) < 2) {
  9746. mg_cry_internal(env->conn,
  9747. "%s: Cannot register CGI variable [%s]",
  9748. __func__,
  9749. fmt);
  9750. return;
  9751. }
  9752. /* Calculate how much space is left in the buffer */
  9753. space = (env->buflen - env->bufused);
  9754. do {
  9755. /* Space for "\0\0" is always needed. */
  9756. if (space <= 2) {
  9757. /* Allocate new buffer */
  9758. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9759. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9760. if (!added) {
  9761. /* Out of memory */
  9762. mg_cry_internal(
  9763. env->conn,
  9764. "%s: Cannot allocate memory for CGI variable [%s]",
  9765. __func__,
  9766. fmt);
  9767. return;
  9768. }
  9769. /* Retarget pointers */
  9770. env->buf = added;
  9771. env->buflen = n;
  9772. for (i = 0, n = 0; i < env->varused; i++) {
  9773. env->var[i] = added + n;
  9774. n += strlen(added + n) + 1;
  9775. }
  9776. space = (env->buflen - env->bufused);
  9777. }
  9778. /* Make a pointer to the free space int the buffer */
  9779. added = env->buf + env->bufused;
  9780. /* Copy VARIABLE=VALUE\0 string into the free space */
  9781. va_start(ap, fmt);
  9782. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9783. va_end(ap);
  9784. /* Do not add truncated strings to the environment */
  9785. if (truncated) {
  9786. /* Reallocate the buffer */
  9787. space = 0;
  9788. }
  9789. } while (truncated);
  9790. /* Calculate number of bytes added to the environment */
  9791. n = strlen(added) + 1;
  9792. env->bufused += n;
  9793. /* Append a pointer to the added string into the envp array */
  9794. env->var[env->varused] = added;
  9795. env->varused++;
  9796. }
  9797. /* Return 0 on success, non-zero if an error occurs. */
  9798. static int
  9799. prepare_cgi_environment(struct mg_connection *conn,
  9800. const char *prog,
  9801. struct cgi_environment *env)
  9802. {
  9803. const char *s;
  9804. struct vec var_vec;
  9805. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9806. int i, truncated, uri_len;
  9807. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9808. return -1;
  9809. }
  9810. env->conn = conn;
  9811. env->buflen = CGI_ENVIRONMENT_SIZE;
  9812. env->bufused = 0;
  9813. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9814. if (env->buf == NULL) {
  9815. mg_cry_internal(conn,
  9816. "%s: Not enough memory for environmental buffer",
  9817. __func__);
  9818. return -1;
  9819. }
  9820. env->varlen = MAX_CGI_ENVIR_VARS;
  9821. env->varused = 0;
  9822. env->var =
  9823. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9824. if (env->var == NULL) {
  9825. mg_cry_internal(conn,
  9826. "%s: Not enough memory for environmental variables",
  9827. __func__);
  9828. mg_free(env->buf);
  9829. return -1;
  9830. }
  9831. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9832. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9833. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9834. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9835. /* Prepare the environment block */
  9836. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9837. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9838. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9839. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9840. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9841. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9842. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9843. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9844. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9845. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9846. /* SCRIPT_NAME */
  9847. uri_len = (int)strlen(conn->request_info.local_uri);
  9848. if (conn->path_info == NULL) {
  9849. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9850. /* URI: /path_to_script/script.cgi */
  9851. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9852. } else {
  9853. /* URI: /path_to_script/ ... using index.cgi */
  9854. const char *index_file = strrchr(prog, '/');
  9855. if (index_file) {
  9856. addenv(env,
  9857. "SCRIPT_NAME=%s%s",
  9858. conn->request_info.local_uri,
  9859. index_file + 1);
  9860. }
  9861. }
  9862. } else {
  9863. /* URI: /path_to_script/script.cgi/path_info */
  9864. addenv(env,
  9865. "SCRIPT_NAME=%.*s",
  9866. uri_len - (int)strlen(conn->path_info),
  9867. conn->request_info.local_uri);
  9868. }
  9869. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9870. if (conn->path_info == NULL) {
  9871. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9872. } else {
  9873. addenv(env,
  9874. "PATH_TRANSLATED=%s%s",
  9875. conn->dom_ctx->config[DOCUMENT_ROOT],
  9876. conn->path_info);
  9877. }
  9878. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9879. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9880. addenv(env, "CONTENT_TYPE=%s", s);
  9881. }
  9882. if (conn->request_info.query_string != NULL) {
  9883. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9884. }
  9885. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9886. addenv(env, "CONTENT_LENGTH=%s", s);
  9887. }
  9888. if ((s = getenv("PATH")) != NULL) {
  9889. addenv(env, "PATH=%s", s);
  9890. }
  9891. if (conn->path_info != NULL) {
  9892. addenv(env, "PATH_INFO=%s", conn->path_info);
  9893. }
  9894. if (conn->status_code > 0) {
  9895. /* CGI error handler should show the status code */
  9896. addenv(env, "STATUS=%d", conn->status_code);
  9897. }
  9898. #if defined(_WIN32)
  9899. if ((s = getenv("COMSPEC")) != NULL) {
  9900. addenv(env, "COMSPEC=%s", s);
  9901. }
  9902. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9903. addenv(env, "SYSTEMROOT=%s", s);
  9904. }
  9905. if ((s = getenv("SystemDrive")) != NULL) {
  9906. addenv(env, "SystemDrive=%s", s);
  9907. }
  9908. if ((s = getenv("ProgramFiles")) != NULL) {
  9909. addenv(env, "ProgramFiles=%s", s);
  9910. }
  9911. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9912. addenv(env, "ProgramFiles(x86)=%s", s);
  9913. }
  9914. #else
  9915. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9916. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9917. }
  9918. #endif /* _WIN32 */
  9919. if ((s = getenv("PERLLIB")) != NULL) {
  9920. addenv(env, "PERLLIB=%s", s);
  9921. }
  9922. if (conn->request_info.remote_user != NULL) {
  9923. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9924. addenv(env, "%s", "AUTH_TYPE=Digest");
  9925. }
  9926. /* Add all headers as HTTP_* variables */
  9927. for (i = 0; i < conn->request_info.num_headers; i++) {
  9928. (void)mg_snprintf(conn,
  9929. &truncated,
  9930. http_var_name,
  9931. sizeof(http_var_name),
  9932. "HTTP_%s",
  9933. conn->request_info.http_headers[i].name);
  9934. if (truncated) {
  9935. mg_cry_internal(conn,
  9936. "%s: HTTP header variable too long [%s]",
  9937. __func__,
  9938. conn->request_info.http_headers[i].name);
  9939. continue;
  9940. }
  9941. /* Convert variable name into uppercase, and change - to _ */
  9942. for (p = http_var_name; *p != '\0'; p++) {
  9943. if (*p == '-') {
  9944. *p = '_';
  9945. }
  9946. *p = (char)toupper((unsigned char)*p);
  9947. }
  9948. addenv(env,
  9949. "%s=%s",
  9950. http_var_name,
  9951. conn->request_info.http_headers[i].value);
  9952. }
  9953. /* Add user-specified variables */
  9954. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9955. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9956. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9957. }
  9958. env->var[env->varused] = NULL;
  9959. env->buf[env->bufused] = '\0';
  9960. return 0;
  9961. }
  9962. /* Data for CGI process control: PID and number of references */
  9963. struct process_control_data {
  9964. pid_t pid;
  9965. ptrdiff_t references;
  9966. };
  9967. static int
  9968. abort_cgi_process(void *data)
  9969. {
  9970. /* Waitpid checks for child status and won't work for a pid that does
  9971. * not identify a child of the current process. Thus, if the pid is
  9972. * reused, we will not affect a different process. */
  9973. struct process_control_data *proc = (struct process_control_data *)data;
  9974. int status = 0;
  9975. ptrdiff_t refs;
  9976. pid_t ret_pid;
  9977. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9978. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9979. /* Stop child process */
  9980. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9981. kill(proc->pid, SIGABRT);
  9982. /* Wait until process is terminated (don't leave zombies) */
  9983. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9984. ;
  9985. } else {
  9986. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9987. }
  9988. /* Dec reference counter */
  9989. refs = mg_atomic_dec(&proc->references);
  9990. if (refs == 0) {
  9991. /* no more references - free data */
  9992. mg_free(data);
  9993. }
  9994. return 0;
  9995. }
  9996. /* Local (static) function assumes all arguments are valid. */
  9997. static void
  9998. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9999. {
  10000. char *buf;
  10001. size_t buflen;
  10002. int headers_len, data_len, i, truncated;
  10003. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10004. const char *status, *status_text, *connection_state;
  10005. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10006. struct mg_request_info ri;
  10007. struct cgi_environment blk;
  10008. FILE *in = NULL, *out = NULL, *err = NULL;
  10009. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10010. pid_t pid = (pid_t)-1;
  10011. struct process_control_data *proc = NULL;
  10012. #if defined(USE_TIMERS)
  10013. double cgi_timeout;
  10014. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  10015. /* Get timeout in seconds */
  10016. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  10017. } else {
  10018. cgi_timeout =
  10019. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10020. }
  10021. #endif
  10022. buf = NULL;
  10023. buflen = conn->phys_ctx->max_request_size;
  10024. i = prepare_cgi_environment(conn, prog, &blk);
  10025. if (i != 0) {
  10026. blk.buf = NULL;
  10027. blk.var = NULL;
  10028. goto done;
  10029. }
  10030. /* CGI must be executed in its own directory. 'dir' must point to the
  10031. * directory containing executable program, 'p' must point to the
  10032. * executable program name relative to 'dir'. */
  10033. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10034. if (truncated) {
  10035. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10036. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10037. goto done;
  10038. }
  10039. if ((p = strrchr(dir, '/')) != NULL) {
  10040. *p++ = '\0';
  10041. } else {
  10042. dir[0] = '.';
  10043. dir[1] = '\0';
  10044. p = (char *)prog;
  10045. }
  10046. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10047. status = strerror(ERRNO);
  10048. mg_cry_internal(
  10049. conn,
  10050. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10051. prog,
  10052. status);
  10053. mg_send_http_error(conn,
  10054. 500,
  10055. "Error: Cannot create CGI pipe: %s",
  10056. status);
  10057. goto done;
  10058. }
  10059. proc = (struct process_control_data *)
  10060. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10061. if (proc == NULL) {
  10062. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10063. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10064. goto done;
  10065. }
  10066. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10067. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  10068. if (pid == (pid_t)-1) {
  10069. status = strerror(ERRNO);
  10070. mg_cry_internal(
  10071. conn,
  10072. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10073. prog,
  10074. status);
  10075. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10076. mg_free(proc);
  10077. proc = NULL;
  10078. goto done;
  10079. }
  10080. /* Store data in shared process_control_data */
  10081. proc->pid = pid;
  10082. proc->references = 1;
  10083. #if defined(USE_TIMERS)
  10084. if (cgi_timeout > 0.0) {
  10085. proc->references = 2;
  10086. // Start a timer for CGI
  10087. timer_add(conn->phys_ctx,
  10088. cgi_timeout /* in seconds */,
  10089. 0.0,
  10090. 1,
  10091. abort_cgi_process,
  10092. (void *)proc,
  10093. NULL);
  10094. }
  10095. #endif
  10096. /* Parent closes only one side of the pipes.
  10097. * If we don't mark them as closed, close() attempt before
  10098. * return from this function throws an exception on Windows.
  10099. * Windows does not like when closed descriptor is closed again. */
  10100. (void)close(fdin[0]);
  10101. (void)close(fdout[1]);
  10102. (void)close(fderr[1]);
  10103. fdin[0] = fdout[1] = fderr[1] = -1;
  10104. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10105. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10106. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10107. status = strerror(ERRNO);
  10108. mg_cry_internal(conn,
  10109. "Error: CGI program \"%s\": Can not open fd: %s",
  10110. prog,
  10111. status);
  10112. mg_send_http_error(conn,
  10113. 500,
  10114. "Error: CGI can not open fd\nfdopen: %s",
  10115. status);
  10116. goto done;
  10117. }
  10118. setbuf(in, NULL);
  10119. setbuf(out, NULL);
  10120. setbuf(err, NULL);
  10121. fout.access.fp = out;
  10122. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10123. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10124. conn->content_len);
  10125. /* This is a POST/PUT request, or another request with body data. */
  10126. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10127. /* Error sending the body data */
  10128. mg_cry_internal(
  10129. conn,
  10130. "Error: CGI program \"%s\": Forward body data failed",
  10131. prog);
  10132. goto done;
  10133. }
  10134. }
  10135. /* Close so child gets an EOF. */
  10136. fclose(in);
  10137. in = NULL;
  10138. fdin[1] = -1;
  10139. /* Now read CGI reply into a buffer. We need to set correct
  10140. * status code, thus we need to see all HTTP headers first.
  10141. * Do not send anything back to client, until we buffer in all
  10142. * HTTP headers. */
  10143. data_len = 0;
  10144. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10145. if (buf == NULL) {
  10146. mg_send_http_error(conn,
  10147. 500,
  10148. "Error: Not enough memory for CGI buffer (%u bytes)",
  10149. (unsigned int)buflen);
  10150. mg_cry_internal(
  10151. conn,
  10152. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10153. "bytes)",
  10154. prog,
  10155. (unsigned int)buflen);
  10156. goto done;
  10157. }
  10158. DEBUG_TRACE("CGI: %s", "wait for response");
  10159. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10160. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10161. if (headers_len <= 0) {
  10162. /* Could not parse the CGI response. Check if some error message on
  10163. * stderr. */
  10164. i = pull_all(err, conn, buf, (int)buflen);
  10165. if (i > 0) {
  10166. /* CGI program explicitly sent an error */
  10167. /* Write the error message to the internal log */
  10168. mg_cry_internal(conn,
  10169. "Error: CGI program \"%s\" sent error "
  10170. "message: [%.*s]",
  10171. prog,
  10172. i,
  10173. buf);
  10174. /* Don't send the error message back to the client */
  10175. mg_send_http_error(conn,
  10176. 500,
  10177. "Error: CGI program \"%s\" failed.",
  10178. prog);
  10179. } else {
  10180. /* CGI program did not explicitly send an error, but a broken
  10181. * respon header */
  10182. mg_cry_internal(conn,
  10183. "Error: CGI program sent malformed or too big "
  10184. "(>%u bytes) HTTP headers: [%.*s]",
  10185. (unsigned)buflen,
  10186. data_len,
  10187. buf);
  10188. mg_send_http_error(conn,
  10189. 500,
  10190. "Error: CGI program sent malformed or too big "
  10191. "(>%u bytes) HTTP headers: [%.*s]",
  10192. (unsigned)buflen,
  10193. data_len,
  10194. buf);
  10195. }
  10196. /* in both cases, abort processing CGI */
  10197. goto done;
  10198. }
  10199. pbuf = buf;
  10200. buf[headers_len - 1] = '\0';
  10201. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10202. /* Make up and send the status line */
  10203. status_text = "OK";
  10204. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10205. != NULL) {
  10206. conn->status_code = atoi(status);
  10207. status_text = status;
  10208. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10209. status_text++;
  10210. }
  10211. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10212. != NULL) {
  10213. conn->status_code = 307;
  10214. } else {
  10215. conn->status_code = 200;
  10216. }
  10217. connection_state =
  10218. get_header(ri.http_headers, ri.num_headers, "Connection");
  10219. if (!header_has_option(connection_state, "keep-alive")) {
  10220. conn->must_close = 1;
  10221. }
  10222. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10223. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10224. /* Send headers */
  10225. for (i = 0; i < ri.num_headers; i++) {
  10226. DEBUG_TRACE("CGI header: %s: %s",
  10227. ri.http_headers[i].name,
  10228. ri.http_headers[i].value);
  10229. mg_printf(conn,
  10230. "%s: %s\r\n",
  10231. ri.http_headers[i].name,
  10232. ri.http_headers[i].value);
  10233. }
  10234. mg_write(conn, "\r\n", 2);
  10235. /* Send chunk of data that may have been read after the headers */
  10236. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10237. /* Read the rest of CGI output and send to the client */
  10238. DEBUG_TRACE("CGI: %s", "forward all data");
  10239. send_file_data(conn, &fout, 0, INT64_MAX);
  10240. DEBUG_TRACE("CGI: %s", "all data sent");
  10241. done:
  10242. mg_free(blk.var);
  10243. mg_free(blk.buf);
  10244. if (pid != (pid_t)-1) {
  10245. abort_cgi_process((void *)proc);
  10246. }
  10247. if (fdin[0] != -1) {
  10248. close(fdin[0]);
  10249. }
  10250. if (fdout[1] != -1) {
  10251. close(fdout[1]);
  10252. }
  10253. if (fderr[1] != -1) {
  10254. close(fderr[1]);
  10255. }
  10256. if (in != NULL) {
  10257. fclose(in);
  10258. } else if (fdin[1] != -1) {
  10259. close(fdin[1]);
  10260. }
  10261. if (out != NULL) {
  10262. fclose(out);
  10263. } else if (fdout[0] != -1) {
  10264. close(fdout[0]);
  10265. }
  10266. if (err != NULL) {
  10267. fclose(err);
  10268. } else if (fderr[0] != -1) {
  10269. close(fderr[0]);
  10270. }
  10271. mg_free(buf);
  10272. }
  10273. #endif /* !NO_CGI */
  10274. #if !defined(NO_FILES)
  10275. static void
  10276. mkcol(struct mg_connection *conn, const char *path)
  10277. {
  10278. int rc, body_len;
  10279. struct de de;
  10280. if (conn == NULL) {
  10281. return;
  10282. }
  10283. /* TODO (mid): Check the mg_send_http_error situations in this function
  10284. */
  10285. memset(&de.file, 0, sizeof(de.file));
  10286. if (!mg_stat(conn, path, &de.file)) {
  10287. mg_cry_internal(conn,
  10288. "%s: mg_stat(%s) failed: %s",
  10289. __func__,
  10290. path,
  10291. strerror(ERRNO));
  10292. }
  10293. if (de.file.last_modified) {
  10294. /* TODO (mid): This check does not seem to make any sense ! */
  10295. /* TODO (mid): Add a webdav unit test first, before changing
  10296. * anything here. */
  10297. mg_send_http_error(
  10298. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10299. return;
  10300. }
  10301. body_len = conn->data_len - conn->request_len;
  10302. if (body_len > 0) {
  10303. mg_send_http_error(
  10304. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10305. return;
  10306. }
  10307. rc = mg_mkdir(conn, path, 0755);
  10308. if (rc == 0) {
  10309. /* Create 201 "Created" response */
  10310. mg_response_header_start(conn, 201);
  10311. send_static_cache_header(conn);
  10312. send_additional_header(conn);
  10313. mg_response_header_add(conn, "Content-Length", "0", -1);
  10314. /* Send all headers - there is no body */
  10315. mg_response_header_send(conn);
  10316. } else {
  10317. if (errno == EEXIST) {
  10318. mg_send_http_error(
  10319. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10320. } else if (errno == EACCES) {
  10321. mg_send_http_error(
  10322. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10323. } else if (errno == ENOENT) {
  10324. mg_send_http_error(
  10325. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10326. } else {
  10327. mg_send_http_error(
  10328. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10329. }
  10330. }
  10331. }
  10332. static void
  10333. put_file(struct mg_connection *conn, const char *path)
  10334. {
  10335. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10336. const char *range;
  10337. int64_t r1, r2;
  10338. int rc;
  10339. if (conn == NULL) {
  10340. return;
  10341. }
  10342. if (mg_stat(conn, path, &file.stat)) {
  10343. /* File already exists */
  10344. conn->status_code = 200;
  10345. if (file.stat.is_directory) {
  10346. /* This is an already existing directory,
  10347. * so there is nothing to do for the server. */
  10348. rc = 0;
  10349. } else {
  10350. /* File exists and is not a directory. */
  10351. /* Can it be replaced? */
  10352. /* Check if the server may write this file */
  10353. if (access(path, W_OK) == 0) {
  10354. /* Access granted */
  10355. rc = 1;
  10356. } else {
  10357. mg_send_http_error(
  10358. conn,
  10359. 403,
  10360. "Error: Put not possible\nReplacing %s is not allowed",
  10361. path);
  10362. return;
  10363. }
  10364. }
  10365. } else {
  10366. /* File should be created */
  10367. conn->status_code = 201;
  10368. rc = put_dir(conn, path);
  10369. }
  10370. if (rc == 0) {
  10371. /* put_dir returns 0 if path is a directory */
  10372. /* Create response */
  10373. mg_response_header_start(conn, conn->status_code);
  10374. send_no_cache_header(conn);
  10375. send_additional_header(conn);
  10376. mg_response_header_add(conn, "Content-Length", "0", -1);
  10377. /* Send all headers - there is no body */
  10378. mg_response_header_send(conn);
  10379. /* Request to create a directory has been fulfilled successfully.
  10380. * No need to put a file. */
  10381. return;
  10382. }
  10383. if (rc == -1) {
  10384. /* put_dir returns -1 if the path is too long */
  10385. mg_send_http_error(conn,
  10386. 414,
  10387. "Error: Path too long\nput_dir(%s): %s",
  10388. path,
  10389. strerror(ERRNO));
  10390. return;
  10391. }
  10392. if (rc == -2) {
  10393. /* put_dir returns -2 if the directory can not be created */
  10394. mg_send_http_error(conn,
  10395. 500,
  10396. "Error: Can not create directory\nput_dir(%s): %s",
  10397. path,
  10398. strerror(ERRNO));
  10399. return;
  10400. }
  10401. /* A file should be created or overwritten. */
  10402. /* Currently CivetWeb does not nead read+write access. */
  10403. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10404. || file.access.fp == NULL) {
  10405. (void)mg_fclose(&file.access);
  10406. mg_send_http_error(conn,
  10407. 500,
  10408. "Error: Can not create file\nfopen(%s): %s",
  10409. path,
  10410. strerror(ERRNO));
  10411. return;
  10412. }
  10413. fclose_on_exec(&file.access, conn);
  10414. range = mg_get_header(conn, "Content-Range");
  10415. r1 = r2 = 0;
  10416. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10417. conn->status_code = 206; /* Partial content */
  10418. fseeko(file.access.fp, r1, SEEK_SET);
  10419. }
  10420. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10421. /* forward_body_data failed.
  10422. * The error code has already been sent to the client,
  10423. * and conn->status_code is already set. */
  10424. (void)mg_fclose(&file.access);
  10425. return;
  10426. }
  10427. if (mg_fclose(&file.access) != 0) {
  10428. /* fclose failed. This might have different reasons, but a likely
  10429. * one is "no space on disk", http 507. */
  10430. conn->status_code = 507;
  10431. }
  10432. /* Create response (status_code has been set before) */
  10433. mg_response_header_start(conn, conn->status_code);
  10434. send_no_cache_header(conn);
  10435. send_additional_header(conn);
  10436. mg_response_header_add(conn, "Content-Length", "0", -1);
  10437. /* Send all headers - there is no body */
  10438. mg_response_header_send(conn);
  10439. }
  10440. static void
  10441. delete_file(struct mg_connection *conn, const char *path)
  10442. {
  10443. struct de de;
  10444. memset(&de.file, 0, sizeof(de.file));
  10445. if (!mg_stat(conn, path, &de.file)) {
  10446. /* mg_stat returns 0 if the file does not exist */
  10447. mg_send_http_error(conn,
  10448. 404,
  10449. "Error: Cannot delete file\nFile %s not found",
  10450. path);
  10451. return;
  10452. }
  10453. if (de.file.is_directory) {
  10454. if (remove_directory(conn, path)) {
  10455. /* Delete is successful: Return 204 without content. */
  10456. mg_send_http_error(conn, 204, "%s", "");
  10457. } else {
  10458. /* Delete is not successful: Return 500 (Server error). */
  10459. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10460. }
  10461. return;
  10462. }
  10463. /* This is an existing file (not a directory).
  10464. * Check if write permission is granted. */
  10465. if (access(path, W_OK) != 0) {
  10466. /* File is read only */
  10467. mg_send_http_error(
  10468. conn,
  10469. 403,
  10470. "Error: Delete not possible\nDeleting %s is not allowed",
  10471. path);
  10472. return;
  10473. }
  10474. /* Try to delete it. */
  10475. if (mg_remove(conn, path) == 0) {
  10476. /* Delete was successful: Return 204 without content. */
  10477. mg_response_header_start(conn, 204);
  10478. send_no_cache_header(conn);
  10479. send_additional_header(conn);
  10480. mg_response_header_add(conn, "Content-Length", "0", -1);
  10481. mg_response_header_send(conn);
  10482. } else {
  10483. /* Delete not successful (file locked). */
  10484. mg_send_http_error(conn,
  10485. 423,
  10486. "Error: Cannot delete file\nremove(%s): %s",
  10487. path,
  10488. strerror(ERRNO));
  10489. }
  10490. }
  10491. #endif /* !NO_FILES */
  10492. #if !defined(NO_FILESYSTEMS)
  10493. static void
  10494. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10495. static void
  10496. do_ssi_include(struct mg_connection *conn,
  10497. const char *ssi,
  10498. char *tag,
  10499. int include_level)
  10500. {
  10501. char file_name[MG_BUF_LEN], path[512], *p;
  10502. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10503. size_t len;
  10504. int truncated = 0;
  10505. if (conn == NULL) {
  10506. return;
  10507. }
  10508. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10509. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10510. * always < MG_BUF_LEN. */
  10511. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10512. /* File name is relative to the webserver root */
  10513. file_name[511] = 0;
  10514. (void)mg_snprintf(conn,
  10515. &truncated,
  10516. path,
  10517. sizeof(path),
  10518. "%s/%s",
  10519. conn->dom_ctx->config[DOCUMENT_ROOT],
  10520. file_name);
  10521. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10522. /* File name is relative to the webserver working directory
  10523. * or it is absolute system path */
  10524. file_name[511] = 0;
  10525. (void)
  10526. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10527. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10528. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10529. /* File name is relative to the currect document */
  10530. file_name[511] = 0;
  10531. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10532. if (!truncated) {
  10533. if ((p = strrchr(path, '/')) != NULL) {
  10534. p[1] = '\0';
  10535. }
  10536. len = strlen(path);
  10537. (void)mg_snprintf(conn,
  10538. &truncated,
  10539. path + len,
  10540. sizeof(path) - len,
  10541. "%s",
  10542. file_name);
  10543. }
  10544. } else {
  10545. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10546. return;
  10547. }
  10548. if (truncated) {
  10549. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10550. return;
  10551. }
  10552. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10553. mg_cry_internal(conn,
  10554. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10555. tag,
  10556. path,
  10557. strerror(ERRNO));
  10558. } else {
  10559. fclose_on_exec(&file.access, conn);
  10560. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10561. > 0) {
  10562. send_ssi_file(conn, path, &file, include_level + 1);
  10563. } else {
  10564. send_file_data(conn, &file, 0, INT64_MAX);
  10565. }
  10566. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10567. }
  10568. }
  10569. #if !defined(NO_POPEN)
  10570. static void
  10571. do_ssi_exec(struct mg_connection *conn, char *tag)
  10572. {
  10573. char cmd[1024] = "";
  10574. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10575. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10576. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10577. } else {
  10578. cmd[1023] = 0;
  10579. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10580. mg_cry_internal(conn,
  10581. "Cannot SSI #exec: [%s]: %s",
  10582. cmd,
  10583. strerror(ERRNO));
  10584. } else {
  10585. send_file_data(conn, &file, 0, INT64_MAX);
  10586. pclose(file.access.fp);
  10587. }
  10588. }
  10589. }
  10590. #endif /* !NO_POPEN */
  10591. static int
  10592. mg_fgetc(struct mg_file *filep)
  10593. {
  10594. if (filep == NULL) {
  10595. return EOF;
  10596. }
  10597. if (filep->access.fp != NULL) {
  10598. return fgetc(filep->access.fp);
  10599. } else {
  10600. return EOF;
  10601. }
  10602. }
  10603. static void
  10604. send_ssi_file(struct mg_connection *conn,
  10605. const char *path,
  10606. struct mg_file *filep,
  10607. int include_level)
  10608. {
  10609. char buf[MG_BUF_LEN];
  10610. int ch, len, in_tag, in_ssi_tag;
  10611. if (include_level > 10) {
  10612. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10613. return;
  10614. }
  10615. in_tag = in_ssi_tag = len = 0;
  10616. /* Read file, byte by byte, and look for SSI include tags */
  10617. while ((ch = mg_fgetc(filep)) != EOF) {
  10618. if (in_tag) {
  10619. /* We are in a tag, either SSI tag or html tag */
  10620. if (ch == '>') {
  10621. /* Tag is closing */
  10622. buf[len++] = '>';
  10623. if (in_ssi_tag) {
  10624. /* Handle SSI tag */
  10625. buf[len] = 0;
  10626. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10627. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10628. #if !defined(NO_POPEN)
  10629. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10630. do_ssi_exec(conn, buf + 9);
  10631. #endif /* !NO_POPEN */
  10632. } else {
  10633. mg_cry_internal(conn,
  10634. "%s: unknown SSI "
  10635. "command: \"%s\"",
  10636. path,
  10637. buf);
  10638. }
  10639. len = 0;
  10640. in_ssi_tag = in_tag = 0;
  10641. } else {
  10642. /* Not an SSI tag */
  10643. /* Flush buffer */
  10644. (void)mg_write(conn, buf, (size_t)len);
  10645. len = 0;
  10646. in_tag = 0;
  10647. }
  10648. } else {
  10649. /* Tag is still open */
  10650. buf[len++] = (char)(ch & 0xff);
  10651. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10652. /* All SSI tags start with <!--# */
  10653. in_ssi_tag = 1;
  10654. }
  10655. if ((len + 2) > (int)sizeof(buf)) {
  10656. /* Tag to long for buffer */
  10657. mg_cry_internal(conn, "%s: tag is too large", path);
  10658. return;
  10659. }
  10660. }
  10661. } else {
  10662. /* We are not in a tag yet. */
  10663. if (ch == '<') {
  10664. /* Tag is opening */
  10665. in_tag = 1;
  10666. if (len > 0) {
  10667. /* Flush current buffer.
  10668. * Buffer is filled with "len" bytes. */
  10669. (void)mg_write(conn, buf, (size_t)len);
  10670. }
  10671. /* Store the < */
  10672. len = 1;
  10673. buf[0] = '<';
  10674. } else {
  10675. /* No Tag */
  10676. /* Add data to buffer */
  10677. buf[len++] = (char)(ch & 0xff);
  10678. /* Flush if buffer is full */
  10679. if (len == (int)sizeof(buf)) {
  10680. mg_write(conn, buf, (size_t)len);
  10681. len = 0;
  10682. }
  10683. }
  10684. }
  10685. }
  10686. /* Send the rest of buffered data */
  10687. if (len > 0) {
  10688. mg_write(conn, buf, (size_t)len);
  10689. }
  10690. }
  10691. static void
  10692. handle_ssi_file_request(struct mg_connection *conn,
  10693. const char *path,
  10694. struct mg_file *filep)
  10695. {
  10696. char date[64];
  10697. time_t curtime = time(NULL);
  10698. const char *cors_orig_cfg;
  10699. const char *cors1, *cors2;
  10700. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10701. return;
  10702. }
  10703. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10704. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10705. /* Cross-origin resource sharing (CORS). */
  10706. cors1 = "Access-Control-Allow-Origin";
  10707. cors2 = cors_orig_cfg;
  10708. } else {
  10709. cors1 = cors2 = "";
  10710. }
  10711. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10712. /* File exists (precondition for calling this function),
  10713. * but can not be opened by the server. */
  10714. mg_send_http_error(conn,
  10715. 500,
  10716. "Error: Cannot read file\nfopen(%s): %s",
  10717. path,
  10718. strerror(ERRNO));
  10719. } else {
  10720. /* Set "must_close" for HTTP/1.x, since we do not know the
  10721. * content length */
  10722. conn->must_close = 1;
  10723. gmt_time_string(date, sizeof(date), &curtime);
  10724. fclose_on_exec(&filep->access, conn);
  10725. /* 200 OK response */
  10726. mg_response_header_start(conn, 200);
  10727. send_no_cache_header(conn);
  10728. send_additional_header(conn);
  10729. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10730. if (cors1[0]) {
  10731. mg_response_header_add(conn, cors1, cors2, -1);
  10732. }
  10733. mg_response_header_send(conn);
  10734. /* Header sent, now send body */
  10735. send_ssi_file(conn, path, filep, 0);
  10736. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10737. }
  10738. }
  10739. #endif /* NO_FILESYSTEMS */
  10740. #if !defined(NO_FILES)
  10741. static void
  10742. send_options(struct mg_connection *conn)
  10743. {
  10744. if (!conn) {
  10745. return;
  10746. }
  10747. /* We do not set a "Cache-Control" header here, but leave the default.
  10748. * Since browsers do not send an OPTIONS request, we can not test the
  10749. * effect anyway. */
  10750. mg_response_header_start(conn, 200);
  10751. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10752. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10753. /* Use the same as before */
  10754. mg_response_header_add(
  10755. conn,
  10756. "Allow",
  10757. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10758. -1);
  10759. mg_response_header_add(conn, "DAV", "1", -1);
  10760. } else {
  10761. /* TODO: Check this later for HTTP/2 */
  10762. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10763. }
  10764. send_additional_header(conn);
  10765. mg_response_header_send(conn);
  10766. }
  10767. /* Writes PROPFIND properties for a collection element */
  10768. static int
  10769. print_props(struct mg_connection *conn,
  10770. const char *uri,
  10771. const char *name,
  10772. struct mg_file_stat *filep)
  10773. {
  10774. size_t href_size, i, j;
  10775. int len;
  10776. char *href, mtime[64];
  10777. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10778. return 0;
  10779. }
  10780. /* Estimate worst case size for encoding */
  10781. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10782. href = (char *)mg_malloc(href_size);
  10783. if (href == NULL) {
  10784. return 0;
  10785. }
  10786. len = mg_url_encode(uri, href, href_size);
  10787. if (len >= 0) {
  10788. /* Append an extra string */
  10789. mg_url_encode(name, href + len, href_size - (size_t)len);
  10790. }
  10791. /* Directory separator should be preserved. */
  10792. for (i = j = 0; href[i]; j++) {
  10793. if (!strncmp(href + i, "%2f", 3)) {
  10794. href[j] = '/';
  10795. i += 3;
  10796. } else {
  10797. href[j] = href[i++];
  10798. }
  10799. }
  10800. href[j] = '\0';
  10801. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10802. mg_printf(conn,
  10803. "<d:response>"
  10804. "<d:href>%s</d:href>"
  10805. "<d:propstat>"
  10806. "<d:prop>"
  10807. "<d:resourcetype>%s</d:resourcetype>"
  10808. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10809. "<d:getlastmodified>%s</d:getlastmodified>"
  10810. "</d:prop>"
  10811. "<d:status>HTTP/1.1 200 OK</d:status>"
  10812. "</d:propstat>"
  10813. "</d:response>\n",
  10814. href,
  10815. filep->is_directory ? "<d:collection/>" : "",
  10816. filep->size,
  10817. mtime);
  10818. mg_free(href);
  10819. return 1;
  10820. }
  10821. static int
  10822. print_dav_dir_entry(struct de *de, void *data)
  10823. {
  10824. struct mg_connection *conn = (struct mg_connection *)data;
  10825. if (!de || !conn
  10826. || !print_props(
  10827. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10828. /* stop scan */
  10829. return 1;
  10830. }
  10831. return 0;
  10832. }
  10833. static void
  10834. handle_propfind(struct mg_connection *conn,
  10835. const char *path,
  10836. struct mg_file_stat *filep)
  10837. {
  10838. const char *depth = mg_get_header(conn, "Depth");
  10839. char date[64];
  10840. time_t curtime = time(NULL);
  10841. gmt_time_string(date, sizeof(date), &curtime);
  10842. if (!conn || !path || !filep || !conn->dom_ctx) {
  10843. return;
  10844. }
  10845. conn->must_close = 1;
  10846. /* return 207 "Multi-Status" */
  10847. mg_response_header_start(conn, 207);
  10848. send_static_cache_header(conn);
  10849. send_additional_header(conn);
  10850. mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10851. mg_response_header_send(conn);
  10852. /* Content */
  10853. mg_printf(conn,
  10854. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10855. "<d:multistatus xmlns:d='DAV:'>\n");
  10856. /* Print properties for the requested resource itself */
  10857. print_props(conn, conn->request_info.local_uri, "", filep);
  10858. /* If it is a directory, print directory entries too if Depth is not 0
  10859. */
  10860. if (filep->is_directory
  10861. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10862. "yes")
  10863. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10864. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10865. }
  10866. mg_printf(conn, "%s\n", "</d:multistatus>");
  10867. }
  10868. #endif
  10869. void
  10870. mg_lock_connection(struct mg_connection *conn)
  10871. {
  10872. if (conn) {
  10873. (void)pthread_mutex_lock(&conn->mutex);
  10874. }
  10875. }
  10876. void
  10877. mg_unlock_connection(struct mg_connection *conn)
  10878. {
  10879. if (conn) {
  10880. (void)pthread_mutex_unlock(&conn->mutex);
  10881. }
  10882. }
  10883. void
  10884. mg_lock_context(struct mg_context *ctx)
  10885. {
  10886. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10887. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10888. }
  10889. }
  10890. void
  10891. mg_unlock_context(struct mg_context *ctx)
  10892. {
  10893. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10894. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10895. }
  10896. }
  10897. #if defined(USE_LUA)
  10898. #include "mod_lua.inl"
  10899. #endif /* USE_LUA */
  10900. #if defined(USE_DUKTAPE)
  10901. #include "mod_duktape.inl"
  10902. #endif /* USE_DUKTAPE */
  10903. #if defined(USE_WEBSOCKET)
  10904. #if !defined(NO_SSL_DL)
  10905. #define SHA_API static
  10906. #include "sha1.inl"
  10907. #endif
  10908. static int
  10909. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10910. {
  10911. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10912. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10913. SHA_CTX sha_ctx;
  10914. int truncated;
  10915. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10916. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10917. if (truncated) {
  10918. conn->must_close = 1;
  10919. return 0;
  10920. }
  10921. DEBUG_TRACE("%s", "Send websocket handshake");
  10922. SHA1_Init(&sha_ctx);
  10923. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10924. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10925. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10926. mg_printf(conn,
  10927. "HTTP/1.1 101 Switching Protocols\r\n"
  10928. "Upgrade: websocket\r\n"
  10929. "Connection: Upgrade\r\n"
  10930. "Sec-WebSocket-Accept: %s\r\n",
  10931. b64_sha);
  10932. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10933. // Send negotiated compression extension parameters
  10934. websocket_deflate_response(conn);
  10935. #endif
  10936. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10937. mg_printf(conn,
  10938. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10939. conn->request_info.acceptedWebSocketSubprotocol);
  10940. } else {
  10941. mg_printf(conn, "%s", "\r\n");
  10942. }
  10943. return 1;
  10944. }
  10945. #if !defined(MG_MAX_UNANSWERED_PING)
  10946. /* Configuration of the maximum number of websocket PINGs that might
  10947. * stay unanswered before the connection is considered broken.
  10948. * Note: The name of this define may still change (until it is
  10949. * defined as a compile parameter in a documentation).
  10950. */
  10951. #define MG_MAX_UNANSWERED_PING (5)
  10952. #endif
  10953. static void
  10954. read_websocket(struct mg_connection *conn,
  10955. mg_websocket_data_handler ws_data_handler,
  10956. void *callback_data)
  10957. {
  10958. /* Pointer to the beginning of the portion of the incoming websocket
  10959. * message queue.
  10960. * The original websocket upgrade request is never removed, so the queue
  10961. * begins after it. */
  10962. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10963. int n, error, exit_by_callback;
  10964. int ret;
  10965. /* body_len is the length of the entire queue in bytes
  10966. * len is the length of the current message
  10967. * data_len is the length of the current message's data payload
  10968. * header_len is the length of the current message's header */
  10969. size_t i, len, mask_len = 0, header_len, body_len;
  10970. uint64_t data_len = 0;
  10971. /* "The masking key is a 32-bit value chosen at random by the client."
  10972. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10973. */
  10974. unsigned char mask[4];
  10975. /* data points to the place where the message is stored when passed to
  10976. * the websocket_data callback. This is either mem on the stack, or a
  10977. * dynamically allocated buffer if it is too large. */
  10978. unsigned char mem[4096];
  10979. unsigned char mop; /* mask flag and opcode */
  10980. /* Variables used for connection monitoring */
  10981. double timeout = -1.0;
  10982. int enable_ping_pong = 0;
  10983. int ping_count = 0;
  10984. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10985. enable_ping_pong =
  10986. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10987. "yes");
  10988. }
  10989. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10990. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10991. }
  10992. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10993. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10994. }
  10995. if (timeout <= 0.0) {
  10996. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  10997. }
  10998. /* Enter data processing loop */
  10999. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11000. conn->request_info.remote_addr,
  11001. conn->request_info.remote_port);
  11002. conn->in_websocket_handling = 1;
  11003. mg_set_thread_name("wsock");
  11004. /* Loop continuously, reading messages from the socket, invoking the
  11005. * callback, and waiting repeatedly until an error occurs. */
  11006. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11007. && (!conn->must_close)) {
  11008. header_len = 0;
  11009. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11010. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11011. len = buf[1] & 127;
  11012. mask_len = (buf[1] & 128) ? 4 : 0;
  11013. if ((len < 126) && (body_len >= mask_len)) {
  11014. /* inline 7-bit length field */
  11015. data_len = len;
  11016. header_len = 2 + mask_len;
  11017. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11018. /* 16-bit length field */
  11019. header_len = 4 + mask_len;
  11020. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11021. } else if (body_len >= (10 + mask_len)) {
  11022. /* 64-bit length field */
  11023. uint32_t l1, l2;
  11024. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11025. memcpy(&l2, &buf[6], 4);
  11026. header_len = 10 + mask_len;
  11027. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11028. if (data_len > (uint64_t)0x7FFF0000ul) {
  11029. /* no can do */
  11030. mg_cry_internal(
  11031. conn,
  11032. "%s",
  11033. "websocket out of memory; closing connection");
  11034. break;
  11035. }
  11036. }
  11037. }
  11038. if ((header_len > 0) && (body_len >= header_len)) {
  11039. /* Allocate space to hold websocket payload */
  11040. unsigned char *data = mem;
  11041. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11042. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11043. conn->phys_ctx);
  11044. if (data == NULL) {
  11045. /* Allocation failed, exit the loop and then close the
  11046. * connection */
  11047. mg_cry_internal(
  11048. conn,
  11049. "%s",
  11050. "websocket out of memory; closing connection");
  11051. break;
  11052. }
  11053. }
  11054. /* Copy the mask before we shift the queue and destroy it */
  11055. if (mask_len > 0) {
  11056. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11057. } else {
  11058. memset(mask, 0, sizeof(mask));
  11059. }
  11060. /* Read frame payload from the first message in the queue into
  11061. * data and advance the queue by moving the memory in place. */
  11062. DEBUG_ASSERT(body_len >= header_len);
  11063. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11064. mop = buf[0]; /* current mask and opcode */
  11065. /* Overflow case */
  11066. len = body_len - header_len;
  11067. memcpy(data, buf + header_len, len);
  11068. error = 0;
  11069. while ((uint64_t)len < data_len) {
  11070. n = pull_inner(NULL,
  11071. conn,
  11072. (char *)(data + len),
  11073. (int)(data_len - len),
  11074. timeout);
  11075. if (n <= -2) {
  11076. error = 1;
  11077. break;
  11078. } else if (n > 0) {
  11079. len += (size_t)n;
  11080. } else {
  11081. /* Timeout: should retry */
  11082. /* TODO: retry condition */
  11083. }
  11084. }
  11085. if (error) {
  11086. mg_cry_internal(
  11087. conn,
  11088. "%s",
  11089. "Websocket pull failed; closing connection");
  11090. if (data != mem) {
  11091. mg_free(data);
  11092. }
  11093. break;
  11094. }
  11095. conn->data_len = conn->request_len;
  11096. } else {
  11097. mop = buf[0]; /* current mask and opcode, overwritten by
  11098. * memmove() */
  11099. /* Length of the message being read at the front of the
  11100. * queue. Cast to 31 bit is OK, since we limited
  11101. * data_len before. */
  11102. len = (size_t)data_len + header_len;
  11103. /* Copy the data payload into the data pointer for the
  11104. * callback. Cast to 31 bit is OK, since we
  11105. * limited data_len */
  11106. memcpy(data, buf + header_len, (size_t)data_len);
  11107. /* Move the queue forward len bytes */
  11108. memmove(buf, buf + len, body_len - len);
  11109. /* Mark the queue as advanced */
  11110. conn->data_len -= (int)len;
  11111. }
  11112. /* Apply mask if necessary */
  11113. if (mask_len > 0) {
  11114. for (i = 0; i < (size_t)data_len; i++) {
  11115. data[i] ^= mask[i & 3];
  11116. }
  11117. }
  11118. exit_by_callback = 0;
  11119. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11120. /* filter PONG messages */
  11121. DEBUG_TRACE("PONG from %s:%u",
  11122. conn->request_info.remote_addr,
  11123. conn->request_info.remote_port);
  11124. /* No unanwered PINGs left */
  11125. ping_count = 0;
  11126. } else if (enable_ping_pong
  11127. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11128. /* reply PING messages */
  11129. DEBUG_TRACE("Reply PING from %s:%u",
  11130. conn->request_info.remote_addr,
  11131. conn->request_info.remote_port);
  11132. ret = mg_websocket_write(conn,
  11133. MG_WEBSOCKET_OPCODE_PONG,
  11134. (char *)data,
  11135. (size_t)data_len);
  11136. if (ret <= 0) {
  11137. /* Error: send failed */
  11138. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11139. break;
  11140. }
  11141. } else {
  11142. /* Exit the loop if callback signals to exit (server side),
  11143. * or "connection close" opcode received (client side). */
  11144. if (ws_data_handler != NULL) {
  11145. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11146. if (mop & 0x40) {
  11147. /* Inflate the data received if bit RSV1 is set. */
  11148. if (!conn->websocket_deflate_initialized) {
  11149. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11150. exit_by_callback = 1;
  11151. }
  11152. if (!exit_by_callback) {
  11153. size_t inflate_buf_size_old = 0;
  11154. size_t inflate_buf_size =
  11155. data_len
  11156. * 10; // Initial guess of the inflated message
  11157. // size. We double the memory when needed.
  11158. Bytef *inflated;
  11159. Bytef *new_mem;
  11160. conn->websocket_inflate_state.avail_in =
  11161. (uInt)(data_len + 4);
  11162. conn->websocket_inflate_state.next_in = data;
  11163. // Add trailing 0x00 0x00 0xff 0xff bytes
  11164. data[data_len] = '\x00';
  11165. data[data_len + 1] = '\x00';
  11166. data[data_len + 2] = '\xff';
  11167. data[data_len + 3] = '\xff';
  11168. do {
  11169. if (inflate_buf_size_old == 0) {
  11170. new_mem = mg_calloc(inflate_buf_size,
  11171. sizeof(Bytef));
  11172. } else {
  11173. inflate_buf_size *= 2;
  11174. new_mem =
  11175. mg_realloc(inflated, inflate_buf_size);
  11176. }
  11177. if (new_mem == NULL) {
  11178. mg_cry_internal(
  11179. conn,
  11180. "Out of memory: Cannot allocate "
  11181. "inflate buffer of %zu bytes",
  11182. inflate_buf_size);
  11183. exit_by_callback = 1;
  11184. break;
  11185. }
  11186. inflated = new_mem;
  11187. conn->websocket_inflate_state.avail_out =
  11188. (uInt)(inflate_buf_size
  11189. - inflate_buf_size_old);
  11190. conn->websocket_inflate_state.next_out =
  11191. inflated + inflate_buf_size_old;
  11192. int ret =
  11193. inflate(&conn->websocket_inflate_state,
  11194. Z_SYNC_FLUSH);
  11195. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11196. || ret == Z_MEM_ERROR) {
  11197. mg_cry_internal(
  11198. conn,
  11199. "ZLIB inflate error: %i %s",
  11200. ret,
  11201. (conn->websocket_inflate_state.msg
  11202. ? conn->websocket_inflate_state.msg
  11203. : "<no error message>"));
  11204. exit_by_callback = 1;
  11205. break;
  11206. }
  11207. inflate_buf_size_old = inflate_buf_size;
  11208. } while (conn->websocket_inflate_state.avail_out
  11209. == 0);
  11210. inflate_buf_size -=
  11211. conn->websocket_inflate_state.avail_out;
  11212. if (!ws_data_handler(conn,
  11213. mop,
  11214. (char *)inflated,
  11215. inflate_buf_size,
  11216. callback_data)) {
  11217. exit_by_callback = 1;
  11218. }
  11219. mg_free(inflated);
  11220. }
  11221. } else
  11222. #endif
  11223. if (!ws_data_handler(conn,
  11224. mop,
  11225. (char *)data,
  11226. (size_t)data_len,
  11227. callback_data)) {
  11228. exit_by_callback = 1;
  11229. }
  11230. }
  11231. }
  11232. /* It a buffer has been allocated, free it again */
  11233. if (data != mem) {
  11234. mg_free(data);
  11235. }
  11236. if (exit_by_callback) {
  11237. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11238. conn->request_info.remote_addr,
  11239. conn->request_info.remote_port);
  11240. break;
  11241. }
  11242. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11243. /* Opcode == 8, connection close */
  11244. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11245. conn->request_info.remote_addr,
  11246. conn->request_info.remote_port);
  11247. break;
  11248. }
  11249. /* Not breaking the loop, process next websocket frame. */
  11250. } else {
  11251. /* Read from the socket into the next available location in the
  11252. * message queue. */
  11253. n = pull_inner(NULL,
  11254. conn,
  11255. conn->buf + conn->data_len,
  11256. conn->buf_size - conn->data_len,
  11257. timeout);
  11258. if (n <= -2) {
  11259. /* Error, no bytes read */
  11260. DEBUG_TRACE("PULL from %s:%u failed",
  11261. conn->request_info.remote_addr,
  11262. conn->request_info.remote_port);
  11263. break;
  11264. }
  11265. if (n > 0) {
  11266. conn->data_len += n;
  11267. /* Reset open PING count */
  11268. ping_count = 0;
  11269. } else {
  11270. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11271. && (!conn->must_close)) {
  11272. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11273. /* Stop sending PING */
  11274. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11275. "- closing connection",
  11276. ping_count,
  11277. conn->request_info.remote_addr,
  11278. conn->request_info.remote_port);
  11279. break;
  11280. }
  11281. if (enable_ping_pong) {
  11282. /* Send Websocket PING message */
  11283. DEBUG_TRACE("PING to %s:%u",
  11284. conn->request_info.remote_addr,
  11285. conn->request_info.remote_port);
  11286. ret = mg_websocket_write(conn,
  11287. MG_WEBSOCKET_OPCODE_PING,
  11288. NULL,
  11289. 0);
  11290. if (ret <= 0) {
  11291. /* Error: send failed */
  11292. DEBUG_TRACE("Send PING failed (%i)", ret);
  11293. break;
  11294. }
  11295. ping_count++;
  11296. }
  11297. }
  11298. /* Timeout: should retry */
  11299. /* TODO: get timeout def */
  11300. }
  11301. }
  11302. }
  11303. /* Leave data processing loop */
  11304. mg_set_thread_name("worker");
  11305. conn->in_websocket_handling = 0;
  11306. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11307. conn->request_info.remote_addr,
  11308. conn->request_info.remote_port);
  11309. }
  11310. static int
  11311. mg_websocket_write_exec(struct mg_connection *conn,
  11312. int opcode,
  11313. const char *data,
  11314. size_t dataLen,
  11315. uint32_t masking_key)
  11316. {
  11317. unsigned char header[14];
  11318. size_t headerLen;
  11319. int retval;
  11320. #if defined(GCC_DIAGNOSTIC)
  11321. /* Disable spurious conversion warning for GCC */
  11322. #pragma GCC diagnostic push
  11323. #pragma GCC diagnostic ignored "-Wconversion"
  11324. #endif
  11325. /* Note that POSIX/Winsock's send() is threadsafe
  11326. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11327. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11328. * push(), although that is only a problem if the packet is large or
  11329. * outgoing buffer is full). */
  11330. /* TODO: Check if this lock should be moved to user land.
  11331. * Currently the server sets this lock for websockets, but
  11332. * not for any other connection. It must be set for every
  11333. * conn read/written by more than one thread, no matter if
  11334. * it is a websocket or regular connection. */
  11335. (void)mg_lock_connection(conn);
  11336. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11337. size_t deflated_size;
  11338. Bytef *deflated;
  11339. // Deflate websocket messages over 100kb
  11340. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11341. if (use_deflate) {
  11342. if (!conn->websocket_deflate_initialized) {
  11343. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11344. return 0;
  11345. }
  11346. // Deflating the message
  11347. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11348. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11349. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11350. deflated_size = compressBound((uLong)dataLen);
  11351. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11352. if (deflated == NULL) {
  11353. mg_cry_internal(
  11354. conn,
  11355. "Out of memory: Cannot allocate deflate buffer of %zu bytes",
  11356. deflated_size);
  11357. mg_unlock_connection(conn);
  11358. return -1;
  11359. }
  11360. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11361. conn->websocket_deflate_state.next_out = deflated;
  11362. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11363. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11364. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11365. } else
  11366. #endif
  11367. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11368. #if defined(GCC_DIAGNOSTIC)
  11369. #pragma GCC diagnostic pop
  11370. #endif
  11371. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11372. if (dataLen < 126) {
  11373. /* inline 7-bit length field */
  11374. header[1] = (unsigned char)dataLen;
  11375. headerLen = 2;
  11376. } else if (dataLen <= 0xFFFF) {
  11377. /* 16-bit length field */
  11378. uint16_t len = htons((uint16_t)dataLen);
  11379. header[1] = 126;
  11380. memcpy(header + 2, &len, 2);
  11381. headerLen = 4;
  11382. } else {
  11383. /* 64-bit length field */
  11384. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11385. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11386. header[1] = 127;
  11387. memcpy(header + 2, &len1, 4);
  11388. memcpy(header + 6, &len2, 4);
  11389. headerLen = 10;
  11390. }
  11391. if (masking_key) {
  11392. /* add mask */
  11393. header[1] |= 0x80;
  11394. memcpy(header + headerLen, &masking_key, 4);
  11395. headerLen += 4;
  11396. }
  11397. retval = mg_write(conn, header, headerLen);
  11398. if (retval != (int)headerLen) {
  11399. /* Did not send complete header */
  11400. retval = -1;
  11401. } else {
  11402. if (dataLen > 0) {
  11403. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11404. if (use_deflate) {
  11405. retval = mg_write(conn, deflated, dataLen);
  11406. mg_free(deflated);
  11407. } else
  11408. #endif
  11409. retval = mg_write(conn, data, dataLen);
  11410. }
  11411. /* if dataLen == 0, the header length (2) is returned */
  11412. }
  11413. /* TODO: Remove this unlock as well, when lock is removed. */
  11414. mg_unlock_connection(conn);
  11415. return retval;
  11416. }
  11417. int
  11418. mg_websocket_write(struct mg_connection *conn,
  11419. int opcode,
  11420. const char *data,
  11421. size_t dataLen)
  11422. {
  11423. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11424. }
  11425. static void
  11426. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11427. {
  11428. size_t i = 0;
  11429. i = 0;
  11430. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11431. /* Convert in 32 bit words, if data is 4 byte aligned */
  11432. while (i < (in_len - 3)) {
  11433. *(uint32_t *)(void *)(out + i) =
  11434. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11435. i += 4;
  11436. }
  11437. }
  11438. if (i != in_len) {
  11439. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11440. while (i < in_len) {
  11441. *(uint8_t *)(void *)(out + i) =
  11442. *(uint8_t *)(void *)(in + i)
  11443. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11444. i++;
  11445. }
  11446. }
  11447. }
  11448. int
  11449. mg_websocket_client_write(struct mg_connection *conn,
  11450. int opcode,
  11451. const char *data,
  11452. size_t dataLen)
  11453. {
  11454. int retval = -1;
  11455. char *masked_data =
  11456. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11457. uint32_t masking_key = 0;
  11458. if (masked_data == NULL) {
  11459. /* Return -1 in an error case */
  11460. mg_cry_internal(conn,
  11461. "%s",
  11462. "Cannot allocate buffer for masked websocket response: "
  11463. "Out of memory");
  11464. return -1;
  11465. }
  11466. do {
  11467. /* Get a masking key - but not 0 */
  11468. masking_key = (uint32_t)get_random();
  11469. } while (masking_key == 0);
  11470. mask_data(data, dataLen, masking_key, masked_data);
  11471. retval = mg_websocket_write_exec(
  11472. conn, opcode, masked_data, dataLen, masking_key);
  11473. mg_free(masked_data);
  11474. return retval;
  11475. }
  11476. static void
  11477. handle_websocket_request(struct mg_connection *conn,
  11478. const char *path,
  11479. int is_callback_resource,
  11480. struct mg_websocket_subprotocols *subprotocols,
  11481. mg_websocket_connect_handler ws_connect_handler,
  11482. mg_websocket_ready_handler ws_ready_handler,
  11483. mg_websocket_data_handler ws_data_handler,
  11484. mg_websocket_close_handler ws_close_handler,
  11485. void *cbData)
  11486. {
  11487. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11488. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11489. ptrdiff_t lua_websock = 0;
  11490. #if !defined(USE_LUA)
  11491. (void)path;
  11492. #endif
  11493. /* Step 1: Check websocket protocol version. */
  11494. /* Step 1.1: Check Sec-WebSocket-Key. */
  11495. if (!websock_key) {
  11496. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11497. * requires a Sec-WebSocket-Key header.
  11498. */
  11499. /* It could be the hixie draft version
  11500. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11501. */
  11502. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11503. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11504. char key3[8];
  11505. if ((key1 != NULL) && (key2 != NULL)) {
  11506. /* This version uses 8 byte body data in a GET request */
  11507. conn->content_len = 8;
  11508. if (8 == mg_read(conn, key3, 8)) {
  11509. /* This is the hixie version */
  11510. mg_send_http_error(conn,
  11511. 426,
  11512. "%s",
  11513. "Protocol upgrade to RFC 6455 required");
  11514. return;
  11515. }
  11516. }
  11517. /* This is an unknown version */
  11518. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11519. return;
  11520. }
  11521. /* Step 1.2: Check websocket protocol version. */
  11522. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11523. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11524. /* Reject wrong versions */
  11525. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11526. return;
  11527. }
  11528. /* Step 1.3: Could check for "Host", but we do not really nead this
  11529. * value for anything, so just ignore it. */
  11530. /* Step 2: If a callback is responsible, call it. */
  11531. if (is_callback_resource) {
  11532. /* Step 2.1 check and select subprotocol */
  11533. const char *protocols[64]; // max 64 headers
  11534. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11535. "Sec-WebSocket-Protocol",
  11536. protocols,
  11537. 64);
  11538. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11539. int cnt = 0;
  11540. int idx;
  11541. unsigned long len;
  11542. const char *sep, *curSubProtocol,
  11543. *acceptedWebSocketSubprotocol = NULL;
  11544. /* look for matching subprotocol */
  11545. do {
  11546. const char *protocol = protocols[cnt];
  11547. do {
  11548. sep = strchr(protocol, ',');
  11549. curSubProtocol = protocol;
  11550. len = sep ? (unsigned long)(sep - protocol)
  11551. : (unsigned long)strlen(protocol);
  11552. while (sep && isspace((unsigned char)*++sep))
  11553. ; // ignore leading whitespaces
  11554. protocol = sep;
  11555. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11556. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11557. && (strncmp(curSubProtocol,
  11558. subprotocols->subprotocols[idx],
  11559. len)
  11560. == 0)) {
  11561. acceptedWebSocketSubprotocol =
  11562. subprotocols->subprotocols[idx];
  11563. break;
  11564. }
  11565. }
  11566. } while (sep && !acceptedWebSocketSubprotocol);
  11567. } while (++cnt < nbSubprotocolHeader
  11568. && !acceptedWebSocketSubprotocol);
  11569. conn->request_info.acceptedWebSocketSubprotocol =
  11570. acceptedWebSocketSubprotocol;
  11571. } else if (nbSubprotocolHeader > 0) {
  11572. /* keep legacy behavior */
  11573. const char *protocol = protocols[0];
  11574. /* The protocol is a comma separated list of names. */
  11575. /* The server must only return one value from this list. */
  11576. /* First check if it is a list or just a single value. */
  11577. const char *sep = strrchr(protocol, ',');
  11578. if (sep == NULL) {
  11579. /* Just a single protocol -> accept it. */
  11580. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11581. } else {
  11582. /* Multiple protocols -> accept the last one. */
  11583. /* This is just a quick fix if the client offers multiple
  11584. * protocols. The handler should have a list of accepted
  11585. * protocols on his own
  11586. * and use it to select one protocol among those the client
  11587. * has
  11588. * offered.
  11589. */
  11590. while (isspace((unsigned char)*++sep)) {
  11591. ; /* ignore leading whitespaces */
  11592. }
  11593. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11594. }
  11595. }
  11596. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11597. websocket_deflate_negotiate(conn);
  11598. #endif
  11599. if ((ws_connect_handler != NULL)
  11600. && (ws_connect_handler(conn, cbData) != 0)) {
  11601. /* C callback has returned non-zero, do not proceed with
  11602. * handshake.
  11603. */
  11604. /* Note that C callbacks are no longer called when Lua is
  11605. * responsible, so C can no longer filter callbacks for Lua. */
  11606. return;
  11607. }
  11608. }
  11609. #if defined(USE_LUA)
  11610. /* Step 3: No callback. Check if Lua is responsible. */
  11611. else {
  11612. /* Step 3.1: Check if Lua is responsible. */
  11613. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11614. lua_websock = match_prefix_strlen(
  11615. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11616. }
  11617. if (lua_websock) {
  11618. /* Step 3.2: Lua is responsible: call it. */
  11619. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11620. if (!conn->lua_websocket_state) {
  11621. /* Lua rejected the new client */
  11622. return;
  11623. }
  11624. }
  11625. }
  11626. #endif
  11627. /* Step 4: Check if there is a responsible websocket handler. */
  11628. if (!is_callback_resource && !lua_websock) {
  11629. /* There is no callback, and Lua is not responsible either. */
  11630. /* Reply with a 404 Not Found. We are still at a standard
  11631. * HTTP request here, before the websocket handshake, so
  11632. * we can still send standard HTTP error replies. */
  11633. mg_send_http_error(conn, 404, "%s", "Not found");
  11634. return;
  11635. }
  11636. /* Step 5: The websocket connection has been accepted */
  11637. if (!send_websocket_handshake(conn, websock_key)) {
  11638. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11639. return;
  11640. }
  11641. /* Step 6: Call the ready handler */
  11642. if (is_callback_resource) {
  11643. if (ws_ready_handler != NULL) {
  11644. ws_ready_handler(conn, cbData);
  11645. }
  11646. #if defined(USE_LUA)
  11647. } else if (lua_websock) {
  11648. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11649. /* the ready handler returned false */
  11650. return;
  11651. }
  11652. #endif
  11653. }
  11654. /* Step 7: Enter the read loop */
  11655. if (is_callback_resource) {
  11656. read_websocket(conn, ws_data_handler, cbData);
  11657. #if defined(USE_LUA)
  11658. } else if (lua_websock) {
  11659. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11660. #endif
  11661. }
  11662. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11663. /* Step 8: Close the deflate & inflate buffers */
  11664. if (conn->websocket_deflate_initialized) {
  11665. deflateEnd(&conn->websocket_deflate_state);
  11666. inflateEnd(&conn->websocket_inflate_state);
  11667. }
  11668. #endif
  11669. /* Step 9: Call the close handler */
  11670. if (ws_close_handler) {
  11671. ws_close_handler(conn, cbData);
  11672. }
  11673. }
  11674. #endif /* !USE_WEBSOCKET */
  11675. /* Is upgrade request:
  11676. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11677. * 1 = upgrade to websocket
  11678. * 2 = upgrade to HTTP/2
  11679. * -1 = upgrade to unknown protocol
  11680. */
  11681. static int
  11682. should_switch_to_protocol(const struct mg_connection *conn)
  11683. {
  11684. const char *upgrade, *connection;
  11685. /* A websocket protocoll has the following HTTP headers:
  11686. *
  11687. * Connection: Upgrade
  11688. * Upgrade: Websocket
  11689. */
  11690. connection = mg_get_header(conn, "Connection");
  11691. if (connection == NULL) {
  11692. return PROTOCOL_TYPE_HTTP1;
  11693. }
  11694. if (!mg_strcasestr(connection, "upgrade")) {
  11695. return PROTOCOL_TYPE_HTTP1;
  11696. }
  11697. upgrade = mg_get_header(conn, "Upgrade");
  11698. if (upgrade == NULL) {
  11699. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11700. return -1;
  11701. }
  11702. /* Upgrade to ... */
  11703. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11704. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11705. * "Sec-WebSocket-Version" are also required.
  11706. * Don't check them here, since even an unsupported websocket protocol
  11707. * request still IS a websocket request (in contrast to a standard HTTP
  11708. * request). It will fail later in handle_websocket_request.
  11709. */
  11710. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11711. }
  11712. if (0 != mg_strcasestr(upgrade, "h2")) {
  11713. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11714. }
  11715. /* Upgrade to another protocol */
  11716. return -1;
  11717. }
  11718. static int
  11719. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11720. {
  11721. int n;
  11722. unsigned int a, b, c, d, slash;
  11723. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11724. slash = 32;
  11725. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11726. n = 0;
  11727. }
  11728. }
  11729. if ((n > 0) && ((size_t)n == vec->len)) {
  11730. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11731. /* IPv4 format */
  11732. if (sa->sa.sa_family == AF_INET) {
  11733. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11734. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11735. | ((uint32_t)c << 8) | (uint32_t)d;
  11736. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11737. return (ip & mask) == net;
  11738. }
  11739. return 0;
  11740. }
  11741. }
  11742. #if defined(USE_IPV6)
  11743. else {
  11744. char ad[50];
  11745. const char *p;
  11746. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11747. slash = 128;
  11748. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11749. n = 0;
  11750. }
  11751. }
  11752. if ((n <= 0) && no_strict) {
  11753. /* no square brackets? */
  11754. p = strchr(vec->ptr, '/');
  11755. if (p && (p < (vec->ptr + vec->len))) {
  11756. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11757. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11758. n += (int)(p - vec->ptr);
  11759. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11760. } else {
  11761. n = 0;
  11762. }
  11763. } else if (vec->len < sizeof(ad)) {
  11764. n = (int)vec->len;
  11765. slash = 128;
  11766. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11767. }
  11768. }
  11769. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11770. p = ad;
  11771. c = 0;
  11772. /* zone indexes are unsupported, at least two colons are needed */
  11773. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11774. if (*(p++) == ':') {
  11775. c++;
  11776. }
  11777. }
  11778. if ((*p == '\0') && (c >= 2)) {
  11779. struct sockaddr_in6 sin6;
  11780. unsigned int i;
  11781. /* for strict validation, an actual IPv6 argument is needed */
  11782. if (sa->sa.sa_family != AF_INET6) {
  11783. return 0;
  11784. }
  11785. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11786. /* IPv6 format */
  11787. for (i = 0; i < 16; i++) {
  11788. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11789. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11790. uint8_t mask = 0;
  11791. if (8 * i + 8 < slash) {
  11792. mask = 0xFFu;
  11793. } else if (8 * i < slash) {
  11794. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11795. }
  11796. if ((ip & mask) != net) {
  11797. return 0;
  11798. }
  11799. }
  11800. return 1;
  11801. }
  11802. }
  11803. }
  11804. }
  11805. #else
  11806. (void)no_strict;
  11807. #endif
  11808. /* malformed */
  11809. return -1;
  11810. }
  11811. static int
  11812. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11813. {
  11814. int throttle = 0;
  11815. struct vec vec, val;
  11816. char mult;
  11817. double v;
  11818. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11819. mult = ',';
  11820. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11821. || (v < 0)
  11822. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11823. && (mult != ','))) {
  11824. continue;
  11825. }
  11826. v *= (lowercase(&mult) == 'k')
  11827. ? 1024
  11828. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11829. if (vec.len == 1 && vec.ptr[0] == '*') {
  11830. throttle = (int)v;
  11831. } else {
  11832. int matched = parse_match_net(&vec, rsa, 0);
  11833. if (matched >= 0) {
  11834. /* a valid IP subnet */
  11835. if (matched) {
  11836. throttle = (int)v;
  11837. }
  11838. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11839. throttle = (int)v;
  11840. }
  11841. }
  11842. }
  11843. return throttle;
  11844. }
  11845. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11846. #include "handle_form.inl"
  11847. static int
  11848. get_first_ssl_listener_index(const struct mg_context *ctx)
  11849. {
  11850. unsigned int i;
  11851. int idx = -1;
  11852. if (ctx) {
  11853. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11854. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11855. }
  11856. }
  11857. return idx;
  11858. }
  11859. /* Return host (without port) */
  11860. static void
  11861. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11862. {
  11863. const char *host_header =
  11864. get_header(ri->http_headers, ri->num_headers, "Host");
  11865. host->ptr = NULL;
  11866. host->len = 0;
  11867. if (host_header != NULL) {
  11868. char *pos;
  11869. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11870. * is found. */
  11871. if (*host_header == '[') {
  11872. pos = strchr(host_header, ']');
  11873. if (!pos) {
  11874. /* Malformed hostname starts with '[', but no ']' found */
  11875. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11876. return;
  11877. }
  11878. /* terminate after ']' */
  11879. host->ptr = host_header;
  11880. host->len = (size_t)(pos + 1 - host_header);
  11881. } else {
  11882. /* Otherwise, a ':' separates hostname and port number */
  11883. pos = strchr(host_header, ':');
  11884. if (pos != NULL) {
  11885. host->len = (size_t)(pos - host_header);
  11886. } else {
  11887. host->len = strlen(host_header);
  11888. }
  11889. host->ptr = host_header;
  11890. }
  11891. }
  11892. }
  11893. static int
  11894. switch_domain_context(struct mg_connection *conn)
  11895. {
  11896. struct vec host;
  11897. get_host_from_request_info(&host, &conn->request_info);
  11898. if (host.ptr) {
  11899. if (conn->ssl) {
  11900. /* This is a HTTPS connection, maybe we have a hostname
  11901. * from SNI (set in ssl_servername_callback). */
  11902. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11903. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11904. /* We are not using the default domain */
  11905. if ((strlen(sslhost) != host.len)
  11906. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11907. /* Mismatch between SNI domain and HTTP domain */
  11908. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11909. sslhost,
  11910. (int)host.len,
  11911. host.ptr);
  11912. return 0;
  11913. }
  11914. }
  11915. } else {
  11916. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11917. while (dom) {
  11918. if ((strlen(dom->config[AUTHENTICATION_DOMAIN]) == host.len)
  11919. && !mg_strncasecmp(host.ptr,
  11920. dom->config[AUTHENTICATION_DOMAIN],
  11921. host.len)) {
  11922. /* Found matching domain */
  11923. DEBUG_TRACE("HTTP domain %s found",
  11924. dom->config[AUTHENTICATION_DOMAIN]);
  11925. /* TODO: Check if this is a HTTP or HTTPS domain */
  11926. conn->dom_ctx = dom;
  11927. break;
  11928. }
  11929. mg_lock_context(conn->phys_ctx);
  11930. dom = dom->next;
  11931. mg_unlock_context(conn->phys_ctx);
  11932. }
  11933. }
  11934. } else {
  11935. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11936. return 1;
  11937. }
  11938. DEBUG_TRACE("HTTP%s Host: %.*s",
  11939. conn->ssl ? "S" : "",
  11940. (int)host.len,
  11941. host.ptr);
  11942. return 1;
  11943. }
  11944. static int mg_construct_local_link(const struct mg_connection *conn,
  11945. char *buf,
  11946. size_t buflen,
  11947. const char *define_proto,
  11948. int define_port,
  11949. const char *define_uri);
  11950. static void
  11951. redirect_to_https_port(struct mg_connection *conn, int port)
  11952. {
  11953. char target_url[MG_BUF_LEN];
  11954. int truncated = 0;
  11955. const char *expect_proto =
  11956. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11957. /* Use "308 Permanent Redirect" */
  11958. int redirect_code = 308;
  11959. /* In any case, close the current connection */
  11960. conn->must_close = 1;
  11961. /* Send host, port, uri and (if it exists) ?query_string */
  11962. if (mg_construct_local_link(
  11963. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11964. < 0) {
  11965. truncated = 1;
  11966. } else if (conn->request_info.query_string != NULL) {
  11967. size_t slen1 = strlen(target_url);
  11968. size_t slen2 = strlen(conn->request_info.query_string);
  11969. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11970. target_url[slen1] = '?';
  11971. memcpy(target_url + slen1 + 1,
  11972. conn->request_info.query_string,
  11973. slen2);
  11974. target_url[slen1 + slen2 + 1] = 0;
  11975. } else {
  11976. truncated = 1;
  11977. }
  11978. }
  11979. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11980. * is used as buffer size) */
  11981. if (truncated) {
  11982. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11983. return;
  11984. }
  11985. /* Use redirect helper function */
  11986. mg_send_http_redirect(conn, target_url, redirect_code);
  11987. }
  11988. static void
  11989. mg_set_handler_type(struct mg_context *phys_ctx,
  11990. struct mg_domain_context *dom_ctx,
  11991. const char *uri,
  11992. int handler_type,
  11993. int is_delete_request,
  11994. mg_request_handler handler,
  11995. struct mg_websocket_subprotocols *subprotocols,
  11996. mg_websocket_connect_handler connect_handler,
  11997. mg_websocket_ready_handler ready_handler,
  11998. mg_websocket_data_handler data_handler,
  11999. mg_websocket_close_handler close_handler,
  12000. mg_authorization_handler auth_handler,
  12001. void *cbdata)
  12002. {
  12003. struct mg_handler_info *tmp_rh, **lastref;
  12004. size_t urilen = strlen(uri);
  12005. if (handler_type == WEBSOCKET_HANDLER) {
  12006. DEBUG_ASSERT(handler == NULL);
  12007. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12008. || ready_handler != NULL || data_handler != NULL
  12009. || close_handler != NULL);
  12010. DEBUG_ASSERT(auth_handler == NULL);
  12011. if (handler != NULL) {
  12012. return;
  12013. }
  12014. if (!is_delete_request && (connect_handler == NULL)
  12015. && (ready_handler == NULL) && (data_handler == NULL)
  12016. && (close_handler == NULL)) {
  12017. return;
  12018. }
  12019. if (auth_handler != NULL) {
  12020. return;
  12021. }
  12022. } else if (handler_type == REQUEST_HANDLER) {
  12023. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12024. && data_handler == NULL && close_handler == NULL);
  12025. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12026. DEBUG_ASSERT(auth_handler == NULL);
  12027. if ((connect_handler != NULL) || (ready_handler != NULL)
  12028. || (data_handler != NULL) || (close_handler != NULL)) {
  12029. return;
  12030. }
  12031. if (!is_delete_request && (handler == NULL)) {
  12032. return;
  12033. }
  12034. if (auth_handler != NULL) {
  12035. return;
  12036. }
  12037. } else if (handler_type == AUTH_HANDLER) {
  12038. DEBUG_ASSERT(handler == NULL);
  12039. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12040. && data_handler == NULL && close_handler == NULL);
  12041. DEBUG_ASSERT(!is_delete_request && (auth_handler != NULL));
  12042. if (handler != NULL) {
  12043. return;
  12044. }
  12045. if ((connect_handler != NULL) || (ready_handler != NULL)
  12046. || (data_handler != NULL) || (close_handler != NULL)) {
  12047. return;
  12048. }
  12049. if (!is_delete_request && (auth_handler == NULL)) {
  12050. return;
  12051. }
  12052. } else {
  12053. /* Unknown handler type. */
  12054. return;
  12055. }
  12056. if (!phys_ctx || !dom_ctx) {
  12057. /* no context available */
  12058. return;
  12059. }
  12060. mg_lock_context(phys_ctx);
  12061. /* first try to find an existing handler */
  12062. do {
  12063. lastref = &(dom_ctx->handlers);
  12064. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12065. tmp_rh = tmp_rh->next) {
  12066. if (tmp_rh->handler_type == handler_type
  12067. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12068. if (!is_delete_request) {
  12069. /* update existing handler */
  12070. if (handler_type == REQUEST_HANDLER) {
  12071. /* Wait for end of use before updating */
  12072. if (tmp_rh->refcount) {
  12073. mg_unlock_context(phys_ctx);
  12074. mg_sleep(1);
  12075. mg_lock_context(phys_ctx);
  12076. /* tmp_rh might have been freed, search again. */
  12077. break;
  12078. }
  12079. /* Ok, the handler is no more use -> Update it */
  12080. tmp_rh->handler = handler;
  12081. } else if (handler_type == WEBSOCKET_HANDLER) {
  12082. tmp_rh->subprotocols = subprotocols;
  12083. tmp_rh->connect_handler = connect_handler;
  12084. tmp_rh->ready_handler = ready_handler;
  12085. tmp_rh->data_handler = data_handler;
  12086. tmp_rh->close_handler = close_handler;
  12087. } else { /* AUTH_HANDLER */
  12088. tmp_rh->auth_handler = auth_handler;
  12089. }
  12090. tmp_rh->cbdata = cbdata;
  12091. } else {
  12092. /* remove existing handler */
  12093. if (handler_type == REQUEST_HANDLER) {
  12094. /* Wait for end of use before removing */
  12095. if (tmp_rh->refcount) {
  12096. tmp_rh->removing = 1;
  12097. mg_unlock_context(phys_ctx);
  12098. mg_sleep(1);
  12099. mg_lock_context(phys_ctx);
  12100. /* tmp_rh might have been freed, search again. */
  12101. break;
  12102. }
  12103. /* Ok, the handler is no more used */
  12104. }
  12105. *lastref = tmp_rh->next;
  12106. mg_free(tmp_rh->uri);
  12107. mg_free(tmp_rh);
  12108. }
  12109. mg_unlock_context(phys_ctx);
  12110. return;
  12111. }
  12112. lastref = &(tmp_rh->next);
  12113. }
  12114. } while (tmp_rh != NULL);
  12115. if (is_delete_request) {
  12116. /* no handler to set, this was a remove request to a non-existing
  12117. * handler */
  12118. mg_unlock_context(phys_ctx);
  12119. return;
  12120. }
  12121. tmp_rh =
  12122. (struct mg_handler_info *)mg_calloc_ctx(1,
  12123. sizeof(struct mg_handler_info),
  12124. phys_ctx);
  12125. if (tmp_rh == NULL) {
  12126. mg_unlock_context(phys_ctx);
  12127. mg_cry_ctx_internal(phys_ctx,
  12128. "%s",
  12129. "Cannot create new request handler struct, OOM");
  12130. return;
  12131. }
  12132. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12133. if (!tmp_rh->uri) {
  12134. mg_unlock_context(phys_ctx);
  12135. mg_free(tmp_rh);
  12136. mg_cry_ctx_internal(phys_ctx,
  12137. "%s",
  12138. "Cannot create new request handler struct, OOM");
  12139. return;
  12140. }
  12141. tmp_rh->uri_len = urilen;
  12142. if (handler_type == REQUEST_HANDLER) {
  12143. tmp_rh->refcount = 0;
  12144. tmp_rh->removing = 0;
  12145. tmp_rh->handler = handler;
  12146. } else if (handler_type == WEBSOCKET_HANDLER) {
  12147. tmp_rh->subprotocols = subprotocols;
  12148. tmp_rh->connect_handler = connect_handler;
  12149. tmp_rh->ready_handler = ready_handler;
  12150. tmp_rh->data_handler = data_handler;
  12151. tmp_rh->close_handler = close_handler;
  12152. } else { /* AUTH_HANDLER */
  12153. tmp_rh->auth_handler = auth_handler;
  12154. }
  12155. tmp_rh->cbdata = cbdata;
  12156. tmp_rh->handler_type = handler_type;
  12157. tmp_rh->next = NULL;
  12158. *lastref = tmp_rh;
  12159. mg_unlock_context(phys_ctx);
  12160. }
  12161. void
  12162. mg_set_request_handler(struct mg_context *ctx,
  12163. const char *uri,
  12164. mg_request_handler handler,
  12165. void *cbdata)
  12166. {
  12167. mg_set_handler_type(ctx,
  12168. &(ctx->dd),
  12169. uri,
  12170. REQUEST_HANDLER,
  12171. handler == NULL,
  12172. handler,
  12173. NULL,
  12174. NULL,
  12175. NULL,
  12176. NULL,
  12177. NULL,
  12178. NULL,
  12179. cbdata);
  12180. }
  12181. void
  12182. mg_set_websocket_handler(struct mg_context *ctx,
  12183. const char *uri,
  12184. mg_websocket_connect_handler connect_handler,
  12185. mg_websocket_ready_handler ready_handler,
  12186. mg_websocket_data_handler data_handler,
  12187. mg_websocket_close_handler close_handler,
  12188. void *cbdata)
  12189. {
  12190. mg_set_websocket_handler_with_subprotocols(ctx,
  12191. uri,
  12192. NULL,
  12193. connect_handler,
  12194. ready_handler,
  12195. data_handler,
  12196. close_handler,
  12197. cbdata);
  12198. }
  12199. void
  12200. mg_set_websocket_handler_with_subprotocols(
  12201. struct mg_context *ctx,
  12202. const char *uri,
  12203. struct mg_websocket_subprotocols *subprotocols,
  12204. mg_websocket_connect_handler connect_handler,
  12205. mg_websocket_ready_handler ready_handler,
  12206. mg_websocket_data_handler data_handler,
  12207. mg_websocket_close_handler close_handler,
  12208. void *cbdata)
  12209. {
  12210. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12211. && (data_handler == NULL)
  12212. && (close_handler == NULL);
  12213. mg_set_handler_type(ctx,
  12214. &(ctx->dd),
  12215. uri,
  12216. WEBSOCKET_HANDLER,
  12217. is_delete_request,
  12218. NULL,
  12219. subprotocols,
  12220. connect_handler,
  12221. ready_handler,
  12222. data_handler,
  12223. close_handler,
  12224. NULL,
  12225. cbdata);
  12226. }
  12227. void
  12228. mg_set_auth_handler(struct mg_context *ctx,
  12229. const char *uri,
  12230. mg_authorization_handler handler,
  12231. void *cbdata)
  12232. {
  12233. mg_set_handler_type(ctx,
  12234. &(ctx->dd),
  12235. uri,
  12236. AUTH_HANDLER,
  12237. handler == NULL,
  12238. NULL,
  12239. NULL,
  12240. NULL,
  12241. NULL,
  12242. NULL,
  12243. NULL,
  12244. handler,
  12245. cbdata);
  12246. }
  12247. static int
  12248. get_request_handler(struct mg_connection *conn,
  12249. int handler_type,
  12250. mg_request_handler *handler,
  12251. struct mg_websocket_subprotocols **subprotocols,
  12252. mg_websocket_connect_handler *connect_handler,
  12253. mg_websocket_ready_handler *ready_handler,
  12254. mg_websocket_data_handler *data_handler,
  12255. mg_websocket_close_handler *close_handler,
  12256. mg_authorization_handler *auth_handler,
  12257. void **cbdata,
  12258. struct mg_handler_info **handler_info)
  12259. {
  12260. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12261. if (request_info) {
  12262. const char *uri = request_info->local_uri;
  12263. size_t urilen = strlen(uri);
  12264. struct mg_handler_info *tmp_rh;
  12265. int step, matched;
  12266. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12267. return 0;
  12268. }
  12269. mg_lock_context(conn->phys_ctx);
  12270. for (step = 0; step < 3; step++) {
  12271. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12272. tmp_rh = tmp_rh->next) {
  12273. if (tmp_rh->handler_type != handler_type) {
  12274. continue;
  12275. }
  12276. if (step == 0) {
  12277. /* first try for an exact match */
  12278. matched = (tmp_rh->uri_len == urilen)
  12279. && (strcmp(tmp_rh->uri, uri) == 0);
  12280. } else if (step == 1) {
  12281. /* next try for a partial match, we will accept
  12282. uri/something */
  12283. matched =
  12284. (tmp_rh->uri_len < urilen)
  12285. && (uri[tmp_rh->uri_len] == '/')
  12286. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12287. } else {
  12288. /* finally try for pattern match */
  12289. matched =
  12290. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12291. }
  12292. if (matched) {
  12293. if (handler_type == WEBSOCKET_HANDLER) {
  12294. *subprotocols = tmp_rh->subprotocols;
  12295. *connect_handler = tmp_rh->connect_handler;
  12296. *ready_handler = tmp_rh->ready_handler;
  12297. *data_handler = tmp_rh->data_handler;
  12298. *close_handler = tmp_rh->close_handler;
  12299. } else if (handler_type == REQUEST_HANDLER) {
  12300. if (tmp_rh->removing) {
  12301. /* Treat as none found */
  12302. step = 2;
  12303. break;
  12304. }
  12305. *handler = tmp_rh->handler;
  12306. /* Acquire handler and give it back */
  12307. tmp_rh->refcount++;
  12308. *handler_info = tmp_rh;
  12309. } else { /* AUTH_HANDLER */
  12310. *auth_handler = tmp_rh->auth_handler;
  12311. }
  12312. *cbdata = tmp_rh->cbdata;
  12313. mg_unlock_context(conn->phys_ctx);
  12314. return 1;
  12315. }
  12316. }
  12317. }
  12318. mg_unlock_context(conn->phys_ctx);
  12319. }
  12320. return 0; /* none found */
  12321. }
  12322. /* Check if the script file is in a path, allowed for script files.
  12323. * This can be used if uploading files is possible not only for the server
  12324. * admin, and the upload mechanism does not check the file extension.
  12325. */
  12326. static int
  12327. is_in_script_path(const struct mg_connection *conn, const char *path)
  12328. {
  12329. /* TODO (Feature): Add config value for allowed script path.
  12330. * Default: All allowed. */
  12331. (void)conn;
  12332. (void)path;
  12333. return 1;
  12334. }
  12335. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12336. static int
  12337. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12338. int bits,
  12339. char *data,
  12340. size_t len,
  12341. void *cbdata)
  12342. {
  12343. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12344. if (pcallbacks->websocket_data) {
  12345. return pcallbacks->websocket_data(conn, bits, data, len);
  12346. }
  12347. /* No handler set - assume "OK" */
  12348. return 1;
  12349. }
  12350. static void
  12351. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12352. void *cbdata)
  12353. {
  12354. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12355. if (pcallbacks->connection_close) {
  12356. pcallbacks->connection_close(conn);
  12357. }
  12358. }
  12359. #endif
  12360. /* This is the heart of the Civetweb's logic.
  12361. * This function is called when the request is read, parsed and validated,
  12362. * and Civetweb must decide what action to take: serve a file, or
  12363. * a directory, or call embedded function, etcetera. */
  12364. static void
  12365. handle_request(struct mg_connection *conn)
  12366. {
  12367. struct mg_request_info *ri = &conn->request_info;
  12368. char path[UTF8_PATH_MAX];
  12369. int uri_len, ssl_index;
  12370. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12371. is_put_or_delete_request = 0, is_callback_resource = 0,
  12372. is_template_text_file = 0;
  12373. int i;
  12374. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12375. mg_request_handler callback_handler = NULL;
  12376. struct mg_handler_info *handler_info = NULL;
  12377. struct mg_websocket_subprotocols *subprotocols;
  12378. mg_websocket_connect_handler ws_connect_handler = NULL;
  12379. mg_websocket_ready_handler ws_ready_handler = NULL;
  12380. mg_websocket_data_handler ws_data_handler = NULL;
  12381. mg_websocket_close_handler ws_close_handler = NULL;
  12382. void *callback_data = NULL;
  12383. mg_authorization_handler auth_handler = NULL;
  12384. void *auth_callback_data = NULL;
  12385. int handler_type;
  12386. time_t curtime = time(NULL);
  12387. char date[64];
  12388. path[0] = 0;
  12389. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12390. conn->request_state = 0;
  12391. /* 1. get the request url */
  12392. /* 1.1. split into url and query string */
  12393. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12394. != NULL) {
  12395. *((char *)conn->request_info.query_string++) = '\0';
  12396. }
  12397. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12398. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12399. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12400. if (ssl_index >= 0) {
  12401. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12402. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12403. redirect_to_https_port(conn, port);
  12404. } else {
  12405. /* A http to https forward port has been specified,
  12406. * but no https port to forward to. */
  12407. mg_send_http_error(conn,
  12408. 503,
  12409. "%s",
  12410. "Error: SSL forward not configured properly");
  12411. mg_cry_internal(conn,
  12412. "%s",
  12413. "Can not redirect to SSL, no SSL port available");
  12414. }
  12415. return;
  12416. }
  12417. uri_len = (int)strlen(ri->local_uri);
  12418. /* 1.3. decode url (if config says so) */
  12419. if (should_decode_url(conn)) {
  12420. mg_url_decode(
  12421. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12422. if (conn->request_info.query_string) {
  12423. url_decode_in_place((char *)conn->request_info.query_string);
  12424. }
  12425. }
  12426. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12427. * not possible */
  12428. remove_dot_segments((char *)ri->local_uri);
  12429. /* step 1. completed, the url is known now */
  12430. uri_len = (int)strlen(ri->local_uri);
  12431. DEBUG_TRACE("URL: %s", ri->local_uri);
  12432. /* 2. if this ip has limited speed, set it for this connection */
  12433. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12434. &conn->client.rsa,
  12435. ri->local_uri);
  12436. /* 3. call a "handle everything" callback, if registered */
  12437. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12438. /* Note that since V1.7 the "begin_request" function is called
  12439. * before an authorization check. If an authorization check is
  12440. * required, use a request_handler instead. */
  12441. i = conn->phys_ctx->callbacks.begin_request(conn);
  12442. if (i > 0) {
  12443. /* callback already processed the request. Store the
  12444. return value as a status code for the access log. */
  12445. conn->status_code = i;
  12446. if (!conn->must_close) {
  12447. discard_unread_request_data(conn);
  12448. }
  12449. return;
  12450. } else if (i == 0) {
  12451. /* civetweb should process the request */
  12452. } else {
  12453. /* unspecified - may change with the next version */
  12454. return;
  12455. }
  12456. }
  12457. /* request not yet handled by a handler or redirect, so the request
  12458. * is processed here */
  12459. /* 4. Check for CORS preflight requests and handle them (if configured).
  12460. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12461. */
  12462. if (!strcmp(ri->request_method, "OPTIONS")) {
  12463. /* Send a response to CORS preflights only if
  12464. * access_control_allow_methods is not NULL and not an empty string.
  12465. * In this case, scripts can still handle CORS. */
  12466. const char *cors_meth_cfg =
  12467. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12468. const char *cors_orig_cfg =
  12469. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12470. const char *cors_origin =
  12471. get_header(ri->http_headers, ri->num_headers, "Origin");
  12472. const char *cors_acrm = get_header(ri->http_headers,
  12473. ri->num_headers,
  12474. "Access-Control-Request-Method");
  12475. /* Todo: check if cors_origin is in cors_orig_cfg.
  12476. * Or, let the client check this. */
  12477. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12478. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12479. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12480. /* This is a valid CORS preflight, and the server is configured
  12481. * to handle it automatically. */
  12482. const char *cors_acrh =
  12483. get_header(ri->http_headers,
  12484. ri->num_headers,
  12485. "Access-Control-Request-Headers");
  12486. gmt_time_string(date, sizeof(date), &curtime);
  12487. mg_printf(conn,
  12488. "HTTP/1.1 200 OK\r\n"
  12489. "Date: %s\r\n"
  12490. "Access-Control-Allow-Origin: %s\r\n"
  12491. "Access-Control-Allow-Methods: %s\r\n"
  12492. "Content-Length: 0\r\n"
  12493. "Connection: %s\r\n",
  12494. date,
  12495. cors_orig_cfg,
  12496. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12497. suggest_connection_header(conn));
  12498. if (cors_acrh != NULL) {
  12499. /* CORS request is asking for additional headers */
  12500. const char *cors_hdr_cfg =
  12501. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12502. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12503. /* Allow only if access_control_allow_headers is
  12504. * not NULL and not an empty string. If this
  12505. * configuration is set to *, allow everything.
  12506. * Otherwise this configuration must be a list
  12507. * of allowed HTTP header names. */
  12508. mg_printf(conn,
  12509. "Access-Control-Allow-Headers: %s\r\n",
  12510. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12511. : cors_hdr_cfg));
  12512. }
  12513. }
  12514. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12515. mg_printf(conn, "\r\n");
  12516. return;
  12517. }
  12518. }
  12519. /* 5. interpret the url to find out how the request must be handled
  12520. */
  12521. /* 5.1. first test, if the request targets the regular http(s)://
  12522. * protocol namespace or the websocket ws(s):// protocol namespace.
  12523. */
  12524. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12525. #if defined(USE_WEBSOCKET)
  12526. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12527. #else
  12528. handler_type = REQUEST_HANDLER;
  12529. #endif /* defined(USE_WEBSOCKET) */
  12530. if (is_websocket_request) {
  12531. HTTP1_only;
  12532. }
  12533. /* 5.2. check if the request will be handled by a callback */
  12534. if (get_request_handler(conn,
  12535. handler_type,
  12536. &callback_handler,
  12537. &subprotocols,
  12538. &ws_connect_handler,
  12539. &ws_ready_handler,
  12540. &ws_data_handler,
  12541. &ws_close_handler,
  12542. NULL,
  12543. &callback_data,
  12544. &handler_info)) {
  12545. /* 5.2.1. A callback will handle this request. All requests
  12546. * handled by a callback have to be considered as requests
  12547. * to a script resource. */
  12548. is_callback_resource = 1;
  12549. is_script_resource = 1;
  12550. is_put_or_delete_request = is_put_or_delete_method(conn);
  12551. } else {
  12552. no_callback_resource:
  12553. /* 5.2.2. No callback is responsible for this request. The URI
  12554. * addresses a file based resource (static content or Lua/cgi
  12555. * scripts in the file system). */
  12556. is_callback_resource = 0;
  12557. interpret_uri(conn,
  12558. path,
  12559. sizeof(path),
  12560. &file.stat,
  12561. &is_found,
  12562. &is_script_resource,
  12563. &is_websocket_request,
  12564. &is_put_or_delete_request,
  12565. &is_template_text_file);
  12566. }
  12567. /* 6. authorization check */
  12568. /* 6.1. a custom authorization handler is installed */
  12569. if (get_request_handler(conn,
  12570. AUTH_HANDLER,
  12571. NULL,
  12572. NULL,
  12573. NULL,
  12574. NULL,
  12575. NULL,
  12576. NULL,
  12577. &auth_handler,
  12578. &auth_callback_data,
  12579. NULL)) {
  12580. if (!auth_handler(conn, auth_callback_data)) {
  12581. return;
  12582. }
  12583. } else if (is_put_or_delete_request && !is_script_resource
  12584. && !is_callback_resource) {
  12585. HTTP1_only;
  12586. /* 6.2. this request is a PUT/DELETE to a real file */
  12587. /* 6.2.1. thus, the server must have real files */
  12588. #if defined(NO_FILES)
  12589. if (1) {
  12590. #else
  12591. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12592. #endif
  12593. /* This server does not have any real files, thus the
  12594. * PUT/DELETE methods are not valid. */
  12595. mg_send_http_error(conn,
  12596. 405,
  12597. "%s method not allowed",
  12598. conn->request_info.request_method);
  12599. return;
  12600. }
  12601. #if !defined(NO_FILES)
  12602. /* 6.2.2. Check if put authorization for static files is
  12603. * available.
  12604. */
  12605. if (!is_authorized_for_put(conn)) {
  12606. send_authorization_request(conn, NULL);
  12607. return;
  12608. }
  12609. #endif
  12610. } else {
  12611. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12612. * or it is a PUT or DELETE request to a resource that does not
  12613. * correspond to a file. Check authorization. */
  12614. if (!check_authorization(conn, path)) {
  12615. send_authorization_request(conn, NULL);
  12616. return;
  12617. }
  12618. }
  12619. /* request is authorized or does not need authorization */
  12620. /* 7. check if there are request handlers for this uri */
  12621. if (is_callback_resource) {
  12622. HTTP1_only;
  12623. if (!is_websocket_request) {
  12624. i = callback_handler(conn, callback_data);
  12625. /* Callback handler will not be used anymore. Release it */
  12626. mg_lock_context(conn->phys_ctx);
  12627. handler_info->refcount--;
  12628. mg_unlock_context(conn->phys_ctx);
  12629. if (i > 0) {
  12630. /* Do nothing, callback has served the request. Store
  12631. * then return value as status code for the log and discard
  12632. * all data from the client not used by the callback. */
  12633. conn->status_code = i;
  12634. if (!conn->must_close) {
  12635. discard_unread_request_data(conn);
  12636. }
  12637. } else {
  12638. /* The handler did NOT handle the request. */
  12639. /* Some proper reactions would be:
  12640. * a) close the connections without sending anything
  12641. * b) send a 404 not found
  12642. * c) try if there is a file matching the URI
  12643. * It would be possible to do a, b or c in the callback
  12644. * implementation, and return 1 - we cannot do anything
  12645. * here, that is not possible in the callback.
  12646. *
  12647. * TODO: What would be the best reaction here?
  12648. * (Note: The reaction may change, if there is a better
  12649. * idea.)
  12650. */
  12651. /* For the moment, use option c: We look for a proper file,
  12652. * but since a file request is not always a script resource,
  12653. * the authorization check might be different. */
  12654. interpret_uri(conn,
  12655. path,
  12656. sizeof(path),
  12657. &file.stat,
  12658. &is_found,
  12659. &is_script_resource,
  12660. &is_websocket_request,
  12661. &is_put_or_delete_request,
  12662. &is_template_text_file);
  12663. callback_handler = NULL;
  12664. /* Here we are at a dead end:
  12665. * According to URI matching, a callback should be
  12666. * responsible for handling the request,
  12667. * we called it, but the callback declared itself
  12668. * not responsible.
  12669. * We use a goto here, to get out of this dead end,
  12670. * and continue with the default handling.
  12671. * A goto here is simpler and better to understand
  12672. * than some curious loop. */
  12673. goto no_callback_resource;
  12674. }
  12675. } else {
  12676. #if defined(USE_WEBSOCKET)
  12677. handle_websocket_request(conn,
  12678. path,
  12679. is_callback_resource,
  12680. subprotocols,
  12681. ws_connect_handler,
  12682. ws_ready_handler,
  12683. ws_data_handler,
  12684. ws_close_handler,
  12685. callback_data);
  12686. #endif
  12687. }
  12688. return;
  12689. }
  12690. /* 8. handle websocket requests */
  12691. #if defined(USE_WEBSOCKET)
  12692. if (is_websocket_request) {
  12693. HTTP1_only;
  12694. if (is_script_resource) {
  12695. if (is_in_script_path(conn, path)) {
  12696. /* Websocket Lua script */
  12697. handle_websocket_request(conn,
  12698. path,
  12699. 0 /* Lua Script */,
  12700. NULL,
  12701. NULL,
  12702. NULL,
  12703. NULL,
  12704. NULL,
  12705. conn->phys_ctx->user_data);
  12706. } else {
  12707. /* Script was in an illegal path */
  12708. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12709. }
  12710. } else {
  12711. mg_send_http_error(conn, 404, "%s", "Not found");
  12712. }
  12713. return;
  12714. } else
  12715. #endif
  12716. #if defined(NO_FILES)
  12717. /* 9a. In case the server uses only callbacks, this uri is
  12718. * unknown.
  12719. * Then, all request handling ends here. */
  12720. mg_send_http_error(conn, 404, "%s", "Not Found");
  12721. #else
  12722. /* 9b. This request is either for a static file or resource handled
  12723. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12724. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12725. mg_send_http_error(conn, 404, "%s", "Not Found");
  12726. return;
  12727. }
  12728. /* 10. Request is handled by a script */
  12729. if (is_script_resource) {
  12730. HTTP1_only;
  12731. handle_file_based_request(conn, path, &file);
  12732. return;
  12733. }
  12734. /* 11. Handle put/delete/mkcol requests */
  12735. if (is_put_or_delete_request) {
  12736. HTTP1_only;
  12737. /* 11.1. PUT method */
  12738. if (!strcmp(ri->request_method, "PUT")) {
  12739. put_file(conn, path);
  12740. return;
  12741. }
  12742. /* 11.2. DELETE method */
  12743. if (!strcmp(ri->request_method, "DELETE")) {
  12744. delete_file(conn, path);
  12745. return;
  12746. }
  12747. /* 11.3. MKCOL method */
  12748. if (!strcmp(ri->request_method, "MKCOL")) {
  12749. mkcol(conn, path);
  12750. return;
  12751. }
  12752. /* 11.4. PATCH method
  12753. * This method is not supported for static resources,
  12754. * only for scripts (Lua, CGI) and callbacks. */
  12755. mg_send_http_error(conn,
  12756. 405,
  12757. "%s method not allowed",
  12758. conn->request_info.request_method);
  12759. return;
  12760. }
  12761. /* 11. File does not exist, or it was configured that it should be
  12762. * hidden */
  12763. if (!is_found || (must_hide_file(conn, path))) {
  12764. mg_send_http_error(conn, 404, "%s", "Not found");
  12765. return;
  12766. }
  12767. /* 12. Directory uris should end with a slash */
  12768. if (file.stat.is_directory && (uri_len > 0)
  12769. && (ri->local_uri[uri_len - 1] != '/')) {
  12770. size_t len = strlen(ri->request_uri);
  12771. size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
  12772. char *new_path = mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
  12773. if (!new_path) {
  12774. mg_send_http_error(conn, 500, "out or memory");
  12775. } else {
  12776. memcpy(new_path, ri->request_uri, len);
  12777. new_path[len] = '/';
  12778. new_path[len + 1] = 0;
  12779. if (ri->query_string) {
  12780. new_path[len + 1] = '?';
  12781. /* Copy query string including terminating zero */
  12782. memcpy(new_path + len + 2, ri->query_string, lenQS);
  12783. }
  12784. mg_send_http_redirect(conn, new_path, 301);
  12785. }
  12786. return;
  12787. }
  12788. /* 13. Handle other methods than GET/HEAD */
  12789. /* 13.1. Handle PROPFIND */
  12790. if (!strcmp(ri->request_method, "PROPFIND")) {
  12791. handle_propfind(conn, path, &file.stat);
  12792. return;
  12793. }
  12794. /* 13.2. Handle OPTIONS for files */
  12795. if (!strcmp(ri->request_method, "OPTIONS")) {
  12796. /* This standard handler is only used for real files.
  12797. * Scripts should support the OPTIONS method themselves, to allow a
  12798. * maximum flexibility.
  12799. * Lua and CGI scripts may fully support CORS this way (including
  12800. * preflights). */
  12801. send_options(conn);
  12802. return;
  12803. }
  12804. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12805. if ((0 != strcmp(ri->request_method, "GET"))
  12806. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12807. mg_send_http_error(conn,
  12808. 405,
  12809. "%s method not allowed",
  12810. conn->request_info.request_method);
  12811. return;
  12812. }
  12813. /* 14. directories */
  12814. if (file.stat.is_directory) {
  12815. /* Substitute files have already been handled above. */
  12816. /* Here we can either generate and send a directory listing,
  12817. * or send an "access denied" error. */
  12818. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12819. "yes")) {
  12820. handle_directory_request(conn, path);
  12821. } else {
  12822. mg_send_http_error(conn,
  12823. 403,
  12824. "%s",
  12825. "Error: Directory listing denied");
  12826. }
  12827. return;
  12828. }
  12829. /* 15. Files with search/replace patterns: LSP and SSI */
  12830. if (is_template_text_file) {
  12831. HTTP1_only;
  12832. handle_file_based_request(conn, path, &file);
  12833. return;
  12834. }
  12835. /* 16. Static file - maybe cached */
  12836. #if !defined(NO_CACHING)
  12837. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12838. /* Send 304 "Not Modified" - this must not send any body data */
  12839. handle_not_modified_static_file_request(conn, &file);
  12840. return;
  12841. }
  12842. #endif /* !NO_CACHING */
  12843. /* 17. Static file - not cached */
  12844. handle_static_file_request(conn, path, &file, NULL, NULL);
  12845. #endif /* !defined(NO_FILES) */
  12846. }
  12847. #if !defined(NO_FILESYSTEMS)
  12848. static void
  12849. handle_file_based_request(struct mg_connection *conn,
  12850. const char *path,
  12851. struct mg_file *file)
  12852. {
  12853. if (!conn || !conn->dom_ctx) {
  12854. return;
  12855. }
  12856. if (0) {
  12857. #if defined(USE_LUA)
  12858. } else if (match_prefix_strlen(
  12859. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS], path)
  12860. > 0) {
  12861. if (is_in_script_path(conn, path)) {
  12862. /* Lua server page: an SSI like page containing mostly plain
  12863. * html code plus some tags with server generated contents. */
  12864. handle_lsp_request(conn, path, file, NULL);
  12865. } else {
  12866. /* Script was in an illegal path */
  12867. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12868. }
  12869. } else if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12870. path)
  12871. > 0) {
  12872. if (is_in_script_path(conn, path)) {
  12873. /* Lua in-server module script: a CGI like script used to
  12874. * generate
  12875. * the
  12876. * entire reply. */
  12877. mg_exec_lua_script(conn, path, NULL);
  12878. } else {
  12879. /* Script was in an illegal path */
  12880. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12881. }
  12882. #endif
  12883. #if defined(USE_DUKTAPE)
  12884. } else if (match_prefix_strlen(
  12885. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS], path)
  12886. > 0) {
  12887. if (is_in_script_path(conn, path)) {
  12888. /* Call duktape to generate the page */
  12889. mg_exec_duktape_script(conn, path);
  12890. } else {
  12891. /* Script was in an illegal path */
  12892. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12893. }
  12894. #endif
  12895. #if !defined(NO_CGI)
  12896. } else if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], path)
  12897. > 0) {
  12898. if (is_in_script_path(conn, path)) {
  12899. /* CGI scripts may support all HTTP methods */
  12900. handle_cgi_request(conn, path);
  12901. } else {
  12902. /* Script was in an illegal path */
  12903. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12904. }
  12905. #endif /* !NO_CGI */
  12906. } else if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  12907. > 0) {
  12908. if (is_in_script_path(conn, path)) {
  12909. handle_ssi_file_request(conn, path, file);
  12910. } else {
  12911. /* Script was in an illegal path */
  12912. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12913. }
  12914. #if !defined(NO_CACHING)
  12915. } else if ((!conn->in_error_handler)
  12916. && is_not_modified(conn, &file->stat)) {
  12917. /* Send 304 "Not Modified" - this must not send any body data */
  12918. handle_not_modified_static_file_request(conn, file);
  12919. #endif /* !NO_CACHING */
  12920. } else {
  12921. handle_static_file_request(conn, path, file, NULL, NULL);
  12922. }
  12923. }
  12924. #endif /* NO_FILESYSTEMS */
  12925. static void
  12926. close_all_listening_sockets(struct mg_context *ctx)
  12927. {
  12928. unsigned int i;
  12929. if (!ctx) {
  12930. return;
  12931. }
  12932. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12933. closesocket(ctx->listening_sockets[i].sock);
  12934. #if defined(USE_X_DOM_SOCKET)
  12935. /* For unix domain sockets, the socket name represents a file that has
  12936. * to be deleted. */
  12937. /* See
  12938. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  12939. */
  12940. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  12941. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  12942. IGNORE_UNUSED_RESULT(
  12943. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  12944. }
  12945. #endif
  12946. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12947. }
  12948. mg_free(ctx->listening_sockets);
  12949. ctx->listening_sockets = NULL;
  12950. mg_free(ctx->listening_socket_fds);
  12951. ctx->listening_socket_fds = NULL;
  12952. }
  12953. /* Valid listening port specification is: [ip_address:]port[s]
  12954. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12955. * Examples for IPv6: [::]:80, [::1]:80,
  12956. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12957. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12958. * In order to bind to both, IPv4 and IPv6, you can either add
  12959. * both ports using 8080,[::]:8080, or the short form +8080.
  12960. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12961. * one only accepting IPv4 the other only IPv6. +8080 creates
  12962. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12963. * environment, they might work differently, or might not work
  12964. * at all - it must be tested what options work best in the
  12965. * relevant network environment.
  12966. */
  12967. static int
  12968. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12969. {
  12970. unsigned int a, b, c, d;
  12971. unsigned port;
  12972. unsigned long portUL;
  12973. int ch, len;
  12974. const char *cb;
  12975. char *endptr;
  12976. #if defined(USE_IPV6)
  12977. char buf[100] = {0};
  12978. #endif
  12979. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12980. * Also, all-zeroes in the socket address means binding to all addresses
  12981. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12982. memset(so, 0, sizeof(*so));
  12983. so->lsa.sin.sin_family = AF_INET;
  12984. *ip_version = 0;
  12985. /* Initialize len as invalid. */
  12986. port = 0;
  12987. len = 0;
  12988. /* Test for different ways to format this string */
  12989. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12990. == 5) {
  12991. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12992. so->lsa.sin.sin_addr.s_addr =
  12993. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12994. so->lsa.sin.sin_port = htons((uint16_t)port);
  12995. *ip_version = 4;
  12996. #if defined(USE_IPV6)
  12997. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12998. && ((size_t)len <= vec->len)
  12999. && mg_inet_pton(
  13000. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13001. /* IPv6 address, examples: see above */
  13002. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13003. */
  13004. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13005. *ip_version = 6;
  13006. #endif
  13007. } else if ((vec->ptr[0] == '+')
  13008. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  13009. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13010. /* Add 1 to len for the + character we skipped before */
  13011. len++;
  13012. #if defined(USE_IPV6)
  13013. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13014. so->lsa.sin6.sin6_family = AF_INET6;
  13015. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13016. *ip_version = 4 + 6;
  13017. #else
  13018. /* Bind to IPv4 only, since IPv6 is not built in. */
  13019. so->lsa.sin.sin_port = htons((uint16_t)port);
  13020. *ip_version = 4;
  13021. #endif
  13022. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13023. && (vec->ptr != endptr)) {
  13024. len = (int)(endptr - vec->ptr);
  13025. port = (uint16_t)portUL;
  13026. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13027. so->lsa.sin.sin_port = htons((uint16_t)port);
  13028. *ip_version = 4;
  13029. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13030. /* String could be a hostname. This check algotithm
  13031. * will only work for RFC 952 compliant hostnames,
  13032. * starting with a letter, containing only letters,
  13033. * digits and hyphen ('-'). Newer specs may allow
  13034. * more, but this is not guaranteed here, since it
  13035. * may interfere with rules for port option lists. */
  13036. /* According to RFC 1035, hostnames are restricted to 255 characters
  13037. * in total (63 between two dots). */
  13038. char hostname[256];
  13039. size_t hostnlen = (size_t)(cb - vec->ptr);
  13040. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13041. /* This would be invalid in any case */
  13042. *ip_version = 0;
  13043. return 0;
  13044. }
  13045. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13046. if (mg_inet_pton(
  13047. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13048. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13049. *ip_version = 4;
  13050. so->lsa.sin.sin_port = htons((uint16_t)port);
  13051. len += (int)(hostnlen + 1);
  13052. } else {
  13053. len = 0;
  13054. }
  13055. #if defined(USE_IPV6)
  13056. } else if (mg_inet_pton(AF_INET6,
  13057. hostname,
  13058. &so->lsa.sin6,
  13059. sizeof(so->lsa.sin6),
  13060. 1)) {
  13061. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13062. *ip_version = 6;
  13063. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13064. len += (int)(hostnlen + 1);
  13065. } else {
  13066. len = 0;
  13067. }
  13068. #endif
  13069. } else {
  13070. len = 0;
  13071. }
  13072. #if defined(USE_X_DOM_SOCKET)
  13073. } else if (vec->ptr[0] == 'x') {
  13074. /* unix (linux) domain socket */
  13075. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13076. len = vec->len;
  13077. so->lsa.sun.sun_family = AF_UNIX;
  13078. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13079. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13080. port = 0;
  13081. *ip_version = 99;
  13082. } else {
  13083. /* String too long */
  13084. len = 0;
  13085. }
  13086. #endif
  13087. } else {
  13088. /* Parsing failure. */
  13089. len = 0;
  13090. }
  13091. /* sscanf and the option splitting code ensure the following condition
  13092. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13093. if ((len > 0) && is_valid_port(port)
  13094. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13095. /* Next character after the port number */
  13096. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13097. so->is_ssl = (ch == 's');
  13098. so->ssl_redir = (ch == 'r');
  13099. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13100. return 1;
  13101. }
  13102. }
  13103. /* Reset ip_version to 0 if there is an error */
  13104. *ip_version = 0;
  13105. return 0;
  13106. }
  13107. /* Is there any SSL port in use? */
  13108. static int
  13109. is_ssl_port_used(const char *ports)
  13110. {
  13111. if (ports) {
  13112. /* There are several different allowed syntax variants:
  13113. * - "80" for a single port using every network interface
  13114. * - "localhost:80" for a single port using only localhost
  13115. * - "80,localhost:8080" for two ports, one bound to localhost
  13116. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13117. * to IPv4 localhost, one to IPv6 localhost
  13118. * - "+80" use port 80 for IPv4 and IPv6
  13119. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13120. * for both: IPv4 and IPv4
  13121. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13122. * additionally port 8080 bound to localhost connections
  13123. *
  13124. * If we just look for 's' anywhere in the string, "localhost:80"
  13125. * will be detected as SSL (false positive).
  13126. * Looking for 's' after a digit may cause false positives in
  13127. * "my24service:8080".
  13128. * Looking from 's' backward if there are only ':' and numbers
  13129. * before will not work for "24service:8080" (non SSL, port 8080)
  13130. * or "24s" (SSL, port 24).
  13131. *
  13132. * Remark: Initially hostnames were not allowed to start with a
  13133. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13134. * Section 2.1).
  13135. *
  13136. * To get this correct, the entire string must be parsed as a whole,
  13137. * reading it as a list element for element and parsing with an
  13138. * algorithm equivalent to parse_port_string.
  13139. *
  13140. * In fact, we use local interface names here, not arbitrary
  13141. * hostnames, so in most cases the only name will be "localhost".
  13142. *
  13143. * So, for now, we use this simple algorithm, that may still return
  13144. * a false positive in bizarre cases.
  13145. */
  13146. int i;
  13147. int portslen = (int)strlen(ports);
  13148. char prevIsNumber = 0;
  13149. for (i = 0; i < portslen; i++) {
  13150. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13151. return 1;
  13152. }
  13153. if (ports[i] >= '0' && ports[i] <= '9') {
  13154. prevIsNumber = 1;
  13155. } else {
  13156. prevIsNumber = 0;
  13157. }
  13158. }
  13159. }
  13160. return 0;
  13161. }
  13162. static int
  13163. set_ports_option(struct mg_context *phys_ctx)
  13164. {
  13165. const char *list;
  13166. int on = 1;
  13167. #if defined(USE_IPV6)
  13168. int off = 0;
  13169. #endif
  13170. struct vec vec;
  13171. struct socket so, *ptr;
  13172. struct mg_pollfd *pfd;
  13173. union usa usa;
  13174. socklen_t len;
  13175. int ip_version;
  13176. int portsTotal = 0;
  13177. int portsOk = 0;
  13178. const char *opt_txt;
  13179. long opt_listen_backlog;
  13180. if (!phys_ctx) {
  13181. return 0;
  13182. }
  13183. memset(&so, 0, sizeof(so));
  13184. memset(&usa, 0, sizeof(usa));
  13185. len = sizeof(usa);
  13186. list = phys_ctx->dd.config[LISTENING_PORTS];
  13187. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13188. portsTotal++;
  13189. if (!parse_port_string(&vec, &so, &ip_version)) {
  13190. mg_cry_ctx_internal(
  13191. phys_ctx,
  13192. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13193. (int)vec.len,
  13194. vec.ptr,
  13195. portsTotal,
  13196. "[IP_ADDRESS:]PORT[s|r]");
  13197. continue;
  13198. }
  13199. #if !defined(NO_SSL)
  13200. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13201. mg_cry_ctx_internal(phys_ctx,
  13202. "Cannot add SSL socket (entry %i)",
  13203. portsTotal);
  13204. continue;
  13205. }
  13206. #endif
  13207. /* Create socket. */
  13208. /* For a list of protocol numbers (e.g., TCP==6) see:
  13209. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13210. */
  13211. if ((so.sock =
  13212. socket(so.lsa.sa.sa_family,
  13213. SOCK_STREAM,
  13214. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13215. == INVALID_SOCKET) {
  13216. mg_cry_ctx_internal(phys_ctx,
  13217. "cannot create socket (entry %i)",
  13218. portsTotal);
  13219. continue;
  13220. }
  13221. #if defined(_WIN32)
  13222. /* Windows SO_REUSEADDR lets many procs binds to a
  13223. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13224. * if someone already has the socket -- DTL */
  13225. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13226. * Windows might need a few seconds before
  13227. * the same port can be used again in the
  13228. * same process, so a short Sleep may be
  13229. * required between mg_stop and mg_start.
  13230. */
  13231. if (setsockopt(so.sock,
  13232. SOL_SOCKET,
  13233. SO_EXCLUSIVEADDRUSE,
  13234. (SOCK_OPT_TYPE)&on,
  13235. sizeof(on))
  13236. != 0) {
  13237. /* Set reuse option, but don't abort on errors. */
  13238. mg_cry_ctx_internal(
  13239. phys_ctx,
  13240. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13241. portsTotal);
  13242. }
  13243. #else
  13244. if (setsockopt(so.sock,
  13245. SOL_SOCKET,
  13246. SO_REUSEADDR,
  13247. (SOCK_OPT_TYPE)&on,
  13248. sizeof(on))
  13249. != 0) {
  13250. /* Set reuse option, but don't abort on errors. */
  13251. mg_cry_ctx_internal(
  13252. phys_ctx,
  13253. "cannot set socket option SO_REUSEADDR (entry %i)",
  13254. portsTotal);
  13255. }
  13256. #endif
  13257. #if defined(USE_X_DOM_SOCKET)
  13258. if (ip_version == 99) {
  13259. /* Unix domain socket */
  13260. } else
  13261. #endif
  13262. if (ip_version > 4) {
  13263. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13264. #if defined(USE_IPV6)
  13265. if (ip_version > 6) {
  13266. if (so.lsa.sa.sa_family == AF_INET6
  13267. && setsockopt(so.sock,
  13268. IPPROTO_IPV6,
  13269. IPV6_V6ONLY,
  13270. (void *)&off,
  13271. sizeof(off))
  13272. != 0) {
  13273. /* Set IPv6 only option, but don't abort on errors. */
  13274. mg_cry_ctx_internal(phys_ctx,
  13275. "cannot set socket option "
  13276. "IPV6_V6ONLY=off (entry %i)",
  13277. portsTotal);
  13278. }
  13279. } else {
  13280. if (so.lsa.sa.sa_family == AF_INET6
  13281. && setsockopt(so.sock,
  13282. IPPROTO_IPV6,
  13283. IPV6_V6ONLY,
  13284. (void *)&on,
  13285. sizeof(on))
  13286. != 0) {
  13287. /* Set IPv6 only option, but don't abort on errors. */
  13288. mg_cry_ctx_internal(phys_ctx,
  13289. "cannot set socket option "
  13290. "IPV6_V6ONLY=on (entry %i)",
  13291. portsTotal);
  13292. }
  13293. }
  13294. #else
  13295. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13296. closesocket(so.sock);
  13297. so.sock = INVALID_SOCKET;
  13298. continue;
  13299. #endif
  13300. }
  13301. if (so.lsa.sa.sa_family == AF_INET) {
  13302. len = sizeof(so.lsa.sin);
  13303. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13304. mg_cry_ctx_internal(phys_ctx,
  13305. "cannot bind to %.*s: %d (%s)",
  13306. (int)vec.len,
  13307. vec.ptr,
  13308. (int)ERRNO,
  13309. strerror(errno));
  13310. closesocket(so.sock);
  13311. so.sock = INVALID_SOCKET;
  13312. continue;
  13313. }
  13314. }
  13315. #if defined(USE_IPV6)
  13316. else if (so.lsa.sa.sa_family == AF_INET6) {
  13317. len = sizeof(so.lsa.sin6);
  13318. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13319. mg_cry_ctx_internal(phys_ctx,
  13320. "cannot bind to IPv6 %.*s: %d (%s)",
  13321. (int)vec.len,
  13322. vec.ptr,
  13323. (int)ERRNO,
  13324. strerror(errno));
  13325. closesocket(so.sock);
  13326. so.sock = INVALID_SOCKET;
  13327. continue;
  13328. }
  13329. }
  13330. #endif
  13331. #if defined(USE_X_DOM_SOCKET)
  13332. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13333. len = sizeof(so.lsa.sun);
  13334. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13335. mg_cry_ctx_internal(phys_ctx,
  13336. "cannot bind to unix socket %s: %d (%s)",
  13337. so.lsa.sun.sun_path,
  13338. (int)ERRNO,
  13339. strerror(errno));
  13340. closesocket(so.sock);
  13341. so.sock = INVALID_SOCKET;
  13342. continue;
  13343. }
  13344. }
  13345. #endif
  13346. else {
  13347. mg_cry_ctx_internal(
  13348. phys_ctx,
  13349. "cannot bind: address family not supported (entry %i)",
  13350. portsTotal);
  13351. closesocket(so.sock);
  13352. so.sock = INVALID_SOCKET;
  13353. continue;
  13354. }
  13355. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13356. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13357. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13358. mg_cry_ctx_internal(phys_ctx,
  13359. "%s value \"%s\" is invalid",
  13360. config_options[LISTEN_BACKLOG_SIZE].name,
  13361. opt_txt);
  13362. closesocket(so.sock);
  13363. so.sock = INVALID_SOCKET;
  13364. continue;
  13365. }
  13366. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13367. mg_cry_ctx_internal(phys_ctx,
  13368. "cannot listen to %.*s: %d (%s)",
  13369. (int)vec.len,
  13370. vec.ptr,
  13371. (int)ERRNO,
  13372. strerror(errno));
  13373. closesocket(so.sock);
  13374. so.sock = INVALID_SOCKET;
  13375. continue;
  13376. }
  13377. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13378. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13379. int err = (int)ERRNO;
  13380. mg_cry_ctx_internal(phys_ctx,
  13381. "call to getsockname failed %.*s: %d (%s)",
  13382. (int)vec.len,
  13383. vec.ptr,
  13384. err,
  13385. strerror(errno));
  13386. closesocket(so.sock);
  13387. so.sock = INVALID_SOCKET;
  13388. continue;
  13389. }
  13390. /* Update lsa port in case of random free ports */
  13391. #if defined(USE_IPV6)
  13392. if (so.lsa.sa.sa_family == AF_INET6) {
  13393. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13394. } else
  13395. #endif
  13396. {
  13397. so.lsa.sin.sin_port = usa.sin.sin_port;
  13398. }
  13399. if ((ptr = (struct socket *)
  13400. mg_realloc_ctx(phys_ctx->listening_sockets,
  13401. (phys_ctx->num_listening_sockets + 1)
  13402. * sizeof(phys_ctx->listening_sockets[0]),
  13403. phys_ctx))
  13404. == NULL) {
  13405. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13406. closesocket(so.sock);
  13407. so.sock = INVALID_SOCKET;
  13408. continue;
  13409. }
  13410. if ((pfd = (struct mg_pollfd *)
  13411. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13412. (phys_ctx->num_listening_sockets + 1)
  13413. * sizeof(phys_ctx->listening_socket_fds[0]),
  13414. phys_ctx))
  13415. == NULL) {
  13416. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13417. closesocket(so.sock);
  13418. so.sock = INVALID_SOCKET;
  13419. mg_free(ptr);
  13420. continue;
  13421. }
  13422. set_close_on_exec(so.sock, NULL, phys_ctx);
  13423. phys_ctx->listening_sockets = ptr;
  13424. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13425. phys_ctx->listening_socket_fds = pfd;
  13426. phys_ctx->num_listening_sockets++;
  13427. portsOk++;
  13428. }
  13429. if (portsOk != portsTotal) {
  13430. close_all_listening_sockets(phys_ctx);
  13431. portsOk = 0;
  13432. }
  13433. return portsOk;
  13434. }
  13435. static const char *
  13436. header_val(const struct mg_connection *conn, const char *header)
  13437. {
  13438. const char *header_value;
  13439. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13440. return "-";
  13441. } else {
  13442. return header_value;
  13443. }
  13444. }
  13445. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13446. static void log_access(const struct mg_connection *conn);
  13447. #include "external_log_access.inl"
  13448. #elif !defined(NO_FILESYSTEMS)
  13449. static void
  13450. log_access(const struct mg_connection *conn)
  13451. {
  13452. const struct mg_request_info *ri;
  13453. struct mg_file fi;
  13454. char date[64], src_addr[IP_ADDR_STR_LEN];
  13455. struct tm *tm;
  13456. const char *referer;
  13457. const char *user_agent;
  13458. char buf[4096];
  13459. if (!conn || !conn->dom_ctx) {
  13460. return;
  13461. }
  13462. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13463. if (mg_fopen(conn,
  13464. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13465. MG_FOPEN_MODE_APPEND,
  13466. &fi)
  13467. == 0) {
  13468. fi.access.fp = NULL;
  13469. }
  13470. } else {
  13471. fi.access.fp = NULL;
  13472. }
  13473. /* Log is written to a file and/or a callback. If both are not set,
  13474. * executing the rest of the function is pointless. */
  13475. if ((fi.access.fp == NULL)
  13476. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13477. return;
  13478. }
  13479. tm = localtime(&conn->conn_birth_time);
  13480. if (tm != NULL) {
  13481. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13482. } else {
  13483. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13484. date[sizeof(date) - 1] = '\0';
  13485. }
  13486. ri = &conn->request_info;
  13487. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13488. referer = header_val(conn, "Referer");
  13489. user_agent = header_val(conn, "User-Agent");
  13490. mg_snprintf(conn,
  13491. NULL, /* Ignore truncation in access log */
  13492. buf,
  13493. sizeof(buf),
  13494. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13495. src_addr,
  13496. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13497. date,
  13498. ri->request_method ? ri->request_method : "-",
  13499. ri->request_uri ? ri->request_uri : "-",
  13500. ri->query_string ? "?" : "",
  13501. ri->query_string ? ri->query_string : "",
  13502. ri->http_version,
  13503. conn->status_code,
  13504. conn->num_bytes_sent,
  13505. referer,
  13506. user_agent);
  13507. if (conn->phys_ctx->callbacks.log_access) {
  13508. conn->phys_ctx->callbacks.log_access(conn, buf);
  13509. }
  13510. if (fi.access.fp) {
  13511. int ok = 1;
  13512. flockfile(fi.access.fp);
  13513. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13514. ok = 0;
  13515. }
  13516. if (fflush(fi.access.fp) != 0) {
  13517. ok = 0;
  13518. }
  13519. funlockfile(fi.access.fp);
  13520. if (mg_fclose(&fi.access) != 0) {
  13521. ok = 0;
  13522. }
  13523. if (!ok) {
  13524. mg_cry_internal(conn,
  13525. "Error writing log file %s",
  13526. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13527. }
  13528. }
  13529. }
  13530. #else
  13531. #error Must either enable filesystems or provide a custom log_access implementation
  13532. #endif /* Externally provided function */
  13533. /* Verify given socket address against the ACL.
  13534. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13535. */
  13536. static int
  13537. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13538. {
  13539. int allowed, flag, matched;
  13540. struct vec vec;
  13541. if (phys_ctx) {
  13542. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13543. /* If any ACL is set, deny by default */
  13544. allowed = (list == NULL) ? '+' : '-';
  13545. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13546. flag = vec.ptr[0];
  13547. matched = -1;
  13548. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13549. vec.ptr++;
  13550. vec.len--;
  13551. matched = parse_match_net(&vec, sa, 1);
  13552. }
  13553. if (matched < 0) {
  13554. mg_cry_ctx_internal(phys_ctx,
  13555. "%s: subnet must be [+|-]IP-addr[/x]",
  13556. __func__);
  13557. return -1;
  13558. }
  13559. if (matched) {
  13560. allowed = flag;
  13561. }
  13562. }
  13563. return allowed == '+';
  13564. }
  13565. return -1;
  13566. }
  13567. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13568. static int
  13569. set_uid_option(struct mg_context *phys_ctx)
  13570. {
  13571. int success = 0;
  13572. if (phys_ctx) {
  13573. /* We are currently running as curr_uid. */
  13574. const uid_t curr_uid = getuid();
  13575. /* If set, we want to run as run_as_user. */
  13576. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13577. const struct passwd *to_pw = NULL;
  13578. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13579. /* run_as_user does not exist on the system. We can't proceed
  13580. * further. */
  13581. mg_cry_ctx_internal(phys_ctx,
  13582. "%s: unknown user [%s]",
  13583. __func__,
  13584. run_as_user);
  13585. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13586. /* There was either no request to change user, or we're already
  13587. * running as run_as_user. Nothing else to do.
  13588. */
  13589. success = 1;
  13590. } else {
  13591. /* Valid change request. */
  13592. if (setgid(to_pw->pw_gid) == -1) {
  13593. mg_cry_ctx_internal(phys_ctx,
  13594. "%s: setgid(%s): %s",
  13595. __func__,
  13596. run_as_user,
  13597. strerror(errno));
  13598. } else if (setgroups(0, NULL) == -1) {
  13599. mg_cry_ctx_internal(phys_ctx,
  13600. "%s: setgroups(): %s",
  13601. __func__,
  13602. strerror(errno));
  13603. } else if (setuid(to_pw->pw_uid) == -1) {
  13604. mg_cry_ctx_internal(phys_ctx,
  13605. "%s: setuid(%s): %s",
  13606. __func__,
  13607. run_as_user,
  13608. strerror(errno));
  13609. } else {
  13610. success = 1;
  13611. }
  13612. }
  13613. }
  13614. return success;
  13615. }
  13616. #endif /* !_WIN32 */
  13617. static void
  13618. tls_dtor(void *key)
  13619. {
  13620. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13621. /* key == pthread_getspecific(sTlsKey); */
  13622. if (tls) {
  13623. if (tls->is_master == 2) {
  13624. tls->is_master = -3; /* Mark memory as dead */
  13625. mg_free(tls);
  13626. }
  13627. }
  13628. pthread_setspecific(sTlsKey, NULL);
  13629. }
  13630. #if !defined(NO_SSL)
  13631. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13632. struct mg_domain_context *dom_ctx,
  13633. const char *pem,
  13634. const char *chain);
  13635. static const char *ssl_error(void);
  13636. static int
  13637. refresh_trust(struct mg_connection *conn)
  13638. {
  13639. struct stat cert_buf;
  13640. int64_t t = 0;
  13641. const char *pem;
  13642. const char *chain;
  13643. int should_verify_peer;
  13644. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13645. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13646. * refresh_trust still can not work. */
  13647. return 0;
  13648. }
  13649. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13650. if (chain == NULL) {
  13651. /* pem is not NULL here */
  13652. chain = pem;
  13653. }
  13654. if (*chain == 0) {
  13655. chain = NULL;
  13656. }
  13657. if (stat(pem, &cert_buf) != -1) {
  13658. t = (int64_t)cert_buf.st_mtime;
  13659. }
  13660. mg_lock_context(conn->phys_ctx);
  13661. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13662. conn->dom_ctx->ssl_cert_last_mtime = t;
  13663. should_verify_peer = 0;
  13664. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13665. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13666. == 0) {
  13667. should_verify_peer = 1;
  13668. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13669. "optional")
  13670. == 0) {
  13671. should_verify_peer = 1;
  13672. }
  13673. }
  13674. if (should_verify_peer) {
  13675. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13676. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13677. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13678. ca_file,
  13679. ca_path)
  13680. != 1) {
  13681. mg_unlock_context(conn->phys_ctx);
  13682. mg_cry_ctx_internal(
  13683. conn->phys_ctx,
  13684. "SSL_CTX_load_verify_locations error: %s "
  13685. "ssl_verify_peer requires setting "
  13686. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13687. "present in "
  13688. "the .conf file?",
  13689. ssl_error());
  13690. return 0;
  13691. }
  13692. }
  13693. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13694. mg_unlock_context(conn->phys_ctx);
  13695. return 0;
  13696. }
  13697. }
  13698. mg_unlock_context(conn->phys_ctx);
  13699. return 1;
  13700. }
  13701. #if defined(OPENSSL_API_1_1)
  13702. #else
  13703. static pthread_mutex_t *ssl_mutexes;
  13704. #endif /* OPENSSL_API_1_1 */
  13705. static int
  13706. sslize(struct mg_connection *conn,
  13707. int (*func)(SSL *),
  13708. const struct mg_client_options *client_options)
  13709. {
  13710. int ret, err;
  13711. int short_trust;
  13712. unsigned timeout = 1024;
  13713. unsigned i;
  13714. if (!conn) {
  13715. return 0;
  13716. }
  13717. short_trust =
  13718. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13719. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13720. if (short_trust) {
  13721. int trust_ret = refresh_trust(conn);
  13722. if (!trust_ret) {
  13723. return trust_ret;
  13724. }
  13725. }
  13726. mg_lock_context(conn->phys_ctx);
  13727. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13728. mg_unlock_context(conn->phys_ctx);
  13729. if (conn->ssl == NULL) {
  13730. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13731. OPENSSL_REMOVE_THREAD_STATE();
  13732. return 0;
  13733. }
  13734. SSL_set_app_data(conn->ssl, (char *)conn);
  13735. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13736. if (ret != 1) {
  13737. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13738. SSL_free(conn->ssl);
  13739. conn->ssl = NULL;
  13740. OPENSSL_REMOVE_THREAD_STATE();
  13741. return 0;
  13742. }
  13743. if (client_options) {
  13744. if (client_options->host_name) {
  13745. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13746. }
  13747. }
  13748. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13749. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13750. /* NOTE: The loop below acts as a back-off, so we can end
  13751. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13752. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13753. if (to >= 0) {
  13754. timeout = (unsigned)to;
  13755. }
  13756. }
  13757. /* SSL functions may fail and require to be called again:
  13758. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13759. * Here "func" could be SSL_connect or SSL_accept. */
  13760. for (i = 0; i <= timeout; i += 50) {
  13761. ERR_clear_error();
  13762. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13763. ret = func(conn->ssl);
  13764. if (ret != 1) {
  13765. err = SSL_get_error(conn->ssl, ret);
  13766. if ((err == SSL_ERROR_WANT_CONNECT)
  13767. || (err == SSL_ERROR_WANT_ACCEPT)
  13768. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13769. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13770. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13771. /* Don't wait if the server is going to be stopped. */
  13772. break;
  13773. }
  13774. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13775. /* Simply retry the function call. */
  13776. mg_sleep(50);
  13777. } else {
  13778. /* Need to retry the function call "later".
  13779. * See https://linux.die.net/man/3/ssl_get_error
  13780. * This is typical for non-blocking sockets. */
  13781. struct mg_pollfd pfd;
  13782. int pollres;
  13783. pfd.fd = conn->client.sock;
  13784. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13785. || (err == SSL_ERROR_WANT_WRITE))
  13786. ? POLLOUT
  13787. : POLLIN;
  13788. pollres =
  13789. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13790. if (pollres < 0) {
  13791. /* Break if error occured (-1)
  13792. * or server shutdown (-2) */
  13793. break;
  13794. }
  13795. }
  13796. } else if (err == SSL_ERROR_SYSCALL) {
  13797. /* This is an IO error. Look at errno. */
  13798. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13799. break;
  13800. } else {
  13801. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13802. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13803. break;
  13804. }
  13805. } else {
  13806. /* success */
  13807. break;
  13808. }
  13809. }
  13810. ERR_clear_error();
  13811. if (ret != 1) {
  13812. SSL_free(conn->ssl);
  13813. conn->ssl = NULL;
  13814. OPENSSL_REMOVE_THREAD_STATE();
  13815. return 0;
  13816. }
  13817. return 1;
  13818. }
  13819. /* Return OpenSSL error message (from CRYPTO lib) */
  13820. static const char *
  13821. ssl_error(void)
  13822. {
  13823. unsigned long err;
  13824. err = ERR_get_error();
  13825. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13826. }
  13827. static int
  13828. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13829. {
  13830. int i;
  13831. const char hexdigit[] = "0123456789abcdef";
  13832. if ((memlen <= 0) || (buflen <= 0)) {
  13833. return 0;
  13834. }
  13835. if (buflen < (3 * memlen)) {
  13836. return 0;
  13837. }
  13838. for (i = 0; i < memlen; i++) {
  13839. if (i > 0) {
  13840. buf[3 * i - 1] = ' ';
  13841. }
  13842. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13843. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13844. }
  13845. buf[3 * memlen - 1] = 0;
  13846. return 1;
  13847. }
  13848. static int
  13849. ssl_get_client_cert_info(const struct mg_connection *conn,
  13850. struct mg_client_cert *client_cert)
  13851. {
  13852. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13853. if (cert) {
  13854. char str_buf[1024];
  13855. unsigned char buf[256];
  13856. char *str_serial = NULL;
  13857. unsigned int ulen;
  13858. int ilen;
  13859. unsigned char *tmp_buf;
  13860. unsigned char *tmp_p;
  13861. /* Handle to algorithm used for fingerprint */
  13862. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13863. /* Get Subject and issuer */
  13864. X509_NAME *subj = X509_get_subject_name(cert);
  13865. X509_NAME *iss = X509_get_issuer_name(cert);
  13866. /* Get serial number */
  13867. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13868. /* Translate serial number to a hex string */
  13869. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13870. if (serial_bn) {
  13871. str_serial = BN_bn2hex(serial_bn);
  13872. BN_free(serial_bn);
  13873. }
  13874. client_cert->serial =
  13875. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13876. /* Translate subject and issuer to a string */
  13877. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13878. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13879. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13880. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13881. /* Calculate SHA1 fingerprint and store as a hex string */
  13882. ulen = 0;
  13883. /* ASN1_digest is deprecated. Do the calculation manually,
  13884. * using EVP_Digest. */
  13885. ilen = i2d_X509(cert, NULL);
  13886. tmp_buf = (ilen > 0)
  13887. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13888. conn->phys_ctx)
  13889. : NULL;
  13890. if (tmp_buf) {
  13891. tmp_p = tmp_buf;
  13892. (void)i2d_X509(cert, &tmp_p);
  13893. if (!EVP_Digest(
  13894. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13895. ulen = 0;
  13896. }
  13897. mg_free(tmp_buf);
  13898. }
  13899. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13900. *str_buf = 0;
  13901. }
  13902. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13903. client_cert->peer_cert = (void *)cert;
  13904. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13905. * see https://linux.die.net/man/3/bn_bn2hex */
  13906. OPENSSL_free(str_serial);
  13907. return 1;
  13908. }
  13909. return 0;
  13910. }
  13911. #if defined(OPENSSL_API_1_1)
  13912. #else
  13913. static void
  13914. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13915. {
  13916. (void)line;
  13917. (void)file;
  13918. if (mode & 1) {
  13919. /* 1 is CRYPTO_LOCK */
  13920. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13921. } else {
  13922. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13923. }
  13924. }
  13925. #endif /* OPENSSL_API_1_1 */
  13926. #if !defined(NO_SSL_DL)
  13927. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13928. static void *
  13929. load_tls_dll(char *ebuf,
  13930. size_t ebuf_len,
  13931. const char *dll_name,
  13932. struct ssl_func *sw,
  13933. int *feature_missing)
  13934. {
  13935. union {
  13936. void *p;
  13937. void (*fp)(void);
  13938. } u;
  13939. void *dll_handle;
  13940. struct ssl_func *fp;
  13941. int ok;
  13942. int truncated = 0;
  13943. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13944. mg_snprintf(NULL,
  13945. NULL, /* No truncation check for ebuf */
  13946. ebuf,
  13947. ebuf_len,
  13948. "%s: cannot load %s",
  13949. __func__,
  13950. dll_name);
  13951. return NULL;
  13952. }
  13953. ok = 1;
  13954. for (fp = sw; fp->name != NULL; fp++) {
  13955. #if defined(_WIN32)
  13956. /* GetProcAddress() returns pointer to function */
  13957. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13958. #else
  13959. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13960. * pointers to function pointers. We need to use a union to make a
  13961. * cast. */
  13962. u.p = dlsym(dll_handle, fp->name);
  13963. #endif /* _WIN32 */
  13964. /* Set pointer (might be NULL) */
  13965. fp->ptr = u.fp;
  13966. if (u.fp == NULL) {
  13967. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13968. if (feature_missing) {
  13969. feature_missing[fp->required]++;
  13970. }
  13971. if (fp->required == TLS_Mandatory) {
  13972. /* Mandatory function is missing */
  13973. if (ok) {
  13974. /* This is the first missing function.
  13975. * Create a new error message. */
  13976. mg_snprintf(NULL,
  13977. &truncated,
  13978. ebuf,
  13979. ebuf_len,
  13980. "%s: %s: cannot find %s",
  13981. __func__,
  13982. dll_name,
  13983. fp->name);
  13984. ok = 0;
  13985. } else {
  13986. /* This is yet anothermissing function.
  13987. * Append existing error message. */
  13988. size_t cur_len = strlen(ebuf);
  13989. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13990. mg_snprintf(NULL,
  13991. &truncated,
  13992. ebuf + cur_len,
  13993. ebuf_len - cur_len - 3,
  13994. ", %s",
  13995. fp->name);
  13996. if (truncated) {
  13997. /* If truncated, add "..." */
  13998. strcat(ebuf, "...");
  13999. }
  14000. }
  14001. }
  14002. }
  14003. }
  14004. }
  14005. if (!ok) {
  14006. (void)dlclose(dll_handle);
  14007. return NULL;
  14008. }
  14009. return dll_handle;
  14010. }
  14011. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14012. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14013. #endif /* NO_SSL_DL */
  14014. #if defined(SSL_ALREADY_INITIALIZED)
  14015. static volatile ptrdiff_t cryptolib_users =
  14016. 1; /* Reference counter for crypto library. */
  14017. #else
  14018. static volatile ptrdiff_t cryptolib_users =
  14019. 0; /* Reference counter for crypto library. */
  14020. #endif
  14021. static int
  14022. initialize_ssl(char *ebuf, size_t ebuf_len)
  14023. {
  14024. #if !defined(OPENSSL_API_1_1)
  14025. int i, num_locks;
  14026. size_t size;
  14027. #endif
  14028. if (ebuf_len > 0) {
  14029. ebuf[0] = 0;
  14030. }
  14031. #if !defined(NO_SSL_DL)
  14032. if (!cryptolib_dll_handle) {
  14033. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14034. cryptolib_dll_handle = load_tls_dll(
  14035. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14036. if (!cryptolib_dll_handle) {
  14037. mg_snprintf(NULL,
  14038. NULL, /* No truncation check for ebuf */
  14039. ebuf,
  14040. ebuf_len,
  14041. "%s: error loading library %s",
  14042. __func__,
  14043. CRYPTO_LIB);
  14044. DEBUG_TRACE("%s", ebuf);
  14045. return 0;
  14046. }
  14047. }
  14048. #endif /* NO_SSL_DL */
  14049. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14050. return 1;
  14051. }
  14052. #if !defined(OPENSSL_API_1_1)
  14053. /* Initialize locking callbacks, needed for thread safety.
  14054. * http://www.openssl.org/support/faq.html#PROG1
  14055. */
  14056. num_locks = CRYPTO_num_locks();
  14057. if (num_locks < 0) {
  14058. num_locks = 0;
  14059. }
  14060. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14061. /* allocate mutex array, if required */
  14062. if (num_locks == 0) {
  14063. /* No mutex array required */
  14064. ssl_mutexes = NULL;
  14065. } else {
  14066. /* Mutex array required - allocate it */
  14067. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14068. /* Check OOM */
  14069. if (ssl_mutexes == NULL) {
  14070. mg_snprintf(NULL,
  14071. NULL, /* No truncation check for ebuf */
  14072. ebuf,
  14073. ebuf_len,
  14074. "%s: cannot allocate mutexes: %s",
  14075. __func__,
  14076. ssl_error());
  14077. DEBUG_TRACE("%s", ebuf);
  14078. return 0;
  14079. }
  14080. /* initialize mutex array */
  14081. for (i = 0; i < num_locks; i++) {
  14082. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14083. mg_snprintf(NULL,
  14084. NULL, /* No truncation check for ebuf */
  14085. ebuf,
  14086. ebuf_len,
  14087. "%s: error initializing mutex %i of %i",
  14088. __func__,
  14089. i,
  14090. num_locks);
  14091. DEBUG_TRACE("%s", ebuf);
  14092. mg_free(ssl_mutexes);
  14093. return 0;
  14094. }
  14095. }
  14096. }
  14097. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14098. CRYPTO_set_id_callback(&mg_current_thread_id);
  14099. #endif /* OPENSSL_API_1_1 */
  14100. #if !defined(NO_SSL_DL)
  14101. if (!ssllib_dll_handle) {
  14102. ssllib_dll_handle =
  14103. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14104. if (!ssllib_dll_handle) {
  14105. #if !defined(OPENSSL_API_1_1)
  14106. mg_free(ssl_mutexes);
  14107. #endif
  14108. DEBUG_TRACE("%s", ebuf);
  14109. return 0;
  14110. }
  14111. }
  14112. #endif /* NO_SSL_DL */
  14113. #if defined(OPENSSL_API_1_1)
  14114. /* Initialize SSL library */
  14115. OPENSSL_init_ssl(0, NULL);
  14116. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14117. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14118. NULL);
  14119. #else
  14120. /* Initialize SSL library */
  14121. SSL_library_init();
  14122. SSL_load_error_strings();
  14123. #endif
  14124. return 1;
  14125. }
  14126. static int
  14127. ssl_use_pem_file(struct mg_context *phys_ctx,
  14128. struct mg_domain_context *dom_ctx,
  14129. const char *pem,
  14130. const char *chain)
  14131. {
  14132. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14133. mg_cry_ctx_internal(phys_ctx,
  14134. "%s: cannot open certificate file %s: %s",
  14135. __func__,
  14136. pem,
  14137. ssl_error());
  14138. return 0;
  14139. }
  14140. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14141. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14142. mg_cry_ctx_internal(phys_ctx,
  14143. "%s: cannot open private key file %s: %s",
  14144. __func__,
  14145. pem,
  14146. ssl_error());
  14147. return 0;
  14148. }
  14149. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14150. mg_cry_ctx_internal(phys_ctx,
  14151. "%s: certificate and private key do not match: %s",
  14152. __func__,
  14153. pem);
  14154. return 0;
  14155. }
  14156. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14157. * chain files that contain private keys and certificates in
  14158. * SSL_CTX_use_certificate_chain_file.
  14159. * The CivetWeb-Server used pem-Files that contained both information.
  14160. * In order to make wolfSSL work, it is split in two files.
  14161. * One file that contains key and certificate used by the server and
  14162. * an optional chain file for the ssl stack.
  14163. */
  14164. if (chain) {
  14165. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14166. mg_cry_ctx_internal(phys_ctx,
  14167. "%s: cannot use certificate chain file %s: %s",
  14168. __func__,
  14169. chain,
  14170. ssl_error());
  14171. return 0;
  14172. }
  14173. }
  14174. return 1;
  14175. }
  14176. #if defined(OPENSSL_API_1_1)
  14177. static unsigned long
  14178. ssl_get_protocol(int version_id)
  14179. {
  14180. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14181. if (version_id > 0)
  14182. ret |= SSL_OP_NO_SSLv2;
  14183. if (version_id > 1)
  14184. ret |= SSL_OP_NO_SSLv3;
  14185. if (version_id > 2)
  14186. ret |= SSL_OP_NO_TLSv1;
  14187. if (version_id > 3)
  14188. ret |= SSL_OP_NO_TLSv1_1;
  14189. if (version_id > 4)
  14190. ret |= SSL_OP_NO_TLSv1_2;
  14191. #if defined(SSL_OP_NO_TLSv1_3)
  14192. if (version_id > 5)
  14193. ret |= SSL_OP_NO_TLSv1_3;
  14194. #endif
  14195. return ret;
  14196. }
  14197. #else
  14198. static long
  14199. ssl_get_protocol(int version_id)
  14200. {
  14201. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14202. if (version_id > 0)
  14203. ret |= SSL_OP_NO_SSLv2;
  14204. if (version_id > 1)
  14205. ret |= SSL_OP_NO_SSLv3;
  14206. if (version_id > 2)
  14207. ret |= SSL_OP_NO_TLSv1;
  14208. if (version_id > 3)
  14209. ret |= SSL_OP_NO_TLSv1_1;
  14210. if (version_id > 4)
  14211. ret |= SSL_OP_NO_TLSv1_2;
  14212. #if defined(SSL_OP_NO_TLSv1_3)
  14213. if (version_id > 5)
  14214. ret |= SSL_OP_NO_TLSv1_3;
  14215. #endif
  14216. return (long)ret;
  14217. }
  14218. #endif /* OPENSSL_API_1_1 */
  14219. /* SSL callback documentation:
  14220. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14221. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14222. * https://linux.die.net/man/3/ssl_set_info_callback */
  14223. /* Note: There is no "const" for the first argument in the documentation
  14224. * examples, however some (maybe most, but not all) headers of OpenSSL
  14225. * versions / OpenSSL compatibility layers have it. Having a different
  14226. * definition will cause a warning in C and an error in C++. Use "const SSL
  14227. * *", while automatical conversion from "SSL *" works for all compilers,
  14228. * but not other way around */
  14229. static void
  14230. ssl_info_callback(const SSL *ssl, int what, int ret)
  14231. {
  14232. (void)ret;
  14233. if (what & SSL_CB_HANDSHAKE_START) {
  14234. SSL_get_app_data(ssl);
  14235. }
  14236. if (what & SSL_CB_HANDSHAKE_DONE) {
  14237. /* TODO: check for openSSL 1.1 */
  14238. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14239. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14240. }
  14241. }
  14242. static int
  14243. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14244. {
  14245. #if defined(GCC_DIAGNOSTIC)
  14246. #pragma GCC diagnostic push
  14247. #pragma GCC diagnostic ignored "-Wcast-align"
  14248. #endif /* defined(GCC_DIAGNOSTIC) */
  14249. /* We used an aligned pointer in SSL_set_app_data */
  14250. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14251. #if defined(GCC_DIAGNOSTIC)
  14252. #pragma GCC diagnostic pop
  14253. #endif /* defined(GCC_DIAGNOSTIC) */
  14254. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14255. (void)ad;
  14256. (void)arg;
  14257. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14258. DEBUG_ASSERT(0);
  14259. return SSL_TLSEXT_ERR_NOACK;
  14260. }
  14261. conn->dom_ctx = &(conn->phys_ctx->dd);
  14262. /* Old clients (Win XP) will not support SNI. Then, there
  14263. * is no server name available in the request - we can
  14264. * only work with the default certificate.
  14265. * Multiple HTTPS hosts on one IP+port are only possible
  14266. * with a certificate containing all alternative names.
  14267. */
  14268. if ((servername == NULL) || (*servername == 0)) {
  14269. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14270. mg_lock_context(conn->phys_ctx);
  14271. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14272. mg_unlock_context(conn->phys_ctx);
  14273. return SSL_TLSEXT_ERR_NOACK;
  14274. }
  14275. DEBUG_TRACE("TLS connection to host %s", servername);
  14276. while (conn->dom_ctx) {
  14277. if (!mg_strcasecmp(servername,
  14278. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14279. /* Found matching domain */
  14280. DEBUG_TRACE("TLS domain %s found",
  14281. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14282. break;
  14283. }
  14284. mg_lock_context(conn->phys_ctx);
  14285. conn->dom_ctx = conn->dom_ctx->next;
  14286. mg_unlock_context(conn->phys_ctx);
  14287. }
  14288. if (conn->dom_ctx == NULL) {
  14289. /* Default domain */
  14290. DEBUG_TRACE("TLS default domain %s used",
  14291. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14292. conn->dom_ctx = &(conn->phys_ctx->dd);
  14293. }
  14294. mg_lock_context(conn->phys_ctx);
  14295. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14296. mg_unlock_context(conn->phys_ctx);
  14297. return SSL_TLSEXT_ERR_OK;
  14298. }
  14299. #if defined(USE_ALPN)
  14300. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14301. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14302. alpn_proto_list + 3 + 8,
  14303. NULL};
  14304. #if defined(USE_HTTP2)
  14305. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14306. alpn_proto_list + 3,
  14307. alpn_proto_list + 3 + 8,
  14308. NULL};
  14309. #endif
  14310. static int
  14311. alpn_select_cb(SSL *ssl,
  14312. const unsigned char **out,
  14313. unsigned char *outlen,
  14314. const unsigned char *in,
  14315. unsigned int inlen,
  14316. void *arg)
  14317. {
  14318. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14319. unsigned int i, j, enable_http2 = 0;
  14320. const char **alpn_proto_order = alpn_proto_order_http1;
  14321. struct mg_workerTLS *tls =
  14322. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14323. (void)ssl;
  14324. if (tls == NULL) {
  14325. /* Need to store protocol in Thread Local Storage */
  14326. /* If there is no Thread Local Storage, don't use ALPN */
  14327. return SSL_TLSEXT_ERR_NOACK;
  14328. }
  14329. #if defined(USE_HTTP2)
  14330. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14331. if (enable_http2) {
  14332. alpn_proto_order = alpn_proto_order_http2;
  14333. }
  14334. #endif
  14335. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14336. /* check all accepted protocols in this order */
  14337. const char *alpn_proto = alpn_proto_order[j];
  14338. /* search input for matching protocol */
  14339. for (i = 0; i < inlen; i++) {
  14340. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14341. *out = in + i + 1;
  14342. *outlen = in[i];
  14343. tls->alpn_proto = alpn_proto;
  14344. return SSL_TLSEXT_ERR_OK;
  14345. }
  14346. }
  14347. }
  14348. /* Nothing found */
  14349. return SSL_TLSEXT_ERR_NOACK;
  14350. }
  14351. static int
  14352. next_protos_advertised_cb(SSL *ssl,
  14353. const unsigned char **data,
  14354. unsigned int *len,
  14355. void *arg)
  14356. {
  14357. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14358. *data = (const unsigned char *)alpn_proto_list;
  14359. *len = (unsigned int)strlen((const char *)data);
  14360. (void)ssl;
  14361. (void)dom_ctx;
  14362. return SSL_TLSEXT_ERR_OK;
  14363. }
  14364. static int
  14365. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14366. {
  14367. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14368. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14369. (const unsigned char *)alpn_proto_list,
  14370. alpn_len);
  14371. if (ret != 0) {
  14372. mg_cry_ctx_internal(phys_ctx,
  14373. "SSL_CTX_set_alpn_protos error: %s",
  14374. ssl_error());
  14375. }
  14376. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14377. alpn_select_cb,
  14378. (void *)dom_ctx);
  14379. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14380. next_protos_advertised_cb,
  14381. (void *)dom_ctx);
  14382. return ret;
  14383. }
  14384. #endif
  14385. /* Setup SSL CTX as required by CivetWeb */
  14386. static int
  14387. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14388. struct mg_domain_context *dom_ctx,
  14389. const char *pem,
  14390. const char *chain)
  14391. {
  14392. int callback_ret;
  14393. int should_verify_peer;
  14394. int peer_certificate_optional;
  14395. const char *ca_path;
  14396. const char *ca_file;
  14397. int use_default_verify_paths;
  14398. int verify_depth;
  14399. struct timespec now_mt;
  14400. md5_byte_t ssl_context_id[16];
  14401. md5_state_t md5state;
  14402. int protocol_ver;
  14403. int ssl_cache_timeout;
  14404. #if defined(OPENSSL_API_1_1)
  14405. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14406. mg_cry_ctx_internal(phys_ctx,
  14407. "SSL_CTX_new (server) error: %s",
  14408. ssl_error());
  14409. return 0;
  14410. }
  14411. #else
  14412. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14413. mg_cry_ctx_internal(phys_ctx,
  14414. "SSL_CTX_new (server) error: %s",
  14415. ssl_error());
  14416. return 0;
  14417. }
  14418. #endif /* OPENSSL_API_1_1 */
  14419. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14420. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14421. | SSL_OP_NO_TLSv1_1);
  14422. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14423. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14424. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14425. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14426. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14427. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14428. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14429. #if defined(SSL_OP_NO_RENEGOTIATION)
  14430. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14431. #endif
  14432. #if !defined(NO_SSL_DL)
  14433. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14434. #endif /* NO_SSL_DL */
  14435. /* In SSL documentation examples callback defined without const
  14436. * specifier 'void (*)(SSL *, int, int)' See:
  14437. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14438. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14439. * But in the source code const SSL is used:
  14440. * 'void (*)(const SSL *, int, int)' See:
  14441. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14442. * Problem about wrong documentation described, but not resolved:
  14443. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14444. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14445. * But when compiled with modern C++ compiler, correct const should be
  14446. * provided
  14447. */
  14448. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14449. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14450. ssl_servername_callback);
  14451. /* If a callback has been specified, call it. */
  14452. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14453. ? 0
  14454. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14455. phys_ctx->user_data));
  14456. /* If callback returns 0, civetweb sets up the SSL certificate.
  14457. * If it returns 1, civetweb assumes the calback already did this.
  14458. * If it returns -1, initializing ssl fails. */
  14459. if (callback_ret < 0) {
  14460. mg_cry_ctx_internal(phys_ctx,
  14461. "SSL callback returned error: %i",
  14462. callback_ret);
  14463. return 0;
  14464. }
  14465. if (callback_ret > 0) {
  14466. /* Callback did everything. */
  14467. return 1;
  14468. }
  14469. /* If a domain callback has been specified, call it. */
  14470. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14471. ? 0
  14472. : (phys_ctx->callbacks.init_ssl_domain(
  14473. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14474. dom_ctx->ssl_ctx,
  14475. phys_ctx->user_data));
  14476. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14477. * If it returns 1, civetweb assumes the calback already did this.
  14478. * If it returns -1, initializing ssl fails. */
  14479. if (callback_ret < 0) {
  14480. mg_cry_ctx_internal(phys_ctx,
  14481. "Domain SSL callback returned error: %i",
  14482. callback_ret);
  14483. return 0;
  14484. }
  14485. if (callback_ret > 0) {
  14486. /* Domain callback did everything. */
  14487. return 1;
  14488. }
  14489. /* Use some combination of start time, domain and port as a SSL
  14490. * context ID. This should be unique on the current machine. */
  14491. md5_init(&md5state);
  14492. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14493. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14494. md5_append(&md5state,
  14495. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14496. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14497. md5_append(&md5state,
  14498. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14499. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14500. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14501. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14502. md5_finish(&md5state, ssl_context_id);
  14503. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14504. (unsigned char *)ssl_context_id,
  14505. sizeof(ssl_context_id));
  14506. if (pem != NULL) {
  14507. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14508. return 0;
  14509. }
  14510. }
  14511. /* Should we support client certificates? */
  14512. /* Default is "no". */
  14513. should_verify_peer = 0;
  14514. peer_certificate_optional = 0;
  14515. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14516. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14517. /* Yes, they are mandatory */
  14518. should_verify_peer = 1;
  14519. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14520. "optional")
  14521. == 0) {
  14522. /* Yes, they are optional */
  14523. should_verify_peer = 1;
  14524. peer_certificate_optional = 1;
  14525. }
  14526. }
  14527. use_default_verify_paths =
  14528. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14529. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14530. == 0);
  14531. if (should_verify_peer) {
  14532. ca_path = dom_ctx->config[SSL_CA_PATH];
  14533. ca_file = dom_ctx->config[SSL_CA_FILE];
  14534. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14535. != 1) {
  14536. mg_cry_ctx_internal(phys_ctx,
  14537. "SSL_CTX_load_verify_locations error: %s "
  14538. "ssl_verify_peer requires setting "
  14539. "either ssl_ca_path or ssl_ca_file. "
  14540. "Is any of them present in the "
  14541. ".conf file?",
  14542. ssl_error());
  14543. return 0;
  14544. }
  14545. if (peer_certificate_optional) {
  14546. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14547. } else {
  14548. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14549. SSL_VERIFY_PEER
  14550. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14551. NULL);
  14552. }
  14553. if (use_default_verify_paths
  14554. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14555. mg_cry_ctx_internal(phys_ctx,
  14556. "SSL_CTX_set_default_verify_paths error: %s",
  14557. ssl_error());
  14558. return 0;
  14559. }
  14560. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14561. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14562. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14563. }
  14564. }
  14565. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14566. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14567. dom_ctx->config[SSL_CIPHER_LIST])
  14568. != 1) {
  14569. mg_cry_ctx_internal(phys_ctx,
  14570. "SSL_CTX_set_cipher_list error: %s",
  14571. ssl_error());
  14572. }
  14573. }
  14574. /* SSL session caching */
  14575. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14576. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14577. : 0);
  14578. if (ssl_cache_timeout > 0) {
  14579. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14580. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14581. * default */
  14582. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14583. }
  14584. #if defined(USE_ALPN)
  14585. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14586. #if !defined(NO_SSL_DL)
  14587. if (!tls_feature_missing[TLS_ALPN])
  14588. #endif
  14589. {
  14590. init_alpn(phys_ctx, dom_ctx);
  14591. }
  14592. #endif
  14593. return 1;
  14594. }
  14595. /* Check if SSL is required.
  14596. * If so, dynamically load SSL library
  14597. * and set up ctx->ssl_ctx pointer. */
  14598. static int
  14599. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14600. {
  14601. void *ssl_ctx = 0;
  14602. int callback_ret;
  14603. const char *pem;
  14604. const char *chain;
  14605. char ebuf[128];
  14606. if (!phys_ctx) {
  14607. return 0;
  14608. }
  14609. if (!dom_ctx) {
  14610. dom_ctx = &(phys_ctx->dd);
  14611. }
  14612. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14613. /* No SSL port is set. No need to setup SSL. */
  14614. return 1;
  14615. }
  14616. /* Check for external SSL_CTX */
  14617. callback_ret =
  14618. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14619. ? 0
  14620. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14621. phys_ctx->user_data));
  14622. if (callback_ret < 0) {
  14623. /* Callback exists and returns <0: Initializing failed. */
  14624. mg_cry_ctx_internal(phys_ctx,
  14625. "external_ssl_ctx callback returned error: %i",
  14626. callback_ret);
  14627. return 0;
  14628. } else if (callback_ret > 0) {
  14629. /* Callback exists and returns >0: Initializing complete,
  14630. * civetweb should not modify the SSL context. */
  14631. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14632. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14633. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14634. return 0;
  14635. }
  14636. return 1;
  14637. }
  14638. /* If the callback does not exist or return 0, civetweb must initialize
  14639. * the SSL context. Handle "domain" callback next. */
  14640. /* Check for external domain SSL_CTX callback. */
  14641. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14642. ? 0
  14643. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14644. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14645. &ssl_ctx,
  14646. phys_ctx->user_data));
  14647. if (callback_ret < 0) {
  14648. /* Callback < 0: Error. Abort init. */
  14649. mg_cry_ctx_internal(
  14650. phys_ctx,
  14651. "external_ssl_ctx_domain callback returned error: %i",
  14652. callback_ret);
  14653. return 0;
  14654. } else if (callback_ret > 0) {
  14655. /* Callback > 0: Consider init done. */
  14656. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14657. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14658. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14659. return 0;
  14660. }
  14661. return 1;
  14662. }
  14663. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14664. * 0, CivetWeb should continue initializing SSL */
  14665. /* If PEM file is not specified and the init_ssl callbacks
  14666. * are not specified, setup will fail. */
  14667. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14668. && (phys_ctx->callbacks.init_ssl == NULL)
  14669. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14670. /* No certificate and no init_ssl callbacks:
  14671. * Essential data to set up TLS is missing.
  14672. */
  14673. mg_cry_ctx_internal(phys_ctx,
  14674. "Initializing SSL failed: -%s is not set",
  14675. config_options[SSL_CERTIFICATE].name);
  14676. return 0;
  14677. }
  14678. /* If a certificate chain is configured, use it. */
  14679. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14680. if (chain == NULL) {
  14681. /* Default: certificate chain in PEM file */
  14682. chain = pem;
  14683. }
  14684. if ((chain != NULL) && (*chain == 0)) {
  14685. /* If the chain is an empty string, don't use it. */
  14686. chain = NULL;
  14687. }
  14688. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14689. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14690. return 0;
  14691. }
  14692. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14693. }
  14694. static void
  14695. uninitialize_ssl(void)
  14696. {
  14697. #if defined(OPENSSL_API_1_1)
  14698. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14699. /* Shutdown according to
  14700. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14701. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14702. */
  14703. CONF_modules_unload(1);
  14704. #else
  14705. int i;
  14706. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14707. /* Shutdown according to
  14708. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14709. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14710. */
  14711. CRYPTO_set_locking_callback(NULL);
  14712. CRYPTO_set_id_callback(NULL);
  14713. ENGINE_cleanup();
  14714. CONF_modules_unload(1);
  14715. ERR_free_strings();
  14716. EVP_cleanup();
  14717. CRYPTO_cleanup_all_ex_data();
  14718. OPENSSL_REMOVE_THREAD_STATE();
  14719. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14720. pthread_mutex_destroy(&ssl_mutexes[i]);
  14721. }
  14722. mg_free(ssl_mutexes);
  14723. ssl_mutexes = NULL;
  14724. #endif /* OPENSSL_API_1_1 */
  14725. }
  14726. }
  14727. #endif /* !NO_SSL */
  14728. #if !defined(NO_FILESYSTEMS)
  14729. static int
  14730. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14731. {
  14732. if (phys_ctx) {
  14733. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14734. const char *path;
  14735. struct mg_connection fc;
  14736. if (!dom_ctx) {
  14737. dom_ctx = &(phys_ctx->dd);
  14738. }
  14739. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14740. if ((path != NULL)
  14741. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14742. mg_cry_ctx_internal(phys_ctx,
  14743. "Cannot open %s: %s",
  14744. path,
  14745. strerror(ERRNO));
  14746. return 0;
  14747. }
  14748. return 1;
  14749. }
  14750. return 0;
  14751. }
  14752. #endif /* NO_FILESYSTEMS */
  14753. static int
  14754. set_acl_option(struct mg_context *phys_ctx)
  14755. {
  14756. union usa sa;
  14757. memset(&sa, 0, sizeof(sa));
  14758. #if defined(USE_IPV6)
  14759. sa.sin6.sin6_family = AF_INET6;
  14760. #else
  14761. sa.sin.sin_family = AF_INET;
  14762. #endif
  14763. return check_acl(phys_ctx, &sa) != -1;
  14764. }
  14765. static void
  14766. reset_per_request_attributes(struct mg_connection *conn)
  14767. {
  14768. if (!conn) {
  14769. return;
  14770. }
  14771. conn->num_bytes_sent = conn->consumed_content = 0;
  14772. conn->path_info = NULL;
  14773. conn->status_code = -1;
  14774. conn->content_len = -1;
  14775. conn->is_chunked = 0;
  14776. conn->must_close = 0;
  14777. conn->request_len = 0;
  14778. conn->request_state = 0;
  14779. conn->throttle = 0;
  14780. conn->accept_gzip = 0;
  14781. conn->response_info.content_length = conn->request_info.content_length = -1;
  14782. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14783. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14784. conn->response_info.status_text = NULL;
  14785. conn->response_info.status_code = 0;
  14786. conn->request_info.remote_user = NULL;
  14787. conn->request_info.request_method = NULL;
  14788. conn->request_info.request_uri = NULL;
  14789. conn->request_info.local_uri = NULL;
  14790. #if defined(MG_LEGACY_INTERFACE)
  14791. /* Legacy before split into local_uri and request_uri */
  14792. conn->request_info.uri = NULL;
  14793. #endif
  14794. }
  14795. static int
  14796. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  14797. {
  14798. if ((so->lsa.sa.sa_family == AF_INET)
  14799. || (so->lsa.sa.sa_family == AF_INET6)) {
  14800. /* Only for TCP sockets */
  14801. if (setsockopt(so->sock,
  14802. IPPROTO_TCP,
  14803. TCP_NODELAY,
  14804. (SOCK_OPT_TYPE)&nodelay_on,
  14805. sizeof(nodelay_on))
  14806. != 0) {
  14807. /* Error */
  14808. return 1;
  14809. }
  14810. }
  14811. /* OK */
  14812. return 0;
  14813. }
  14814. #if !defined(__ZEPHYR__)
  14815. static void
  14816. close_socket_gracefully(struct mg_connection *conn)
  14817. {
  14818. #if defined(_WIN32)
  14819. char buf[MG_BUF_LEN];
  14820. int n;
  14821. #endif
  14822. struct linger linger;
  14823. int error_code = 0;
  14824. int linger_timeout = -2;
  14825. socklen_t opt_len = sizeof(error_code);
  14826. if (!conn) {
  14827. return;
  14828. }
  14829. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14830. * "Note that enabling a nonzero timeout on a nonblocking socket
  14831. * is not recommended.", so set it to blocking now */
  14832. set_blocking_mode(conn->client.sock);
  14833. /* Send FIN to the client */
  14834. shutdown(conn->client.sock, SHUTDOWN_WR);
  14835. #if defined(_WIN32)
  14836. /* Read and discard pending incoming data. If we do not do that and
  14837. * close
  14838. * the socket, the data in the send buffer may be discarded. This
  14839. * behaviour is seen on Windows, when client keeps sending data
  14840. * when server decides to close the connection; then when client
  14841. * does recv() it gets no data back. */
  14842. do {
  14843. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14844. } while (n > 0);
  14845. #endif
  14846. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14847. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14848. }
  14849. /* Set linger option according to configuration */
  14850. if (linger_timeout >= 0) {
  14851. /* Set linger option to avoid socket hanging out after close. This
  14852. * prevent ephemeral port exhaust problem under high QPS. */
  14853. linger.l_onoff = 1;
  14854. #if defined(_MSC_VER)
  14855. #pragma warning(push)
  14856. #pragma warning(disable : 4244)
  14857. #endif
  14858. #if defined(GCC_DIAGNOSTIC)
  14859. #pragma GCC diagnostic push
  14860. #pragma GCC diagnostic ignored "-Wconversion"
  14861. #endif
  14862. /* Data type of linger structure elements may differ,
  14863. * so we don't know what cast we need here.
  14864. * Disable type conversion warnings. */
  14865. linger.l_linger = (linger_timeout + 999) / 1000;
  14866. #if defined(GCC_DIAGNOSTIC)
  14867. #pragma GCC diagnostic pop
  14868. #endif
  14869. #if defined(_MSC_VER)
  14870. #pragma warning(pop)
  14871. #endif
  14872. } else {
  14873. linger.l_onoff = 0;
  14874. linger.l_linger = 0;
  14875. }
  14876. if (linger_timeout < -1) {
  14877. /* Default: don't configure any linger */
  14878. } else if (getsockopt(conn->client.sock,
  14879. SOL_SOCKET,
  14880. SO_ERROR,
  14881. #if defined(_WIN32) /* WinSock uses different data type here */
  14882. (char *)&error_code,
  14883. #else
  14884. &error_code,
  14885. #endif
  14886. &opt_len)
  14887. != 0) {
  14888. /* Cannot determine if socket is already closed. This should
  14889. * not occur and never did in a test. Log an error message
  14890. * and continue. */
  14891. mg_cry_internal(conn,
  14892. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14893. __func__,
  14894. strerror(ERRNO));
  14895. #if defined(_WIN32)
  14896. } else if (error_code == WSAECONNRESET) {
  14897. #else
  14898. } else if (error_code == ECONNRESET) {
  14899. #endif
  14900. /* Socket already closed by client/peer, close socket without linger
  14901. */
  14902. } else {
  14903. /* Set linger timeout */
  14904. if (setsockopt(conn->client.sock,
  14905. SOL_SOCKET,
  14906. SO_LINGER,
  14907. (char *)&linger,
  14908. sizeof(linger))
  14909. != 0) {
  14910. mg_cry_internal(
  14911. conn,
  14912. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14913. __func__,
  14914. linger.l_onoff,
  14915. linger.l_linger,
  14916. strerror(ERRNO));
  14917. }
  14918. }
  14919. /* Now we know that our FIN is ACK-ed, safe to close */
  14920. closesocket(conn->client.sock);
  14921. conn->client.sock = INVALID_SOCKET;
  14922. }
  14923. #endif
  14924. static void
  14925. close_connection(struct mg_connection *conn)
  14926. {
  14927. #if defined(USE_SERVER_STATS)
  14928. conn->conn_state = 6; /* to close */
  14929. #endif
  14930. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14931. if (conn->lua_websocket_state) {
  14932. lua_websocket_close(conn, conn->lua_websocket_state);
  14933. conn->lua_websocket_state = NULL;
  14934. }
  14935. #endif
  14936. mg_lock_connection(conn);
  14937. /* Set close flag, so keep-alive loops will stop */
  14938. conn->must_close = 1;
  14939. /* call the connection_close callback if assigned */
  14940. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14941. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14942. conn->phys_ctx->callbacks.connection_close(conn);
  14943. }
  14944. }
  14945. /* Reset user data, after close callback is called.
  14946. * Do not reuse it. If the user needs a destructor,
  14947. * it must be done in the connection_close callback. */
  14948. mg_set_user_connection_data(conn, NULL);
  14949. #if defined(USE_SERVER_STATS)
  14950. conn->conn_state = 7; /* closing */
  14951. #endif
  14952. #if !defined(NO_SSL)
  14953. if (conn->ssl != NULL) {
  14954. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14955. */
  14956. SSL_shutdown(conn->ssl);
  14957. SSL_free(conn->ssl);
  14958. OPENSSL_REMOVE_THREAD_STATE();
  14959. conn->ssl = NULL;
  14960. }
  14961. #endif
  14962. if (conn->client.sock != INVALID_SOCKET) {
  14963. #if defined(__ZEPHYR__)
  14964. closesocket(conn->client.sock);
  14965. #else
  14966. close_socket_gracefully(conn);
  14967. #endif
  14968. conn->client.sock = INVALID_SOCKET;
  14969. }
  14970. mg_unlock_connection(conn);
  14971. #if defined(USE_SERVER_STATS)
  14972. conn->conn_state = 8; /* closed */
  14973. #endif
  14974. }
  14975. void
  14976. mg_close_connection(struct mg_connection *conn)
  14977. {
  14978. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14979. return;
  14980. }
  14981. #if defined(USE_WEBSOCKET)
  14982. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14983. if (conn->in_websocket_handling) {
  14984. /* Set close flag, so the server thread can exit. */
  14985. conn->must_close = 1;
  14986. return;
  14987. }
  14988. }
  14989. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14990. unsigned int i;
  14991. /* client context: loops must end */
  14992. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14993. conn->must_close = 1;
  14994. /* We need to get the client thread out of the select/recv call
  14995. * here. */
  14996. /* Since we use a sleep quantum of some seconds to check for recv
  14997. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14998. /* join worker thread */
  14999. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15000. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15001. }
  15002. }
  15003. #endif /* defined(USE_WEBSOCKET) */
  15004. close_connection(conn);
  15005. #if !defined(NO_SSL)
  15006. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15007. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15008. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15009. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15010. }
  15011. #endif
  15012. #if defined(USE_WEBSOCKET)
  15013. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15014. mg_free(conn->phys_ctx->worker_threadids);
  15015. (void)pthread_mutex_destroy(&conn->mutex);
  15016. mg_free(conn);
  15017. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15018. (void)pthread_mutex_destroy(&conn->mutex);
  15019. mg_free(conn);
  15020. }
  15021. #else
  15022. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15023. (void)pthread_mutex_destroy(&conn->mutex);
  15024. mg_free(conn);
  15025. }
  15026. #endif /* defined(USE_WEBSOCKET) */
  15027. }
  15028. static struct mg_connection *
  15029. mg_connect_client_impl(const struct mg_client_options *client_options,
  15030. int use_ssl,
  15031. char *ebuf,
  15032. size_t ebuf_len)
  15033. {
  15034. struct mg_connection *conn = NULL;
  15035. SOCKET sock;
  15036. union usa sa;
  15037. struct sockaddr *psa;
  15038. socklen_t len;
  15039. unsigned max_req_size =
  15040. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15041. /* Size of structures, aligned to 8 bytes */
  15042. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15043. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15044. conn =
  15045. (struct mg_connection *)mg_calloc(1,
  15046. conn_size + ctx_size + max_req_size);
  15047. if (conn == NULL) {
  15048. mg_snprintf(NULL,
  15049. NULL, /* No truncation check for ebuf */
  15050. ebuf,
  15051. ebuf_len,
  15052. "calloc(): %s",
  15053. strerror(ERRNO));
  15054. return NULL;
  15055. }
  15056. #if defined(GCC_DIAGNOSTIC)
  15057. #pragma GCC diagnostic push
  15058. #pragma GCC diagnostic ignored "-Wcast-align"
  15059. #endif /* defined(GCC_DIAGNOSTIC) */
  15060. /* conn_size is aligned to 8 bytes */
  15061. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15062. #if defined(GCC_DIAGNOSTIC)
  15063. #pragma GCC diagnostic pop
  15064. #endif /* defined(GCC_DIAGNOSTIC) */
  15065. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15066. conn->buf_size = (int)max_req_size;
  15067. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15068. conn->dom_ctx = &(conn->phys_ctx->dd);
  15069. if (!connect_socket(conn->phys_ctx,
  15070. client_options->host,
  15071. client_options->port,
  15072. use_ssl,
  15073. ebuf,
  15074. ebuf_len,
  15075. &sock,
  15076. &sa)) {
  15077. /* ebuf is set by connect_socket,
  15078. * free all memory and return NULL; */
  15079. mg_free(conn);
  15080. return NULL;
  15081. }
  15082. #if !defined(NO_SSL)
  15083. #if defined(OPENSSL_API_1_1)
  15084. if (use_ssl
  15085. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15086. == NULL) {
  15087. mg_snprintf(NULL,
  15088. NULL, /* No truncation check for ebuf */
  15089. ebuf,
  15090. ebuf_len,
  15091. "SSL_CTX_new error: %s",
  15092. ssl_error());
  15093. closesocket(sock);
  15094. mg_free(conn);
  15095. return NULL;
  15096. }
  15097. #else
  15098. if (use_ssl
  15099. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15100. == NULL) {
  15101. mg_snprintf(NULL,
  15102. NULL, /* No truncation check for ebuf */
  15103. ebuf,
  15104. ebuf_len,
  15105. "SSL_CTX_new error: %s",
  15106. ssl_error());
  15107. closesocket(sock);
  15108. mg_free(conn);
  15109. return NULL;
  15110. }
  15111. #endif /* OPENSSL_API_1_1 */
  15112. #endif /* NO_SSL */
  15113. #if defined(USE_IPV6)
  15114. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15115. : sizeof(conn->client.rsa.sin6);
  15116. psa = (sa.sa.sa_family == AF_INET)
  15117. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15118. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15119. #else
  15120. len = sizeof(conn->client.rsa.sin);
  15121. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15122. #endif
  15123. conn->client.sock = sock;
  15124. conn->client.lsa = sa;
  15125. if (getsockname(sock, psa, &len) != 0) {
  15126. mg_cry_internal(conn,
  15127. "%s: getsockname() failed: %s",
  15128. __func__,
  15129. strerror(ERRNO));
  15130. }
  15131. conn->client.is_ssl = use_ssl ? 1 : 0;
  15132. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15133. mg_snprintf(NULL,
  15134. NULL, /* No truncation check for ebuf */
  15135. ebuf,
  15136. ebuf_len,
  15137. "Can not create mutex");
  15138. #if !defined(NO_SSL)
  15139. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15140. #endif
  15141. closesocket(sock);
  15142. mg_free(conn);
  15143. return NULL;
  15144. }
  15145. #if !defined(NO_SSL)
  15146. if (use_ssl) {
  15147. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15148. * SSL_CTX_set_verify call is needed to switch off server
  15149. * certificate checking, which is off by default in OpenSSL and
  15150. * on in yaSSL. */
  15151. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15152. * SSL_VERIFY_PEER, verify_ssl_server); */
  15153. if (client_options->client_cert) {
  15154. if (!ssl_use_pem_file(conn->phys_ctx,
  15155. conn->dom_ctx,
  15156. client_options->client_cert,
  15157. NULL)) {
  15158. mg_snprintf(NULL,
  15159. NULL, /* No truncation check for ebuf */
  15160. ebuf,
  15161. ebuf_len,
  15162. "Can not use SSL client certificate");
  15163. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15164. closesocket(sock);
  15165. mg_free(conn);
  15166. return NULL;
  15167. }
  15168. }
  15169. if (client_options->server_cert) {
  15170. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15171. client_options->server_cert,
  15172. NULL)
  15173. != 1) {
  15174. mg_cry_internal(conn,
  15175. "SSL_CTX_load_verify_locations error: %s ",
  15176. ssl_error());
  15177. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15178. closesocket(sock);
  15179. mg_free(conn);
  15180. return NULL;
  15181. }
  15182. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15183. } else {
  15184. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15185. }
  15186. if (!sslize(conn, SSL_connect, client_options)) {
  15187. mg_snprintf(NULL,
  15188. NULL, /* No truncation check for ebuf */
  15189. ebuf,
  15190. ebuf_len,
  15191. "SSL connection error");
  15192. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15193. closesocket(sock);
  15194. mg_free(conn);
  15195. return NULL;
  15196. }
  15197. }
  15198. #endif
  15199. return conn;
  15200. }
  15201. CIVETWEB_API struct mg_connection *
  15202. mg_connect_client_secure(const struct mg_client_options *client_options,
  15203. char *error_buffer,
  15204. size_t error_buffer_size)
  15205. {
  15206. return mg_connect_client_impl(client_options,
  15207. 1,
  15208. error_buffer,
  15209. error_buffer_size);
  15210. }
  15211. struct mg_connection *
  15212. mg_connect_client(const char *host,
  15213. int port,
  15214. int use_ssl,
  15215. char *error_buffer,
  15216. size_t error_buffer_size)
  15217. {
  15218. struct mg_client_options opts;
  15219. memset(&opts, 0, sizeof(opts));
  15220. opts.host = host;
  15221. opts.port = port;
  15222. return mg_connect_client_impl(&opts,
  15223. use_ssl,
  15224. error_buffer,
  15225. error_buffer_size);
  15226. }
  15227. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15228. struct mg_connection *
  15229. mg_connect_client2(const char *host,
  15230. const char *protocol,
  15231. int port,
  15232. const char *path,
  15233. struct mg_init_data *init,
  15234. struct mg_error_data *error)
  15235. {
  15236. int is_ssl, is_ws;
  15237. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15238. if (error != NULL) {
  15239. error->code = 0;
  15240. if (error->text_buffer_size > 0) {
  15241. *error->text = 0;
  15242. }
  15243. }
  15244. if ((host == NULL) || (protocol == NULL)) {
  15245. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15246. mg_snprintf(NULL,
  15247. NULL, /* No truncation check for error buffers */
  15248. error->text,
  15249. error->text_buffer_size,
  15250. "%s",
  15251. "Invalid parameters");
  15252. }
  15253. return NULL;
  15254. }
  15255. /* check all known protocolls */
  15256. if (!mg_strcasecmp(protocol, "http")) {
  15257. is_ssl = 0;
  15258. is_ws = 0;
  15259. } else if (!mg_strcasecmp(protocol, "https")) {
  15260. is_ssl = 1;
  15261. is_ws = 0;
  15262. #if defined(USE_WEBSOCKET)
  15263. } else if (!mg_strcasecmp(protocol, "ws")) {
  15264. is_ssl = 0;
  15265. is_ws = 1;
  15266. } else if (!mg_strcasecmp(protocol, "wss")) {
  15267. is_ssl = 1;
  15268. is_ws = 1;
  15269. #endif
  15270. } else {
  15271. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15272. mg_snprintf(NULL,
  15273. NULL, /* No truncation check for error buffers */
  15274. error->text,
  15275. error->text_buffer_size,
  15276. "Protocol %s not supported",
  15277. protocol);
  15278. }
  15279. return NULL;
  15280. }
  15281. /* TODO: The current implementation here just calls the old
  15282. * implementations, without using any new options. This is just a first
  15283. * step to test the new interfaces. */
  15284. #if defined(USE_WEBSOCKET)
  15285. if (is_ws) {
  15286. /* TODO: implement all options */
  15287. return mg_connect_websocket_client(
  15288. host,
  15289. port,
  15290. is_ssl,
  15291. ((error != NULL) ? error->text : NULL),
  15292. ((error != NULL) ? error->text_buffer_size : 0),
  15293. (path ? path : ""),
  15294. NULL /* TODO: origin */,
  15295. experimental_websocket_client_data_wrapper,
  15296. experimental_websocket_client_close_wrapper,
  15297. (void *)init->callbacks);
  15298. }
  15299. #endif
  15300. /* TODO: all additional options */
  15301. struct mg_client_options opts;
  15302. memset(&opts, 0, sizeof(opts));
  15303. opts.host = host;
  15304. opts.port = port;
  15305. return mg_connect_client_impl(&opts,
  15306. is_ssl,
  15307. ((error != NULL) ? error->text : NULL),
  15308. ((error != NULL) ? error->text_buffer_size
  15309. : 0));
  15310. }
  15311. #endif
  15312. static const struct {
  15313. const char *proto;
  15314. size_t proto_len;
  15315. unsigned default_port;
  15316. } abs_uri_protocols[] = {{"http://", 7, 80},
  15317. {"https://", 8, 443},
  15318. {"ws://", 5, 80},
  15319. {"wss://", 6, 443},
  15320. {NULL, 0, 0}};
  15321. /* Check if the uri is valid.
  15322. * return 0 for invalid uri,
  15323. * return 1 for *,
  15324. * return 2 for relative uri,
  15325. * return 3 for absolute uri without port,
  15326. * return 4 for absolute uri with port */
  15327. static int
  15328. get_uri_type(const char *uri)
  15329. {
  15330. int i;
  15331. const char *hostend, *portbegin;
  15332. char *portend;
  15333. unsigned long port;
  15334. /* According to the HTTP standard
  15335. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15336. * URI can be an asterisk (*) or should start with slash (relative uri),
  15337. * or it should start with the protocol (absolute uri). */
  15338. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15339. /* asterisk */
  15340. return 1;
  15341. }
  15342. /* Valid URIs according to RFC 3986
  15343. * (https://www.ietf.org/rfc/rfc3986.txt)
  15344. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15345. * and unreserved characters A-Z a-z 0-9 and -._~
  15346. * and % encoded symbols.
  15347. */
  15348. for (i = 0; uri[i] != 0; i++) {
  15349. if (uri[i] < 33) {
  15350. /* control characters and spaces are invalid */
  15351. return 0;
  15352. }
  15353. /* Allow everything else here (See #894) */
  15354. }
  15355. /* A relative uri starts with a / character */
  15356. if (uri[0] == '/') {
  15357. /* relative uri */
  15358. return 2;
  15359. }
  15360. /* It could be an absolute uri: */
  15361. /* This function only checks if the uri is valid, not if it is
  15362. * addressing the current server. So civetweb can also be used
  15363. * as a proxy server. */
  15364. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15365. if (mg_strncasecmp(uri,
  15366. abs_uri_protocols[i].proto,
  15367. abs_uri_protocols[i].proto_len)
  15368. == 0) {
  15369. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15370. if (!hostend) {
  15371. return 0;
  15372. }
  15373. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15374. if (!portbegin) {
  15375. return 3;
  15376. }
  15377. port = strtoul(portbegin + 1, &portend, 10);
  15378. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15379. return 0;
  15380. }
  15381. return 4;
  15382. }
  15383. }
  15384. return 0;
  15385. }
  15386. /* Return NULL or the relative uri at the current server */
  15387. static const char *
  15388. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15389. {
  15390. const char *server_domain;
  15391. size_t server_domain_len;
  15392. size_t request_domain_len = 0;
  15393. unsigned long port = 0;
  15394. int i, auth_domain_check_enabled;
  15395. const char *hostbegin = NULL;
  15396. const char *hostend = NULL;
  15397. const char *portbegin;
  15398. char *portend;
  15399. auth_domain_check_enabled =
  15400. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15401. /* DNS is case insensitive, so use case insensitive string compare here
  15402. */
  15403. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15404. if (mg_strncasecmp(uri,
  15405. abs_uri_protocols[i].proto,
  15406. abs_uri_protocols[i].proto_len)
  15407. == 0) {
  15408. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15409. hostend = strchr(hostbegin, '/');
  15410. if (!hostend) {
  15411. return 0;
  15412. }
  15413. portbegin = strchr(hostbegin, ':');
  15414. if ((!portbegin) || (portbegin > hostend)) {
  15415. port = abs_uri_protocols[i].default_port;
  15416. request_domain_len = (size_t)(hostend - hostbegin);
  15417. } else {
  15418. port = strtoul(portbegin + 1, &portend, 10);
  15419. if ((portend != hostend) || (port <= 0)
  15420. || !is_valid_port(port)) {
  15421. return 0;
  15422. }
  15423. request_domain_len = (size_t)(portbegin - hostbegin);
  15424. }
  15425. /* protocol found, port set */
  15426. break;
  15427. }
  15428. }
  15429. if (!port) {
  15430. /* port remains 0 if the protocol is not found */
  15431. return 0;
  15432. }
  15433. /* Check if the request is directed to a different server. */
  15434. /* First check if the port is the same. */
  15435. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15436. /* Request is directed to a different port */
  15437. return 0;
  15438. }
  15439. /* Finally check if the server corresponds to the authentication
  15440. * domain of the server (the server domain).
  15441. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15442. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15443. * but do not allow substrings (like
  15444. * http://notmydomain.com/path/file.ext
  15445. * or http://mydomain.com.fake/path/file.ext).
  15446. */
  15447. if (auth_domain_check_enabled) {
  15448. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15449. server_domain_len = strlen(server_domain);
  15450. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15451. return 0;
  15452. }
  15453. if ((request_domain_len == server_domain_len)
  15454. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15455. /* Request is directed to this server - full name match. */
  15456. } else {
  15457. if (request_domain_len < (server_domain_len + 2)) {
  15458. /* Request is directed to another server: The server name
  15459. * is longer than the request name.
  15460. * Drop this case here to avoid overflows in the
  15461. * following checks. */
  15462. return 0;
  15463. }
  15464. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15465. /* Request is directed to another server: It could be a
  15466. * substring
  15467. * like notmyserver.com */
  15468. return 0;
  15469. }
  15470. if (0
  15471. != memcmp(server_domain,
  15472. hostbegin + request_domain_len - server_domain_len,
  15473. server_domain_len)) {
  15474. /* Request is directed to another server:
  15475. * The server name is different. */
  15476. return 0;
  15477. }
  15478. }
  15479. }
  15480. return hostend;
  15481. }
  15482. static int
  15483. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15484. {
  15485. if (ebuf_len > 0) {
  15486. ebuf[0] = '\0';
  15487. }
  15488. *err = 0;
  15489. reset_per_request_attributes(conn);
  15490. if (!conn) {
  15491. mg_snprintf(conn,
  15492. NULL, /* No truncation check for ebuf */
  15493. ebuf,
  15494. ebuf_len,
  15495. "%s",
  15496. "Internal error");
  15497. *err = 500;
  15498. return 0;
  15499. }
  15500. /* Set the time the request was received. This value should be used for
  15501. * timeouts. */
  15502. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15503. conn->request_len =
  15504. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15505. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15506. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15507. mg_snprintf(conn,
  15508. NULL, /* No truncation check for ebuf */
  15509. ebuf,
  15510. ebuf_len,
  15511. "%s",
  15512. "Invalid message size");
  15513. *err = 500;
  15514. return 0;
  15515. }
  15516. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15517. mg_snprintf(conn,
  15518. NULL, /* No truncation check for ebuf */
  15519. ebuf,
  15520. ebuf_len,
  15521. "%s",
  15522. "Message too large");
  15523. *err = 413;
  15524. return 0;
  15525. }
  15526. if (conn->request_len <= 0) {
  15527. if (conn->data_len > 0) {
  15528. mg_snprintf(conn,
  15529. NULL, /* No truncation check for ebuf */
  15530. ebuf,
  15531. ebuf_len,
  15532. "%s",
  15533. "Malformed message");
  15534. *err = 400;
  15535. } else {
  15536. /* Server did not recv anything -> just close the connection */
  15537. conn->must_close = 1;
  15538. mg_snprintf(conn,
  15539. NULL, /* No truncation check for ebuf */
  15540. ebuf,
  15541. ebuf_len,
  15542. "%s",
  15543. "No data received");
  15544. *err = 0;
  15545. }
  15546. return 0;
  15547. }
  15548. return 1;
  15549. }
  15550. static int
  15551. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15552. {
  15553. const char *cl;
  15554. conn->connection_type =
  15555. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15556. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15557. return 0;
  15558. }
  15559. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15560. <= 0) {
  15561. mg_snprintf(conn,
  15562. NULL, /* No truncation check for ebuf */
  15563. ebuf,
  15564. ebuf_len,
  15565. "%s",
  15566. "Bad request");
  15567. *err = 400;
  15568. return 0;
  15569. }
  15570. /* Message is a valid request */
  15571. if (!switch_domain_context(conn)) {
  15572. mg_snprintf(conn,
  15573. NULL, /* No truncation check for ebuf */
  15574. ebuf,
  15575. ebuf_len,
  15576. "%s",
  15577. "Bad request: Host mismatch");
  15578. *err = 400;
  15579. return 0;
  15580. }
  15581. if (((cl = get_header(conn->request_info.http_headers,
  15582. conn->request_info.num_headers,
  15583. "Transfer-Encoding"))
  15584. != NULL)
  15585. && mg_strcasecmp(cl, "identity")) {
  15586. if (mg_strcasecmp(cl, "chunked")) {
  15587. mg_snprintf(conn,
  15588. NULL, /* No truncation check for ebuf */
  15589. ebuf,
  15590. ebuf_len,
  15591. "%s",
  15592. "Bad request");
  15593. *err = 400;
  15594. return 0;
  15595. }
  15596. conn->is_chunked = 1;
  15597. conn->content_len = 0; /* not yet read */
  15598. } else if ((cl = get_header(conn->request_info.http_headers,
  15599. conn->request_info.num_headers,
  15600. "Content-Length"))
  15601. != NULL) {
  15602. /* Request has content length set */
  15603. char *endptr = NULL;
  15604. conn->content_len = strtoll(cl, &endptr, 10);
  15605. if ((endptr == cl) || (conn->content_len < 0)) {
  15606. mg_snprintf(conn,
  15607. NULL, /* No truncation check for ebuf */
  15608. ebuf,
  15609. ebuf_len,
  15610. "%s",
  15611. "Bad request");
  15612. *err = 411;
  15613. return 0;
  15614. }
  15615. /* Publish the content length back to the request info. */
  15616. conn->request_info.content_length = conn->content_len;
  15617. } else {
  15618. /* There is no exception, see RFC7230. */
  15619. conn->content_len = 0;
  15620. }
  15621. return 1;
  15622. }
  15623. /* conn is assumed to be valid in this internal function */
  15624. static int
  15625. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15626. {
  15627. const char *cl;
  15628. conn->connection_type =
  15629. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15630. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15631. return 0;
  15632. }
  15633. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15634. <= 0) {
  15635. mg_snprintf(conn,
  15636. NULL, /* No truncation check for ebuf */
  15637. ebuf,
  15638. ebuf_len,
  15639. "%s",
  15640. "Bad response");
  15641. *err = 400;
  15642. return 0;
  15643. }
  15644. /* Message is a valid response */
  15645. if (((cl = get_header(conn->response_info.http_headers,
  15646. conn->response_info.num_headers,
  15647. "Transfer-Encoding"))
  15648. != NULL)
  15649. && mg_strcasecmp(cl, "identity")) {
  15650. if (mg_strcasecmp(cl, "chunked")) {
  15651. mg_snprintf(conn,
  15652. NULL, /* No truncation check for ebuf */
  15653. ebuf,
  15654. ebuf_len,
  15655. "%s",
  15656. "Bad request");
  15657. *err = 400;
  15658. return 0;
  15659. }
  15660. conn->is_chunked = 1;
  15661. conn->content_len = 0; /* not yet read */
  15662. } else if ((cl = get_header(conn->response_info.http_headers,
  15663. conn->response_info.num_headers,
  15664. "Content-Length"))
  15665. != NULL) {
  15666. char *endptr = NULL;
  15667. conn->content_len = strtoll(cl, &endptr, 10);
  15668. if ((endptr == cl) || (conn->content_len < 0)) {
  15669. mg_snprintf(conn,
  15670. NULL, /* No truncation check for ebuf */
  15671. ebuf,
  15672. ebuf_len,
  15673. "%s",
  15674. "Bad request");
  15675. *err = 411;
  15676. return 0;
  15677. }
  15678. /* Publish the content length back to the response info. */
  15679. conn->response_info.content_length = conn->content_len;
  15680. /* TODO: check if it is still used in response_info */
  15681. conn->request_info.content_length = conn->content_len;
  15682. /* TODO: we should also consider HEAD method */
  15683. if (conn->response_info.status_code == 304) {
  15684. conn->content_len = 0;
  15685. }
  15686. } else {
  15687. /* TODO: we should also consider HEAD method */
  15688. if (((conn->response_info.status_code >= 100)
  15689. && (conn->response_info.status_code <= 199))
  15690. || (conn->response_info.status_code == 204)
  15691. || (conn->response_info.status_code == 304)) {
  15692. conn->content_len = 0;
  15693. } else {
  15694. conn->content_len = -1; /* unknown content length */
  15695. }
  15696. }
  15697. return 1;
  15698. }
  15699. int
  15700. mg_get_response(struct mg_connection *conn,
  15701. char *ebuf,
  15702. size_t ebuf_len,
  15703. int timeout)
  15704. {
  15705. int err, ret;
  15706. char txt[32]; /* will not overflow */
  15707. char *save_timeout;
  15708. char *new_timeout;
  15709. if (ebuf_len > 0) {
  15710. ebuf[0] = '\0';
  15711. }
  15712. if (!conn) {
  15713. mg_snprintf(conn,
  15714. NULL, /* No truncation check for ebuf */
  15715. ebuf,
  15716. ebuf_len,
  15717. "%s",
  15718. "Parameter error");
  15719. return -1;
  15720. }
  15721. /* Reset the previous responses */
  15722. conn->data_len = 0;
  15723. /* Implementation of API function for HTTP clients */
  15724. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15725. if (timeout >= 0) {
  15726. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15727. new_timeout = txt;
  15728. } else {
  15729. new_timeout = NULL;
  15730. }
  15731. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15732. ret = get_response(conn, ebuf, ebuf_len, &err);
  15733. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15734. #if defined(MG_LEGACY_INTERFACE)
  15735. /* TODO: 1) uri is deprecated;
  15736. * 2) here, ri.uri is the http response code */
  15737. conn->request_info.uri = conn->request_info.request_uri;
  15738. #endif
  15739. conn->request_info.local_uri = conn->request_info.request_uri;
  15740. /* TODO (mid): Define proper return values - maybe return length?
  15741. * For the first test use <0 for error and >0 for OK */
  15742. return (ret == 0) ? -1 : +1;
  15743. }
  15744. struct mg_connection *
  15745. mg_download(const char *host,
  15746. int port,
  15747. int use_ssl,
  15748. char *ebuf,
  15749. size_t ebuf_len,
  15750. const char *fmt,
  15751. ...)
  15752. {
  15753. struct mg_connection *conn;
  15754. va_list ap;
  15755. int i;
  15756. int reqerr;
  15757. if (ebuf_len > 0) {
  15758. ebuf[0] = '\0';
  15759. }
  15760. va_start(ap, fmt);
  15761. /* open a connection */
  15762. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15763. if (conn != NULL) {
  15764. i = mg_vprintf(conn, fmt, ap);
  15765. if (i <= 0) {
  15766. mg_snprintf(conn,
  15767. NULL, /* No truncation check for ebuf */
  15768. ebuf,
  15769. ebuf_len,
  15770. "%s",
  15771. "Error sending request");
  15772. } else {
  15773. /* make sure the buffer is clear */
  15774. conn->data_len = 0;
  15775. get_response(conn, ebuf, ebuf_len, &reqerr);
  15776. #if defined(MG_LEGACY_INTERFACE)
  15777. /* TODO: 1) uri is deprecated;
  15778. * 2) here, ri.uri is the http response code */
  15779. conn->request_info.uri = conn->request_info.request_uri;
  15780. #endif
  15781. conn->request_info.local_uri = conn->request_info.request_uri;
  15782. }
  15783. }
  15784. /* if an error occurred, close the connection */
  15785. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15786. mg_close_connection(conn);
  15787. conn = NULL;
  15788. }
  15789. va_end(ap);
  15790. return conn;
  15791. }
  15792. struct websocket_client_thread_data {
  15793. struct mg_connection *conn;
  15794. mg_websocket_data_handler data_handler;
  15795. mg_websocket_close_handler close_handler;
  15796. void *callback_data;
  15797. };
  15798. #if defined(USE_WEBSOCKET)
  15799. #if defined(_WIN32)
  15800. static unsigned __stdcall websocket_client_thread(void *data)
  15801. #else
  15802. static void *
  15803. websocket_client_thread(void *data)
  15804. #endif
  15805. {
  15806. struct websocket_client_thread_data *cdata =
  15807. (struct websocket_client_thread_data *)data;
  15808. void *user_thread_ptr = NULL;
  15809. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  15810. struct sigaction sa;
  15811. /* Ignore SIGPIPE */
  15812. memset(&sa, 0, sizeof(sa));
  15813. sa.sa_handler = SIG_IGN;
  15814. sigaction(SIGPIPE, &sa, NULL);
  15815. #endif
  15816. mg_set_thread_name("ws-clnt");
  15817. if (cdata->conn->phys_ctx) {
  15818. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15819. /* 3 indicates a websocket client thread */
  15820. /* TODO: check if conn->phys_ctx can be set */
  15821. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15822. cdata->conn->phys_ctx, 3);
  15823. }
  15824. }
  15825. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15826. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15827. if (cdata->close_handler != NULL) {
  15828. cdata->close_handler(cdata->conn, cdata->callback_data);
  15829. }
  15830. /* The websocket_client context has only this thread. If it runs out,
  15831. set the stop_flag to 2 (= "stopped"). */
  15832. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15833. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15834. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15835. 3,
  15836. user_thread_ptr);
  15837. }
  15838. mg_free((void *)cdata);
  15839. #if defined(_WIN32)
  15840. return 0;
  15841. #else
  15842. return NULL;
  15843. #endif
  15844. }
  15845. #endif
  15846. static struct mg_connection *
  15847. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15848. int use_ssl,
  15849. char *error_buffer,
  15850. size_t error_buffer_size,
  15851. const char *path,
  15852. const char *origin,
  15853. const char *extensions,
  15854. mg_websocket_data_handler data_func,
  15855. mg_websocket_close_handler close_func,
  15856. void *user_data)
  15857. {
  15858. struct mg_connection *conn = NULL;
  15859. #if defined(USE_WEBSOCKET)
  15860. struct websocket_client_thread_data *thread_data;
  15861. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15862. const char *host = client_options->host;
  15863. int i;
  15864. #if defined(__clang__)
  15865. #pragma clang diagnostic push
  15866. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15867. #endif
  15868. /* Establish the client connection and request upgrade */
  15869. conn = mg_connect_client_impl(client_options,
  15870. use_ssl,
  15871. error_buffer,
  15872. error_buffer_size);
  15873. /* Connection object will be null if something goes wrong */
  15874. if (conn == NULL) {
  15875. /* error_buffer should be already filled ... */
  15876. if (!error_buffer[0]) {
  15877. /* ... if not add an error message */
  15878. mg_snprintf(conn,
  15879. NULL, /* No truncation check for ebuf */
  15880. error_buffer,
  15881. error_buffer_size,
  15882. "Unexpected error");
  15883. }
  15884. return NULL;
  15885. }
  15886. if (origin != NULL) {
  15887. if (extensions != NULL) {
  15888. i = mg_printf(conn,
  15889. "GET %s HTTP/1.1\r\n"
  15890. "Host: %s\r\n"
  15891. "Upgrade: websocket\r\n"
  15892. "Connection: Upgrade\r\n"
  15893. "Sec-WebSocket-Key: %s\r\n"
  15894. "Sec-WebSocket-Version: 13\r\n"
  15895. "Sec-WebSocket-Extensions: %s\r\n"
  15896. "Origin: %s\r\n"
  15897. "\r\n",
  15898. path,
  15899. host,
  15900. magic,
  15901. extensions,
  15902. origin);
  15903. } else {
  15904. i = mg_printf(conn,
  15905. "GET %s HTTP/1.1\r\n"
  15906. "Host: %s\r\n"
  15907. "Upgrade: websocket\r\n"
  15908. "Connection: Upgrade\r\n"
  15909. "Sec-WebSocket-Key: %s\r\n"
  15910. "Sec-WebSocket-Version: 13\r\n"
  15911. "Origin: %s\r\n"
  15912. "\r\n",
  15913. path,
  15914. host,
  15915. magic,
  15916. origin);
  15917. }
  15918. } else {
  15919. if (extensions != NULL) {
  15920. i = mg_printf(conn,
  15921. "GET %s HTTP/1.1\r\n"
  15922. "Host: %s\r\n"
  15923. "Upgrade: websocket\r\n"
  15924. "Connection: Upgrade\r\n"
  15925. "Sec-WebSocket-Key: %s\r\n"
  15926. "Sec-WebSocket-Version: 13\r\n"
  15927. "Sec-WebSocket-Extensions: %s\r\n"
  15928. "\r\n",
  15929. path,
  15930. host,
  15931. magic,
  15932. extensions);
  15933. } else {
  15934. i = mg_printf(conn,
  15935. "GET %s HTTP/1.1\r\n"
  15936. "Host: %s\r\n"
  15937. "Upgrade: websocket\r\n"
  15938. "Connection: Upgrade\r\n"
  15939. "Sec-WebSocket-Key: %s\r\n"
  15940. "Sec-WebSocket-Version: 13\r\n"
  15941. "\r\n",
  15942. path,
  15943. host,
  15944. magic);
  15945. }
  15946. }
  15947. if (i <= 0) {
  15948. mg_snprintf(conn,
  15949. NULL, /* No truncation check for ebuf */
  15950. error_buffer,
  15951. error_buffer_size,
  15952. "%s",
  15953. "Error sending request");
  15954. mg_close_connection(conn);
  15955. return NULL;
  15956. }
  15957. conn->data_len = 0;
  15958. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15959. mg_close_connection(conn);
  15960. return NULL;
  15961. }
  15962. conn->request_info.local_uri = conn->request_info.request_uri;
  15963. #if defined(__clang__)
  15964. #pragma clang diagnostic pop
  15965. #endif
  15966. if (conn->response_info.status_code != 101) {
  15967. /* We sent an "upgrade" request. For a correct websocket
  15968. * protocol handshake, we expect a "101 Continue" response.
  15969. * Otherwise it is a protocol violation. Maybe the HTTP
  15970. * Server does not know websockets. */
  15971. if (!*error_buffer) {
  15972. /* set an error, if not yet set */
  15973. mg_snprintf(conn,
  15974. NULL, /* No truncation check for ebuf */
  15975. error_buffer,
  15976. error_buffer_size,
  15977. "Unexpected server reply");
  15978. }
  15979. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15980. mg_close_connection(conn);
  15981. return NULL;
  15982. }
  15983. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15984. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15985. if (!thread_data) {
  15986. DEBUG_TRACE("%s\r\n", "Out of memory");
  15987. mg_close_connection(conn);
  15988. return NULL;
  15989. }
  15990. thread_data->conn = conn;
  15991. thread_data->data_handler = data_func;
  15992. thread_data->close_handler = close_func;
  15993. thread_data->callback_data = user_data;
  15994. conn->phys_ctx->worker_threadids =
  15995. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15996. if (!conn->phys_ctx->worker_threadids) {
  15997. DEBUG_TRACE("%s\r\n", "Out of memory");
  15998. mg_free(thread_data);
  15999. mg_close_connection(conn);
  16000. return NULL;
  16001. }
  16002. /* Now upgrade to ws/wss client context */
  16003. conn->phys_ctx->user_data = user_data;
  16004. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16005. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16006. /* Start a thread to read the websocket client connection
  16007. * This thread will automatically stop when mg_disconnect is
  16008. * called on the client connection */
  16009. if (mg_start_thread_with_id(websocket_client_thread,
  16010. thread_data,
  16011. conn->phys_ctx->worker_threadids)
  16012. != 0) {
  16013. conn->phys_ctx->cfg_worker_threads = 0;
  16014. mg_free(thread_data);
  16015. mg_close_connection(conn);
  16016. conn = NULL;
  16017. DEBUG_TRACE("%s",
  16018. "Websocket client connect thread could not be started\r\n");
  16019. }
  16020. #else
  16021. /* Appease "unused parameter" warnings */
  16022. (void)client_options;
  16023. (void)use_ssl;
  16024. (void)error_buffer;
  16025. (void)error_buffer_size;
  16026. (void)path;
  16027. (void)origin;
  16028. (void)user_data;
  16029. (void)data_func;
  16030. (void)close_func;
  16031. #endif
  16032. return conn;
  16033. }
  16034. struct mg_connection *
  16035. mg_connect_websocket_client(const char *host,
  16036. int port,
  16037. int use_ssl,
  16038. char *error_buffer,
  16039. size_t error_buffer_size,
  16040. const char *path,
  16041. const char *origin,
  16042. mg_websocket_data_handler data_func,
  16043. mg_websocket_close_handler close_func,
  16044. void *user_data)
  16045. {
  16046. struct mg_client_options client_options;
  16047. memset(&client_options, 0, sizeof(client_options));
  16048. client_options.host = host;
  16049. client_options.port = port;
  16050. return mg_connect_websocket_client_impl(&client_options,
  16051. use_ssl,
  16052. error_buffer,
  16053. error_buffer_size,
  16054. path,
  16055. origin,
  16056. NULL,
  16057. data_func,
  16058. close_func,
  16059. user_data);
  16060. }
  16061. struct mg_connection *
  16062. mg_connect_websocket_client_secure(
  16063. const struct mg_client_options *client_options,
  16064. char *error_buffer,
  16065. size_t error_buffer_size,
  16066. const char *path,
  16067. const char *origin,
  16068. mg_websocket_data_handler data_func,
  16069. mg_websocket_close_handler close_func,
  16070. void *user_data)
  16071. {
  16072. if (!client_options) {
  16073. return NULL;
  16074. }
  16075. return mg_connect_websocket_client_impl(client_options,
  16076. 1,
  16077. error_buffer,
  16078. error_buffer_size,
  16079. path,
  16080. origin,
  16081. NULL,
  16082. data_func,
  16083. close_func,
  16084. user_data);
  16085. }
  16086. struct mg_connection *
  16087. mg_connect_websocket_client_extensions(const char *host,
  16088. int port,
  16089. int use_ssl,
  16090. char *error_buffer,
  16091. size_t error_buffer_size,
  16092. const char *path,
  16093. const char *origin,
  16094. const char *extensions,
  16095. mg_websocket_data_handler data_func,
  16096. mg_websocket_close_handler close_func,
  16097. void *user_data)
  16098. {
  16099. struct mg_client_options client_options;
  16100. memset(&client_options, 0, sizeof(client_options));
  16101. client_options.host = host;
  16102. client_options.port = port;
  16103. return mg_connect_websocket_client_impl(&client_options,
  16104. use_ssl,
  16105. error_buffer,
  16106. error_buffer_size,
  16107. path,
  16108. origin,
  16109. extensions,
  16110. data_func,
  16111. close_func,
  16112. user_data);
  16113. }
  16114. struct mg_connection *
  16115. mg_connect_websocket_client_secure_extensions(
  16116. const struct mg_client_options *client_options,
  16117. char *error_buffer,
  16118. size_t error_buffer_size,
  16119. const char *path,
  16120. const char *origin,
  16121. const char *extensions,
  16122. mg_websocket_data_handler data_func,
  16123. mg_websocket_close_handler close_func,
  16124. void *user_data)
  16125. {
  16126. if (!client_options) {
  16127. return NULL;
  16128. }
  16129. return mg_connect_websocket_client_impl(client_options,
  16130. 1,
  16131. error_buffer,
  16132. error_buffer_size,
  16133. path,
  16134. origin,
  16135. extensions,
  16136. data_func,
  16137. close_func,
  16138. user_data);
  16139. }
  16140. /* Prepare connection data structure */
  16141. static void
  16142. init_connection(struct mg_connection *conn)
  16143. {
  16144. /* Is keep alive allowed by the server */
  16145. int keep_alive_enabled =
  16146. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16147. if (!keep_alive_enabled) {
  16148. conn->must_close = 1;
  16149. }
  16150. /* Important: on new connection, reset the receiving buffer. Credit
  16151. * goes to crule42. */
  16152. conn->data_len = 0;
  16153. conn->handled_requests = 0;
  16154. conn->connection_type = CONNECTION_TYPE_INVALID;
  16155. mg_set_user_connection_data(conn, NULL);
  16156. #if defined(USE_SERVER_STATS)
  16157. conn->conn_state = 2; /* init */
  16158. #endif
  16159. /* call the init_connection callback if assigned */
  16160. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16161. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16162. void *conn_data = NULL;
  16163. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16164. mg_set_user_connection_data(conn, conn_data);
  16165. }
  16166. }
  16167. }
  16168. /* Process a connection - may handle multiple requests
  16169. * using the same connection.
  16170. * Must be called with a valid connection (conn and
  16171. * conn->phys_ctx must be valid).
  16172. */
  16173. static void
  16174. process_new_connection(struct mg_connection *conn)
  16175. {
  16176. struct mg_request_info *ri = &conn->request_info;
  16177. int keep_alive, discard_len;
  16178. char ebuf[100];
  16179. const char *hostend;
  16180. int reqerr, uri_type;
  16181. #if defined(USE_SERVER_STATS)
  16182. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16183. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16184. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16185. #endif
  16186. DEBUG_TRACE("Start processing connection from %s",
  16187. conn->request_info.remote_addr);
  16188. /* Loop over multiple requests sent using the same connection
  16189. * (while "keep alive"). */
  16190. do {
  16191. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16192. conn->handled_requests + 1);
  16193. #if defined(USE_SERVER_STATS)
  16194. conn->conn_state = 3; /* ready */
  16195. #endif
  16196. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16197. /* The request sent by the client could not be understood by
  16198. * the server, or it was incomplete or a timeout. Send an
  16199. * error message and close the connection. */
  16200. if (reqerr > 0) {
  16201. DEBUG_ASSERT(ebuf[0] != '\0');
  16202. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16203. }
  16204. } else if (strcmp(ri->http_version, "1.0")
  16205. && strcmp(ri->http_version, "1.1")) {
  16206. /* HTTP/2 is not allowed here */
  16207. mg_snprintf(conn,
  16208. NULL, /* No truncation check for ebuf */
  16209. ebuf,
  16210. sizeof(ebuf),
  16211. "Bad HTTP version: [%s]",
  16212. ri->http_version);
  16213. mg_send_http_error(conn, 505, "%s", ebuf);
  16214. }
  16215. if (ebuf[0] == '\0') {
  16216. uri_type = get_uri_type(conn->request_info.request_uri);
  16217. switch (uri_type) {
  16218. case 1:
  16219. /* Asterisk */
  16220. conn->request_info.local_uri = 0;
  16221. /* TODO: Deal with '*'. */
  16222. break;
  16223. case 2:
  16224. /* relative uri */
  16225. conn->request_info.local_uri = conn->request_info.request_uri;
  16226. break;
  16227. case 3:
  16228. case 4:
  16229. /* absolute uri (with/without port) */
  16230. hostend = get_rel_url_at_current_server(
  16231. conn->request_info.request_uri, conn);
  16232. if (hostend) {
  16233. conn->request_info.local_uri = hostend;
  16234. } else {
  16235. conn->request_info.local_uri = NULL;
  16236. }
  16237. break;
  16238. default:
  16239. mg_snprintf(conn,
  16240. NULL, /* No truncation check for ebuf */
  16241. ebuf,
  16242. sizeof(ebuf),
  16243. "Invalid URI");
  16244. mg_send_http_error(conn, 400, "%s", ebuf);
  16245. conn->request_info.local_uri = NULL;
  16246. break;
  16247. }
  16248. #if defined(MG_LEGACY_INTERFACE)
  16249. /* Legacy before split into local_uri and request_uri */
  16250. conn->request_info.uri = conn->request_info.local_uri;
  16251. #endif
  16252. }
  16253. if (ebuf[0] != '\0') {
  16254. conn->protocol_type = -1;
  16255. } else {
  16256. /* HTTP/1 allows protocol upgrade */
  16257. conn->protocol_type = should_switch_to_protocol(conn);
  16258. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16259. /* This will occur, if a HTTP/1.1 request should be upgraded
  16260. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16261. * Since most (all?) major browsers only support HTTP/2 using
  16262. * ALPN, this is hard to test and very low priority.
  16263. * Deactivate it (at least for now).
  16264. */
  16265. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16266. }
  16267. }
  16268. DEBUG_TRACE("http: %s, error: %s",
  16269. (ri->http_version ? ri->http_version : "none"),
  16270. (ebuf[0] ? ebuf : "none"));
  16271. if (ebuf[0] == '\0') {
  16272. if (conn->request_info.local_uri) {
  16273. /* handle request to local server */
  16274. #if defined(USE_SERVER_STATS)
  16275. conn->conn_state = 4; /* processing */
  16276. #endif
  16277. handle_request(conn);
  16278. #if defined(USE_SERVER_STATS)
  16279. conn->conn_state = 5; /* processed */
  16280. mg_atomic_add64(&(conn->phys_ctx->total_data_read),
  16281. conn->consumed_content);
  16282. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  16283. conn->num_bytes_sent);
  16284. #endif
  16285. DEBUG_TRACE("%s", "handle_request done");
  16286. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16287. conn->phys_ctx->callbacks.end_request(conn,
  16288. conn->status_code);
  16289. DEBUG_TRACE("%s", "end_request callback done");
  16290. }
  16291. log_access(conn);
  16292. } else {
  16293. /* TODO: handle non-local request (PROXY) */
  16294. conn->must_close = 1;
  16295. }
  16296. } else {
  16297. conn->must_close = 1;
  16298. }
  16299. /* Response complete. Free header buffer */
  16300. free_buffered_response_header_list(conn);
  16301. if (ri->remote_user != NULL) {
  16302. mg_free((void *)ri->remote_user);
  16303. /* Important! When having connections with and without auth
  16304. * would cause double free and then crash */
  16305. ri->remote_user = NULL;
  16306. }
  16307. /* NOTE(lsm): order is important here. should_keep_alive() call
  16308. * is using parsed request, which will be invalid after
  16309. * memmove's below.
  16310. * Therefore, memorize should_keep_alive() result now for later
  16311. * use in loop exit condition. */
  16312. /* Enable it only if this request is completely discardable. */
  16313. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16314. && should_keep_alive(conn) && (conn->content_len >= 0)
  16315. && (conn->request_len > 0)
  16316. && ((conn->is_chunked == 4)
  16317. || (!conn->is_chunked
  16318. && ((conn->consumed_content == conn->content_len)
  16319. || ((conn->request_len + conn->content_len)
  16320. <= conn->data_len))))
  16321. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16322. if (keep_alive) {
  16323. /* Discard all buffered data for this request */
  16324. discard_len =
  16325. ((conn->request_len + conn->content_len) < conn->data_len)
  16326. ? (int)(conn->request_len + conn->content_len)
  16327. : conn->data_len;
  16328. conn->data_len -= discard_len;
  16329. if (conn->data_len > 0) {
  16330. DEBUG_TRACE("discard_len = %d", discard_len);
  16331. memmove(conn->buf,
  16332. conn->buf + discard_len,
  16333. (size_t)conn->data_len);
  16334. }
  16335. }
  16336. DEBUG_ASSERT(conn->data_len >= 0);
  16337. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16338. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16339. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16340. (long int)conn->data_len,
  16341. (long int)conn->buf_size);
  16342. break;
  16343. }
  16344. conn->handled_requests++;
  16345. } while (keep_alive);
  16346. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16347. conn->request_info.remote_addr,
  16348. difftime(time(NULL), conn->conn_birth_time));
  16349. close_connection(conn);
  16350. #if defined(USE_SERVER_STATS)
  16351. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16352. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16353. #endif
  16354. }
  16355. #if defined(ALTERNATIVE_QUEUE)
  16356. static void
  16357. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16358. {
  16359. unsigned int i;
  16360. while (!ctx->stop_flag) {
  16361. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16362. /* find a free worker slot and signal it */
  16363. if (ctx->client_socks[i].in_use == 2) {
  16364. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16365. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16366. ctx->client_socks[i] = *sp;
  16367. ctx->client_socks[i].in_use = 1;
  16368. /* socket has been moved to the consumer */
  16369. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16370. (void)event_signal(ctx->client_wait_events[i]);
  16371. return;
  16372. }
  16373. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16374. }
  16375. }
  16376. /* queue is full */
  16377. mg_sleep(1);
  16378. }
  16379. /* must consume */
  16380. set_blocking_mode(sp->sock);
  16381. closesocket(sp->sock);
  16382. }
  16383. static int
  16384. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16385. {
  16386. DEBUG_TRACE("%s", "going idle");
  16387. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16388. ctx->client_socks[thread_index].in_use = 2;
  16389. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16390. event_wait(ctx->client_wait_events[thread_index]);
  16391. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16392. *sp = ctx->client_socks[thread_index];
  16393. if (ctx->stop_flag) {
  16394. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16395. if (sp->in_use == 1) {
  16396. /* must consume */
  16397. set_blocking_mode(sp->sock);
  16398. closesocket(sp->sock);
  16399. }
  16400. return 0;
  16401. }
  16402. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16403. if (sp->in_use == 1) {
  16404. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16405. return 1;
  16406. }
  16407. /* must not reach here */
  16408. DEBUG_ASSERT(0);
  16409. return 0;
  16410. }
  16411. #else /* ALTERNATIVE_QUEUE */
  16412. /* Worker threads take accepted socket from the queue */
  16413. static int
  16414. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16415. {
  16416. (void)thread_index;
  16417. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16418. DEBUG_TRACE("%s", "going idle");
  16419. /* If the queue is empty, wait. We're idle at this point. */
  16420. while ((ctx->sq_head == ctx->sq_tail)
  16421. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16422. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16423. }
  16424. /* If we're stopping, sq_head may be equal to sq_tail. */
  16425. if (ctx->sq_head > ctx->sq_tail) {
  16426. /* Copy socket from the queue and increment tail */
  16427. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16428. ctx->sq_tail++;
  16429. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16430. /* Wrap pointers if needed */
  16431. while (ctx->sq_tail > ctx->sq_size) {
  16432. ctx->sq_tail -= ctx->sq_size;
  16433. ctx->sq_head -= ctx->sq_size;
  16434. }
  16435. }
  16436. (void)pthread_cond_signal(&ctx->sq_empty);
  16437. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16438. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16439. }
  16440. /* Master thread adds accepted socket to a queue */
  16441. static void
  16442. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16443. {
  16444. int queue_filled;
  16445. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16446. queue_filled = ctx->sq_head - ctx->sq_tail;
  16447. /* If the queue is full, wait */
  16448. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16449. && (queue_filled >= ctx->sq_size)) {
  16450. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16451. #if defined(USE_SERVER_STATS)
  16452. if (queue_filled > ctx->sq_max_fill) {
  16453. ctx->sq_max_fill = queue_filled;
  16454. }
  16455. #endif
  16456. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16457. ctx->sq_blocked = 0; /* Not blocked now */
  16458. queue_filled = ctx->sq_head - ctx->sq_tail;
  16459. }
  16460. if (queue_filled < ctx->sq_size) {
  16461. /* Copy socket to the queue and increment head */
  16462. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16463. ctx->sq_head++;
  16464. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16465. }
  16466. queue_filled = ctx->sq_head - ctx->sq_tail;
  16467. #if defined(USE_SERVER_STATS)
  16468. if (queue_filled > ctx->sq_max_fill) {
  16469. ctx->sq_max_fill = queue_filled;
  16470. }
  16471. #endif
  16472. (void)pthread_cond_signal(&ctx->sq_full);
  16473. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16474. }
  16475. #endif /* ALTERNATIVE_QUEUE */
  16476. static void
  16477. worker_thread_run(struct mg_connection *conn)
  16478. {
  16479. struct mg_context *ctx = conn->phys_ctx;
  16480. int thread_index;
  16481. struct mg_workerTLS tls;
  16482. mg_set_thread_name("worker");
  16483. tls.is_master = 0;
  16484. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16485. #if defined(_WIN32)
  16486. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16487. #endif
  16488. /* Initialize thread local storage before calling any callback */
  16489. pthread_setspecific(sTlsKey, &tls);
  16490. /* Check if there is a user callback */
  16491. if (ctx->callbacks.init_thread) {
  16492. /* call init_thread for a worker thread (type 1), and store the
  16493. * return value */
  16494. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16495. } else {
  16496. /* No callback: set user pointer to NULL */
  16497. tls.user_ptr = NULL;
  16498. }
  16499. /* Connection structure has been pre-allocated */
  16500. thread_index = (int)(conn - ctx->worker_connections);
  16501. if ((thread_index < 0)
  16502. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16503. mg_cry_ctx_internal(ctx,
  16504. "Internal error: Invalid worker index %i",
  16505. thread_index);
  16506. return;
  16507. }
  16508. /* Request buffers are not pre-allocated. They are private to the
  16509. * request and do not contain any state information that might be
  16510. * of interest to anyone observing a server status. */
  16511. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16512. if (conn->buf == NULL) {
  16513. mg_cry_ctx_internal(
  16514. ctx,
  16515. "Out of memory: Cannot allocate buffer for worker %i",
  16516. thread_index);
  16517. return;
  16518. }
  16519. conn->buf_size = (int)ctx->max_request_size;
  16520. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16521. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16522. conn->request_info.user_data = ctx->user_data;
  16523. /* Allocate a mutex for this connection to allow communication both
  16524. * within the request handler and from elsewhere in the application
  16525. */
  16526. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16527. mg_free(conn->buf);
  16528. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16529. return;
  16530. }
  16531. #if defined(USE_SERVER_STATS)
  16532. conn->conn_state = 1; /* not consumed */
  16533. #endif
  16534. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16535. * signal sq_empty condvar to wake up the master waiting in
  16536. * produce_socket() */
  16537. while (consume_socket(ctx, &conn->client, thread_index)) {
  16538. /* New connections must start with new protocol negotiation */
  16539. tls.alpn_proto = NULL;
  16540. #if defined(USE_SERVER_STATS)
  16541. conn->conn_close_time = 0;
  16542. #endif
  16543. conn->conn_birth_time = time(NULL);
  16544. /* Fill in IP, port info early so even if SSL setup below fails,
  16545. * error handler would have the corresponding info.
  16546. * Thanks to Johannes Winkelmann for the patch.
  16547. */
  16548. conn->request_info.remote_port =
  16549. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16550. conn->request_info.server_port =
  16551. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16552. sockaddr_to_string(conn->request_info.remote_addr,
  16553. sizeof(conn->request_info.remote_addr),
  16554. &conn->client.rsa);
  16555. DEBUG_TRACE("Start processing connection from %s",
  16556. conn->request_info.remote_addr);
  16557. conn->request_info.is_ssl = conn->client.is_ssl;
  16558. if (conn->client.is_ssl) {
  16559. #if !defined(NO_SSL)
  16560. /* HTTPS connection */
  16561. if (sslize(conn, SSL_accept, NULL)) {
  16562. /* conn->dom_ctx is set in get_request */
  16563. /* Get SSL client certificate information (if set) */
  16564. struct mg_client_cert client_cert;
  16565. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16566. conn->request_info.client_cert = &client_cert;
  16567. }
  16568. /* process HTTPS connection */
  16569. #if defined(USE_HTTP2)
  16570. if ((tls.alpn_proto != NULL)
  16571. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16572. /* process HTTPS/2 connection */
  16573. init_connection(conn);
  16574. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16575. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16576. conn->content_len =
  16577. -1; /* content length is not predefined */
  16578. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16579. process_new_http2_connection(conn);
  16580. } else
  16581. #endif
  16582. {
  16583. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16584. init_connection(conn);
  16585. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16586. /* Start with HTTP, WS will be an "upgrade" request later */
  16587. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16588. process_new_connection(conn);
  16589. }
  16590. /* Free client certificate info */
  16591. if (conn->request_info.client_cert) {
  16592. mg_free((void *)(conn->request_info.client_cert->subject));
  16593. mg_free((void *)(conn->request_info.client_cert->issuer));
  16594. mg_free((void *)(conn->request_info.client_cert->serial));
  16595. mg_free((void *)(conn->request_info.client_cert->finger));
  16596. /* Free certificate memory */
  16597. X509_free(
  16598. (X509 *)conn->request_info.client_cert->peer_cert);
  16599. conn->request_info.client_cert->peer_cert = 0;
  16600. conn->request_info.client_cert->subject = 0;
  16601. conn->request_info.client_cert->issuer = 0;
  16602. conn->request_info.client_cert->serial = 0;
  16603. conn->request_info.client_cert->finger = 0;
  16604. conn->request_info.client_cert = 0;
  16605. }
  16606. } else {
  16607. /* make sure the connection is cleaned up on SSL failure */
  16608. close_connection(conn);
  16609. }
  16610. #endif
  16611. } else {
  16612. /* process HTTP connection */
  16613. init_connection(conn);
  16614. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16615. /* Start with HTTP, WS will be an "upgrade" request later */
  16616. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16617. process_new_connection(conn);
  16618. }
  16619. DEBUG_TRACE("%s", "Connection closed");
  16620. #if defined(USE_SERVER_STATS)
  16621. conn->conn_close_time = time(NULL);
  16622. #endif
  16623. }
  16624. /* Call exit thread user callback */
  16625. if (ctx->callbacks.exit_thread) {
  16626. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16627. }
  16628. /* delete thread local storage objects */
  16629. pthread_setspecific(sTlsKey, NULL);
  16630. #if defined(_WIN32)
  16631. CloseHandle(tls.pthread_cond_helper_mutex);
  16632. #endif
  16633. pthread_mutex_destroy(&conn->mutex);
  16634. /* Free the request buffer. */
  16635. conn->buf_size = 0;
  16636. mg_free(conn->buf);
  16637. conn->buf = NULL;
  16638. #if defined(USE_SERVER_STATS)
  16639. conn->conn_state = 9; /* done */
  16640. #endif
  16641. DEBUG_TRACE("%s", "exiting");
  16642. }
  16643. /* Threads have different return types on Windows and Unix. */
  16644. #if defined(_WIN32)
  16645. static unsigned __stdcall worker_thread(void *thread_func_param)
  16646. {
  16647. worker_thread_run((struct mg_connection *)thread_func_param);
  16648. return 0;
  16649. }
  16650. #else
  16651. static void *
  16652. worker_thread(void *thread_func_param)
  16653. {
  16654. #if !defined(__ZEPHYR__)
  16655. struct sigaction sa;
  16656. /* Ignore SIGPIPE */
  16657. memset(&sa, 0, sizeof(sa));
  16658. sa.sa_handler = SIG_IGN;
  16659. sigaction(SIGPIPE, &sa, NULL);
  16660. #endif
  16661. worker_thread_run((struct mg_connection *)thread_func_param);
  16662. return NULL;
  16663. }
  16664. #endif /* _WIN32 */
  16665. /* This is an internal function, thus all arguments are expected to be
  16666. * valid - a NULL check is not required. */
  16667. static void
  16668. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16669. {
  16670. struct socket so;
  16671. char src_addr[IP_ADDR_STR_LEN];
  16672. socklen_t len = sizeof(so.rsa);
  16673. #if !defined(__ZEPHYR__)
  16674. int on = 1;
  16675. #endif
  16676. memset(&so, 0, sizeof(so));
  16677. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16678. == INVALID_SOCKET) {
  16679. } else if (check_acl(ctx, &so.rsa) != 1) {
  16680. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16681. mg_cry_ctx_internal(ctx,
  16682. "%s: %s is not allowed to connect",
  16683. __func__,
  16684. src_addr);
  16685. closesocket(so.sock);
  16686. } else {
  16687. /* Put so socket structure into the queue */
  16688. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16689. set_close_on_exec(so.sock, NULL, ctx);
  16690. so.is_ssl = listener->is_ssl;
  16691. so.ssl_redir = listener->ssl_redir;
  16692. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16693. mg_cry_ctx_internal(ctx,
  16694. "%s: getsockname() failed: %s",
  16695. __func__,
  16696. strerror(ERRNO));
  16697. }
  16698. #if !defined(__ZEPHYR__)
  16699. if ((so.lsa.sa.sa_family == AF_INET)
  16700. || (so.lsa.sa.sa_family == AF_INET6)) {
  16701. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  16702. * This is needed because if HTTP-level keep-alive
  16703. * is enabled, and client resets the connection, server won't get
  16704. * TCP FIN or RST and will keep the connection open forever. With
  16705. * TCP keep-alive, next keep-alive handshake will figure out that
  16706. * the client is down and will close the server end.
  16707. * Thanks to Igor Klopov who suggested the patch. */
  16708. if (setsockopt(so.sock,
  16709. SOL_SOCKET,
  16710. SO_KEEPALIVE,
  16711. (SOCK_OPT_TYPE)&on,
  16712. sizeof(on))
  16713. != 0) {
  16714. mg_cry_ctx_internal(
  16715. ctx,
  16716. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16717. __func__,
  16718. strerror(ERRNO));
  16719. }
  16720. }
  16721. #endif
  16722. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16723. * to effectively fill up the underlying IP packet payload and
  16724. * reduce the overhead of sending lots of small buffers. However
  16725. * this hurts the server's throughput (ie. operations per second)
  16726. * when HTTP 1.1 persistent connections are used and the responses
  16727. * are relatively small (eg. less than 1400 bytes).
  16728. */
  16729. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16730. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16731. if (set_tcp_nodelay(&so, 1) != 0) {
  16732. mg_cry_ctx_internal(
  16733. ctx,
  16734. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16735. __func__,
  16736. strerror(ERRNO));
  16737. }
  16738. }
  16739. /* The "non blocking" property should already be
  16740. * inherited from the parent socket. Set it for
  16741. * non-compliant socket implementations. */
  16742. set_non_blocking_mode(so.sock);
  16743. so.in_use = 0;
  16744. produce_socket(ctx, &so);
  16745. }
  16746. }
  16747. static void
  16748. master_thread_run(struct mg_context *ctx)
  16749. {
  16750. struct mg_workerTLS tls;
  16751. struct mg_pollfd *pfd;
  16752. unsigned int i;
  16753. unsigned int workerthreadcount;
  16754. if (!ctx) {
  16755. return;
  16756. }
  16757. mg_set_thread_name("master");
  16758. /* Increase priority of the master thread */
  16759. #if defined(_WIN32)
  16760. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16761. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16762. int min_prio = sched_get_priority_min(SCHED_RR);
  16763. int max_prio = sched_get_priority_max(SCHED_RR);
  16764. if ((min_prio >= 0) && (max_prio >= 0)
  16765. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16766. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16767. struct sched_param sched_param = {0};
  16768. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16769. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16770. }
  16771. #endif
  16772. /* Initialize thread local storage */
  16773. #if defined(_WIN32)
  16774. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16775. #endif
  16776. tls.is_master = 1;
  16777. pthread_setspecific(sTlsKey, &tls);
  16778. if (ctx->callbacks.init_thread) {
  16779. /* Callback for the master thread (type 0) */
  16780. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16781. } else {
  16782. tls.user_ptr = NULL;
  16783. }
  16784. /* Lua background script "start" event */
  16785. #if defined(USE_LUA)
  16786. if (ctx->lua_background_state) {
  16787. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16788. /* call "start()" in Lua */
  16789. lua_getglobal(lstate, "start");
  16790. (void)lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16791. }
  16792. #endif
  16793. /* Server starts *now* */
  16794. ctx->start_time = time(NULL);
  16795. /* Server accept loop */
  16796. pfd = ctx->listening_socket_fds;
  16797. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16798. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16799. pfd[i].fd = ctx->listening_sockets[i].sock;
  16800. pfd[i].events = POLLIN;
  16801. }
  16802. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16803. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16804. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16805. * successful poll, and POLLIN is defined as
  16806. * (POLLRDNORM | POLLRDBAND)
  16807. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16808. * pfd[i].revents == POLLIN. */
  16809. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16810. && (pfd[i].revents & POLLIN)) {
  16811. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16812. }
  16813. }
  16814. }
  16815. }
  16816. /* Here stop_flag is 1 - Initiate shutdown. */
  16817. DEBUG_TRACE("%s", "stopping workers");
  16818. /* Stop signal received: somebody called mg_stop. Quit. */
  16819. close_all_listening_sockets(ctx);
  16820. /* Wakeup workers that are waiting for connections to handle. */
  16821. #if defined(ALTERNATIVE_QUEUE)
  16822. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16823. event_signal(ctx->client_wait_events[i]);
  16824. }
  16825. #else
  16826. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16827. pthread_cond_broadcast(&ctx->sq_full);
  16828. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16829. #endif
  16830. /* Join all worker threads to avoid leaking threads. */
  16831. workerthreadcount = ctx->cfg_worker_threads;
  16832. for (i = 0; i < workerthreadcount; i++) {
  16833. if (ctx->worker_threadids[i] != 0) {
  16834. mg_join_thread(ctx->worker_threadids[i]);
  16835. }
  16836. }
  16837. #if defined(USE_LUA)
  16838. /* Free Lua state of lua background task */
  16839. if (ctx->lua_background_state) {
  16840. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16841. /* call "stop()" in Lua */
  16842. lua_getglobal(lstate, "stop");
  16843. (void)lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16844. lua_close(lstate);
  16845. ctx->lua_background_state = 0;
  16846. }
  16847. #endif
  16848. DEBUG_TRACE("%s", "exiting");
  16849. /* call exit thread callback */
  16850. if (ctx->callbacks.exit_thread) {
  16851. /* Callback for the master thread (type 0) */
  16852. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16853. }
  16854. #if defined(_WIN32)
  16855. CloseHandle(tls.pthread_cond_helper_mutex);
  16856. #endif
  16857. pthread_setspecific(sTlsKey, NULL);
  16858. /* Signal mg_stop() that we're done.
  16859. * WARNING: This must be the very last thing this
  16860. * thread does, as ctx becomes invalid after this line. */
  16861. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16862. }
  16863. /* Threads have different return types on Windows and Unix. */
  16864. #if defined(_WIN32)
  16865. static unsigned __stdcall master_thread(void *thread_func_param)
  16866. {
  16867. master_thread_run((struct mg_context *)thread_func_param);
  16868. return 0;
  16869. }
  16870. #else
  16871. static void *
  16872. master_thread(void *thread_func_param)
  16873. {
  16874. #if !defined(__ZEPHYR__)
  16875. struct sigaction sa;
  16876. /* Ignore SIGPIPE */
  16877. memset(&sa, 0, sizeof(sa));
  16878. sa.sa_handler = SIG_IGN;
  16879. sigaction(SIGPIPE, &sa, NULL);
  16880. #endif
  16881. master_thread_run((struct mg_context *)thread_func_param);
  16882. return NULL;
  16883. }
  16884. #endif /* _WIN32 */
  16885. static void
  16886. free_context(struct mg_context *ctx)
  16887. {
  16888. int i;
  16889. struct mg_handler_info *tmp_rh;
  16890. if (ctx == NULL) {
  16891. return;
  16892. }
  16893. /* Call user callback */
  16894. if (ctx->callbacks.exit_context) {
  16895. ctx->callbacks.exit_context(ctx);
  16896. }
  16897. /* All threads exited, no sync is needed. Destroy thread mutex and
  16898. * condvars
  16899. */
  16900. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16901. #if defined(ALTERNATIVE_QUEUE)
  16902. mg_free(ctx->client_socks);
  16903. if (ctx->client_wait_events != NULL) {
  16904. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16905. event_destroy(ctx->client_wait_events[i]);
  16906. }
  16907. mg_free(ctx->client_wait_events);
  16908. }
  16909. #else
  16910. (void)pthread_cond_destroy(&ctx->sq_empty);
  16911. (void)pthread_cond_destroy(&ctx->sq_full);
  16912. mg_free(ctx->squeue);
  16913. #endif
  16914. /* Destroy other context global data structures mutex */
  16915. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16916. /* Deallocate config parameters */
  16917. for (i = 0; i < NUM_OPTIONS; i++) {
  16918. if (ctx->dd.config[i] != NULL) {
  16919. #if defined(_MSC_VER)
  16920. #pragma warning(suppress : 6001)
  16921. #endif
  16922. mg_free(ctx->dd.config[i]);
  16923. }
  16924. }
  16925. /* Deallocate request handlers */
  16926. while (ctx->dd.handlers) {
  16927. tmp_rh = ctx->dd.handlers;
  16928. ctx->dd.handlers = tmp_rh->next;
  16929. mg_free(tmp_rh->uri);
  16930. mg_free(tmp_rh);
  16931. }
  16932. #if !defined(NO_SSL)
  16933. /* Deallocate SSL context */
  16934. if (ctx->dd.ssl_ctx != NULL) {
  16935. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16936. int callback_ret =
  16937. (ctx->callbacks.external_ssl_ctx == NULL)
  16938. ? 0
  16939. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16940. if (callback_ret == 0) {
  16941. SSL_CTX_free(ctx->dd.ssl_ctx);
  16942. }
  16943. /* else: ignore error and ommit SSL_CTX_free in case
  16944. * callback_ret is 1 */
  16945. }
  16946. #endif /* !NO_SSL */
  16947. /* Deallocate worker thread ID array */
  16948. mg_free(ctx->worker_threadids);
  16949. /* Deallocate worker thread ID array */
  16950. mg_free(ctx->worker_connections);
  16951. /* deallocate system name string */
  16952. mg_free(ctx->systemName);
  16953. /* Deallocate context itself */
  16954. mg_free(ctx);
  16955. }
  16956. void
  16957. mg_stop(struct mg_context *ctx)
  16958. {
  16959. pthread_t mt;
  16960. if (!ctx) {
  16961. return;
  16962. }
  16963. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16964. * two threads is not allowed. */
  16965. mt = ctx->masterthreadid;
  16966. if (mt == 0) {
  16967. return;
  16968. }
  16969. ctx->masterthreadid = 0;
  16970. /* Set stop flag, so all threads know they have to exit. */
  16971. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16972. /* Join timer thread */
  16973. #if defined(USE_TIMERS)
  16974. timers_exit(ctx);
  16975. #endif
  16976. /* Wait until everything has stopped. */
  16977. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16978. (void)mg_sleep(10);
  16979. }
  16980. /* Wait to stop master thread */
  16981. mg_join_thread(mt);
  16982. /* Close remaining Lua states */
  16983. #if defined(USE_LUA)
  16984. lua_ctx_exit(ctx);
  16985. #endif
  16986. /* Free memory */
  16987. free_context(ctx);
  16988. }
  16989. static void
  16990. get_system_name(char **sysName)
  16991. {
  16992. #if defined(_WIN32)
  16993. #if defined(_WIN32_WCE)
  16994. *sysName = mg_strdup("WinCE");
  16995. #else
  16996. char name[128];
  16997. DWORD dwVersion = 0;
  16998. DWORD dwMajorVersion = 0;
  16999. DWORD dwMinorVersion = 0;
  17000. DWORD dwBuild = 0;
  17001. BOOL wowRet, isWoW = FALSE;
  17002. #if defined(_MSC_VER)
  17003. #pragma warning(push)
  17004. /* GetVersion was declared deprecated */
  17005. #pragma warning(disable : 4996)
  17006. #endif
  17007. dwVersion = GetVersion();
  17008. #if defined(_MSC_VER)
  17009. #pragma warning(pop)
  17010. #endif
  17011. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17012. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17013. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17014. (void)dwBuild;
  17015. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17016. sprintf(name,
  17017. "Windows %u.%u%s",
  17018. (unsigned)dwMajorVersion,
  17019. (unsigned)dwMinorVersion,
  17020. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17021. *sysName = mg_strdup(name);
  17022. #endif
  17023. #elif defined(__ZEPHYR__)
  17024. *sysName = mg_strdup("Zephyr OS");
  17025. #else
  17026. struct utsname name;
  17027. memset(&name, 0, sizeof(name));
  17028. uname(&name);
  17029. *sysName = mg_strdup(name.sysname);
  17030. #endif
  17031. }
  17032. static void
  17033. legacy_init(const char **options)
  17034. {
  17035. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17036. if (options) {
  17037. const char **run_options = options;
  17038. const char *optname = config_options[LISTENING_PORTS].name;
  17039. /* Try to find the "listening_ports" option */
  17040. while (*run_options) {
  17041. if (!strcmp(*run_options, optname)) {
  17042. ports_option = run_options[1];
  17043. }
  17044. run_options += 2;
  17045. }
  17046. }
  17047. if (is_ssl_port_used(ports_option)) {
  17048. /* Initialize with SSL support */
  17049. mg_init_library(MG_FEATURES_TLS);
  17050. } else {
  17051. /* Initialize without SSL support */
  17052. mg_init_library(MG_FEATURES_DEFAULT);
  17053. }
  17054. }
  17055. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  17056. static
  17057. #endif
  17058. struct mg_context *
  17059. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17060. {
  17061. struct mg_context *ctx;
  17062. const char *name, *value, *default_value;
  17063. int idx, ok, workerthreadcount;
  17064. unsigned int i;
  17065. int itmp;
  17066. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17067. const char **options =
  17068. ((init != NULL) ? (init->configuration_options) : (NULL));
  17069. struct mg_workerTLS tls;
  17070. if (error != NULL) {
  17071. error->code = 0;
  17072. if (error->text_buffer_size > 0) {
  17073. *error->text = 0;
  17074. }
  17075. }
  17076. if (mg_init_library_called == 0) {
  17077. /* Legacy INIT, if mg_start is called without mg_init_library.
  17078. * Note: This will cause a memory leak when unloading the library.
  17079. */
  17080. legacy_init(options);
  17081. }
  17082. if (mg_init_library_called == 0) {
  17083. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17084. mg_snprintf(NULL,
  17085. NULL, /* No truncation check for error buffers */
  17086. error->text,
  17087. error->text_buffer_size,
  17088. "%s",
  17089. "Library uninitialized");
  17090. }
  17091. return NULL;
  17092. }
  17093. /* Allocate context and initialize reasonable general case defaults. */
  17094. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  17095. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17096. mg_snprintf(NULL,
  17097. NULL, /* No truncation check for error buffers */
  17098. error->text,
  17099. error->text_buffer_size,
  17100. "%s",
  17101. "Out of memory");
  17102. }
  17103. return NULL;
  17104. }
  17105. /* Random number generator will initialize at the first call */
  17106. ctx->dd.auth_nonce_mask =
  17107. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17108. /* Save started thread index to reuse in other external API calls
  17109. * For the sake of thread synchronization all non-civetweb threads
  17110. * can be considered as single external thread */
  17111. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17112. tls.is_master = -1; /* Thread calling mg_start */
  17113. tls.thread_idx = ctx->starter_thread_idx;
  17114. #if defined(_WIN32)
  17115. tls.pthread_cond_helper_mutex = NULL;
  17116. #endif
  17117. pthread_setspecific(sTlsKey, &tls);
  17118. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17119. #if !defined(ALTERNATIVE_QUEUE)
  17120. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17121. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17122. ctx->sq_blocked = 0;
  17123. #endif
  17124. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17125. if (!ok) {
  17126. const char *err_msg =
  17127. "Cannot initialize thread synchronization objects";
  17128. /* Fatal error - abort start. However, this situation should never
  17129. * occur in practice. */
  17130. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17131. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17132. mg_snprintf(NULL,
  17133. NULL, /* No truncation check for error buffers */
  17134. error->text,
  17135. error->text_buffer_size,
  17136. "%s",
  17137. err_msg);
  17138. }
  17139. mg_free(ctx);
  17140. pthread_setspecific(sTlsKey, NULL);
  17141. return NULL;
  17142. }
  17143. if ((init != NULL) && (init->callbacks != NULL)) {
  17144. /* Set all callbacks except exit_context. */
  17145. ctx->callbacks = *init->callbacks;
  17146. exit_callback = init->callbacks->exit_context;
  17147. /* The exit callback is activated once the context is successfully
  17148. * created. It should not be called, if an incomplete context object
  17149. * is deleted during a failed initialization. */
  17150. ctx->callbacks.exit_context = 0;
  17151. }
  17152. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17153. ctx->dd.handlers = NULL;
  17154. ctx->dd.next = NULL;
  17155. #if defined(USE_LUA)
  17156. lua_ctx_init(ctx);
  17157. #endif
  17158. /* Store options */
  17159. while (options && (name = *options++) != NULL) {
  17160. if ((idx = get_option_index(name)) == -1) {
  17161. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17162. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17163. mg_snprintf(NULL,
  17164. NULL, /* No truncation check for error buffers */
  17165. error->text,
  17166. error->text_buffer_size,
  17167. "Invalid configuration option: %s",
  17168. name);
  17169. }
  17170. free_context(ctx);
  17171. pthread_setspecific(sTlsKey, NULL);
  17172. return NULL;
  17173. } else if ((value = *options++) == NULL) {
  17174. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17175. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17176. mg_snprintf(NULL,
  17177. NULL, /* No truncation check for error buffers */
  17178. error->text,
  17179. error->text_buffer_size,
  17180. "Invalid configuration option value: %s",
  17181. name);
  17182. }
  17183. free_context(ctx);
  17184. pthread_setspecific(sTlsKey, NULL);
  17185. return NULL;
  17186. }
  17187. if (ctx->dd.config[idx] != NULL) {
  17188. /* A duplicate configuration option is not an error - the last
  17189. * option value will be used. */
  17190. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17191. mg_free(ctx->dd.config[idx]);
  17192. }
  17193. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17194. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17195. }
  17196. /* Set default value if needed */
  17197. for (i = 0; config_options[i].name != NULL; i++) {
  17198. default_value = config_options[i].default_value;
  17199. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17200. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17201. }
  17202. }
  17203. /* Request size option */
  17204. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17205. if (itmp < 1024) {
  17206. mg_cry_ctx_internal(ctx,
  17207. "%s too small",
  17208. config_options[MAX_REQUEST_SIZE].name);
  17209. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17210. mg_snprintf(NULL,
  17211. NULL, /* No truncation check for error buffers */
  17212. error->text,
  17213. error->text_buffer_size,
  17214. "Invalid configuration option value: %s",
  17215. config_options[MAX_REQUEST_SIZE].name);
  17216. }
  17217. free_context(ctx);
  17218. pthread_setspecific(sTlsKey, NULL);
  17219. return NULL;
  17220. }
  17221. ctx->max_request_size = (unsigned)itmp;
  17222. /* Queue length */
  17223. #if !defined(ALTERNATIVE_QUEUE)
  17224. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17225. if (itmp < 1) {
  17226. mg_cry_ctx_internal(ctx,
  17227. "%s too small",
  17228. config_options[CONNECTION_QUEUE_SIZE].name);
  17229. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17230. mg_snprintf(NULL,
  17231. NULL, /* No truncation check for error buffers */
  17232. error->text,
  17233. error->text_buffer_size,
  17234. "Invalid configuration option value: %s",
  17235. config_options[CONNECTION_QUEUE_SIZE].name);
  17236. }
  17237. free_context(ctx);
  17238. pthread_setspecific(sTlsKey, NULL);
  17239. return NULL;
  17240. }
  17241. ctx->squeue =
  17242. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17243. if (ctx->squeue == NULL) {
  17244. mg_cry_ctx_internal(ctx,
  17245. "Out of memory: Cannot allocate %s",
  17246. config_options[CONNECTION_QUEUE_SIZE].name);
  17247. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17248. mg_snprintf(NULL,
  17249. NULL, /* No truncation check for error buffers */
  17250. error->text,
  17251. error->text_buffer_size,
  17252. "Out of memory: Cannot allocate %s",
  17253. config_options[CONNECTION_QUEUE_SIZE].name);
  17254. }
  17255. free_context(ctx);
  17256. pthread_setspecific(sTlsKey, NULL);
  17257. return NULL;
  17258. }
  17259. ctx->sq_size = itmp;
  17260. #endif
  17261. /* Worker thread count option */
  17262. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17263. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17264. if (workerthreadcount <= 0) {
  17265. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17266. } else {
  17267. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17268. }
  17269. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17270. mg_snprintf(NULL,
  17271. NULL, /* No truncation check for error buffers */
  17272. error->text,
  17273. error->text_buffer_size,
  17274. "Invalid configuration option value: %s",
  17275. config_options[NUM_THREADS].name);
  17276. }
  17277. free_context(ctx);
  17278. pthread_setspecific(sTlsKey, NULL);
  17279. return NULL;
  17280. }
  17281. /* Document root */
  17282. #if defined(NO_FILES)
  17283. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17284. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17285. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17286. mg_snprintf(NULL,
  17287. NULL, /* No truncation check for error buffers */
  17288. error->text,
  17289. error->text_buffer_size,
  17290. "Invalid configuration option value: %s",
  17291. config_options[DOCUMENT_ROOT].name);
  17292. }
  17293. free_context(ctx);
  17294. pthread_setspecific(sTlsKey, NULL);
  17295. return NULL;
  17296. }
  17297. #endif
  17298. get_system_name(&ctx->systemName);
  17299. #if defined(USE_LUA)
  17300. /* If a Lua background script has been configured, start it. */
  17301. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17302. char ebuf[256];
  17303. struct vec opt_vec;
  17304. struct vec eq_vec;
  17305. const char *sparams;
  17306. /* Create a Lua state, load all standard libraries and the mg table */
  17307. lua_State *state = mg_lua_context_script_prepare(
  17308. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17309. if (!state) {
  17310. mg_cry_ctx_internal(ctx,
  17311. "lua_background_script load error: %s",
  17312. ebuf);
  17313. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17314. mg_snprintf(NULL,
  17315. NULL, /* No truncation check for error buffers */
  17316. error->text,
  17317. error->text_buffer_size,
  17318. "Error in script %s: %s",
  17319. config_options[DOCUMENT_ROOT].name,
  17320. ebuf);
  17321. }
  17322. free_context(ctx);
  17323. pthread_setspecific(sTlsKey, NULL);
  17324. return NULL;
  17325. }
  17326. /* Add a table with parameters into mg.params */
  17327. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17328. if (sparams && sparams[0]) {
  17329. lua_getglobal(state, "mg");
  17330. lua_pushstring(state, "params");
  17331. lua_newtable(state);
  17332. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17333. != NULL) {
  17334. reg_llstring(
  17335. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17336. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17337. break;
  17338. }
  17339. lua_rawset(state, -3);
  17340. lua_pop(state, 1);
  17341. }
  17342. /* Call script */
  17343. state = mg_lua_context_script_run(state,
  17344. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17345. ctx,
  17346. ebuf,
  17347. sizeof(ebuf));
  17348. if (!state) {
  17349. mg_cry_ctx_internal(ctx,
  17350. "lua_background_script start error: %s",
  17351. ebuf);
  17352. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17353. mg_snprintf(NULL,
  17354. NULL, /* No truncation check for error buffers */
  17355. error->text,
  17356. error->text_buffer_size,
  17357. "Error in script %s: %s",
  17358. config_options[DOCUMENT_ROOT].name,
  17359. ebuf);
  17360. }
  17361. free_context(ctx);
  17362. pthread_setspecific(sTlsKey, NULL);
  17363. return NULL;
  17364. }
  17365. /* state remains valid */
  17366. ctx->lua_background_state = (void *)state;
  17367. } else {
  17368. ctx->lua_background_state = 0;
  17369. }
  17370. #endif
  17371. /* Step by step initialization of ctx - depending on build options */
  17372. #if !defined(NO_FILESYSTEMS)
  17373. if (!set_gpass_option(ctx, NULL)) {
  17374. const char *err_msg = "Invalid global password file";
  17375. /* Fatal error - abort start. */
  17376. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17377. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17378. mg_snprintf(NULL,
  17379. NULL, /* No truncation check for error buffers */
  17380. error->text,
  17381. error->text_buffer_size,
  17382. "%s",
  17383. err_msg);
  17384. }
  17385. free_context(ctx);
  17386. pthread_setspecific(sTlsKey, NULL);
  17387. return NULL;
  17388. }
  17389. #endif
  17390. #if !defined(NO_SSL)
  17391. if (!init_ssl_ctx(ctx, NULL)) {
  17392. const char *err_msg = "Error initializing SSL context";
  17393. /* Fatal error - abort start. */
  17394. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17395. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17396. mg_snprintf(NULL,
  17397. NULL, /* No truncation check for error buffers */
  17398. error->text,
  17399. error->text_buffer_size,
  17400. "%s",
  17401. err_msg);
  17402. }
  17403. free_context(ctx);
  17404. pthread_setspecific(sTlsKey, NULL);
  17405. return NULL;
  17406. }
  17407. #endif
  17408. if (!set_ports_option(ctx)) {
  17409. const char *err_msg = "Failed to setup server ports";
  17410. /* Fatal error - abort start. */
  17411. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17412. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17413. mg_snprintf(NULL,
  17414. NULL, /* No truncation check for error buffers */
  17415. error->text,
  17416. error->text_buffer_size,
  17417. "%s",
  17418. err_msg);
  17419. }
  17420. free_context(ctx);
  17421. pthread_setspecific(sTlsKey, NULL);
  17422. return NULL;
  17423. }
  17424. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17425. if (!set_uid_option(ctx)) {
  17426. const char *err_msg = "Failed to run as configured user";
  17427. /* Fatal error - abort start. */
  17428. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17429. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17430. mg_snprintf(NULL,
  17431. NULL, /* No truncation check for error buffers */
  17432. error->text,
  17433. error->text_buffer_size,
  17434. "%s",
  17435. err_msg);
  17436. }
  17437. free_context(ctx);
  17438. pthread_setspecific(sTlsKey, NULL);
  17439. return NULL;
  17440. }
  17441. #endif
  17442. if (!set_acl_option(ctx)) {
  17443. const char *err_msg = "Failed to setup access control list";
  17444. /* Fatal error - abort start. */
  17445. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17446. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17447. mg_snprintf(NULL,
  17448. NULL, /* No truncation check for error buffers */
  17449. error->text,
  17450. error->text_buffer_size,
  17451. "%s",
  17452. err_msg);
  17453. }
  17454. free_context(ctx);
  17455. pthread_setspecific(sTlsKey, NULL);
  17456. return NULL;
  17457. }
  17458. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17459. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17460. sizeof(pthread_t),
  17461. ctx);
  17462. if (ctx->worker_threadids == NULL) {
  17463. const char *err_msg = "Not enough memory for worker thread ID array";
  17464. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17465. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17466. mg_snprintf(NULL,
  17467. NULL, /* No truncation check for error buffers */
  17468. error->text,
  17469. error->text_buffer_size,
  17470. "%s",
  17471. err_msg);
  17472. }
  17473. free_context(ctx);
  17474. pthread_setspecific(sTlsKey, NULL);
  17475. return NULL;
  17476. }
  17477. ctx->worker_connections =
  17478. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17479. sizeof(struct mg_connection),
  17480. ctx);
  17481. if (ctx->worker_connections == NULL) {
  17482. const char *err_msg =
  17483. "Not enough memory for worker thread connection array";
  17484. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17485. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17486. mg_snprintf(NULL,
  17487. NULL, /* No truncation check for error buffers */
  17488. error->text,
  17489. error->text_buffer_size,
  17490. "%s",
  17491. err_msg);
  17492. }
  17493. free_context(ctx);
  17494. pthread_setspecific(sTlsKey, NULL);
  17495. return NULL;
  17496. }
  17497. #if defined(ALTERNATIVE_QUEUE)
  17498. ctx->client_wait_events =
  17499. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17500. sizeof(ctx->client_wait_events[0]),
  17501. ctx);
  17502. if (ctx->client_wait_events == NULL) {
  17503. const char *err_msg = "Not enough memory for worker event array";
  17504. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17505. mg_free(ctx->worker_threadids);
  17506. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17507. mg_snprintf(NULL,
  17508. NULL, /* No truncation check for error buffers */
  17509. error->text,
  17510. error->text_buffer_size,
  17511. "%s",
  17512. err_msg);
  17513. }
  17514. free_context(ctx);
  17515. pthread_setspecific(sTlsKey, NULL);
  17516. return NULL;
  17517. }
  17518. ctx->client_socks =
  17519. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17520. sizeof(ctx->client_socks[0]),
  17521. ctx);
  17522. if (ctx->client_socks == NULL) {
  17523. const char *err_msg = "Not enough memory for worker socket array";
  17524. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17525. mg_free(ctx->client_wait_events);
  17526. mg_free(ctx->worker_threadids);
  17527. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17528. mg_snprintf(NULL,
  17529. NULL, /* No truncation check for error buffers */
  17530. error->text,
  17531. error->text_buffer_size,
  17532. "%s",
  17533. err_msg);
  17534. }
  17535. free_context(ctx);
  17536. pthread_setspecific(sTlsKey, NULL);
  17537. return NULL;
  17538. }
  17539. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17540. ctx->client_wait_events[i] = event_create();
  17541. if (ctx->client_wait_events[i] == 0) {
  17542. const char *err_msg = "Error creating worker event %i";
  17543. mg_cry_ctx_internal(ctx, err_msg, i);
  17544. while (i > 0) {
  17545. i--;
  17546. event_destroy(ctx->client_wait_events[i]);
  17547. }
  17548. mg_free(ctx->client_socks);
  17549. mg_free(ctx->client_wait_events);
  17550. mg_free(ctx->worker_threadids);
  17551. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17552. mg_snprintf(NULL,
  17553. NULL, /* No truncation check for error buffers */
  17554. error->text,
  17555. error->text_buffer_size,
  17556. err_msg,
  17557. i);
  17558. }
  17559. free_context(ctx);
  17560. pthread_setspecific(sTlsKey, NULL);
  17561. return NULL;
  17562. }
  17563. }
  17564. #endif
  17565. #if defined(USE_TIMERS)
  17566. if (timers_init(ctx) != 0) {
  17567. const char *err_msg = "Error creating timers";
  17568. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17569. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17570. mg_snprintf(NULL,
  17571. NULL, /* No truncation check for error buffers */
  17572. error->text,
  17573. error->text_buffer_size,
  17574. "%s",
  17575. err_msg);
  17576. }
  17577. free_context(ctx);
  17578. pthread_setspecific(sTlsKey, NULL);
  17579. return NULL;
  17580. }
  17581. #endif
  17582. /* Context has been created - init user libraries */
  17583. if (ctx->callbacks.init_context) {
  17584. ctx->callbacks.init_context(ctx);
  17585. }
  17586. /* From now, the context is successfully created.
  17587. * When it is destroyed, the exit callback should be called. */
  17588. ctx->callbacks.exit_context = exit_callback;
  17589. ctx->context_type = CONTEXT_SERVER; /* server context */
  17590. /* Start worker threads */
  17591. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17592. /* worker_thread sets up the other fields */
  17593. ctx->worker_connections[i].phys_ctx = ctx;
  17594. if (mg_start_thread_with_id(worker_thread,
  17595. &ctx->worker_connections[i],
  17596. &ctx->worker_threadids[i])
  17597. != 0) {
  17598. long error_no = (long)ERRNO;
  17599. /* thread was not created */
  17600. if (i > 0) {
  17601. /* If the second, third, ... thread cannot be created, set a
  17602. * warning, but keep running. */
  17603. mg_cry_ctx_internal(ctx,
  17604. "Cannot start worker thread %i: error %ld",
  17605. i + 1,
  17606. error_no);
  17607. /* If the server initialization should stop here, all
  17608. * threads that have already been created must be stopped
  17609. * first, before any free_context(ctx) call.
  17610. */
  17611. } else {
  17612. /* If the first worker thread cannot be created, stop
  17613. * initialization and free the entire server context. */
  17614. mg_cry_ctx_internal(ctx,
  17615. "Cannot create threads: error %ld",
  17616. error_no);
  17617. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17618. mg_snprintf(
  17619. NULL,
  17620. NULL, /* No truncation check for error buffers */
  17621. error->text,
  17622. error->text_buffer_size,
  17623. "Cannot create first worker thread: error %ld",
  17624. error_no);
  17625. }
  17626. free_context(ctx);
  17627. pthread_setspecific(sTlsKey, NULL);
  17628. return NULL;
  17629. }
  17630. break;
  17631. }
  17632. }
  17633. /* Start master (listening) thread */
  17634. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17635. pthread_setspecific(sTlsKey, NULL);
  17636. return ctx;
  17637. }
  17638. struct mg_context *
  17639. mg_start(const struct mg_callbacks *callbacks,
  17640. void *user_data,
  17641. const char **options)
  17642. {
  17643. struct mg_init_data init = {0};
  17644. init.callbacks = callbacks;
  17645. init.user_data = user_data;
  17646. init.configuration_options = options;
  17647. return mg_start2(&init, NULL);
  17648. }
  17649. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17650. /* Add an additional domain to an already running web server. */
  17651. int
  17652. mg_start_domain2(struct mg_context *ctx,
  17653. const char **options,
  17654. struct mg_error_data *error)
  17655. {
  17656. const char *name;
  17657. const char *value;
  17658. const char *default_value;
  17659. struct mg_domain_context *new_dom;
  17660. struct mg_domain_context *dom;
  17661. int idx, i;
  17662. if (error != NULL) {
  17663. error->code = 0;
  17664. if (error->text_buffer_size > 0) {
  17665. *error->text = 0;
  17666. }
  17667. }
  17668. if ((ctx == NULL) || (options == NULL)) {
  17669. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17670. mg_snprintf(NULL,
  17671. NULL, /* No truncation check for error buffers */
  17672. error->text,
  17673. error->text_buffer_size,
  17674. "%s",
  17675. "Invalid parameters");
  17676. }
  17677. return -1;
  17678. }
  17679. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17680. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17681. mg_snprintf(NULL,
  17682. NULL, /* No truncation check for error buffers */
  17683. error->text,
  17684. error->text_buffer_size,
  17685. "%s",
  17686. "Server already stopped");
  17687. }
  17688. return -1;
  17689. }
  17690. new_dom = (struct mg_domain_context *)
  17691. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17692. if (!new_dom) {
  17693. /* Out of memory */
  17694. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17695. mg_snprintf(NULL,
  17696. NULL, /* No truncation check for error buffers */
  17697. error->text,
  17698. error->text_buffer_size,
  17699. "%s",
  17700. "Out or memory");
  17701. }
  17702. return -6;
  17703. }
  17704. /* Store options - TODO: unite duplicate code */
  17705. while (options && (name = *options++) != NULL) {
  17706. if ((idx = get_option_index(name)) == -1) {
  17707. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17708. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17709. mg_snprintf(NULL,
  17710. NULL, /* No truncation check for error buffers */
  17711. error->text,
  17712. error->text_buffer_size,
  17713. "Invalid option: %s",
  17714. name);
  17715. }
  17716. mg_free(new_dom);
  17717. return -2;
  17718. } else if ((value = *options++) == NULL) {
  17719. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17720. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17721. mg_snprintf(NULL,
  17722. NULL, /* No truncation check for error buffers */
  17723. error->text,
  17724. error->text_buffer_size,
  17725. "Invalid option value: %s",
  17726. name);
  17727. }
  17728. mg_free(new_dom);
  17729. return -2;
  17730. }
  17731. if (new_dom->config[idx] != NULL) {
  17732. /* Duplicate option: Later values overwrite earlier ones. */
  17733. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17734. mg_free(new_dom->config[idx]);
  17735. }
  17736. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17737. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17738. }
  17739. /* Authentication domain is mandatory */
  17740. /* TODO: Maybe use a new option hostname? */
  17741. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17742. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17743. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17744. mg_snprintf(NULL,
  17745. NULL, /* No truncation check for error buffers */
  17746. error->text,
  17747. error->text_buffer_size,
  17748. "Mandatory option %s missing",
  17749. config_options[AUTHENTICATION_DOMAIN].name);
  17750. }
  17751. mg_free(new_dom);
  17752. return -4;
  17753. }
  17754. /* Set default value if needed. Take the config value from
  17755. * ctx as a default value. */
  17756. for (i = 0; config_options[i].name != NULL; i++) {
  17757. default_value = ctx->dd.config[i];
  17758. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17759. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17760. }
  17761. }
  17762. new_dom->handlers = NULL;
  17763. new_dom->next = NULL;
  17764. new_dom->nonce_count = 0;
  17765. new_dom->auth_nonce_mask =
  17766. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17767. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17768. new_dom->shared_lua_websockets = NULL;
  17769. #endif
  17770. #if !defined(NO_SSL)
  17771. if (!init_ssl_ctx(ctx, new_dom)) {
  17772. /* Init SSL failed */
  17773. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17774. mg_snprintf(NULL,
  17775. NULL, /* No truncation check for error buffers */
  17776. error->text,
  17777. error->text_buffer_size,
  17778. "%s",
  17779. "Initializing SSL context failed");
  17780. }
  17781. mg_free(new_dom);
  17782. return -3;
  17783. }
  17784. #endif
  17785. /* Add element to linked list. */
  17786. mg_lock_context(ctx);
  17787. idx = 0;
  17788. dom = &(ctx->dd);
  17789. for (;;) {
  17790. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17791. dom->config[AUTHENTICATION_DOMAIN])) {
  17792. /* Domain collision */
  17793. mg_cry_ctx_internal(ctx,
  17794. "domain %s already in use",
  17795. new_dom->config[AUTHENTICATION_DOMAIN]);
  17796. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17797. mg_snprintf(NULL,
  17798. NULL, /* No truncation check for error buffers */
  17799. error->text,
  17800. error->text_buffer_size,
  17801. "Domain %s specified by %s is already in use",
  17802. new_dom->config[AUTHENTICATION_DOMAIN],
  17803. config_options[AUTHENTICATION_DOMAIN].name);
  17804. }
  17805. mg_free(new_dom);
  17806. mg_unlock_context(ctx);
  17807. return -5;
  17808. }
  17809. /* Count number of domains */
  17810. idx++;
  17811. if (dom->next == NULL) {
  17812. dom->next = new_dom;
  17813. break;
  17814. }
  17815. dom = dom->next;
  17816. }
  17817. mg_unlock_context(ctx);
  17818. /* Return domain number */
  17819. return idx;
  17820. }
  17821. int
  17822. mg_start_domain(struct mg_context *ctx, const char **options)
  17823. {
  17824. return mg_start_domain2(ctx, options, NULL);
  17825. }
  17826. #endif
  17827. /* Feature check API function */
  17828. unsigned
  17829. mg_check_feature(unsigned feature)
  17830. {
  17831. static const unsigned feature_set = 0
  17832. /* Set bits for available features according to API documentation.
  17833. * This bit mask is created at compile time, according to the active
  17834. * preprocessor defines. It is a single const value at runtime. */
  17835. #if !defined(NO_FILES)
  17836. | MG_FEATURES_FILES
  17837. #endif
  17838. #if !defined(NO_SSL)
  17839. | MG_FEATURES_SSL
  17840. #endif
  17841. #if !defined(NO_CGI)
  17842. | MG_FEATURES_CGI
  17843. #endif
  17844. #if defined(USE_IPV6)
  17845. | MG_FEATURES_IPV6
  17846. #endif
  17847. #if defined(USE_WEBSOCKET)
  17848. | MG_FEATURES_WEBSOCKET
  17849. #endif
  17850. #if defined(USE_LUA)
  17851. | MG_FEATURES_LUA
  17852. #endif
  17853. #if defined(USE_DUKTAPE)
  17854. | MG_FEATURES_SSJS
  17855. #endif
  17856. #if !defined(NO_CACHING)
  17857. | MG_FEATURES_CACHE
  17858. #endif
  17859. #if defined(USE_SERVER_STATS)
  17860. | MG_FEATURES_STATS
  17861. #endif
  17862. #if defined(USE_ZLIB)
  17863. | MG_FEATURES_COMPRESSION
  17864. #endif
  17865. #if defined(USE_HTTP2)
  17866. | MG_FEATURES_HTTP2
  17867. #endif
  17868. #if defined(USE_X_DOM_SOCKET)
  17869. | MG_FEATURES_X_DOMAIN_SOCKET
  17870. #endif
  17871. /* Set some extra bits not defined in the API documentation.
  17872. * These bits may change without further notice. */
  17873. #if defined(MG_LEGACY_INTERFACE)
  17874. | 0x80000000u
  17875. #endif
  17876. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17877. | 0x40000000u
  17878. #endif
  17879. #if !defined(NO_RESPONSE_BUFFERING)
  17880. | 0x20000000u
  17881. #endif
  17882. #if defined(MEMORY_DEBUGGING)
  17883. | 0x10000000u
  17884. #endif
  17885. ;
  17886. return (feature & feature_set);
  17887. }
  17888. static size_t
  17889. mg_str_append(char **dst, char *end, const char *src)
  17890. {
  17891. size_t len = strlen(src);
  17892. if (*dst != end) {
  17893. /* Append src if enough space, or close dst. */
  17894. if ((size_t)(end - *dst) > len) {
  17895. strcpy(*dst, src);
  17896. *dst += len;
  17897. } else {
  17898. *dst = end;
  17899. }
  17900. }
  17901. return len;
  17902. }
  17903. /* Get system information. It can be printed or stored by the caller.
  17904. * Return the size of available information. */
  17905. int
  17906. mg_get_system_info(char *buffer, int buflen)
  17907. {
  17908. char *end, *append_eoobj = NULL, block[256];
  17909. size_t system_info_length = 0;
  17910. #if defined(_WIN32)
  17911. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17912. #else
  17913. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17914. #endif
  17915. if ((buffer == NULL) || (buflen < 1)) {
  17916. buflen = 0;
  17917. end = buffer;
  17918. } else {
  17919. *buffer = 0;
  17920. end = buffer + buflen;
  17921. }
  17922. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17923. /* has enough space to append eoobj */
  17924. append_eoobj = buffer;
  17925. if (end) {
  17926. end -= sizeof(eoobj) - 1;
  17927. }
  17928. }
  17929. system_info_length += mg_str_append(&buffer, end, "{");
  17930. /* Server version */
  17931. {
  17932. const char *version = mg_version();
  17933. mg_snprintf(NULL,
  17934. NULL,
  17935. block,
  17936. sizeof(block),
  17937. "%s\"version\" : \"%s\"",
  17938. eol,
  17939. version);
  17940. system_info_length += mg_str_append(&buffer, end, block);
  17941. }
  17942. /* System info */
  17943. {
  17944. #if defined(_WIN32)
  17945. DWORD dwVersion = 0;
  17946. DWORD dwMajorVersion = 0;
  17947. DWORD dwMinorVersion = 0;
  17948. SYSTEM_INFO si;
  17949. GetSystemInfo(&si);
  17950. #if defined(_MSC_VER)
  17951. #pragma warning(push)
  17952. /* GetVersion was declared deprecated */
  17953. #pragma warning(disable : 4996)
  17954. #endif
  17955. dwVersion = GetVersion();
  17956. #if defined(_MSC_VER)
  17957. #pragma warning(pop)
  17958. #endif
  17959. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17960. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17961. mg_snprintf(NULL,
  17962. NULL,
  17963. block,
  17964. sizeof(block),
  17965. ",%s\"os\" : \"Windows %u.%u\"",
  17966. eol,
  17967. (unsigned)dwMajorVersion,
  17968. (unsigned)dwMinorVersion);
  17969. system_info_length += mg_str_append(&buffer, end, block);
  17970. mg_snprintf(NULL,
  17971. NULL,
  17972. block,
  17973. sizeof(block),
  17974. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17975. eol,
  17976. (unsigned)si.wProcessorArchitecture,
  17977. (unsigned)si.dwNumberOfProcessors,
  17978. (unsigned)si.dwActiveProcessorMask);
  17979. system_info_length += mg_str_append(&buffer, end, block);
  17980. #elif defined(__ZEPHYR__)
  17981. mg_snprintf(NULL,
  17982. NULL,
  17983. block,
  17984. sizeof(block),
  17985. ",%s\"os\" : \"%s %s\"",
  17986. eol,
  17987. "Zephyr OS",
  17988. ZEPHYR_VERSION);
  17989. system_info_length += mg_str_append(&buffer, end, block);
  17990. #else
  17991. struct utsname name;
  17992. memset(&name, 0, sizeof(name));
  17993. uname(&name);
  17994. mg_snprintf(NULL,
  17995. NULL,
  17996. block,
  17997. sizeof(block),
  17998. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17999. eol,
  18000. name.sysname,
  18001. name.version,
  18002. name.release,
  18003. name.machine);
  18004. system_info_length += mg_str_append(&buffer, end, block);
  18005. #endif
  18006. }
  18007. /* Features */
  18008. {
  18009. mg_snprintf(NULL,
  18010. NULL,
  18011. block,
  18012. sizeof(block),
  18013. ",%s\"features\" : %lu"
  18014. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18015. eol,
  18016. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18017. eol,
  18018. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18019. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18020. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18021. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18022. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18023. : "",
  18024. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18025. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18026. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18027. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18028. system_info_length += mg_str_append(&buffer, end, block);
  18029. #if defined(USE_LUA)
  18030. mg_snprintf(NULL,
  18031. NULL,
  18032. block,
  18033. sizeof(block),
  18034. ",%s\"lua_version\" : \"%u (%s)\"",
  18035. eol,
  18036. (unsigned)LUA_VERSION_NUM,
  18037. LUA_RELEASE);
  18038. system_info_length += mg_str_append(&buffer, end, block);
  18039. #endif
  18040. #if defined(USE_DUKTAPE)
  18041. mg_snprintf(NULL,
  18042. NULL,
  18043. block,
  18044. sizeof(block),
  18045. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18046. eol,
  18047. (unsigned)DUK_VERSION / 10000,
  18048. ((unsigned)DUK_VERSION / 100) % 100,
  18049. (unsigned)DUK_VERSION % 100);
  18050. system_info_length += mg_str_append(&buffer, end, block);
  18051. #endif
  18052. }
  18053. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18054. {
  18055. #if defined(BUILD_DATE)
  18056. const char *bd = BUILD_DATE;
  18057. #else
  18058. #if defined(GCC_DIAGNOSTIC)
  18059. #if GCC_VERSION >= 40900
  18060. #pragma GCC diagnostic push
  18061. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18062. * does not work in some versions. If "BUILD_DATE" is defined to some
  18063. * string, it is used instead of __DATE__. */
  18064. #pragma GCC diagnostic ignored "-Wdate-time"
  18065. #endif
  18066. #endif
  18067. const char *bd = __DATE__;
  18068. #if defined(GCC_DIAGNOSTIC)
  18069. #if GCC_VERSION >= 40900
  18070. #pragma GCC diagnostic pop
  18071. #endif
  18072. #endif
  18073. #endif
  18074. mg_snprintf(
  18075. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18076. system_info_length += mg_str_append(&buffer, end, block);
  18077. }
  18078. /* Compiler information */
  18079. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18080. {
  18081. #if defined(_MSC_VER)
  18082. mg_snprintf(NULL,
  18083. NULL,
  18084. block,
  18085. sizeof(block),
  18086. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18087. eol,
  18088. (unsigned)_MSC_VER,
  18089. (unsigned)_MSC_FULL_VER);
  18090. system_info_length += mg_str_append(&buffer, end, block);
  18091. #elif defined(__MINGW64__)
  18092. mg_snprintf(NULL,
  18093. NULL,
  18094. block,
  18095. sizeof(block),
  18096. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18097. eol,
  18098. (unsigned)__MINGW64_VERSION_MAJOR,
  18099. (unsigned)__MINGW64_VERSION_MINOR);
  18100. system_info_length += mg_str_append(&buffer, end, block);
  18101. mg_snprintf(NULL,
  18102. NULL,
  18103. block,
  18104. sizeof(block),
  18105. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18106. eol,
  18107. (unsigned)__MINGW32_MAJOR_VERSION,
  18108. (unsigned)__MINGW32_MINOR_VERSION);
  18109. system_info_length += mg_str_append(&buffer, end, block);
  18110. #elif defined(__MINGW32__)
  18111. mg_snprintf(NULL,
  18112. NULL,
  18113. block,
  18114. sizeof(block),
  18115. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18116. eol,
  18117. (unsigned)__MINGW32_MAJOR_VERSION,
  18118. (unsigned)__MINGW32_MINOR_VERSION);
  18119. system_info_length += mg_str_append(&buffer, end, block);
  18120. #elif defined(__clang__)
  18121. mg_snprintf(NULL,
  18122. NULL,
  18123. block,
  18124. sizeof(block),
  18125. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18126. eol,
  18127. __clang_major__,
  18128. __clang_minor__,
  18129. __clang_patchlevel__,
  18130. __clang_version__);
  18131. system_info_length += mg_str_append(&buffer, end, block);
  18132. #elif defined(__GNUC__)
  18133. mg_snprintf(NULL,
  18134. NULL,
  18135. block,
  18136. sizeof(block),
  18137. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18138. eol,
  18139. (unsigned)__GNUC__,
  18140. (unsigned)__GNUC_MINOR__,
  18141. (unsigned)__GNUC_PATCHLEVEL__);
  18142. system_info_length += mg_str_append(&buffer, end, block);
  18143. #elif defined(__INTEL_COMPILER)
  18144. mg_snprintf(NULL,
  18145. NULL,
  18146. block,
  18147. sizeof(block),
  18148. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18149. eol,
  18150. (unsigned)__INTEL_COMPILER);
  18151. system_info_length += mg_str_append(&buffer, end, block);
  18152. #elif defined(__BORLANDC__)
  18153. mg_snprintf(NULL,
  18154. NULL,
  18155. block,
  18156. sizeof(block),
  18157. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18158. eol,
  18159. (unsigned)__BORLANDC__);
  18160. system_info_length += mg_str_append(&buffer, end, block);
  18161. #elif defined(__SUNPRO_C)
  18162. mg_snprintf(NULL,
  18163. NULL,
  18164. block,
  18165. sizeof(block),
  18166. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18167. eol,
  18168. (unsigned)__SUNPRO_C);
  18169. system_info_length += mg_str_append(&buffer, end, block);
  18170. #else
  18171. mg_snprintf(NULL,
  18172. NULL,
  18173. block,
  18174. sizeof(block),
  18175. ",%s\"compiler\" : \"other\"",
  18176. eol);
  18177. system_info_length += mg_str_append(&buffer, end, block);
  18178. #endif
  18179. }
  18180. /* Determine 32/64 bit data mode.
  18181. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18182. {
  18183. mg_snprintf(NULL,
  18184. NULL,
  18185. block,
  18186. sizeof(block),
  18187. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18188. "char:%u/%u, "
  18189. "ptr:%u, size:%u, time:%u\"",
  18190. eol,
  18191. (unsigned)sizeof(short),
  18192. (unsigned)sizeof(int),
  18193. (unsigned)sizeof(long),
  18194. (unsigned)sizeof(long long),
  18195. (unsigned)sizeof(float),
  18196. (unsigned)sizeof(double),
  18197. (unsigned)sizeof(long double),
  18198. (unsigned)sizeof(char),
  18199. (unsigned)sizeof(wchar_t),
  18200. (unsigned)sizeof(void *),
  18201. (unsigned)sizeof(size_t),
  18202. (unsigned)sizeof(time_t));
  18203. system_info_length += mg_str_append(&buffer, end, block);
  18204. }
  18205. /* Terminate string */
  18206. if (append_eoobj) {
  18207. strcat(append_eoobj, eoobj);
  18208. }
  18209. system_info_length += sizeof(eoobj) - 1;
  18210. return (int)system_info_length;
  18211. }
  18212. /* Get context information. It can be printed or stored by the caller.
  18213. * Return the size of available information. */
  18214. int
  18215. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18216. {
  18217. #if defined(USE_SERVER_STATS)
  18218. char *end, *append_eoobj = NULL, block[256];
  18219. size_t context_info_length = 0;
  18220. #if defined(_WIN32)
  18221. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18222. #else
  18223. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18224. #endif
  18225. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18226. if ((buffer == NULL) || (buflen < 1)) {
  18227. buflen = 0;
  18228. end = buffer;
  18229. } else {
  18230. *buffer = 0;
  18231. end = buffer + buflen;
  18232. }
  18233. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18234. /* has enough space to append eoobj */
  18235. append_eoobj = buffer;
  18236. end -= sizeof(eoobj) - 1;
  18237. }
  18238. context_info_length += mg_str_append(&buffer, end, "{");
  18239. if (ms) { /* <-- should be always true */
  18240. /* Memory information */
  18241. int blockCount = (int)ms->blockCount;
  18242. int64_t totalMemUsed = ms->totalMemUsed;
  18243. int64_t maxMemUsed = ms->maxMemUsed;
  18244. if (totalMemUsed > maxMemUsed) {
  18245. maxMemUsed = totalMemUsed;
  18246. }
  18247. mg_snprintf(NULL,
  18248. NULL,
  18249. block,
  18250. sizeof(block),
  18251. "%s\"memory\" : {%s"
  18252. "\"blocks\" : %i,%s"
  18253. "\"used\" : %" INT64_FMT ",%s"
  18254. "\"maxUsed\" : %" INT64_FMT "%s"
  18255. "}",
  18256. eol,
  18257. eol,
  18258. blockCount,
  18259. eol,
  18260. totalMemUsed,
  18261. eol,
  18262. maxMemUsed,
  18263. eol);
  18264. context_info_length += mg_str_append(&buffer, end, block);
  18265. }
  18266. if (ctx) {
  18267. /* Declare all variables at begin of the block, to comply
  18268. * with old C standards. */
  18269. char start_time_str[64] = {0};
  18270. char now_str[64] = {0};
  18271. time_t start_time = ctx->start_time;
  18272. time_t now = time(NULL);
  18273. int64_t total_data_read, total_data_written;
  18274. int active_connections = (int)ctx->active_connections;
  18275. int max_active_connections = (int)ctx->max_active_connections;
  18276. int total_connections = (int)ctx->total_connections;
  18277. if (active_connections > max_active_connections) {
  18278. max_active_connections = active_connections;
  18279. }
  18280. if (active_connections > total_connections) {
  18281. total_connections = active_connections;
  18282. }
  18283. /* Connections information */
  18284. mg_snprintf(NULL,
  18285. NULL,
  18286. block,
  18287. sizeof(block),
  18288. ",%s\"connections\" : {%s"
  18289. "\"active\" : %i,%s"
  18290. "\"maxActive\" : %i,%s"
  18291. "\"total\" : %i%s"
  18292. "}",
  18293. eol,
  18294. eol,
  18295. active_connections,
  18296. eol,
  18297. max_active_connections,
  18298. eol,
  18299. total_connections,
  18300. eol);
  18301. context_info_length += mg_str_append(&buffer, end, block);
  18302. /* Queue information */
  18303. #if !defined(ALTERNATIVE_QUEUE)
  18304. mg_snprintf(NULL,
  18305. NULL,
  18306. block,
  18307. sizeof(block),
  18308. ",%s\"queue\" : {%s"
  18309. "\"length\" : %i,%s"
  18310. "\"filled\" : %i,%s"
  18311. "\"maxFilled\" : %i,%s"
  18312. "\"full\" : %s%s"
  18313. "}",
  18314. eol,
  18315. eol,
  18316. ctx->sq_size,
  18317. eol,
  18318. ctx->sq_head - ctx->sq_tail,
  18319. eol,
  18320. ctx->sq_max_fill,
  18321. eol,
  18322. (ctx->sq_blocked ? "true" : "false"),
  18323. eol);
  18324. context_info_length += mg_str_append(&buffer, end, block);
  18325. #endif
  18326. /* Requests information */
  18327. mg_snprintf(NULL,
  18328. NULL,
  18329. block,
  18330. sizeof(block),
  18331. ",%s\"requests\" : {%s"
  18332. "\"total\" : %lu%s"
  18333. "}",
  18334. eol,
  18335. eol,
  18336. (unsigned long)ctx->total_requests,
  18337. eol);
  18338. context_info_length += mg_str_append(&buffer, end, block);
  18339. /* Data information */
  18340. total_data_read =
  18341. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18342. total_data_written =
  18343. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18344. mg_snprintf(NULL,
  18345. NULL,
  18346. block,
  18347. sizeof(block),
  18348. ",%s\"data\" : {%s"
  18349. "\"read\" : %" INT64_FMT ",%s"
  18350. "\"written\" : %" INT64_FMT "%s"
  18351. "}",
  18352. eol,
  18353. eol,
  18354. total_data_read,
  18355. eol,
  18356. total_data_written,
  18357. eol);
  18358. context_info_length += mg_str_append(&buffer, end, block);
  18359. /* Execution time information */
  18360. gmt_time_string(start_time_str,
  18361. sizeof(start_time_str) - 1,
  18362. &start_time);
  18363. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18364. mg_snprintf(NULL,
  18365. NULL,
  18366. block,
  18367. sizeof(block),
  18368. ",%s\"time\" : {%s"
  18369. "\"uptime\" : %.0f,%s"
  18370. "\"start\" : \"%s\",%s"
  18371. "\"now\" : \"%s\"%s"
  18372. "}",
  18373. eol,
  18374. eol,
  18375. difftime(now, start_time),
  18376. eol,
  18377. start_time_str,
  18378. eol,
  18379. now_str,
  18380. eol);
  18381. context_info_length += mg_str_append(&buffer, end, block);
  18382. }
  18383. /* Terminate string */
  18384. if (append_eoobj) {
  18385. strcat(append_eoobj, eoobj);
  18386. }
  18387. context_info_length += sizeof(eoobj) - 1;
  18388. return (int)context_info_length;
  18389. #else
  18390. (void)ctx;
  18391. if ((buffer != NULL) && (buflen > 0)) {
  18392. *buffer = 0;
  18393. }
  18394. return 0;
  18395. #endif
  18396. }
  18397. void
  18398. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18399. {
  18400. /* https://github.com/civetweb/civetweb/issues/727 */
  18401. if (conn != NULL) {
  18402. conn->must_close = 1;
  18403. }
  18404. }
  18405. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18406. /* Get connection information. It can be printed or stored by the caller.
  18407. * Return the size of available information. */
  18408. int
  18409. mg_get_connection_info(const struct mg_context *ctx,
  18410. int idx,
  18411. char *buffer,
  18412. int buflen)
  18413. {
  18414. const struct mg_connection *conn;
  18415. const struct mg_request_info *ri;
  18416. char *end, *append_eoobj = NULL, block[256];
  18417. size_t connection_info_length = 0;
  18418. int state = 0;
  18419. const char *state_str = "unknown";
  18420. #if defined(_WIN32)
  18421. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18422. #else
  18423. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18424. #endif
  18425. if ((buffer == NULL) || (buflen < 1)) {
  18426. buflen = 0;
  18427. end = buffer;
  18428. } else {
  18429. *buffer = 0;
  18430. end = buffer + buflen;
  18431. }
  18432. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18433. /* has enough space to append eoobj */
  18434. append_eoobj = buffer;
  18435. end -= sizeof(eoobj) - 1;
  18436. }
  18437. if ((ctx == NULL) || (idx < 0)) {
  18438. /* Parameter error */
  18439. return 0;
  18440. }
  18441. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18442. /* Out of range */
  18443. return 0;
  18444. }
  18445. /* Take connection [idx]. This connection is not locked in
  18446. * any way, so some other thread might use it. */
  18447. conn = (ctx->worker_connections) + idx;
  18448. /* Initialize output string */
  18449. connection_info_length += mg_str_append(&buffer, end, "{");
  18450. /* Init variables */
  18451. ri = &(conn->request_info);
  18452. #if defined(USE_SERVER_STATS)
  18453. state = conn->conn_state;
  18454. /* State as string */
  18455. switch (state) {
  18456. case 0:
  18457. state_str = "undefined";
  18458. break;
  18459. case 1:
  18460. state_str = "not used";
  18461. break;
  18462. case 2:
  18463. state_str = "init";
  18464. break;
  18465. case 3:
  18466. state_str = "ready";
  18467. break;
  18468. case 4:
  18469. state_str = "processing";
  18470. break;
  18471. case 5:
  18472. state_str = "processed";
  18473. break;
  18474. case 6:
  18475. state_str = "to close";
  18476. break;
  18477. case 7:
  18478. state_str = "closing";
  18479. break;
  18480. case 8:
  18481. state_str = "closed";
  18482. break;
  18483. case 9:
  18484. state_str = "done";
  18485. break;
  18486. }
  18487. #endif
  18488. /* Connection info */
  18489. if ((state >= 3) && (state < 9)) {
  18490. mg_snprintf(NULL,
  18491. NULL,
  18492. block,
  18493. sizeof(block),
  18494. "%s\"connection\" : {%s"
  18495. "\"remote\" : {%s"
  18496. "\"protocol\" : \"%s\",%s"
  18497. "\"addr\" : \"%s\",%s"
  18498. "\"port\" : %u%s"
  18499. "},%s"
  18500. "\"handled_requests\" : %u%s"
  18501. "}",
  18502. eol,
  18503. eol,
  18504. eol,
  18505. get_proto_name(conn),
  18506. eol,
  18507. ri->remote_addr,
  18508. eol,
  18509. ri->remote_port,
  18510. eol,
  18511. eol,
  18512. conn->handled_requests,
  18513. eol);
  18514. connection_info_length += mg_str_append(&buffer, end, block);
  18515. }
  18516. /* Request info */
  18517. if ((state >= 4) && (state < 6)) {
  18518. mg_snprintf(NULL,
  18519. NULL,
  18520. block,
  18521. sizeof(block),
  18522. "%s%s\"request_info\" : {%s"
  18523. "\"method\" : \"%s\",%s"
  18524. "\"uri\" : \"%s\",%s"
  18525. "\"query\" : %s%s%s%s"
  18526. "}",
  18527. (connection_info_length > 1 ? "," : ""),
  18528. eol,
  18529. eol,
  18530. ri->request_method,
  18531. eol,
  18532. ri->request_uri,
  18533. eol,
  18534. ri->query_string ? "\"" : "",
  18535. ri->query_string ? ri->query_string : "null",
  18536. ri->query_string ? "\"" : "",
  18537. eol);
  18538. connection_info_length += mg_str_append(&buffer, end, block);
  18539. }
  18540. /* Execution time information */
  18541. if ((state >= 2) && (state < 9)) {
  18542. char start_time_str[64] = {0};
  18543. char close_time_str[64] = {0};
  18544. time_t start_time = conn->conn_birth_time;
  18545. time_t close_time = 0;
  18546. double time_diff;
  18547. gmt_time_string(start_time_str,
  18548. sizeof(start_time_str) - 1,
  18549. &start_time);
  18550. #if defined(USE_SERVER_STATS)
  18551. close_time = conn->conn_close_time;
  18552. #endif
  18553. if (close_time != 0) {
  18554. time_diff = difftime(close_time, start_time);
  18555. gmt_time_string(close_time_str,
  18556. sizeof(close_time_str) - 1,
  18557. &close_time);
  18558. } else {
  18559. time_t now = time(NULL);
  18560. time_diff = difftime(now, start_time);
  18561. close_time_str[0] = 0; /* or use "now" ? */
  18562. }
  18563. mg_snprintf(NULL,
  18564. NULL,
  18565. block,
  18566. sizeof(block),
  18567. "%s%s\"time\" : {%s"
  18568. "\"uptime\" : %.0f,%s"
  18569. "\"start\" : \"%s\",%s"
  18570. "\"closed\" : \"%s\"%s"
  18571. "}",
  18572. (connection_info_length > 1 ? "," : ""),
  18573. eol,
  18574. eol,
  18575. time_diff,
  18576. eol,
  18577. start_time_str,
  18578. eol,
  18579. close_time_str,
  18580. eol);
  18581. connection_info_length += mg_str_append(&buffer, end, block);
  18582. }
  18583. /* Remote user name */
  18584. if ((ri->remote_user) && (state < 9)) {
  18585. mg_snprintf(NULL,
  18586. NULL,
  18587. block,
  18588. sizeof(block),
  18589. "%s%s\"user\" : {%s"
  18590. "\"name\" : \"%s\",%s"
  18591. "}",
  18592. (connection_info_length > 1 ? "," : ""),
  18593. eol,
  18594. eol,
  18595. ri->remote_user,
  18596. eol);
  18597. connection_info_length += mg_str_append(&buffer, end, block);
  18598. }
  18599. /* Data block */
  18600. if (state >= 3) {
  18601. mg_snprintf(NULL,
  18602. NULL,
  18603. block,
  18604. sizeof(block),
  18605. "%s%s\"data\" : {%s"
  18606. "\"read\" : %" INT64_FMT ",%s"
  18607. "\"written\" : %" INT64_FMT "%s"
  18608. "}",
  18609. (connection_info_length > 1 ? "," : ""),
  18610. eol,
  18611. eol,
  18612. conn->consumed_content,
  18613. eol,
  18614. conn->num_bytes_sent,
  18615. eol);
  18616. connection_info_length += mg_str_append(&buffer, end, block);
  18617. }
  18618. /* State */
  18619. mg_snprintf(NULL,
  18620. NULL,
  18621. block,
  18622. sizeof(block),
  18623. "%s%s\"state\" : \"%s\"",
  18624. (connection_info_length > 1 ? "," : ""),
  18625. eol,
  18626. state_str);
  18627. connection_info_length += mg_str_append(&buffer, end, block);
  18628. /* Terminate string */
  18629. if (append_eoobj) {
  18630. strcat(append_eoobj, eoobj);
  18631. }
  18632. connection_info_length += sizeof(eoobj) - 1;
  18633. return (int)connection_info_length;
  18634. }
  18635. #endif
  18636. /* Initialize this library. This function does not need to be thread safe.
  18637. */
  18638. unsigned
  18639. mg_init_library(unsigned features)
  18640. {
  18641. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18642. unsigned features_inited = features_to_init;
  18643. if (mg_init_library_called <= 0) {
  18644. /* Not initialized yet */
  18645. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18646. return 0;
  18647. }
  18648. }
  18649. mg_global_lock();
  18650. if (mg_init_library_called <= 0) {
  18651. #if defined(_WIN32)
  18652. int file_mutex_init = 1;
  18653. int wsa = 1;
  18654. #else
  18655. int mutexattr_init = 1;
  18656. #endif
  18657. int failed = 1;
  18658. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18659. if (key_create == 0) {
  18660. #if defined(_WIN32)
  18661. file_mutex_init =
  18662. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18663. if (file_mutex_init == 0) {
  18664. /* Start WinSock */
  18665. WSADATA data;
  18666. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18667. }
  18668. #else
  18669. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18670. if (mutexattr_init == 0) {
  18671. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18672. PTHREAD_MUTEX_RECURSIVE);
  18673. }
  18674. #endif
  18675. }
  18676. if (failed) {
  18677. #if defined(_WIN32)
  18678. if (wsa == 0) {
  18679. (void)WSACleanup();
  18680. }
  18681. if (file_mutex_init == 0) {
  18682. (void)pthread_mutex_destroy(&global_log_file_lock);
  18683. }
  18684. #else
  18685. if (mutexattr_init == 0) {
  18686. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18687. }
  18688. #endif
  18689. if (key_create == 0) {
  18690. (void)pthread_key_delete(sTlsKey);
  18691. }
  18692. mg_global_unlock();
  18693. (void)pthread_mutex_destroy(&global_lock_mutex);
  18694. return 0;
  18695. }
  18696. #if defined(USE_LUA)
  18697. lua_init_optional_libraries();
  18698. #endif
  18699. }
  18700. mg_global_unlock();
  18701. #if !defined(NO_SSL)
  18702. if (features_to_init & MG_FEATURES_SSL) {
  18703. if (!mg_ssl_initialized) {
  18704. char ebuf[128];
  18705. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18706. mg_ssl_initialized = 1;
  18707. } else {
  18708. (void)ebuf;
  18709. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18710. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18711. }
  18712. } else {
  18713. /* ssl already initialized */
  18714. }
  18715. }
  18716. #endif
  18717. mg_global_lock();
  18718. if (mg_init_library_called <= 0) {
  18719. mg_init_library_called = 1;
  18720. } else {
  18721. mg_init_library_called++;
  18722. }
  18723. mg_global_unlock();
  18724. return features_inited;
  18725. }
  18726. /* Un-initialize this library. */
  18727. unsigned
  18728. mg_exit_library(void)
  18729. {
  18730. if (mg_init_library_called <= 0) {
  18731. return 0;
  18732. }
  18733. mg_global_lock();
  18734. mg_init_library_called--;
  18735. if (mg_init_library_called == 0) {
  18736. #if !defined(NO_SSL)
  18737. if (mg_ssl_initialized) {
  18738. uninitialize_ssl();
  18739. mg_ssl_initialized = 0;
  18740. }
  18741. #endif
  18742. #if defined(_WIN32)
  18743. (void)WSACleanup();
  18744. (void)pthread_mutex_destroy(&global_log_file_lock);
  18745. #else
  18746. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18747. #endif
  18748. (void)pthread_key_delete(sTlsKey);
  18749. #if defined(USE_LUA)
  18750. lua_exit_optional_libraries();
  18751. #endif
  18752. mg_global_unlock();
  18753. (void)pthread_mutex_destroy(&global_lock_mutex);
  18754. return 1;
  18755. }
  18756. mg_global_unlock();
  18757. return 1;
  18758. }
  18759. /* End of civetweb.c */