civetweb.c 577 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478
  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. #if defined(USE_MBEDTLS)
  380. #include "mod_mbedtls.inl"
  381. #endif
  382. /********************************************************************/
  383. /* CivetWeb configuration defines */
  384. /********************************************************************/
  385. /* Maximum number of threads that can be configured.
  386. * The number of threads actually created depends on the "num_threads"
  387. * configuration parameter, but this is the upper limit. */
  388. #if !defined(MAX_WORKER_THREADS)
  389. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  390. #endif
  391. /* Timeout interval for select/poll calls.
  392. * The timeouts depend on "*_timeout_ms" configuration values, but long
  393. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  394. * This reduces the time required to stop the server. */
  395. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  396. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  397. #endif
  398. /* Do not try to compress files smaller than this limit. */
  399. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  400. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  401. #endif
  402. #if !defined(PASSWORDS_FILE_NAME)
  403. #define PASSWORDS_FILE_NAME ".htpasswd"
  404. #endif
  405. /* Initial buffer size for all CGI environment variables. In case there is
  406. * not enough space, another block is allocated. */
  407. #if !defined(CGI_ENVIRONMENT_SIZE)
  408. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  409. #endif
  410. /* Maximum number of environment variables. */
  411. #if !defined(MAX_CGI_ENVIR_VARS)
  412. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  413. #endif
  414. /* General purpose buffer size. */
  415. #if !defined(MG_BUF_LEN) /* in bytes */
  416. #define MG_BUF_LEN (1024 * 8)
  417. #endif
  418. /********************************************************************/
  419. /* Helper makros */
  420. #if !defined(ARRAY_SIZE)
  421. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  422. #endif
  423. #include <stdint.h>
  424. /* Standard defines */
  425. #if !defined(INT64_MAX)
  426. #define INT64_MAX (9223372036854775807)
  427. #endif
  428. #define SHUTDOWN_RD (0)
  429. #define SHUTDOWN_WR (1)
  430. #define SHUTDOWN_BOTH (2)
  431. mg_static_assert(MAX_WORKER_THREADS >= 1,
  432. "worker threads must be a positive number");
  433. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  434. "size_t data type size check");
  435. #if defined(_WIN32) /* WINDOWS include block */
  436. #include <malloc.h> /* *alloc( */
  437. #include <stdlib.h> /* *alloc( */
  438. #include <time.h> /* struct timespec */
  439. #include <windows.h>
  440. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  441. #include <ws2tcpip.h>
  442. typedef const char *SOCK_OPT_TYPE;
  443. #if !defined(PATH_MAX)
  444. #define W_PATH_MAX (MAX_PATH)
  445. /* at most three UTF-8 chars per wchar_t */
  446. #define PATH_MAX (W_PATH_MAX * 3)
  447. #else
  448. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  449. #endif
  450. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  451. #if !defined(_IN_PORT_T)
  452. #if !defined(in_port_t)
  453. #define in_port_t u_short
  454. #endif
  455. #endif
  456. #if !defined(_WIN32_WCE)
  457. #include <direct.h>
  458. #include <io.h>
  459. #include <process.h>
  460. #else /* _WIN32_WCE */
  461. #define NO_CGI /* WinCE has no pipes */
  462. #define NO_POPEN /* WinCE has no popen */
  463. typedef long off_t;
  464. #define errno ((int)(GetLastError()))
  465. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  466. #endif /* _WIN32_WCE */
  467. #define MAKEUQUAD(lo, hi) \
  468. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  469. #define RATE_DIFF (10000000) /* 100 nsecs */
  470. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  471. #define SYS2UNIX_TIME(lo, hi) \
  472. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  473. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  474. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  475. * Also use _strtoui64 on modern M$ compilers */
  476. #if defined(_MSC_VER)
  477. #if (_MSC_VER < 1300)
  478. #define STRX(x) #x
  479. #define STR(x) STRX(x)
  480. #define __func__ __FILE__ ":" STR(__LINE__)
  481. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  482. #define strtoll(x, y, z) (_atoi64(x))
  483. #else
  484. #define __func__ __FUNCTION__
  485. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  486. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  487. #endif
  488. #endif /* _MSC_VER */
  489. #define ERRNO ((int)(GetLastError()))
  490. #define NO_SOCKLEN_T
  491. #if defined(_WIN64) || defined(__MINGW64__)
  492. #if !defined(SSL_LIB)
  493. #if defined(OPENSSL_API_1_1)
  494. #define SSL_LIB "libssl-1_1-x64.dll"
  495. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  496. #endif /* OPENSSL_API_1_1 */
  497. #if defined(OPENSSL_API_1_0)
  498. #define SSL_LIB "ssleay64.dll"
  499. #define CRYPTO_LIB "libeay64.dll"
  500. #endif /* OPENSSL_API_1_0 */
  501. #endif
  502. #else /* defined(_WIN64) || defined(__MINGW64__) */
  503. #if !defined(SSL_LIB)
  504. #if defined(OPENSSL_API_1_1)
  505. #define SSL_LIB "libssl-1_1.dll"
  506. #define CRYPTO_LIB "libcrypto-1_1.dll"
  507. #endif /* OPENSSL_API_1_1 */
  508. #if defined(OPENSSL_API_1_0)
  509. #define SSL_LIB "ssleay32.dll"
  510. #define CRYPTO_LIB "libeay32.dll"
  511. #endif /* OPENSSL_API_1_0 */
  512. #endif /* SSL_LIB */
  513. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  514. #define O_NONBLOCK (0)
  515. #if !defined(W_OK)
  516. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  517. #endif
  518. #define _POSIX_
  519. #define INT64_FMT "I64d"
  520. #define UINT64_FMT "I64u"
  521. #define WINCDECL __cdecl
  522. #define vsnprintf_impl _vsnprintf
  523. #define access _access
  524. #define mg_sleep(x) (Sleep(x))
  525. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  526. #if !defined(popen)
  527. #define popen(x, y) (_popen(x, y))
  528. #endif
  529. #if !defined(pclose)
  530. #define pclose(x) (_pclose(x))
  531. #endif
  532. #define close(x) (_close(x))
  533. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  534. #define RTLD_LAZY (0)
  535. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  536. #define fdopen(x, y) (_fdopen((x), (y)))
  537. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  538. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  539. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  540. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  541. #define sleep(x) (Sleep((x)*1000))
  542. #define rmdir(x) (_rmdir(x))
  543. #if defined(_WIN64) || !defined(__MINGW32__)
  544. /* Only MinGW 32 bit is missing this function */
  545. #define timegm(x) (_mkgmtime(x))
  546. #else
  547. time_t timegm(struct tm *tm);
  548. #define NEED_TIMEGM
  549. #endif
  550. #if !defined(fileno)
  551. #define fileno(x) (_fileno(x))
  552. #endif /* !fileno MINGW #defines fileno */
  553. typedef struct {
  554. CRITICAL_SECTION sec; /* Immovable */
  555. } pthread_mutex_t;
  556. typedef DWORD pthread_key_t;
  557. typedef HANDLE pthread_t;
  558. typedef struct {
  559. pthread_mutex_t threadIdSec;
  560. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  561. } pthread_cond_t;
  562. #if !defined(__clockid_t_defined)
  563. typedef DWORD clockid_t;
  564. #endif
  565. #if !defined(CLOCK_MONOTONIC)
  566. #define CLOCK_MONOTONIC (1)
  567. #endif
  568. #if !defined(CLOCK_REALTIME)
  569. #define CLOCK_REALTIME (2)
  570. #endif
  571. #if !defined(CLOCK_THREAD)
  572. #define CLOCK_THREAD (3)
  573. #endif
  574. #if !defined(CLOCK_PROCESS)
  575. #define CLOCK_PROCESS (4)
  576. #endif
  577. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  578. #define _TIMESPEC_DEFINED
  579. #endif
  580. #if !defined(_TIMESPEC_DEFINED)
  581. struct timespec {
  582. time_t tv_sec; /* seconds */
  583. long tv_nsec; /* nanoseconds */
  584. };
  585. #endif
  586. #if !defined(WIN_PTHREADS_TIME_H)
  587. #define MUST_IMPLEMENT_CLOCK_GETTIME
  588. #endif
  589. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  590. #define clock_gettime mg_clock_gettime
  591. static int
  592. clock_gettime(clockid_t clk_id, struct timespec *tp)
  593. {
  594. FILETIME ft;
  595. ULARGE_INTEGER li, li2;
  596. BOOL ok = FALSE;
  597. double d;
  598. static double perfcnt_per_sec = 0.0;
  599. static BOOL initialized = FALSE;
  600. if (!initialized) {
  601. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  602. perfcnt_per_sec = 1.0 / li.QuadPart;
  603. initialized = TRUE;
  604. }
  605. if (tp) {
  606. memset(tp, 0, sizeof(*tp));
  607. if (clk_id == CLOCK_REALTIME) {
  608. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  609. GetSystemTimeAsFileTime(&ft);
  610. li.LowPart = ft.dwLowDateTime;
  611. li.HighPart = ft.dwHighDateTime;
  612. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  613. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  614. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  615. ok = TRUE;
  616. /* END: CLOCK_REALTIME */
  617. } else if (clk_id == CLOCK_MONOTONIC) {
  618. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  619. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  620. d = li.QuadPart * perfcnt_per_sec;
  621. tp->tv_sec = (time_t)d;
  622. d -= (double)tp->tv_sec;
  623. tp->tv_nsec = (long)(d * 1.0E9);
  624. ok = TRUE;
  625. /* END: CLOCK_MONOTONIC */
  626. } else if (clk_id == CLOCK_THREAD) {
  627. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  628. FILETIME t_create, t_exit, t_kernel, t_user;
  629. if (GetThreadTimes(GetCurrentThread(),
  630. &t_create,
  631. &t_exit,
  632. &t_kernel,
  633. &t_user)) {
  634. li.LowPart = t_user.dwLowDateTime;
  635. li.HighPart = t_user.dwHighDateTime;
  636. li2.LowPart = t_kernel.dwLowDateTime;
  637. li2.HighPart = t_kernel.dwHighDateTime;
  638. li.QuadPart += li2.QuadPart;
  639. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  640. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  641. ok = TRUE;
  642. }
  643. /* END: CLOCK_THREAD */
  644. } else if (clk_id == CLOCK_PROCESS) {
  645. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  646. FILETIME t_create, t_exit, t_kernel, t_user;
  647. if (GetProcessTimes(GetCurrentProcess(),
  648. &t_create,
  649. &t_exit,
  650. &t_kernel,
  651. &t_user)) {
  652. li.LowPart = t_user.dwLowDateTime;
  653. li.HighPart = t_user.dwHighDateTime;
  654. li2.LowPart = t_kernel.dwLowDateTime;
  655. li2.HighPart = t_kernel.dwHighDateTime;
  656. li.QuadPart += li2.QuadPart;
  657. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  658. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  659. ok = TRUE;
  660. }
  661. /* END: CLOCK_PROCESS */
  662. } else {
  663. /* BEGIN: unknown clock */
  664. /* ok = FALSE; already set by init */
  665. /* END: unknown clock */
  666. }
  667. }
  668. return ok ? 0 : -1;
  669. }
  670. #endif
  671. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  672. static int pthread_mutex_lock(pthread_mutex_t *);
  673. static int pthread_mutex_unlock(pthread_mutex_t *);
  674. static void path_to_unicode(const struct mg_connection *conn,
  675. const char *path,
  676. wchar_t *wbuf,
  677. size_t wbuf_len);
  678. /* All file operations need to be rewritten to solve #246. */
  679. struct mg_file;
  680. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  681. /* POSIX dirent interface */
  682. struct dirent {
  683. char d_name[PATH_MAX];
  684. };
  685. typedef struct DIR {
  686. HANDLE handle;
  687. WIN32_FIND_DATAW info;
  688. struct dirent result;
  689. } DIR;
  690. #if defined(HAVE_POLL)
  691. #define mg_pollfd pollfd
  692. #else
  693. struct mg_pollfd {
  694. SOCKET fd;
  695. short events;
  696. short revents;
  697. };
  698. #endif
  699. /* Mark required libraries */
  700. #if defined(_MSC_VER)
  701. #pragma comment(lib, "Ws2_32.lib")
  702. #endif
  703. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  704. #include <inttypes.h>
  705. typedef const void *SOCK_OPT_TYPE;
  706. #if defined(ANDROID)
  707. typedef unsigned short int in_port_t;
  708. #endif
  709. #if !defined(__ZEPHYR__)
  710. #include <arpa/inet.h>
  711. #include <ctype.h>
  712. #include <dirent.h>
  713. #include <grp.h>
  714. #include <limits.h>
  715. #include <netdb.h>
  716. #include <netinet/in.h>
  717. #include <netinet/tcp.h>
  718. #include <pthread.h>
  719. #include <pwd.h>
  720. #include <stdarg.h>
  721. #include <stddef.h>
  722. #include <stdio.h>
  723. #include <stdlib.h>
  724. #include <string.h>
  725. #include <sys/poll.h>
  726. #include <sys/socket.h>
  727. #include <sys/time.h>
  728. #include <sys/utsname.h>
  729. #include <sys/wait.h>
  730. #include <time.h>
  731. #include <unistd.h>
  732. #endif
  733. #define vsnprintf_impl vsnprintf
  734. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  735. #include <dlfcn.h>
  736. #endif
  737. #if defined(__MACH__)
  738. #define SSL_LIB "libssl.dylib"
  739. #define CRYPTO_LIB "libcrypto.dylib"
  740. #else
  741. #if !defined(SSL_LIB)
  742. #define SSL_LIB "libssl.so"
  743. #endif
  744. #if !defined(CRYPTO_LIB)
  745. #define CRYPTO_LIB "libcrypto.so"
  746. #endif
  747. #endif
  748. #if !defined(O_BINARY)
  749. #define O_BINARY (0)
  750. #endif /* O_BINARY */
  751. #define closesocket(a) (close(a))
  752. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  753. #define mg_remove(conn, x) (remove(x))
  754. #define mg_sleep(x) (usleep((x)*1000))
  755. #define mg_opendir(conn, x) (opendir(x))
  756. #define mg_closedir(x) (closedir(x))
  757. #define mg_readdir(x) (readdir(x))
  758. #define ERRNO (errno)
  759. #define INVALID_SOCKET (-1)
  760. #define INT64_FMT PRId64
  761. #define UINT64_FMT PRIu64
  762. typedef int SOCKET;
  763. #define WINCDECL
  764. #if defined(__hpux)
  765. /* HPUX 11 does not have monotonic, fall back to realtime */
  766. #if !defined(CLOCK_MONOTONIC)
  767. #define CLOCK_MONOTONIC CLOCK_REALTIME
  768. #endif
  769. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  770. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  771. * the prototypes use int* rather than socklen_t* which matches the
  772. * actual library expectation. When called with the wrong size arg
  773. * accept() returns a zero client inet addr and check_acl() always
  774. * fails. Since socklen_t is widely used below, just force replace
  775. * their typedef with int. - DTL
  776. */
  777. #define socklen_t int
  778. #endif /* hpux */
  779. #define mg_pollfd pollfd
  780. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  781. /* In case our C library is missing "timegm", provide an implementation */
  782. #if defined(NEED_TIMEGM)
  783. static inline int
  784. is_leap(int y)
  785. {
  786. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  787. }
  788. static inline int
  789. count_leap(int y)
  790. {
  791. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  792. }
  793. time_t
  794. timegm(struct tm *tm)
  795. {
  796. static const unsigned short ydays[] = {
  797. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  798. int year = tm->tm_year + 1900;
  799. int mon = tm->tm_mon;
  800. int mday = tm->tm_mday - 1;
  801. int hour = tm->tm_hour;
  802. int min = tm->tm_min;
  803. int sec = tm->tm_sec;
  804. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  805. || (mday >= ydays[mon + 1] - ydays[mon]
  806. + (mon == 1 && is_leap(year) ? 1 : 0))
  807. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  808. return -1;
  809. time_t res = year - 1970;
  810. res *= 365;
  811. res += mday;
  812. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  813. res += count_leap(year);
  814. res *= 24;
  815. res += hour;
  816. res *= 60;
  817. res += min;
  818. res *= 60;
  819. res += sec;
  820. return res;
  821. }
  822. #endif /* NEED_TIMEGM */
  823. /* va_copy should always be a macro, C99 and C++11 - DTL */
  824. #if !defined(va_copy)
  825. #define va_copy(x, y) ((x) = (y))
  826. #endif
  827. #if defined(_WIN32)
  828. /* Create substitutes for POSIX functions in Win32. */
  829. #if defined(GCC_DIAGNOSTIC)
  830. /* Show no warning in case system functions are not used. */
  831. #pragma GCC diagnostic push
  832. #pragma GCC diagnostic ignored "-Wunused-function"
  833. #endif
  834. static pthread_mutex_t global_log_file_lock;
  835. FUNCTION_MAY_BE_UNUSED
  836. static DWORD
  837. pthread_self(void)
  838. {
  839. return GetCurrentThreadId();
  840. }
  841. FUNCTION_MAY_BE_UNUSED
  842. static int
  843. pthread_key_create(
  844. pthread_key_t *key,
  845. void (*_ignored)(void *) /* destructor not supported for Windows */
  846. )
  847. {
  848. (void)_ignored;
  849. if ((key != 0)) {
  850. *key = TlsAlloc();
  851. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  852. }
  853. return -2;
  854. }
  855. FUNCTION_MAY_BE_UNUSED
  856. static int
  857. pthread_key_delete(pthread_key_t key)
  858. {
  859. return TlsFree(key) ? 0 : 1;
  860. }
  861. FUNCTION_MAY_BE_UNUSED
  862. static int
  863. pthread_setspecific(pthread_key_t key, void *value)
  864. {
  865. return TlsSetValue(key, value) ? 0 : 1;
  866. }
  867. FUNCTION_MAY_BE_UNUSED
  868. static void *
  869. pthread_getspecific(pthread_key_t key)
  870. {
  871. return TlsGetValue(key);
  872. }
  873. #if defined(GCC_DIAGNOSTIC)
  874. /* Enable unused function warning again */
  875. #pragma GCC diagnostic pop
  876. #endif
  877. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  878. #else
  879. static pthread_mutexattr_t pthread_mutex_attr;
  880. #endif /* _WIN32 */
  881. #if defined(_WIN32_WCE)
  882. /* Create substitutes for POSIX functions in Win32. */
  883. #if defined(GCC_DIAGNOSTIC)
  884. /* Show no warning in case system functions are not used. */
  885. #pragma GCC diagnostic push
  886. #pragma GCC diagnostic ignored "-Wunused-function"
  887. #endif
  888. FUNCTION_MAY_BE_UNUSED
  889. static time_t
  890. time(time_t *ptime)
  891. {
  892. time_t t;
  893. SYSTEMTIME st;
  894. FILETIME ft;
  895. GetSystemTime(&st);
  896. SystemTimeToFileTime(&st, &ft);
  897. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  898. if (ptime != NULL) {
  899. *ptime = t;
  900. }
  901. return t;
  902. }
  903. FUNCTION_MAY_BE_UNUSED
  904. static struct tm *
  905. localtime_s(const time_t *ptime, struct tm *ptm)
  906. {
  907. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  908. FILETIME ft, lft;
  909. SYSTEMTIME st;
  910. TIME_ZONE_INFORMATION tzinfo;
  911. if (ptm == NULL) {
  912. return NULL;
  913. }
  914. *(int64_t *)&ft = t;
  915. FileTimeToLocalFileTime(&ft, &lft);
  916. FileTimeToSystemTime(&lft, &st);
  917. ptm->tm_year = st.wYear - 1900;
  918. ptm->tm_mon = st.wMonth - 1;
  919. ptm->tm_wday = st.wDayOfWeek;
  920. ptm->tm_mday = st.wDay;
  921. ptm->tm_hour = st.wHour;
  922. ptm->tm_min = st.wMinute;
  923. ptm->tm_sec = st.wSecond;
  924. ptm->tm_yday = 0; /* hope nobody uses this */
  925. ptm->tm_isdst =
  926. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  927. return ptm;
  928. }
  929. FUNCTION_MAY_BE_UNUSED
  930. static struct tm *
  931. gmtime_s(const time_t *ptime, struct tm *ptm)
  932. {
  933. /* FIXME(lsm): fix this. */
  934. return localtime_s(ptime, ptm);
  935. }
  936. static ptrdiff_t mg_atomic_inc(volatile ptrdiff_t *addr);
  937. static struct tm tm_array[MAX_WORKER_THREADS]; /* Must be 2^n */
  938. static volatile ptrdiff_t tm_index = 0;
  939. FUNCTION_MAY_BE_UNUSED
  940. static struct tm *
  941. localtime(const time_t *ptime)
  942. {
  943. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  944. return localtime_s(ptime, tm_array + i);
  945. }
  946. FUNCTION_MAY_BE_UNUSED
  947. static struct tm *
  948. gmtime(const time_t *ptime)
  949. {
  950. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  951. return gmtime_s(ptime, tm_array + i);
  952. }
  953. FUNCTION_MAY_BE_UNUSED
  954. static size_t
  955. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  956. {
  957. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  958. * for WinCE"); */
  959. return 0;
  960. }
  961. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  962. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  963. #define remove(f) mg_remove(NULL, f)
  964. FUNCTION_MAY_BE_UNUSED
  965. static int
  966. rename(const char *a, const char *b)
  967. {
  968. wchar_t wa[W_PATH_MAX];
  969. wchar_t wb[W_PATH_MAX];
  970. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  971. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  972. return MoveFileW(wa, wb) ? 0 : -1;
  973. }
  974. struct stat {
  975. int64_t st_size;
  976. time_t st_mtime;
  977. };
  978. FUNCTION_MAY_BE_UNUSED
  979. static int
  980. stat(const char *name, struct stat *st)
  981. {
  982. wchar_t wbuf[W_PATH_MAX];
  983. WIN32_FILE_ATTRIBUTE_DATA attr;
  984. time_t creation_time, write_time;
  985. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  986. memset(&attr, 0, sizeof(attr));
  987. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  988. st->st_size =
  989. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  990. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  991. attr.ftLastWriteTime.dwHighDateTime);
  992. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  993. attr.ftCreationTime.dwHighDateTime);
  994. if (creation_time > write_time) {
  995. st->st_mtime = creation_time;
  996. } else {
  997. st->st_mtime = write_time;
  998. }
  999. return 0;
  1000. }
  1001. #define access(x, a) 1 /* not required anyway */
  1002. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  1003. /* Values from errno.h in Windows SDK (Visual Studio). */
  1004. #define EEXIST 17
  1005. #define EACCES 13
  1006. #define ENOENT 2
  1007. #if defined(GCC_DIAGNOSTIC)
  1008. /* Enable unused function warning again */
  1009. #pragma GCC diagnostic pop
  1010. #endif
  1011. #endif /* defined(_WIN32_WCE) */
  1012. #if defined(GCC_DIAGNOSTIC)
  1013. /* Show no warning in case system functions are not used. */
  1014. #pragma GCC diagnostic push
  1015. #pragma GCC diagnostic ignored "-Wunused-function"
  1016. #endif /* defined(GCC_DIAGNOSTIC) */
  1017. #if defined(__clang__)
  1018. /* Show no warning in case system functions are not used. */
  1019. #pragma clang diagnostic push
  1020. #pragma clang diagnostic ignored "-Wunused-function"
  1021. #endif
  1022. static pthread_mutex_t global_lock_mutex;
  1023. FUNCTION_MAY_BE_UNUSED
  1024. static void
  1025. mg_global_lock(void)
  1026. {
  1027. (void)pthread_mutex_lock(&global_lock_mutex);
  1028. }
  1029. FUNCTION_MAY_BE_UNUSED
  1030. static void
  1031. mg_global_unlock(void)
  1032. {
  1033. (void)pthread_mutex_unlock(&global_lock_mutex);
  1034. }
  1035. #if defined(_WIN64)
  1036. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  1037. #elif defined(_WIN32)
  1038. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  1039. #endif
  1040. /* Atomic functions working on ptrdiff_t ("signed size_t").
  1041. * Operations: Increment, Decrement, Add, Maximum.
  1042. * Up to size_t, they do not an atomic "load" operation.
  1043. */
  1044. FUNCTION_MAY_BE_UNUSED
  1045. static ptrdiff_t
  1046. mg_atomic_inc(volatile ptrdiff_t *addr)
  1047. {
  1048. ptrdiff_t ret;
  1049. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1050. ret = InterlockedIncrement64(addr);
  1051. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1052. ret = InterlockedIncrement(addr);
  1053. #elif defined(__GNUC__) \
  1054. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1055. && !defined(NO_ATOMICS)
  1056. ret = __sync_add_and_fetch(addr, 1);
  1057. #else
  1058. mg_global_lock();
  1059. ret = (++(*addr));
  1060. mg_global_unlock();
  1061. #endif
  1062. return ret;
  1063. }
  1064. FUNCTION_MAY_BE_UNUSED
  1065. static ptrdiff_t
  1066. mg_atomic_dec(volatile ptrdiff_t *addr)
  1067. {
  1068. ptrdiff_t ret;
  1069. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1070. ret = InterlockedDecrement64(addr);
  1071. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1072. ret = InterlockedDecrement(addr);
  1073. #elif defined(__GNUC__) \
  1074. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1075. && !defined(NO_ATOMICS)
  1076. ret = __sync_sub_and_fetch(addr, 1);
  1077. #else
  1078. mg_global_lock();
  1079. ret = (--(*addr));
  1080. mg_global_unlock();
  1081. #endif
  1082. return ret;
  1083. }
  1084. #if defined(USE_SERVER_STATS)
  1085. static ptrdiff_t
  1086. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1087. {
  1088. ptrdiff_t ret;
  1089. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1090. ret = InterlockedAdd64(addr, value);
  1091. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1092. ret = InterlockedExchangeAdd(addr, value) + value;
  1093. #elif defined(__GNUC__) \
  1094. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1095. && !defined(NO_ATOMICS)
  1096. ret = __sync_add_and_fetch(addr, value);
  1097. #else
  1098. mg_global_lock();
  1099. *addr += value;
  1100. ret = (*addr);
  1101. mg_global_unlock();
  1102. #endif
  1103. return ret;
  1104. }
  1105. FUNCTION_MAY_BE_UNUSED
  1106. static ptrdiff_t
  1107. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1108. ptrdiff_t oldval,
  1109. ptrdiff_t newval)
  1110. {
  1111. ptrdiff_t ret;
  1112. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1113. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1114. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1115. ret = InterlockedCompareExchange(addr, newval, oldval);
  1116. #elif defined(__GNUC__) \
  1117. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1118. && !defined(NO_ATOMICS)
  1119. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1120. #else
  1121. mg_global_lock();
  1122. ret = *addr;
  1123. if ((ret != newval) && (ret == oldval)) {
  1124. *addr = newval;
  1125. }
  1126. mg_global_unlock();
  1127. #endif
  1128. return ret;
  1129. }
  1130. static void
  1131. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1132. {
  1133. register ptrdiff_t tmp = *addr;
  1134. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1135. while (tmp < value) {
  1136. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1137. }
  1138. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1139. while (tmp < value) {
  1140. tmp = InterlockedCompareExchange(addr, value, tmp);
  1141. }
  1142. #elif defined(__GNUC__) \
  1143. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1144. && !defined(NO_ATOMICS)
  1145. while (tmp < value) {
  1146. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1147. }
  1148. #else
  1149. mg_global_lock();
  1150. if (*addr < value) {
  1151. *addr = value;
  1152. }
  1153. mg_global_unlock();
  1154. #endif
  1155. }
  1156. static int64_t
  1157. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1158. {
  1159. int64_t ret;
  1160. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1161. ret = InterlockedAdd64(addr, value);
  1162. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1163. ret = InterlockedExchangeAdd64(addr, value) + value;
  1164. #elif defined(__GNUC__) \
  1165. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1166. && !defined(NO_ATOMICS)
  1167. ret = __sync_add_and_fetch(addr, value);
  1168. #else
  1169. mg_global_lock();
  1170. *addr += value;
  1171. ret = (*addr);
  1172. mg_global_unlock();
  1173. #endif
  1174. return ret;
  1175. }
  1176. #endif
  1177. #if defined(GCC_DIAGNOSTIC)
  1178. /* Show no warning in case system functions are not used. */
  1179. #pragma GCC diagnostic pop
  1180. #endif /* defined(GCC_DIAGNOSTIC) */
  1181. #if defined(__clang__)
  1182. /* Show no warning in case system functions are not used. */
  1183. #pragma clang diagnostic pop
  1184. #endif
  1185. #if defined(USE_SERVER_STATS)
  1186. struct mg_memory_stat {
  1187. volatile ptrdiff_t totalMemUsed;
  1188. volatile ptrdiff_t maxMemUsed;
  1189. volatile ptrdiff_t blockCount;
  1190. };
  1191. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1192. static void *
  1193. mg_malloc_ex(size_t size,
  1194. struct mg_context *ctx,
  1195. const char *file,
  1196. unsigned line)
  1197. {
  1198. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1199. void *memory = 0;
  1200. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1201. #if defined(MEMORY_DEBUGGING)
  1202. char mallocStr[256];
  1203. #else
  1204. (void)file;
  1205. (void)line;
  1206. #endif
  1207. if (data) {
  1208. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1209. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1210. mg_atomic_inc(&mstat->blockCount);
  1211. ((uintptr_t *)data)[0] = size;
  1212. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1213. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1214. }
  1215. #if defined(MEMORY_DEBUGGING)
  1216. sprintf(mallocStr,
  1217. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1218. memory,
  1219. (unsigned long)size,
  1220. (unsigned long)mstat->totalMemUsed,
  1221. (unsigned long)mstat->blockCount,
  1222. file,
  1223. line);
  1224. DEBUG_TRACE("%s", mallocStr);
  1225. #endif
  1226. return memory;
  1227. }
  1228. static void *
  1229. mg_calloc_ex(size_t count,
  1230. size_t size,
  1231. struct mg_context *ctx,
  1232. const char *file,
  1233. unsigned line)
  1234. {
  1235. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1236. if (data) {
  1237. memset(data, 0, size * count);
  1238. }
  1239. return data;
  1240. }
  1241. static void
  1242. mg_free_ex(void *memory, const char *file, unsigned line)
  1243. {
  1244. #if defined(MEMORY_DEBUGGING)
  1245. char mallocStr[256];
  1246. #else
  1247. (void)file;
  1248. (void)line;
  1249. #endif
  1250. if (memory) {
  1251. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1252. uintptr_t size = ((uintptr_t *)data)[0];
  1253. struct mg_memory_stat *mstat =
  1254. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1255. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1256. mg_atomic_dec(&mstat->blockCount);
  1257. #if defined(MEMORY_DEBUGGING)
  1258. sprintf(mallocStr,
  1259. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1260. memory,
  1261. (unsigned long)size,
  1262. (unsigned long)mstat->totalMemUsed,
  1263. (unsigned long)mstat->blockCount,
  1264. file,
  1265. line);
  1266. DEBUG_TRACE("%s", mallocStr);
  1267. #endif
  1268. free(data);
  1269. }
  1270. }
  1271. static void *
  1272. mg_realloc_ex(void *memory,
  1273. size_t newsize,
  1274. struct mg_context *ctx,
  1275. const char *file,
  1276. unsigned line)
  1277. {
  1278. void *data;
  1279. void *_realloc;
  1280. uintptr_t oldsize;
  1281. #if defined(MEMORY_DEBUGGING)
  1282. char mallocStr[256];
  1283. #else
  1284. (void)file;
  1285. (void)line;
  1286. #endif
  1287. if (newsize) {
  1288. if (memory) {
  1289. /* Reallocate existing block */
  1290. struct mg_memory_stat *mstat;
  1291. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1292. oldsize = ((uintptr_t *)data)[0];
  1293. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1294. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1295. if (_realloc) {
  1296. data = _realloc;
  1297. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1298. #if defined(MEMORY_DEBUGGING)
  1299. sprintf(mallocStr,
  1300. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1301. memory,
  1302. (unsigned long)oldsize,
  1303. (unsigned long)mstat->totalMemUsed,
  1304. (unsigned long)mstat->blockCount,
  1305. file,
  1306. line);
  1307. DEBUG_TRACE("%s", mallocStr);
  1308. #endif
  1309. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1310. #if defined(MEMORY_DEBUGGING)
  1311. sprintf(mallocStr,
  1312. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1313. memory,
  1314. (unsigned long)newsize,
  1315. (unsigned long)mstat->totalMemUsed,
  1316. (unsigned long)mstat->blockCount,
  1317. file,
  1318. line);
  1319. DEBUG_TRACE("%s", mallocStr);
  1320. #endif
  1321. *(uintptr_t *)data = newsize;
  1322. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1323. } else {
  1324. #if defined(MEMORY_DEBUGGING)
  1325. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1326. #endif
  1327. return _realloc;
  1328. }
  1329. } else {
  1330. /* Allocate new block */
  1331. data = mg_malloc_ex(newsize, ctx, file, line);
  1332. }
  1333. } else {
  1334. /* Free existing block */
  1335. data = 0;
  1336. mg_free_ex(memory, file, line);
  1337. }
  1338. return data;
  1339. }
  1340. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1341. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1342. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1343. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1344. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1345. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1346. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1347. #else /* USE_SERVER_STATS */
  1348. static __inline void *
  1349. mg_malloc(size_t a)
  1350. {
  1351. return malloc(a);
  1352. }
  1353. static __inline void *
  1354. mg_calloc(size_t a, size_t b)
  1355. {
  1356. return calloc(a, b);
  1357. }
  1358. static __inline void *
  1359. mg_realloc(void *a, size_t b)
  1360. {
  1361. return realloc(a, b);
  1362. }
  1363. static __inline void
  1364. mg_free(void *a)
  1365. {
  1366. free(a);
  1367. }
  1368. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1369. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1370. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1371. #define mg_free_ctx(a, c) mg_free(a)
  1372. #endif /* USE_SERVER_STATS */
  1373. static void mg_vsnprintf(const struct mg_connection *conn,
  1374. int *truncated,
  1375. char *buf,
  1376. size_t buflen,
  1377. const char *fmt,
  1378. va_list ap);
  1379. static void mg_snprintf(const struct mg_connection *conn,
  1380. int *truncated,
  1381. char *buf,
  1382. size_t buflen,
  1383. PRINTF_FORMAT_STRING(const char *fmt),
  1384. ...) PRINTF_ARGS(5, 6);
  1385. /* This following lines are just meant as a reminder to use the mg-functions
  1386. * for memory management */
  1387. #if defined(malloc)
  1388. #undef malloc
  1389. #endif
  1390. #if defined(calloc)
  1391. #undef calloc
  1392. #endif
  1393. #if defined(realloc)
  1394. #undef realloc
  1395. #endif
  1396. #if defined(free)
  1397. #undef free
  1398. #endif
  1399. #if defined(snprintf)
  1400. #undef snprintf
  1401. #endif
  1402. #if defined(vsnprintf)
  1403. #undef vsnprintf
  1404. #endif
  1405. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1406. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1407. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1408. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1409. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1410. #if defined(_WIN32)
  1411. /* vsnprintf must not be used in any system,
  1412. * but this define only works well for Windows. */
  1413. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1414. #endif
  1415. /* mg_init_library counter */
  1416. static int mg_init_library_called = 0;
  1417. #if !defined(NO_SSL)
  1418. static int mg_ssl_initialized = 0;
  1419. /* TODO: Selection of SSL library and version */
  1420. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1)
  1421. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1422. #endif
  1423. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1424. #error "Multiple OPENSSL_API versions defined"
  1425. #endif
  1426. #endif /* NO_SSL */
  1427. static pthread_key_t sTlsKey; /* Thread local storage index */
  1428. static volatile ptrdiff_t thread_idx_max = 0;
  1429. #if defined(MG_LEGACY_INTERFACE)
  1430. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1431. #endif
  1432. struct mg_workerTLS {
  1433. int is_master;
  1434. unsigned long thread_idx;
  1435. void *user_ptr;
  1436. #if defined(_WIN32)
  1437. HANDLE pthread_cond_helper_mutex;
  1438. struct mg_workerTLS *next_waiting_thread;
  1439. #endif
  1440. const char *alpn_proto;
  1441. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1442. char txtbuf[4];
  1443. #endif
  1444. };
  1445. #if defined(GCC_DIAGNOSTIC)
  1446. /* Show no warning in case system functions are not used. */
  1447. #pragma GCC diagnostic push
  1448. #pragma GCC diagnostic ignored "-Wunused-function"
  1449. #endif /* defined(GCC_DIAGNOSTIC) */
  1450. #if defined(__clang__)
  1451. /* Show no warning in case system functions are not used. */
  1452. #pragma clang diagnostic push
  1453. #pragma clang diagnostic ignored "-Wunused-function"
  1454. #endif
  1455. /* Get a unique thread ID as unsigned long, independent from the data type
  1456. * of thread IDs defined by the operating system API.
  1457. * If two calls to mg_current_thread_id return the same value, they calls
  1458. * are done from the same thread. If they return different values, they are
  1459. * done from different threads. (Provided this function is used in the same
  1460. * process context and threads are not repeatedly created and deleted, but
  1461. * CivetWeb does not do that).
  1462. * This function must match the signature required for SSL id callbacks:
  1463. * CRYPTO_set_id_callback
  1464. */
  1465. FUNCTION_MAY_BE_UNUSED
  1466. static unsigned long
  1467. mg_current_thread_id(void)
  1468. {
  1469. #if defined(_WIN32)
  1470. return GetCurrentThreadId();
  1471. #else
  1472. #if defined(__clang__)
  1473. #pragma clang diagnostic push
  1474. #pragma clang diagnostic ignored "-Wunreachable-code"
  1475. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1476. * or not, so one of the two conditions will be unreachable by construction.
  1477. * Unfortunately the C standard does not define a way to check this at
  1478. * compile time, since the #if preprocessor conditions can not use the sizeof
  1479. * operator as an argument. */
  1480. #endif
  1481. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1482. /* This is the problematic case for CRYPTO_set_id_callback:
  1483. * The OS pthread_t can not be cast to unsigned long. */
  1484. struct mg_workerTLS *tls =
  1485. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1486. if (tls == NULL) {
  1487. /* SSL called from an unknown thread: Create some thread index.
  1488. */
  1489. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1490. tls->is_master = -2; /* -2 means "3rd party thread" */
  1491. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1492. pthread_setspecific(sTlsKey, tls);
  1493. }
  1494. return tls->thread_idx;
  1495. } else {
  1496. /* pthread_t may be any data type, so a simple cast to unsigned long
  1497. * can rise a warning/error, depending on the platform.
  1498. * Here memcpy is used as an anything-to-anything cast. */
  1499. unsigned long ret = 0;
  1500. pthread_t t = pthread_self();
  1501. memcpy(&ret, &t, sizeof(pthread_t));
  1502. return ret;
  1503. }
  1504. #if defined(__clang__)
  1505. #pragma clang diagnostic pop
  1506. #endif
  1507. #endif
  1508. }
  1509. FUNCTION_MAY_BE_UNUSED
  1510. static uint64_t
  1511. mg_get_current_time_ns(void)
  1512. {
  1513. struct timespec tsnow;
  1514. clock_gettime(CLOCK_REALTIME, &tsnow);
  1515. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1516. }
  1517. #if defined(GCC_DIAGNOSTIC)
  1518. /* Show no warning in case system functions are not used. */
  1519. #pragma GCC diagnostic pop
  1520. #endif /* defined(GCC_DIAGNOSTIC) */
  1521. #if defined(__clang__)
  1522. /* Show no warning in case system functions are not used. */
  1523. #pragma clang diagnostic pop
  1524. #endif
  1525. #if defined(NEED_DEBUG_TRACE_FUNC)
  1526. static void
  1527. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1528. {
  1529. va_list args;
  1530. struct timespec tsnow;
  1531. /* Get some operating system independent thread id */
  1532. unsigned long thread_id = mg_current_thread_id();
  1533. clock_gettime(CLOCK_REALTIME, &tsnow);
  1534. flockfile(DEBUG_TRACE_STREAM);
  1535. fprintf(DEBUG_TRACE_STREAM,
  1536. "*** %lu.%09lu %lu %s:%u: ",
  1537. (unsigned long)tsnow.tv_sec,
  1538. (unsigned long)tsnow.tv_nsec,
  1539. thread_id,
  1540. func,
  1541. line);
  1542. va_start(args, fmt);
  1543. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1544. va_end(args);
  1545. putc('\n', DEBUG_TRACE_STREAM);
  1546. fflush(DEBUG_TRACE_STREAM);
  1547. funlockfile(DEBUG_TRACE_STREAM);
  1548. }
  1549. #endif /* NEED_DEBUG_TRACE_FUNC */
  1550. #define MD5_STATIC static
  1551. #include "md5.inl"
  1552. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1553. #if defined(NO_SOCKLEN_T)
  1554. typedef int socklen_t;
  1555. #endif /* NO_SOCKLEN_T */
  1556. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1557. #if !defined(MSG_NOSIGNAL)
  1558. #define MSG_NOSIGNAL (0)
  1559. #endif
  1560. #if defined(NO_SSL)
  1561. #if !defined(USE_MBEDTLS)
  1562. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1563. typedef struct SSL_CTX SSL_CTX;
  1564. #endif
  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. };
  2108. #if defined(USE_IPV6)
  2109. #define USA_IN_PORT_UNSAFE(s) \
  2110. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  2111. #else
  2112. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  2113. #endif
  2114. /* Describes a string (chunk of memory). */
  2115. struct vec {
  2116. const char *ptr;
  2117. size_t len;
  2118. };
  2119. struct mg_file_stat {
  2120. /* File properties filled by mg_stat: */
  2121. uint64_t size;
  2122. time_t last_modified;
  2123. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2124. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2125. * case we need a "Content-Eencoding: gzip" header */
  2126. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2127. };
  2128. struct mg_file_access {
  2129. /* File properties filled by mg_fopen: */
  2130. FILE *fp;
  2131. };
  2132. struct mg_file {
  2133. struct mg_file_stat stat;
  2134. struct mg_file_access access;
  2135. };
  2136. #define STRUCT_FILE_INITIALIZER \
  2137. { \
  2138. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2139. { \
  2140. (FILE *)NULL \
  2141. } \
  2142. }
  2143. /* Describes listening socket, or socket which was accept()-ed by the master
  2144. * thread and queued for future handling by the worker thread. */
  2145. struct socket {
  2146. SOCKET sock; /* Listening socket */
  2147. union usa lsa; /* Local socket address */
  2148. union usa rsa; /* Remote socket address */
  2149. unsigned char is_ssl; /* Is port SSL-ed */
  2150. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2151. * port */
  2152. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2153. };
  2154. /* Enum const for all options must be in sync with
  2155. * static struct mg_option config_options[]
  2156. * This is tested in the unit test (test/private.c)
  2157. * "Private Config Options"
  2158. */
  2159. enum {
  2160. /* Once for each server */
  2161. LISTENING_PORTS,
  2162. NUM_THREADS,
  2163. RUN_AS_USER,
  2164. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2165. * socket option typedef TCP_NODELAY. */
  2166. MAX_REQUEST_SIZE,
  2167. LINGER_TIMEOUT,
  2168. CONNECTION_QUEUE_SIZE,
  2169. LISTEN_BACKLOG_SIZE,
  2170. #if defined(__linux__)
  2171. ALLOW_SENDFILE_CALL,
  2172. #endif
  2173. #if defined(_WIN32)
  2174. CASE_SENSITIVE_FILES,
  2175. #endif
  2176. THROTTLE,
  2177. ACCESS_LOG_FILE,
  2178. ERROR_LOG_FILE,
  2179. ENABLE_KEEP_ALIVE,
  2180. REQUEST_TIMEOUT,
  2181. KEEP_ALIVE_TIMEOUT,
  2182. #if defined(USE_WEBSOCKET)
  2183. WEBSOCKET_TIMEOUT,
  2184. ENABLE_WEBSOCKET_PING_PONG,
  2185. #endif
  2186. DECODE_URL,
  2187. #if defined(USE_LUA)
  2188. LUA_BACKGROUND_SCRIPT,
  2189. LUA_BACKGROUND_SCRIPT_PARAMS,
  2190. #endif
  2191. #if defined(USE_HTTP2)
  2192. ENABLE_HTTP2,
  2193. #endif
  2194. /* Once for each domain */
  2195. DOCUMENT_ROOT,
  2196. CGI_EXTENSIONS,
  2197. CGI2_EXTENSIONS,
  2198. CGI_ENVIRONMENT,
  2199. CGI2_ENVIRONMENT,
  2200. CGI_INTERPRETER,
  2201. CGI2_INTERPRETER,
  2202. CGI_INTERPRETER_ARGS,
  2203. CGI2_INTERPRETER_ARGS,
  2204. #if defined(USE_TIMERS)
  2205. CGI_TIMEOUT,
  2206. CGI2_TIMEOUT,
  2207. #endif
  2208. PUT_DELETE_PASSWORDS_FILE,
  2209. PROTECT_URI,
  2210. AUTHENTICATION_DOMAIN,
  2211. ENABLE_AUTH_DOMAIN_CHECK,
  2212. SSI_EXTENSIONS,
  2213. ENABLE_DIRECTORY_LISTING,
  2214. GLOBAL_PASSWORDS_FILE,
  2215. INDEX_FILES,
  2216. ACCESS_CONTROL_LIST,
  2217. EXTRA_MIME_TYPES,
  2218. SSL_CERTIFICATE,
  2219. SSL_CERTIFICATE_CHAIN,
  2220. URL_REWRITE_PATTERN,
  2221. HIDE_FILES,
  2222. SSL_DO_VERIFY_PEER,
  2223. SSL_CACHE_TIMEOUT,
  2224. SSL_CA_PATH,
  2225. SSL_CA_FILE,
  2226. SSL_VERIFY_DEPTH,
  2227. SSL_DEFAULT_VERIFY_PATHS,
  2228. SSL_CIPHER_LIST,
  2229. SSL_PROTOCOL_VERSION,
  2230. SSL_SHORT_TRUST,
  2231. #if defined(USE_LUA)
  2232. LUA_PRELOAD_FILE,
  2233. LUA_SCRIPT_EXTENSIONS,
  2234. LUA_SERVER_PAGE_EXTENSIONS,
  2235. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2236. LUA_DEBUG_PARAMS,
  2237. #endif
  2238. #endif
  2239. #if defined(USE_DUKTAPE)
  2240. DUKTAPE_SCRIPT_EXTENSIONS,
  2241. #endif
  2242. #if defined(USE_WEBSOCKET)
  2243. WEBSOCKET_ROOT,
  2244. #endif
  2245. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2246. LUA_WEBSOCKET_EXTENSIONS,
  2247. #endif
  2248. ACCESS_CONTROL_ALLOW_ORIGIN,
  2249. ACCESS_CONTROL_ALLOW_METHODS,
  2250. ACCESS_CONTROL_ALLOW_HEADERS,
  2251. ERROR_PAGES,
  2252. #if !defined(NO_CACHING)
  2253. STATIC_FILE_MAX_AGE,
  2254. STATIC_FILE_CACHE_CONTROL,
  2255. #endif
  2256. #if !defined(NO_SSL)
  2257. STRICT_HTTPS_MAX_AGE,
  2258. #endif
  2259. ADDITIONAL_HEADER,
  2260. ALLOW_INDEX_SCRIPT_SUB_RES,
  2261. #if defined(DAEMONIZE)
  2262. ENABLE_DAEMONIZE,
  2263. #endif
  2264. NUM_OPTIONS
  2265. };
  2266. /* Config option name, config types, default value.
  2267. * Must be in the same order as the enum const above.
  2268. */
  2269. static const struct mg_option config_options[] = {
  2270. /* Once for each server */
  2271. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2272. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2273. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2274. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2275. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2276. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2277. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2278. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2279. #if defined(__linux__)
  2280. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2281. #endif
  2282. #if defined(_WIN32)
  2283. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2284. #endif
  2285. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2286. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2287. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2288. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2289. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2290. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2291. #if defined(USE_WEBSOCKET)
  2292. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2293. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2294. #endif
  2295. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2296. #if defined(USE_LUA)
  2297. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2298. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2299. #endif
  2300. #if defined(USE_HTTP2)
  2301. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2302. #endif
  2303. /* Once for each domain */
  2304. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2305. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2306. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2307. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2308. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2309. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2310. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2311. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2312. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2313. #if defined(USE_TIMERS)
  2314. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2315. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2316. #endif
  2317. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2318. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2319. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2320. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2321. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2322. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2323. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2324. {"index_files",
  2325. MG_CONFIG_TYPE_STRING_LIST,
  2326. #if defined(USE_LUA)
  2327. "index.xhtml,index.html,index.htm,"
  2328. "index.lp,index.lsp,index.lua,index.cgi,"
  2329. "index.shtml,index.php"},
  2330. #else
  2331. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2332. #endif
  2333. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2334. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2335. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2336. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2337. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2338. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2339. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2340. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  2341. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2342. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2343. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2344. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2345. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2346. #if defined(USE_HTTP2)
  2347. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  2348. * as a minimum in 2020 */
  2349. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  2350. #else
  2351. /* Keep the default (compatibility) */
  2352. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2353. #endif /* defined(USE_HTTP2) */
  2354. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2355. #if defined(USE_LUA)
  2356. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2357. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2358. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2359. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2360. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2361. #endif
  2362. #endif
  2363. #if defined(USE_DUKTAPE)
  2364. /* The support for duktape is still in alpha version state.
  2365. * The name of this config option might change. */
  2366. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2367. #endif
  2368. #if defined(USE_WEBSOCKET)
  2369. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2370. #endif
  2371. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2372. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2373. #endif
  2374. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2375. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2376. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2377. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2378. #if !defined(NO_CACHING)
  2379. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2380. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2381. #endif
  2382. #if !defined(NO_SSL)
  2383. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2384. #endif
  2385. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2386. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2387. #if defined(DAEMONIZE)
  2388. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2389. #endif
  2390. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2391. /* Check if the config_options and the corresponding enum have compatible
  2392. * sizes. */
  2393. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2394. == (NUM_OPTIONS + 1),
  2395. "config_options and enum not sync");
  2396. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2397. struct mg_handler_info {
  2398. /* Name/Pattern of the URI. */
  2399. char *uri;
  2400. size_t uri_len;
  2401. /* handler type */
  2402. int handler_type;
  2403. /* Handler for http/https or authorization requests. */
  2404. mg_request_handler handler;
  2405. unsigned int refcount;
  2406. int removing;
  2407. /* Handler for ws/wss (websocket) requests. */
  2408. mg_websocket_connect_handler connect_handler;
  2409. mg_websocket_ready_handler ready_handler;
  2410. mg_websocket_data_handler data_handler;
  2411. mg_websocket_close_handler close_handler;
  2412. /* accepted subprotocols for ws/wss requests. */
  2413. struct mg_websocket_subprotocols *subprotocols;
  2414. /* Handler for authorization requests */
  2415. mg_authorization_handler auth_handler;
  2416. /* User supplied argument for the handler function. */
  2417. void *cbdata;
  2418. /* next handler in a linked list */
  2419. struct mg_handler_info *next;
  2420. };
  2421. enum {
  2422. CONTEXT_INVALID,
  2423. CONTEXT_SERVER,
  2424. CONTEXT_HTTP_CLIENT,
  2425. CONTEXT_WS_CLIENT
  2426. };
  2427. struct mg_domain_context {
  2428. SSL_CTX *ssl_ctx; /* SSL context */
  2429. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2430. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2431. int64_t ssl_cert_last_mtime;
  2432. /* Server nonce */
  2433. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2434. unsigned long nonce_count; /* Used nonces, used for authentication */
  2435. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2436. /* linked list of shared lua websockets */
  2437. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2438. #endif
  2439. /* Linked list of domains */
  2440. struct mg_domain_context *next;
  2441. };
  2442. /* Stop flag can be "volatile" or require a lock.
  2443. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  2444. * states a read operation for int is always atomic. */
  2445. #if defined(STOP_FLAG_NEEDS_LOCK)
  2446. typedef ptrdiff_t volatile stop_flag_t;
  2447. static int
  2448. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2449. {
  2450. stop_flag_t sf = mg_atomic_add(f, 0);
  2451. return (sf == 0);
  2452. }
  2453. static int
  2454. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2455. {
  2456. stop_flag_t sf = mg_atomic_add(f, 0);
  2457. return (sf == 2);
  2458. }
  2459. static void
  2460. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2461. {
  2462. stop_flag_t sf;
  2463. do {
  2464. sf = mg_atomic_compare_and_swap(f, *f, v);
  2465. } while (sf != v);
  2466. }
  2467. #else /* STOP_FLAG_NEEDS_LOCK */
  2468. typedef int volatile stop_flag_t;
  2469. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2470. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2471. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2472. #endif /* STOP_FLAG_NEEDS_LOCK */
  2473. struct mg_context {
  2474. /* Part 1 - Physical context:
  2475. * This holds threads, ports, timeouts, ...
  2476. * set for the entire server, independent from the
  2477. * addressed hostname.
  2478. */
  2479. /* Connection related */
  2480. int context_type; /* See CONTEXT_* above */
  2481. struct socket *listening_sockets;
  2482. struct mg_pollfd *listening_socket_fds;
  2483. unsigned int num_listening_sockets;
  2484. struct mg_connection *worker_connections; /* The connection struct, pre-
  2485. * allocated for each worker */
  2486. #if defined(USE_SERVER_STATS)
  2487. volatile ptrdiff_t active_connections;
  2488. volatile ptrdiff_t max_active_connections;
  2489. volatile ptrdiff_t total_connections;
  2490. volatile ptrdiff_t total_requests;
  2491. volatile int64_t total_data_read;
  2492. volatile int64_t total_data_written;
  2493. #endif
  2494. /* Thread related */
  2495. stop_flag_t stop_flag; /* Should we stop event loop */
  2496. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2497. pthread_t masterthreadid; /* The master thread ID */
  2498. unsigned int
  2499. cfg_worker_threads; /* The number of configured worker threads. */
  2500. pthread_t *worker_threadids; /* The worker thread IDs */
  2501. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2502. /* Connection to thread dispatching */
  2503. #if defined(ALTERNATIVE_QUEUE)
  2504. struct socket *client_socks;
  2505. void **client_wait_events;
  2506. #else
  2507. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2508. worker thread */
  2509. volatile int sq_head; /* Head of the socket queue */
  2510. volatile int sq_tail; /* Tail of the socket queue */
  2511. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2512. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2513. volatile int sq_blocked; /* Status information: sq is full */
  2514. int sq_size; /* No of elements in socket queue */
  2515. #if defined(USE_SERVER_STATS)
  2516. int sq_max_fill;
  2517. #endif /* USE_SERVER_STATS */
  2518. #endif /* ALTERNATIVE_QUEUE */
  2519. /* Memory related */
  2520. unsigned int max_request_size; /* The max request size */
  2521. #if defined(USE_SERVER_STATS)
  2522. struct mg_memory_stat ctx_memory;
  2523. #endif
  2524. /* Operating system related */
  2525. char *systemName; /* What operating system is running */
  2526. time_t start_time; /* Server start time, used for authentication
  2527. * and for diagnstics. */
  2528. #if defined(USE_TIMERS)
  2529. struct ttimers *timers;
  2530. #endif
  2531. /* Lua specific: Background operations and shared websockets */
  2532. #if defined(USE_LUA)
  2533. void *lua_background_state;
  2534. #endif
  2535. /* Server nonce */
  2536. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2537. * ssl_cert_last_mtime, nonce_count, and
  2538. * next (linked list) */
  2539. /* Server callbacks */
  2540. struct mg_callbacks callbacks; /* User-defined callback function */
  2541. void *user_data; /* User-defined data */
  2542. /* Part 2 - Logical domain:
  2543. * This holds hostname, TLS certificate, document root, ...
  2544. * set for a domain hosted at the server.
  2545. * There may be multiple domains hosted at one physical server.
  2546. * The default domain "dd" is the first element of a list of
  2547. * domains.
  2548. */
  2549. struct mg_domain_context dd; /* default domain */
  2550. };
  2551. #if defined(USE_SERVER_STATS)
  2552. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2553. static struct mg_memory_stat *
  2554. get_memory_stat(struct mg_context *ctx)
  2555. {
  2556. if (ctx) {
  2557. return &(ctx->ctx_memory);
  2558. }
  2559. return &mg_common_memory;
  2560. }
  2561. #endif
  2562. enum {
  2563. CONNECTION_TYPE_INVALID = 0,
  2564. CONNECTION_TYPE_REQUEST = 1,
  2565. CONNECTION_TYPE_RESPONSE = 2
  2566. };
  2567. enum {
  2568. PROTOCOL_TYPE_HTTP1 = 0,
  2569. PROTOCOL_TYPE_WEBSOCKET = 1,
  2570. PROTOCOL_TYPE_HTTP2 = 2
  2571. };
  2572. #if defined(USE_HTTP2)
  2573. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2574. #define HTTP2_DYN_TABLE_SIZE (256)
  2575. #endif
  2576. struct mg_http2_connection {
  2577. uint32_t stream_id;
  2578. uint32_t dyn_table_size;
  2579. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2580. };
  2581. #endif
  2582. struct mg_connection {
  2583. int connection_type; /* see CONNECTION_TYPE_* above */
  2584. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2585. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2586. fully sent */
  2587. #if defined(USE_HTTP2)
  2588. struct mg_http2_connection http2;
  2589. #endif
  2590. struct mg_request_info request_info;
  2591. struct mg_response_info response_info;
  2592. struct mg_context *phys_ctx;
  2593. struct mg_domain_context *dom_ctx;
  2594. #if defined(USE_SERVER_STATS)
  2595. int conn_state; /* 0 = undef, numerical value may change in different
  2596. * versions. For the current definition, see
  2597. * mg_get_connection_info_impl */
  2598. #endif
  2599. SSL *ssl; /* SSL descriptor */
  2600. struct socket client; /* Connected client */
  2601. time_t conn_birth_time; /* Time (wall clock) when connection was
  2602. * established */
  2603. #if defined(USE_SERVER_STATS)
  2604. time_t conn_close_time; /* Time (wall clock) when connection was
  2605. * closed (or 0 if still open) */
  2606. #endif
  2607. struct timespec req_time; /* Time (since system start) when the request
  2608. * was received */
  2609. int64_t num_bytes_sent; /* Total bytes sent to client */
  2610. int64_t content_len; /* How many bytes of content can be read
  2611. * !is_chunked: Content-Length header value
  2612. * or -1 (until connection closed,
  2613. * not allowed for a request)
  2614. * is_chunked: >= 0, appended gradually
  2615. */
  2616. int64_t consumed_content; /* How many bytes of content have been read */
  2617. int is_chunked; /* Transfer-Encoding is chunked:
  2618. * 0 = not chunked,
  2619. * 1 = chunked, not yet, or some data read,
  2620. * 2 = chunked, has error,
  2621. * 3 = chunked, all data read except trailer,
  2622. * 4 = chunked, all data read
  2623. */
  2624. char *buf; /* Buffer for received data */
  2625. char *path_info; /* PATH_INFO part of the URL */
  2626. int must_close; /* 1 if connection must be closed */
  2627. int accept_gzip; /* 1 if gzip encoding is accepted */
  2628. int in_error_handler; /* 1 if in handler for user defined error
  2629. * pages */
  2630. #if defined(USE_WEBSOCKET)
  2631. int in_websocket_handling; /* 1 if in read_websocket */
  2632. #endif
  2633. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2634. && defined(MG_EXPERIMENTAL_INTERFACES)
  2635. /* Parameters for websocket data compression according to rfc7692 */
  2636. int websocket_deflate_server_max_windows_bits;
  2637. int websocket_deflate_client_max_windows_bits;
  2638. int websocket_deflate_server_no_context_takeover;
  2639. int websocket_deflate_client_no_context_takeover;
  2640. int websocket_deflate_initialized;
  2641. int websocket_deflate_flush;
  2642. z_stream websocket_deflate_state;
  2643. z_stream websocket_inflate_state;
  2644. #endif
  2645. int handled_requests; /* Number of requests handled by this connection
  2646. */
  2647. int buf_size; /* Buffer size */
  2648. int request_len; /* Size of the request + headers in a buffer */
  2649. int data_len; /* Total size of data in a buffer */
  2650. int status_code; /* HTTP reply status code, e.g. 200 */
  2651. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2652. * throttle */
  2653. time_t last_throttle_time; /* Last time throttled data was sent */
  2654. int last_throttle_bytes; /* Bytes sent this second */
  2655. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2656. * atomic transmissions for websockets */
  2657. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2658. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2659. #endif
  2660. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2661. * for quick access */
  2662. };
  2663. /* Directory entry */
  2664. struct de {
  2665. struct mg_connection *conn;
  2666. char *file_name;
  2667. struct mg_file_stat file;
  2668. };
  2669. #define mg_cry_internal(conn, fmt, ...) \
  2670. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2671. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2672. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2673. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2674. struct mg_context *ctx,
  2675. const char *func,
  2676. unsigned line,
  2677. const char *fmt,
  2678. ...) PRINTF_ARGS(5, 6);
  2679. #if !defined(NO_THREAD_NAME)
  2680. #if defined(_WIN32) && defined(_MSC_VER)
  2681. /* Set the thread name for debugging purposes in Visual Studio
  2682. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2683. */
  2684. #pragma pack(push, 8)
  2685. typedef struct tagTHREADNAME_INFO {
  2686. DWORD dwType; /* Must be 0x1000. */
  2687. LPCSTR szName; /* Pointer to name (in user addr space). */
  2688. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2689. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2690. } THREADNAME_INFO;
  2691. #pragma pack(pop)
  2692. #elif defined(__linux__)
  2693. #include <sys/prctl.h>
  2694. #include <sys/sendfile.h>
  2695. #if defined(ALTERNATIVE_QUEUE)
  2696. #include <sys/eventfd.h>
  2697. #endif /* ALTERNATIVE_QUEUE */
  2698. #if defined(ALTERNATIVE_QUEUE)
  2699. static void *
  2700. event_create(void)
  2701. {
  2702. int evhdl = eventfd(0, EFD_CLOEXEC);
  2703. int *ret;
  2704. if (evhdl == -1) {
  2705. /* Linux uses -1 on error, Windows NULL. */
  2706. /* However, Linux does not return 0 on success either. */
  2707. return 0;
  2708. }
  2709. ret = (int *)mg_malloc(sizeof(int));
  2710. if (ret) {
  2711. *ret = evhdl;
  2712. } else {
  2713. (void)close(evhdl);
  2714. }
  2715. return (void *)ret;
  2716. }
  2717. static int
  2718. event_wait(void *eventhdl)
  2719. {
  2720. uint64_t u;
  2721. int evhdl, s;
  2722. if (!eventhdl) {
  2723. /* error */
  2724. return 0;
  2725. }
  2726. evhdl = *(int *)eventhdl;
  2727. s = (int)read(evhdl, &u, sizeof(u));
  2728. if (s != sizeof(u)) {
  2729. /* error */
  2730. return 0;
  2731. }
  2732. (void)u; /* the value is not required */
  2733. return 1;
  2734. }
  2735. static int
  2736. event_signal(void *eventhdl)
  2737. {
  2738. uint64_t u = 1;
  2739. int evhdl, s;
  2740. if (!eventhdl) {
  2741. /* error */
  2742. return 0;
  2743. }
  2744. evhdl = *(int *)eventhdl;
  2745. s = (int)write(evhdl, &u, sizeof(u));
  2746. if (s != sizeof(u)) {
  2747. /* error */
  2748. return 0;
  2749. }
  2750. return 1;
  2751. }
  2752. static void
  2753. event_destroy(void *eventhdl)
  2754. {
  2755. int evhdl;
  2756. if (!eventhdl) {
  2757. /* error */
  2758. return;
  2759. }
  2760. evhdl = *(int *)eventhdl;
  2761. close(evhdl);
  2762. mg_free(eventhdl);
  2763. }
  2764. #endif
  2765. #endif
  2766. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2767. struct posix_event {
  2768. pthread_mutex_t mutex;
  2769. pthread_cond_t cond;
  2770. int signaled;
  2771. };
  2772. static void *
  2773. event_create(void)
  2774. {
  2775. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2776. if (ret == 0) {
  2777. /* out of memory */
  2778. return 0;
  2779. }
  2780. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2781. /* pthread mutex not available */
  2782. mg_free(ret);
  2783. return 0;
  2784. }
  2785. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2786. /* pthread cond not available */
  2787. pthread_mutex_destroy(&(ret->mutex));
  2788. mg_free(ret);
  2789. return 0;
  2790. }
  2791. ret->signaled = 0;
  2792. return (void *)ret;
  2793. }
  2794. static int
  2795. event_wait(void *eventhdl)
  2796. {
  2797. struct posix_event *ev = (struct posix_event *)eventhdl;
  2798. pthread_mutex_lock(&(ev->mutex));
  2799. while (!ev->signaled) {
  2800. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2801. }
  2802. ev->signaled = 0;
  2803. pthread_mutex_unlock(&(ev->mutex));
  2804. return 1;
  2805. }
  2806. static int
  2807. event_signal(void *eventhdl)
  2808. {
  2809. struct posix_event *ev = (struct posix_event *)eventhdl;
  2810. pthread_mutex_lock(&(ev->mutex));
  2811. pthread_cond_signal(&(ev->cond));
  2812. ev->signaled = 1;
  2813. pthread_mutex_unlock(&(ev->mutex));
  2814. return 1;
  2815. }
  2816. static void
  2817. event_destroy(void *eventhdl)
  2818. {
  2819. struct posix_event *ev = (struct posix_event *)eventhdl;
  2820. pthread_cond_destroy(&(ev->cond));
  2821. pthread_mutex_destroy(&(ev->mutex));
  2822. mg_free(ev);
  2823. }
  2824. #endif
  2825. static void
  2826. mg_set_thread_name(const char *name)
  2827. {
  2828. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2829. mg_snprintf(
  2830. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2831. #if defined(_WIN32)
  2832. #if defined(_MSC_VER)
  2833. /* Windows and Visual Studio Compiler */
  2834. __try {
  2835. THREADNAME_INFO info;
  2836. info.dwType = 0x1000;
  2837. info.szName = threadName;
  2838. info.dwThreadID = ~0U;
  2839. info.dwFlags = 0;
  2840. RaiseException(0x406D1388,
  2841. 0,
  2842. sizeof(info) / sizeof(ULONG_PTR),
  2843. (ULONG_PTR *)&info);
  2844. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2845. }
  2846. #elif defined(__MINGW32__)
  2847. /* No option known to set thread name for MinGW known */
  2848. #endif
  2849. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2850. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2851. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2852. #if defined(__MACH__)
  2853. /* OS X only current thread name can be changed */
  2854. (void)pthread_setname_np(threadName);
  2855. #else
  2856. (void)pthread_setname_np(pthread_self(), threadName);
  2857. #endif
  2858. #elif defined(__linux__)
  2859. /* On Linux we can use the prctl function.
  2860. * When building for Linux Standard Base (LSB) use
  2861. * NO_THREAD_NAME. However, thread names are a big
  2862. * help for debugging, so the stadard is to set them.
  2863. */
  2864. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2865. #endif
  2866. }
  2867. #else /* !defined(NO_THREAD_NAME) */
  2868. void
  2869. mg_set_thread_name(const char *threadName)
  2870. {
  2871. }
  2872. #endif
  2873. const struct mg_option *
  2874. mg_get_valid_options(void)
  2875. {
  2876. return config_options;
  2877. }
  2878. /* Do not open file (unused) */
  2879. #define MG_FOPEN_MODE_NONE (0)
  2880. /* Open file for read only access */
  2881. #define MG_FOPEN_MODE_READ (1)
  2882. /* Open file for writing, create and overwrite */
  2883. #define MG_FOPEN_MODE_WRITE (2)
  2884. /* Open file for writing, create and append */
  2885. #define MG_FOPEN_MODE_APPEND (4)
  2886. static int
  2887. is_file_opened(const struct mg_file_access *fileacc)
  2888. {
  2889. if (!fileacc) {
  2890. return 0;
  2891. }
  2892. return (fileacc->fp != NULL);
  2893. }
  2894. #if !defined(NO_FILESYSTEMS)
  2895. static int mg_stat(const struct mg_connection *conn,
  2896. const char *path,
  2897. struct mg_file_stat *filep);
  2898. /* Reject files with special characters */
  2899. static int
  2900. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2901. {
  2902. const uint8_t *c = (const uint8_t *)path;
  2903. (void)conn; /* not used */
  2904. if ((c == NULL) || (c[0] == 0)) {
  2905. /* Null pointer or empty path --> suspicious */
  2906. return 1;
  2907. }
  2908. while (*c) {
  2909. if (*c <= 32) {
  2910. /* Control character or space */
  2911. return 0;
  2912. }
  2913. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2914. /* stdin/stdout redirection character */
  2915. return 0;
  2916. }
  2917. #if defined(_WIN32)
  2918. if (*c == '\\') {
  2919. /* Windows backslash */
  2920. return 0;
  2921. }
  2922. #else
  2923. if (*c == '&') {
  2924. /* Linux ampersand */
  2925. return 0;
  2926. }
  2927. #endif
  2928. c++;
  2929. }
  2930. /* Nothing suspicious found */
  2931. return 0;
  2932. }
  2933. /* mg_fopen will open a file either in memory or on the disk.
  2934. * The input parameter path is a string in UTF-8 encoding.
  2935. * The input parameter mode is MG_FOPEN_MODE_*
  2936. * On success, fp will be set in the output struct mg_file.
  2937. * All status members will also be set.
  2938. * The function returns 1 on success, 0 on error. */
  2939. static int
  2940. mg_fopen(const struct mg_connection *conn,
  2941. const char *path,
  2942. int mode,
  2943. struct mg_file *filep)
  2944. {
  2945. int found;
  2946. if (!filep) {
  2947. return 0;
  2948. }
  2949. filep->access.fp = NULL;
  2950. if (mg_path_suspicious(conn, path)) {
  2951. return 0;
  2952. }
  2953. /* filep is initialized in mg_stat: all fields with memset to,
  2954. * some fields like size and modification date with values */
  2955. found = mg_stat(conn, path, &(filep->stat));
  2956. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2957. /* file does not exist and will not be created */
  2958. return 0;
  2959. }
  2960. #if defined(_WIN32)
  2961. {
  2962. wchar_t wbuf[W_PATH_MAX];
  2963. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2964. switch (mode) {
  2965. case MG_FOPEN_MODE_READ:
  2966. filep->access.fp = _wfopen(wbuf, L"rb");
  2967. break;
  2968. case MG_FOPEN_MODE_WRITE:
  2969. filep->access.fp = _wfopen(wbuf, L"wb");
  2970. break;
  2971. case MG_FOPEN_MODE_APPEND:
  2972. filep->access.fp = _wfopen(wbuf, L"ab");
  2973. break;
  2974. }
  2975. }
  2976. #else
  2977. /* Linux et al already use unicode. No need to convert. */
  2978. switch (mode) {
  2979. case MG_FOPEN_MODE_READ:
  2980. filep->access.fp = fopen(path, "r");
  2981. break;
  2982. case MG_FOPEN_MODE_WRITE:
  2983. filep->access.fp = fopen(path, "w");
  2984. break;
  2985. case MG_FOPEN_MODE_APPEND:
  2986. filep->access.fp = fopen(path, "a");
  2987. break;
  2988. }
  2989. #endif
  2990. if (!found) {
  2991. /* File did not exist before fopen was called.
  2992. * Maybe it has been created now. Get stat info
  2993. * like creation time now. */
  2994. found = mg_stat(conn, path, &(filep->stat));
  2995. (void)found;
  2996. }
  2997. /* return OK if file is opened */
  2998. return (filep->access.fp != NULL);
  2999. }
  3000. /* return 0 on success, just like fclose */
  3001. static int
  3002. mg_fclose(struct mg_file_access *fileacc)
  3003. {
  3004. int ret = -1;
  3005. if (fileacc != NULL) {
  3006. if (fileacc->fp != NULL) {
  3007. ret = fclose(fileacc->fp);
  3008. }
  3009. /* reset all members of fileacc */
  3010. memset(fileacc, 0, sizeof(*fileacc));
  3011. }
  3012. return ret;
  3013. }
  3014. #endif /* NO_FILESYSTEMS */
  3015. static void
  3016. mg_strlcpy(register char *dst, register const char *src, size_t n)
  3017. {
  3018. for (; *src != '\0' && n > 1; n--) {
  3019. *dst++ = *src++;
  3020. }
  3021. *dst = '\0';
  3022. }
  3023. static int
  3024. lowercase(const char *s)
  3025. {
  3026. return tolower((unsigned char)*s);
  3027. }
  3028. int
  3029. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  3030. {
  3031. int diff = 0;
  3032. if (len > 0) {
  3033. do {
  3034. diff = lowercase(s1++) - lowercase(s2++);
  3035. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  3036. }
  3037. return diff;
  3038. }
  3039. int
  3040. mg_strcasecmp(const char *s1, const char *s2)
  3041. {
  3042. int diff;
  3043. do {
  3044. diff = lowercase(s1++) - lowercase(s2++);
  3045. } while (diff == 0 && s1[-1] != '\0');
  3046. return diff;
  3047. }
  3048. static char *
  3049. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3050. {
  3051. char *p;
  3052. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3053. * defined */
  3054. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3055. mg_strlcpy(p, ptr, len + 1);
  3056. }
  3057. return p;
  3058. }
  3059. static char *
  3060. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3061. {
  3062. return mg_strndup_ctx(str, strlen(str), ctx);
  3063. }
  3064. static char *
  3065. mg_strdup(const char *str)
  3066. {
  3067. return mg_strndup_ctx(str, strlen(str), NULL);
  3068. }
  3069. static const char *
  3070. mg_strcasestr(const char *big_str, const char *small_str)
  3071. {
  3072. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3073. if (big_len >= small_len) {
  3074. for (i = 0; i <= (big_len - small_len); i++) {
  3075. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3076. return big_str + i;
  3077. }
  3078. }
  3079. }
  3080. return NULL;
  3081. }
  3082. /* Return null terminated string of given maximum length.
  3083. * Report errors if length is exceeded. */
  3084. static void
  3085. mg_vsnprintf(const struct mg_connection *conn,
  3086. int *truncated,
  3087. char *buf,
  3088. size_t buflen,
  3089. const char *fmt,
  3090. va_list ap)
  3091. {
  3092. int n, ok;
  3093. if (buflen == 0) {
  3094. if (truncated) {
  3095. *truncated = 1;
  3096. }
  3097. return;
  3098. }
  3099. #if defined(__clang__)
  3100. #pragma clang diagnostic push
  3101. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3102. /* Using fmt as a non-literal is intended here, since it is mostly called
  3103. * indirectly by mg_snprintf */
  3104. #endif
  3105. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3106. ok = (n >= 0) && ((size_t)n < buflen);
  3107. #if defined(__clang__)
  3108. #pragma clang diagnostic pop
  3109. #endif
  3110. if (ok) {
  3111. if (truncated) {
  3112. *truncated = 0;
  3113. }
  3114. } else {
  3115. if (truncated) {
  3116. *truncated = 1;
  3117. }
  3118. mg_cry_internal(conn,
  3119. "truncating vsnprintf buffer: [%.*s]",
  3120. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3121. buf);
  3122. n = (int)buflen - 1;
  3123. }
  3124. buf[n] = '\0';
  3125. }
  3126. static void
  3127. mg_snprintf(const struct mg_connection *conn,
  3128. int *truncated,
  3129. char *buf,
  3130. size_t buflen,
  3131. const char *fmt,
  3132. ...)
  3133. {
  3134. va_list ap;
  3135. va_start(ap, fmt);
  3136. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3137. va_end(ap);
  3138. }
  3139. static int
  3140. get_option_index(const char *name)
  3141. {
  3142. int i;
  3143. for (i = 0; config_options[i].name != NULL; i++) {
  3144. if (strcmp(config_options[i].name, name) == 0) {
  3145. return i;
  3146. }
  3147. }
  3148. return -1;
  3149. }
  3150. const char *
  3151. mg_get_option(const struct mg_context *ctx, const char *name)
  3152. {
  3153. int i;
  3154. if ((i = get_option_index(name)) == -1) {
  3155. return NULL;
  3156. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3157. return "";
  3158. } else {
  3159. return ctx->dd.config[i];
  3160. }
  3161. }
  3162. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3163. struct mg_context *
  3164. mg_get_context(const struct mg_connection *conn)
  3165. {
  3166. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3167. }
  3168. void *
  3169. mg_get_user_data(const struct mg_context *ctx)
  3170. {
  3171. return (ctx == NULL) ? NULL : ctx->user_data;
  3172. }
  3173. void *
  3174. mg_get_user_context_data(const struct mg_connection *conn)
  3175. {
  3176. return mg_get_user_data(mg_get_context(conn));
  3177. }
  3178. void *
  3179. mg_get_thread_pointer(const struct mg_connection *conn)
  3180. {
  3181. /* both methods should return the same pointer */
  3182. if (conn) {
  3183. /* quick access, in case conn is known */
  3184. return conn->tls_user_ptr;
  3185. } else {
  3186. /* otherwise get pointer from thread local storage (TLS) */
  3187. struct mg_workerTLS *tls =
  3188. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3189. return tls->user_ptr;
  3190. }
  3191. }
  3192. void
  3193. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  3194. {
  3195. if (conn != NULL) {
  3196. conn->request_info.conn_data = data;
  3197. }
  3198. }
  3199. void *
  3200. mg_get_user_connection_data(const struct mg_connection *conn)
  3201. {
  3202. if (conn != NULL) {
  3203. return conn->request_info.conn_data;
  3204. }
  3205. return NULL;
  3206. }
  3207. #if defined(MG_LEGACY_INTERFACE)
  3208. /* Deprecated: Use mg_get_server_ports instead. */
  3209. size_t
  3210. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3211. {
  3212. size_t i;
  3213. if (!ctx) {
  3214. return 0;
  3215. }
  3216. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3217. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3218. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3219. }
  3220. return i;
  3221. }
  3222. #endif
  3223. int
  3224. mg_get_server_ports(const struct mg_context *ctx,
  3225. int size,
  3226. struct mg_server_port *ports)
  3227. {
  3228. int i, cnt = 0;
  3229. if (size <= 0) {
  3230. return -1;
  3231. }
  3232. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3233. if (!ctx) {
  3234. return -1;
  3235. }
  3236. if (!ctx->listening_sockets) {
  3237. return -1;
  3238. }
  3239. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3240. ports[cnt].port =
  3241. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3242. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3243. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3244. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3245. /* IPv4 */
  3246. ports[cnt].protocol = 1;
  3247. cnt++;
  3248. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3249. /* IPv6 */
  3250. ports[cnt].protocol = 3;
  3251. cnt++;
  3252. }
  3253. }
  3254. return cnt;
  3255. }
  3256. static void
  3257. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3258. {
  3259. buf[0] = '\0';
  3260. if (!usa) {
  3261. return;
  3262. }
  3263. if (usa->sa.sa_family == AF_INET) {
  3264. getnameinfo(&usa->sa,
  3265. sizeof(usa->sin),
  3266. buf,
  3267. (unsigned)len,
  3268. NULL,
  3269. 0,
  3270. NI_NUMERICHOST);
  3271. }
  3272. #if defined(USE_IPV6)
  3273. else if (usa->sa.sa_family == AF_INET6) {
  3274. getnameinfo(&usa->sa,
  3275. sizeof(usa->sin6),
  3276. buf,
  3277. (unsigned)len,
  3278. NULL,
  3279. 0,
  3280. NI_NUMERICHOST);
  3281. }
  3282. #endif
  3283. }
  3284. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3285. * included in all responses other than 100, 101, 5xx. */
  3286. static void
  3287. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3288. {
  3289. #if !defined(REENTRANT_TIME)
  3290. struct tm *tm;
  3291. tm = ((t != NULL) ? gmtime(t) : NULL);
  3292. if (tm != NULL) {
  3293. #else
  3294. struct tm _tm;
  3295. struct tm *tm = &_tm;
  3296. if (t != NULL) {
  3297. gmtime_r(t, tm);
  3298. #endif
  3299. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3300. } else {
  3301. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3302. buf[buf_len - 1] = '\0';
  3303. }
  3304. }
  3305. /* difftime for struct timespec. Return value is in seconds. */
  3306. static double
  3307. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3308. {
  3309. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3310. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3311. }
  3312. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3313. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3314. const char *func,
  3315. unsigned line,
  3316. const char *fmt,
  3317. va_list ap);
  3318. #include "external_mg_cry_internal_impl.inl"
  3319. #elif !defined(NO_FILESYSTEMS)
  3320. /* Print error message to the opened error log stream. */
  3321. static void
  3322. mg_cry_internal_impl(const struct mg_connection *conn,
  3323. const char *func,
  3324. unsigned line,
  3325. const char *fmt,
  3326. va_list ap)
  3327. {
  3328. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3329. struct mg_file fi;
  3330. time_t timestamp;
  3331. /* Unused, in the RELEASE build */
  3332. (void)func;
  3333. (void)line;
  3334. #if defined(GCC_DIAGNOSTIC)
  3335. #pragma GCC diagnostic push
  3336. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3337. #endif
  3338. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3339. #if defined(GCC_DIAGNOSTIC)
  3340. #pragma GCC diagnostic pop
  3341. #endif
  3342. buf[sizeof(buf) - 1] = 0;
  3343. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3344. if (!conn) {
  3345. puts(buf);
  3346. return;
  3347. }
  3348. /* Do not lock when getting the callback value, here and below.
  3349. * I suppose this is fine, since function cannot disappear in the
  3350. * same way string option can. */
  3351. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3352. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3353. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3354. if (mg_fopen(conn,
  3355. conn->dom_ctx->config[ERROR_LOG_FILE],
  3356. MG_FOPEN_MODE_APPEND,
  3357. &fi)
  3358. == 0) {
  3359. fi.access.fp = NULL;
  3360. }
  3361. } else {
  3362. fi.access.fp = NULL;
  3363. }
  3364. if (fi.access.fp != NULL) {
  3365. flockfile(fi.access.fp);
  3366. timestamp = time(NULL);
  3367. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3368. fprintf(fi.access.fp,
  3369. "[%010lu] [error] [client %s] ",
  3370. (unsigned long)timestamp,
  3371. src_addr);
  3372. if (conn->request_info.request_method != NULL) {
  3373. fprintf(fi.access.fp,
  3374. "%s %s: ",
  3375. conn->request_info.request_method,
  3376. conn->request_info.request_uri
  3377. ? conn->request_info.request_uri
  3378. : "");
  3379. }
  3380. fprintf(fi.access.fp, "%s", buf);
  3381. fputc('\n', fi.access.fp);
  3382. fflush(fi.access.fp);
  3383. funlockfile(fi.access.fp);
  3384. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3385. * mg_cry here anyway ;-) */
  3386. }
  3387. }
  3388. }
  3389. #else
  3390. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3391. #endif /* Externally provided function */
  3392. /* Construct fake connection structure. Used for logging, if connection
  3393. * is not applicable at the moment of logging. */
  3394. static struct mg_connection *
  3395. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3396. {
  3397. static const struct mg_connection conn_zero = {0};
  3398. *fc = conn_zero;
  3399. fc->phys_ctx = ctx;
  3400. fc->dom_ctx = &(ctx->dd);
  3401. return fc;
  3402. }
  3403. static void
  3404. mg_cry_internal_wrap(const struct mg_connection *conn,
  3405. struct mg_context *ctx,
  3406. const char *func,
  3407. unsigned line,
  3408. const char *fmt,
  3409. ...)
  3410. {
  3411. va_list ap;
  3412. va_start(ap, fmt);
  3413. if (!conn && ctx) {
  3414. struct mg_connection fc;
  3415. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3416. } else {
  3417. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3418. }
  3419. va_end(ap);
  3420. }
  3421. void
  3422. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3423. {
  3424. va_list ap;
  3425. va_start(ap, fmt);
  3426. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3427. va_end(ap);
  3428. }
  3429. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3430. const char *
  3431. mg_version(void)
  3432. {
  3433. return CIVETWEB_VERSION;
  3434. }
  3435. const struct mg_request_info *
  3436. mg_get_request_info(const struct mg_connection *conn)
  3437. {
  3438. if (!conn) {
  3439. return NULL;
  3440. }
  3441. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3442. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3443. char txt[16];
  3444. struct mg_workerTLS *tls =
  3445. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3446. sprintf(txt, "%03i", conn->response_info.status_code);
  3447. if (strlen(txt) == 3) {
  3448. memcpy(tls->txtbuf, txt, 4);
  3449. } else {
  3450. strcpy(tls->txtbuf, "ERR");
  3451. }
  3452. ((struct mg_connection *)conn)->request_info.local_uri =
  3453. ((struct mg_connection *)conn)->request_info.request_uri =
  3454. tls->txtbuf; /* use thread safe buffer */
  3455. ((struct mg_connection *)conn)->request_info.num_headers =
  3456. conn->response_info.num_headers;
  3457. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3458. conn->response_info.http_headers,
  3459. sizeof(conn->response_info.http_headers));
  3460. } else
  3461. #endif
  3462. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3463. return NULL;
  3464. }
  3465. return &conn->request_info;
  3466. }
  3467. const struct mg_response_info *
  3468. mg_get_response_info(const struct mg_connection *conn)
  3469. {
  3470. if (!conn) {
  3471. return NULL;
  3472. }
  3473. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3474. return NULL;
  3475. }
  3476. return &conn->response_info;
  3477. }
  3478. static const char *
  3479. get_proto_name(const struct mg_connection *conn)
  3480. {
  3481. #if defined(__clang__)
  3482. #pragma clang diagnostic push
  3483. #pragma clang diagnostic ignored "-Wunreachable-code"
  3484. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3485. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3486. * unreachable, but splitting into four different #ifdef clauses here is more
  3487. * complicated.
  3488. */
  3489. #endif
  3490. const struct mg_request_info *ri = &conn->request_info;
  3491. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3492. ? (ri->is_ssl ? "wss" : "ws")
  3493. : (ri->is_ssl ? "https" : "http"));
  3494. return proto;
  3495. #if defined(__clang__)
  3496. #pragma clang diagnostic pop
  3497. #endif
  3498. }
  3499. static int
  3500. mg_construct_local_link(const struct mg_connection *conn,
  3501. char *buf,
  3502. size_t buflen,
  3503. const char *define_proto,
  3504. int define_port,
  3505. const char *define_uri)
  3506. {
  3507. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3508. return -1;
  3509. } else {
  3510. int truncated = 0;
  3511. const struct mg_request_info *ri = &conn->request_info;
  3512. const char *proto =
  3513. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3514. const char *uri =
  3515. (define_uri != NULL)
  3516. ? define_uri
  3517. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3518. int port = (define_port > 0)
  3519. ? define_port
  3520. : htons(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  3521. int default_port = 80;
  3522. if (uri == NULL) {
  3523. return -1;
  3524. }
  3525. if (define_proto) {
  3526. /* If we got a protocol name, use the default port accordingly. */
  3527. if ((0 == strcmp(define_proto, "https"))
  3528. || (0 == strcmp(define_proto, "wss"))) {
  3529. default_port = 443;
  3530. }
  3531. } else if (ri->is_ssl) {
  3532. /* If we did not get a protocol name, use TLS as default if it is
  3533. * already used. */
  3534. default_port = 443;
  3535. }
  3536. {
  3537. #if defined(USE_IPV6)
  3538. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3539. #endif
  3540. int auth_domain_check_enabled =
  3541. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3542. && (!mg_strcasecmp(
  3543. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3544. const char *server_domain =
  3545. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3546. char portstr[16];
  3547. char server_ip[48];
  3548. if (port != default_port) {
  3549. sprintf(portstr, ":%u", (unsigned)port);
  3550. } else {
  3551. portstr[0] = 0;
  3552. }
  3553. if (!auth_domain_check_enabled || !server_domain) {
  3554. sockaddr_to_string(server_ip,
  3555. sizeof(server_ip),
  3556. &conn->client.lsa);
  3557. server_domain = server_ip;
  3558. }
  3559. mg_snprintf(conn,
  3560. &truncated,
  3561. buf,
  3562. buflen,
  3563. #if defined(USE_IPV6)
  3564. "%s://%s%s%s%s%s",
  3565. proto,
  3566. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3567. server_domain,
  3568. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3569. #else
  3570. "%s://%s%s%s",
  3571. proto,
  3572. server_domain,
  3573. #endif
  3574. portstr,
  3575. ri->local_uri);
  3576. if (truncated) {
  3577. return -1;
  3578. }
  3579. return 0;
  3580. }
  3581. }
  3582. }
  3583. int
  3584. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3585. {
  3586. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3587. }
  3588. /* Skip the characters until one of the delimiters characters found.
  3589. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3590. * Advance pointer to buffer to the next word. Return found 0-terminated
  3591. * word.
  3592. * Delimiters can be quoted with quotechar. */
  3593. static char *
  3594. skip_quoted(char **buf,
  3595. const char *delimiters,
  3596. const char *whitespace,
  3597. char quotechar)
  3598. {
  3599. char *p, *begin_word, *end_word, *end_whitespace;
  3600. begin_word = *buf;
  3601. end_word = begin_word + strcspn(begin_word, delimiters);
  3602. /* Check for quotechar */
  3603. if (end_word > begin_word) {
  3604. p = end_word - 1;
  3605. while (*p == quotechar) {
  3606. /* While the delimiter is quoted, look for the next delimiter.
  3607. */
  3608. /* This happens, e.g., in calls from parse_auth_header,
  3609. * if the user name contains a " character. */
  3610. /* If there is anything beyond end_word, copy it. */
  3611. if (*end_word != '\0') {
  3612. size_t end_off = strcspn(end_word + 1, delimiters);
  3613. memmove(p, end_word, end_off + 1);
  3614. p += end_off; /* p must correspond to end_word - 1 */
  3615. end_word += end_off + 1;
  3616. } else {
  3617. *p = '\0';
  3618. break;
  3619. }
  3620. }
  3621. for (p++; p < end_word; p++) {
  3622. *p = '\0';
  3623. }
  3624. }
  3625. if (*end_word == '\0') {
  3626. *buf = end_word;
  3627. } else {
  3628. #if defined(GCC_DIAGNOSTIC)
  3629. /* Disable spurious conversion warning for GCC */
  3630. #pragma GCC diagnostic push
  3631. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3632. #endif /* defined(GCC_DIAGNOSTIC) */
  3633. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3634. #if defined(GCC_DIAGNOSTIC)
  3635. #pragma GCC diagnostic pop
  3636. #endif /* defined(GCC_DIAGNOSTIC) */
  3637. for (p = end_word; p < end_whitespace; p++) {
  3638. *p = '\0';
  3639. }
  3640. *buf = end_whitespace;
  3641. }
  3642. return begin_word;
  3643. }
  3644. /* Return HTTP header value, or NULL if not found. */
  3645. static const char *
  3646. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3647. {
  3648. int i;
  3649. for (i = 0; i < num_hdr; i++) {
  3650. if (!mg_strcasecmp(name, hdr[i].name)) {
  3651. return hdr[i].value;
  3652. }
  3653. }
  3654. return NULL;
  3655. }
  3656. #if defined(USE_WEBSOCKET)
  3657. /* Retrieve requested HTTP header multiple values, and return the number of
  3658. * found occurrences */
  3659. static int
  3660. get_req_headers(const struct mg_request_info *ri,
  3661. const char *name,
  3662. const char **output,
  3663. int output_max_size)
  3664. {
  3665. int i;
  3666. int cnt = 0;
  3667. if (ri) {
  3668. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3669. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3670. output[cnt++] = ri->http_headers[i].value;
  3671. }
  3672. }
  3673. }
  3674. return cnt;
  3675. }
  3676. #endif
  3677. const char *
  3678. mg_get_header(const struct mg_connection *conn, const char *name)
  3679. {
  3680. if (!conn) {
  3681. return NULL;
  3682. }
  3683. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3684. return get_header(conn->request_info.http_headers,
  3685. conn->request_info.num_headers,
  3686. name);
  3687. }
  3688. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3689. return get_header(conn->response_info.http_headers,
  3690. conn->response_info.num_headers,
  3691. name);
  3692. }
  3693. return NULL;
  3694. }
  3695. static const char *
  3696. get_http_version(const struct mg_connection *conn)
  3697. {
  3698. if (!conn) {
  3699. return NULL;
  3700. }
  3701. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3702. return conn->request_info.http_version;
  3703. }
  3704. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3705. return conn->response_info.http_version;
  3706. }
  3707. return NULL;
  3708. }
  3709. /* A helper function for traversing a comma separated list of values.
  3710. * It returns a list pointer shifted to the next value, or NULL if the end
  3711. * of the list found.
  3712. * Value is stored in val vector. If value has form "x=y", then eq_val
  3713. * vector is initialized to point to the "y" part, and val vector length
  3714. * is adjusted to point only to "x". */
  3715. static const char *
  3716. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3717. {
  3718. int end;
  3719. reparse:
  3720. if (val == NULL || list == NULL || *list == '\0') {
  3721. /* End of the list */
  3722. return NULL;
  3723. }
  3724. /* Skip over leading LWS */
  3725. while (*list == ' ' || *list == '\t')
  3726. list++;
  3727. val->ptr = list;
  3728. if ((list = strchr(val->ptr, ',')) != NULL) {
  3729. /* Comma found. Store length and shift the list ptr */
  3730. val->len = ((size_t)(list - val->ptr));
  3731. list++;
  3732. } else {
  3733. /* This value is the last one */
  3734. list = val->ptr + strlen(val->ptr);
  3735. val->len = ((size_t)(list - val->ptr));
  3736. }
  3737. /* Adjust length for trailing LWS */
  3738. end = (int)val->len - 1;
  3739. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3740. end--;
  3741. val->len = (size_t)(end) + (size_t)(1);
  3742. if (val->len == 0) {
  3743. /* Ignore any empty entries. */
  3744. goto reparse;
  3745. }
  3746. if (eq_val != NULL) {
  3747. /* Value has form "x=y", adjust pointers and lengths
  3748. * so that val points to "x", and eq_val points to "y". */
  3749. eq_val->len = 0;
  3750. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3751. if (eq_val->ptr != NULL) {
  3752. eq_val->ptr++; /* Skip over '=' character */
  3753. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3754. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3755. }
  3756. }
  3757. return list;
  3758. }
  3759. /* A helper function for checking if a comma separated list of values
  3760. * contains
  3761. * the given option (case insensitvely).
  3762. * 'header' can be NULL, in which case false is returned. */
  3763. static int
  3764. header_has_option(const char *header, const char *option)
  3765. {
  3766. struct vec opt_vec;
  3767. struct vec eq_vec;
  3768. DEBUG_ASSERT(option != NULL);
  3769. DEBUG_ASSERT(option[0] != '\0');
  3770. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3771. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3772. return 1;
  3773. }
  3774. return 0;
  3775. }
  3776. /* Perform case-insensitive match of string against pattern */
  3777. static ptrdiff_t
  3778. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3779. {
  3780. const char *or_str;
  3781. ptrdiff_t i, j, len, res;
  3782. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3783. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3784. return (res > 0) ? res
  3785. : match_prefix(or_str + 1,
  3786. (size_t)((pattern + pattern_len)
  3787. - (or_str + 1)),
  3788. str);
  3789. }
  3790. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3791. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3792. continue;
  3793. } else if (pattern[i] == '$') {
  3794. return (str[j] == '\0') ? j : -1;
  3795. } else if (pattern[i] == '*') {
  3796. i++;
  3797. if (pattern[i] == '*') {
  3798. i++;
  3799. len = (ptrdiff_t)strlen(str + j);
  3800. } else {
  3801. len = (ptrdiff_t)strcspn(str + j, "/");
  3802. }
  3803. if (i == (ptrdiff_t)pattern_len) {
  3804. return j + len;
  3805. }
  3806. do {
  3807. res = match_prefix(pattern + i,
  3808. (pattern_len - (size_t)i),
  3809. str + j + len);
  3810. } while (res == -1 && len-- > 0);
  3811. return (res == -1) ? -1 : j + res + len;
  3812. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3813. return -1;
  3814. }
  3815. }
  3816. return (ptrdiff_t)j;
  3817. }
  3818. static ptrdiff_t
  3819. match_prefix_strlen(const char *pattern, const char *str)
  3820. {
  3821. if (pattern == NULL) {
  3822. return -1;
  3823. }
  3824. return match_prefix(pattern, strlen(pattern), str);
  3825. }
  3826. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3827. * This function must tolerate situations when connection info is not
  3828. * set up, for example if request parsing failed. */
  3829. static int
  3830. should_keep_alive(const struct mg_connection *conn)
  3831. {
  3832. const char *http_version;
  3833. const char *header;
  3834. /* First satisfy needs of the server */
  3835. if ((conn == NULL) || conn->must_close) {
  3836. /* Close, if civetweb framework needs to close */
  3837. return 0;
  3838. }
  3839. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3840. /* Close, if keep alive is not enabled */
  3841. return 0;
  3842. }
  3843. /* Check explicit wish of the client */
  3844. header = mg_get_header(conn, "Connection");
  3845. if (header) {
  3846. /* If there is a connection header from the client, obey */
  3847. if (header_has_option(header, "keep-alive")) {
  3848. return 1;
  3849. }
  3850. return 0;
  3851. }
  3852. /* Use default of the standard */
  3853. http_version = get_http_version(conn);
  3854. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3855. /* HTTP 1.1 default is keep alive */
  3856. return 1;
  3857. }
  3858. /* HTTP 1.0 (and earlier) default is to close the connection */
  3859. return 0;
  3860. }
  3861. static int
  3862. should_decode_url(const struct mg_connection *conn)
  3863. {
  3864. if (!conn || !conn->dom_ctx) {
  3865. return 0;
  3866. }
  3867. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3868. }
  3869. static const char *
  3870. suggest_connection_header(const struct mg_connection *conn)
  3871. {
  3872. return should_keep_alive(conn) ? "keep-alive" : "close";
  3873. }
  3874. #include "response.inl"
  3875. static void
  3876. send_no_cache_header(struct mg_connection *conn)
  3877. {
  3878. /* Send all current and obsolete cache opt-out directives. */
  3879. mg_response_header_add(conn,
  3880. "Cache-Control",
  3881. "no-cache, no-store, "
  3882. "must-revalidate, private, max-age=0",
  3883. -1);
  3884. mg_response_header_add(conn, "Expires", "0", -1);
  3885. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3886. /* Obsolete, but still send it for HTTP/1.0 */
  3887. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3888. }
  3889. }
  3890. static void
  3891. send_static_cache_header(struct mg_connection *conn)
  3892. {
  3893. #if !defined(NO_CACHING)
  3894. int max_age;
  3895. char val[64];
  3896. const char *cache_control =
  3897. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3898. /* If there is a full cache-control option configured,0 use it */
  3899. if (cache_control != NULL) {
  3900. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3901. return;
  3902. }
  3903. /* Read the server config to check how long a file may be cached.
  3904. * The configuration is in seconds. */
  3905. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3906. if (max_age <= 0) {
  3907. /* 0 means "do not cache". All values <0 are reserved
  3908. * and may be used differently in the future. */
  3909. /* If a file should not be cached, do not only send
  3910. * max-age=0, but also pragmas and Expires headers. */
  3911. send_no_cache_header(conn);
  3912. return;
  3913. }
  3914. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3915. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3916. /* See also https://www.mnot.net/cache_docs/ */
  3917. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3918. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3919. * leap
  3920. * year to 31622400 seconds. For the moment, we just send whatever has
  3921. * been configured, still the behavior for >1 year should be considered
  3922. * as undefined. */
  3923. mg_snprintf(
  3924. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3925. mg_response_header_add(conn, "Cache-Control", val, -1);
  3926. #else /* NO_CACHING */
  3927. send_no_cache_header(conn);
  3928. #endif /* !NO_CACHING */
  3929. }
  3930. static void
  3931. send_additional_header(struct mg_connection *conn)
  3932. {
  3933. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3934. #if !defined(NO_SSL)
  3935. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3936. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3937. if (max_age >= 0) {
  3938. char val[64];
  3939. mg_snprintf(conn,
  3940. NULL,
  3941. val,
  3942. sizeof(val),
  3943. "max-age=%lu",
  3944. (unsigned long)max_age);
  3945. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3946. }
  3947. }
  3948. #endif
  3949. if (header && header[0]) {
  3950. mg_response_header_add_lines(conn, header);
  3951. }
  3952. }
  3953. #if !defined(NO_FILESYSTEMS)
  3954. static void handle_file_based_request(struct mg_connection *conn,
  3955. const char *path,
  3956. struct mg_file *filep);
  3957. #endif /* NO_FILESYSTEMS */
  3958. const char *
  3959. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3960. {
  3961. /* See IANA HTTP status code assignment:
  3962. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3963. */
  3964. switch (response_code) {
  3965. /* RFC2616 Section 10.1 - Informational 1xx */
  3966. case 100:
  3967. return "Continue"; /* RFC2616 Section 10.1.1 */
  3968. case 101:
  3969. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3970. case 102:
  3971. return "Processing"; /* RFC2518 Section 10.1 */
  3972. /* RFC2616 Section 10.2 - Successful 2xx */
  3973. case 200:
  3974. return "OK"; /* RFC2616 Section 10.2.1 */
  3975. case 201:
  3976. return "Created"; /* RFC2616 Section 10.2.2 */
  3977. case 202:
  3978. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3979. case 203:
  3980. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3981. case 204:
  3982. return "No Content"; /* RFC2616 Section 10.2.5 */
  3983. case 205:
  3984. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3985. case 206:
  3986. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3987. case 207:
  3988. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3989. */
  3990. case 208:
  3991. return "Already Reported"; /* RFC5842 Section 7.1 */
  3992. case 226:
  3993. return "IM used"; /* RFC3229 Section 10.4.1 */
  3994. /* RFC2616 Section 10.3 - Redirection 3xx */
  3995. case 300:
  3996. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3997. case 301:
  3998. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3999. case 302:
  4000. return "Found"; /* RFC2616 Section 10.3.3 */
  4001. case 303:
  4002. return "See Other"; /* RFC2616 Section 10.3.4 */
  4003. case 304:
  4004. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  4005. case 305:
  4006. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  4007. case 307:
  4008. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  4009. case 308:
  4010. return "Permanent Redirect"; /* RFC7238 Section 3 */
  4011. /* RFC2616 Section 10.4 - Client Error 4xx */
  4012. case 400:
  4013. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  4014. case 401:
  4015. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  4016. case 402:
  4017. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  4018. case 403:
  4019. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  4020. case 404:
  4021. return "Not Found"; /* RFC2616 Section 10.4.5 */
  4022. case 405:
  4023. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  4024. case 406:
  4025. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  4026. case 407:
  4027. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  4028. case 408:
  4029. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  4030. case 409:
  4031. return "Conflict"; /* RFC2616 Section 10.4.10 */
  4032. case 410:
  4033. return "Gone"; /* RFC2616 Section 10.4.11 */
  4034. case 411:
  4035. return "Length Required"; /* RFC2616 Section 10.4.12 */
  4036. case 412:
  4037. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  4038. case 413:
  4039. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  4040. case 414:
  4041. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  4042. case 415:
  4043. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  4044. case 416:
  4045. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  4046. */
  4047. case 417:
  4048. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  4049. case 421:
  4050. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  4051. case 422:
  4052. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  4053. * Section 11.2 */
  4054. case 423:
  4055. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  4056. case 424:
  4057. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  4058. * Section 11.4 */
  4059. case 426:
  4060. return "Upgrade Required"; /* RFC 2817 Section 4 */
  4061. case 428:
  4062. return "Precondition Required"; /* RFC 6585, Section 3 */
  4063. case 429:
  4064. return "Too Many Requests"; /* RFC 6585, Section 4 */
  4065. case 431:
  4066. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  4067. case 451:
  4068. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  4069. * Section 3 */
  4070. /* RFC2616 Section 10.5 - Server Error 5xx */
  4071. case 500:
  4072. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  4073. case 501:
  4074. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  4075. case 502:
  4076. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4077. case 503:
  4078. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4079. case 504:
  4080. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4081. case 505:
  4082. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4083. case 506:
  4084. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4085. case 507:
  4086. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4087. * Section 11.5 */
  4088. case 508:
  4089. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4090. case 510:
  4091. return "Not Extended"; /* RFC 2774, Section 7 */
  4092. case 511:
  4093. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4094. /* Other status codes, not shown in the IANA HTTP status code
  4095. * assignment.
  4096. * E.g., "de facto" standards due to common use, ... */
  4097. case 418:
  4098. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4099. case 419:
  4100. return "Authentication Timeout"; /* common use */
  4101. case 420:
  4102. return "Enhance Your Calm"; /* common use */
  4103. case 440:
  4104. return "Login Timeout"; /* common use */
  4105. case 509:
  4106. return "Bandwidth Limit Exceeded"; /* common use */
  4107. default:
  4108. /* This error code is unknown. This should not happen. */
  4109. if (conn) {
  4110. mg_cry_internal(conn,
  4111. "Unknown HTTP response code: %u",
  4112. response_code);
  4113. }
  4114. /* Return at least a category according to RFC 2616 Section 10. */
  4115. if (response_code >= 100 && response_code < 200) {
  4116. /* Unknown informational status code */
  4117. return "Information";
  4118. }
  4119. if (response_code >= 200 && response_code < 300) {
  4120. /* Unknown success code */
  4121. return "Success";
  4122. }
  4123. if (response_code >= 300 && response_code < 400) {
  4124. /* Unknown redirection code */
  4125. return "Redirection";
  4126. }
  4127. if (response_code >= 400 && response_code < 500) {
  4128. /* Unknown request error code */
  4129. return "Client Error";
  4130. }
  4131. if (response_code >= 500 && response_code < 600) {
  4132. /* Unknown server error code */
  4133. return "Server Error";
  4134. }
  4135. /* Response code not even within reasonable range */
  4136. return "";
  4137. }
  4138. }
  4139. static int
  4140. mg_send_http_error_impl(struct mg_connection *conn,
  4141. int status,
  4142. const char *fmt,
  4143. va_list args)
  4144. {
  4145. char errmsg_buf[MG_BUF_LEN];
  4146. va_list ap;
  4147. int has_body;
  4148. #if !defined(NO_FILESYSTEMS)
  4149. char path_buf[PATH_MAX];
  4150. int len, i, page_handler_found, scope, truncated;
  4151. const char *error_handler = NULL;
  4152. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4153. const char *error_page_file_ext, *tstr;
  4154. #endif /* NO_FILESYSTEMS */
  4155. int handled_by_callback = 0;
  4156. if ((conn == NULL) || (fmt == NULL)) {
  4157. return -2;
  4158. }
  4159. /* Set status (for log) */
  4160. conn->status_code = status;
  4161. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4162. has_body = ((status > 199) && (status != 204) && (status != 304));
  4163. /* Prepare message in buf, if required */
  4164. if (has_body
  4165. || (!conn->in_error_handler
  4166. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4167. /* Store error message in errmsg_buf */
  4168. va_copy(ap, args);
  4169. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4170. va_end(ap);
  4171. /* In a debug build, print all html errors */
  4172. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4173. }
  4174. /* If there is a http_error callback, call it.
  4175. * But don't do it recursively, if callback calls mg_send_http_error again.
  4176. */
  4177. if (!conn->in_error_handler
  4178. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4179. /* Mark in_error_handler to avoid recursion and call user callback. */
  4180. conn->in_error_handler = 1;
  4181. handled_by_callback =
  4182. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4183. == 0);
  4184. conn->in_error_handler = 0;
  4185. }
  4186. if (!handled_by_callback) {
  4187. /* Check for recursion */
  4188. if (conn->in_error_handler) {
  4189. DEBUG_TRACE(
  4190. "Recursion when handling error %u - fall back to default",
  4191. status);
  4192. #if !defined(NO_FILESYSTEMS)
  4193. } else {
  4194. /* Send user defined error pages, if defined */
  4195. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4196. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4197. page_handler_found = 0;
  4198. if (error_handler != NULL) {
  4199. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4200. switch (scope) {
  4201. case 1: /* Handler for specific error, e.g. 404 error */
  4202. mg_snprintf(conn,
  4203. &truncated,
  4204. path_buf,
  4205. sizeof(path_buf) - 32,
  4206. "%serror%03u.",
  4207. error_handler,
  4208. status);
  4209. break;
  4210. case 2: /* Handler for error group, e.g., 5xx error
  4211. * handler
  4212. * for all server errors (500-599) */
  4213. mg_snprintf(conn,
  4214. &truncated,
  4215. path_buf,
  4216. sizeof(path_buf) - 32,
  4217. "%serror%01uxx.",
  4218. error_handler,
  4219. status / 100);
  4220. break;
  4221. default: /* Handler for all errors */
  4222. mg_snprintf(conn,
  4223. &truncated,
  4224. path_buf,
  4225. sizeof(path_buf) - 32,
  4226. "%serror.",
  4227. error_handler);
  4228. break;
  4229. }
  4230. /* String truncation in buf may only occur if
  4231. * error_handler is too long. This string is
  4232. * from the config, not from a client. */
  4233. (void)truncated;
  4234. /* The following code is redundant, but it should avoid
  4235. * false positives in static source code analyzers and
  4236. * vulnerability scanners.
  4237. */
  4238. path_buf[sizeof(path_buf) - 32] = 0;
  4239. len = (int)strlen(path_buf);
  4240. if (len > (int)sizeof(path_buf) - 32) {
  4241. len = (int)sizeof(path_buf) - 32;
  4242. }
  4243. /* Start with the file extenstion from the configuration. */
  4244. tstr = strchr(error_page_file_ext, '.');
  4245. while (tstr) {
  4246. for (i = 1;
  4247. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4248. i++) {
  4249. /* buffer overrun is not possible here, since
  4250. * (i < 32) && (len < sizeof(path_buf) - 32)
  4251. * ==> (i + len) < sizeof(path_buf) */
  4252. path_buf[len + i - 1] = tstr[i];
  4253. }
  4254. /* buffer overrun is not possible here, since
  4255. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4256. * ==> (i + len) <= sizeof(path_buf) */
  4257. path_buf[len + i - 1] = 0;
  4258. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4259. DEBUG_TRACE("Check error page %s - found",
  4260. path_buf);
  4261. page_handler_found = 1;
  4262. break;
  4263. }
  4264. DEBUG_TRACE("Check error page %s - not found",
  4265. path_buf);
  4266. /* Continue with the next file extenstion from the
  4267. * configuration (if there is a next one). */
  4268. tstr = strchr(tstr + i, '.');
  4269. }
  4270. }
  4271. }
  4272. if (page_handler_found) {
  4273. conn->in_error_handler = 1;
  4274. handle_file_based_request(conn, path_buf, &error_page_file);
  4275. conn->in_error_handler = 0;
  4276. return 0;
  4277. }
  4278. #endif /* NO_FILESYSTEMS */
  4279. }
  4280. /* No custom error page. Send default error page. */
  4281. conn->must_close = 1;
  4282. mg_response_header_start(conn, status);
  4283. send_no_cache_header(conn);
  4284. send_additional_header(conn);
  4285. if (has_body) {
  4286. mg_response_header_add(conn,
  4287. "Content-Type",
  4288. "text/plain; charset=utf-8",
  4289. -1);
  4290. }
  4291. mg_response_header_send(conn);
  4292. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4293. if (has_body) {
  4294. /* For other errors, send a generic error message. */
  4295. const char *status_text = mg_get_response_code_text(conn, status);
  4296. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4297. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4298. } else {
  4299. /* No body allowed. Close the connection. */
  4300. DEBUG_TRACE("Error %i", status);
  4301. }
  4302. }
  4303. return 0;
  4304. }
  4305. int
  4306. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4307. {
  4308. va_list ap;
  4309. int ret;
  4310. va_start(ap, fmt);
  4311. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4312. va_end(ap);
  4313. return ret;
  4314. }
  4315. int
  4316. mg_send_http_ok(struct mg_connection *conn,
  4317. const char *mime_type,
  4318. long long content_length)
  4319. {
  4320. if ((mime_type == NULL) || (*mime_type == 0)) {
  4321. /* No content type defined: default to text/html */
  4322. mime_type = "text/html";
  4323. }
  4324. mg_response_header_start(conn, 200);
  4325. send_no_cache_header(conn);
  4326. send_additional_header(conn);
  4327. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  4328. if (content_length < 0) {
  4329. /* Size not known. Use chunked encoding (HTTP/1.x) */
  4330. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  4331. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  4332. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  4333. }
  4334. } else {
  4335. char len[32];
  4336. int trunc = 0;
  4337. mg_snprintf(conn,
  4338. &trunc,
  4339. len,
  4340. sizeof(len),
  4341. "%" UINT64_FMT,
  4342. (uint64_t)content_length);
  4343. if (!trunc) {
  4344. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  4345. * !trunc is always true */
  4346. mg_response_header_add(conn, "Content-Length", len, -1);
  4347. }
  4348. }
  4349. mg_response_header_send(conn);
  4350. return 0;
  4351. }
  4352. int
  4353. mg_send_http_redirect(struct mg_connection *conn,
  4354. const char *target_url,
  4355. int redirect_code)
  4356. {
  4357. /* Send a 30x redirect response.
  4358. *
  4359. * Redirect types (status codes):
  4360. *
  4361. * Status | Perm/Temp | Method | Version
  4362. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4363. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4364. * 303 | temporary | always use GET | HTTP/1.1
  4365. * 307 | temporary | always keep method | HTTP/1.1
  4366. * 308 | permanent | always keep method | HTTP/1.1
  4367. */
  4368. const char *redirect_text;
  4369. int ret;
  4370. size_t content_len = 0;
  4371. #if defined(MG_SEND_REDIRECT_BODY)
  4372. char reply[MG_BUF_LEN];
  4373. #endif
  4374. /* In case redirect_code=0, use 307. */
  4375. if (redirect_code == 0) {
  4376. redirect_code = 307;
  4377. }
  4378. /* In case redirect_code is none of the above, return error. */
  4379. if ((redirect_code != 301) && (redirect_code != 302)
  4380. && (redirect_code != 303) && (redirect_code != 307)
  4381. && (redirect_code != 308)) {
  4382. /* Parameter error */
  4383. return -2;
  4384. }
  4385. /* Get proper text for response code */
  4386. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4387. /* If target_url is not defined, redirect to "/". */
  4388. if ((target_url == NULL) || (*target_url == 0)) {
  4389. target_url = "/";
  4390. }
  4391. #if defined(MG_SEND_REDIRECT_BODY)
  4392. /* TODO: condition name? */
  4393. /* Prepare a response body with a hyperlink.
  4394. *
  4395. * According to RFC2616 (and RFC1945 before):
  4396. * Unless the request method was HEAD, the entity of the
  4397. * response SHOULD contain a short hypertext note with a hyperlink to
  4398. * the new URI(s).
  4399. *
  4400. * However, this response body is not useful in M2M communication.
  4401. * Probably the original reason in the RFC was, clients not supporting
  4402. * a 30x HTTP redirect could still show the HTML page and let the user
  4403. * press the link. Since current browsers support 30x HTTP, the additional
  4404. * HTML body does not seem to make sense anymore.
  4405. *
  4406. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4407. * but it only notes:
  4408. * The server's response payload usually contains a short
  4409. * hypertext note with a hyperlink to the new URI(s).
  4410. *
  4411. * Deactivated by default. If you need the 30x body, set the define.
  4412. */
  4413. mg_snprintf(
  4414. conn,
  4415. NULL /* ignore truncation */,
  4416. reply,
  4417. sizeof(reply),
  4418. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4419. redirect_text,
  4420. target_url,
  4421. target_url);
  4422. content_len = strlen(reply);
  4423. #endif
  4424. /* Do not send any additional header. For all other options,
  4425. * including caching, there are suitable defaults. */
  4426. ret = mg_printf(conn,
  4427. "HTTP/1.1 %i %s\r\n"
  4428. "Location: %s\r\n"
  4429. "Content-Length: %u\r\n"
  4430. "Connection: %s\r\n\r\n",
  4431. redirect_code,
  4432. redirect_text,
  4433. target_url,
  4434. (unsigned int)content_len,
  4435. suggest_connection_header(conn));
  4436. #if defined(MG_SEND_REDIRECT_BODY)
  4437. /* Send response body */
  4438. if (ret > 0) {
  4439. /* ... unless it is a HEAD request */
  4440. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4441. ret = mg_write(conn, reply, content_len);
  4442. }
  4443. }
  4444. #endif
  4445. return (ret > 0) ? ret : -1;
  4446. }
  4447. #if defined(_WIN32)
  4448. /* Create substitutes for POSIX functions in Win32. */
  4449. #if defined(GCC_DIAGNOSTIC)
  4450. /* Show no warning in case system functions are not used. */
  4451. #pragma GCC diagnostic push
  4452. #pragma GCC diagnostic ignored "-Wunused-function"
  4453. #endif
  4454. static int
  4455. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4456. {
  4457. (void)unused;
  4458. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4459. InitializeCriticalSection(&mutex->sec);
  4460. return 0;
  4461. }
  4462. static int
  4463. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4464. {
  4465. DeleteCriticalSection(&mutex->sec);
  4466. return 0;
  4467. }
  4468. static int
  4469. pthread_mutex_lock(pthread_mutex_t *mutex)
  4470. {
  4471. EnterCriticalSection(&mutex->sec);
  4472. return 0;
  4473. }
  4474. static int
  4475. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4476. {
  4477. LeaveCriticalSection(&mutex->sec);
  4478. return 0;
  4479. }
  4480. FUNCTION_MAY_BE_UNUSED
  4481. static int
  4482. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4483. {
  4484. (void)unused;
  4485. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4486. cv->waiting_thread = NULL;
  4487. return 0;
  4488. }
  4489. FUNCTION_MAY_BE_UNUSED
  4490. static int
  4491. pthread_cond_timedwait(pthread_cond_t *cv,
  4492. pthread_mutex_t *mutex,
  4493. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4494. {
  4495. struct mg_workerTLS **ptls,
  4496. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4497. int ok;
  4498. int64_t nsnow, nswaitabs, nswaitrel;
  4499. DWORD mswaitrel;
  4500. pthread_mutex_lock(&cv->threadIdSec);
  4501. /* Add this thread to cv's waiting list */
  4502. ptls = &cv->waiting_thread;
  4503. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4504. ;
  4505. tls->next_waiting_thread = NULL;
  4506. *ptls = tls;
  4507. pthread_mutex_unlock(&cv->threadIdSec);
  4508. if (abstime) {
  4509. nsnow = mg_get_current_time_ns();
  4510. nswaitabs =
  4511. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4512. nswaitrel = nswaitabs - nsnow;
  4513. if (nswaitrel < 0) {
  4514. nswaitrel = 0;
  4515. }
  4516. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4517. } else {
  4518. mswaitrel = (DWORD)INFINITE;
  4519. }
  4520. pthread_mutex_unlock(mutex);
  4521. ok = (WAIT_OBJECT_0
  4522. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4523. if (!ok) {
  4524. ok = 1;
  4525. pthread_mutex_lock(&cv->threadIdSec);
  4526. ptls = &cv->waiting_thread;
  4527. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4528. if (*ptls == tls) {
  4529. *ptls = tls->next_waiting_thread;
  4530. ok = 0;
  4531. break;
  4532. }
  4533. }
  4534. pthread_mutex_unlock(&cv->threadIdSec);
  4535. if (ok) {
  4536. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4537. (DWORD)INFINITE);
  4538. }
  4539. }
  4540. /* This thread has been removed from cv's waiting list */
  4541. pthread_mutex_lock(mutex);
  4542. return ok ? 0 : -1;
  4543. }
  4544. FUNCTION_MAY_BE_UNUSED
  4545. static int
  4546. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4547. {
  4548. return pthread_cond_timedwait(cv, mutex, NULL);
  4549. }
  4550. FUNCTION_MAY_BE_UNUSED
  4551. static int
  4552. pthread_cond_signal(pthread_cond_t *cv)
  4553. {
  4554. HANDLE wkup = NULL;
  4555. BOOL ok = FALSE;
  4556. pthread_mutex_lock(&cv->threadIdSec);
  4557. if (cv->waiting_thread) {
  4558. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4559. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4560. ok = SetEvent(wkup);
  4561. DEBUG_ASSERT(ok);
  4562. }
  4563. pthread_mutex_unlock(&cv->threadIdSec);
  4564. return ok ? 0 : 1;
  4565. }
  4566. FUNCTION_MAY_BE_UNUSED
  4567. static int
  4568. pthread_cond_broadcast(pthread_cond_t *cv)
  4569. {
  4570. pthread_mutex_lock(&cv->threadIdSec);
  4571. while (cv->waiting_thread) {
  4572. pthread_cond_signal(cv);
  4573. }
  4574. pthread_mutex_unlock(&cv->threadIdSec);
  4575. return 0;
  4576. }
  4577. FUNCTION_MAY_BE_UNUSED
  4578. static int
  4579. pthread_cond_destroy(pthread_cond_t *cv)
  4580. {
  4581. pthread_mutex_lock(&cv->threadIdSec);
  4582. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4583. pthread_mutex_unlock(&cv->threadIdSec);
  4584. pthread_mutex_destroy(&cv->threadIdSec);
  4585. return 0;
  4586. }
  4587. #if defined(ALTERNATIVE_QUEUE)
  4588. FUNCTION_MAY_BE_UNUSED
  4589. static void *
  4590. event_create(void)
  4591. {
  4592. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4593. }
  4594. FUNCTION_MAY_BE_UNUSED
  4595. static int
  4596. event_wait(void *eventhdl)
  4597. {
  4598. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4599. return (res == WAIT_OBJECT_0);
  4600. }
  4601. FUNCTION_MAY_BE_UNUSED
  4602. static int
  4603. event_signal(void *eventhdl)
  4604. {
  4605. return (int)SetEvent((HANDLE)eventhdl);
  4606. }
  4607. FUNCTION_MAY_BE_UNUSED
  4608. static void
  4609. event_destroy(void *eventhdl)
  4610. {
  4611. CloseHandle((HANDLE)eventhdl);
  4612. }
  4613. #endif
  4614. #if defined(GCC_DIAGNOSTIC)
  4615. /* Enable unused function warning again */
  4616. #pragma GCC diagnostic pop
  4617. #endif
  4618. /* For Windows, change all slashes to backslashes in path names. */
  4619. static void
  4620. change_slashes_to_backslashes(char *path)
  4621. {
  4622. int i;
  4623. for (i = 0; path[i] != '\0'; i++) {
  4624. if (path[i] == '/') {
  4625. path[i] = '\\';
  4626. }
  4627. /* remove double backslash (check i > 0 to preserve UNC paths,
  4628. * like \\server\file.txt) */
  4629. if ((i > 0) && (path[i] == '\\')) {
  4630. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4631. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4632. }
  4633. }
  4634. }
  4635. }
  4636. static int
  4637. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4638. {
  4639. int diff;
  4640. do {
  4641. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4642. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4643. s1++;
  4644. s2++;
  4645. } while ((diff == 0) && (s1[-1] != L'\0'));
  4646. return diff;
  4647. }
  4648. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4649. * wbuf and wbuf_len is a target buffer and its length. */
  4650. static void
  4651. path_to_unicode(const struct mg_connection *conn,
  4652. const char *path,
  4653. wchar_t *wbuf,
  4654. size_t wbuf_len)
  4655. {
  4656. char buf[PATH_MAX], buf2[PATH_MAX];
  4657. wchar_t wbuf2[W_PATH_MAX + 1];
  4658. DWORD long_len, err;
  4659. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4660. mg_strlcpy(buf, path, sizeof(buf));
  4661. change_slashes_to_backslashes(buf);
  4662. /* Convert to Unicode and back. If doubly-converted string does not
  4663. * match the original, something is fishy, reject. */
  4664. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4665. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4666. WideCharToMultiByte(
  4667. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4668. if (strcmp(buf, buf2) != 0) {
  4669. wbuf[0] = L'\0';
  4670. }
  4671. /* Windows file systems are not case sensitive, but you can still use
  4672. * uppercase and lowercase letters (on all modern file systems).
  4673. * The server can check if the URI uses the same upper/lowercase
  4674. * letters an the file system, effectively making Windows servers
  4675. * case sensitive (like Linux servers are). It is still not possible
  4676. * to use two files with the same name in different cases on Windows
  4677. * (like /a and /A) - this would be possible in Linux.
  4678. * As a default, Windows is not case sensitive, but the case sensitive
  4679. * file name check can be activated by an additional configuration. */
  4680. if (conn) {
  4681. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4682. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4683. "yes")) {
  4684. /* Use case sensitive compare function */
  4685. fcompare = wcscmp;
  4686. }
  4687. }
  4688. (void)conn; /* conn is currently unused */
  4689. #if !defined(_WIN32_WCE)
  4690. /* Only accept a full file path, not a Windows short (8.3) path. */
  4691. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4692. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4693. if (long_len == 0) {
  4694. err = GetLastError();
  4695. if (err == ERROR_FILE_NOT_FOUND) {
  4696. /* File does not exist. This is not always a problem here. */
  4697. return;
  4698. }
  4699. }
  4700. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4701. /* Short name is used. */
  4702. wbuf[0] = L'\0';
  4703. }
  4704. #else
  4705. (void)long_len;
  4706. (void)wbuf2;
  4707. (void)err;
  4708. if (strchr(path, '~')) {
  4709. wbuf[0] = L'\0';
  4710. }
  4711. #endif
  4712. }
  4713. #if !defined(NO_FILESYSTEMS)
  4714. /* Get file information, return 1 if file exists, 0 if not */
  4715. static int
  4716. mg_stat(const struct mg_connection *conn,
  4717. const char *path,
  4718. struct mg_file_stat *filep)
  4719. {
  4720. wchar_t wbuf[W_PATH_MAX];
  4721. WIN32_FILE_ATTRIBUTE_DATA info;
  4722. time_t creation_time;
  4723. size_t len;
  4724. if (!filep) {
  4725. return 0;
  4726. }
  4727. memset(filep, 0, sizeof(*filep));
  4728. if (mg_path_suspicious(conn, path)) {
  4729. return 0;
  4730. }
  4731. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4732. /* Windows happily opens files with some garbage at the end of file name.
  4733. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4734. * "a.cgi", despite one would expect an error back. */
  4735. len = strlen(path);
  4736. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4737. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4738. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4739. filep->last_modified =
  4740. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4741. info.ftLastWriteTime.dwHighDateTime);
  4742. /* On Windows, the file creation time can be higher than the
  4743. * modification time, e.g. when a file is copied.
  4744. * Since the Last-Modified timestamp is used for caching
  4745. * it should be based on the most recent timestamp. */
  4746. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4747. info.ftCreationTime.dwHighDateTime);
  4748. if (creation_time > filep->last_modified) {
  4749. filep->last_modified = creation_time;
  4750. }
  4751. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4752. return 1;
  4753. }
  4754. return 0;
  4755. }
  4756. #endif
  4757. static int
  4758. mg_remove(const struct mg_connection *conn, const char *path)
  4759. {
  4760. wchar_t wbuf[W_PATH_MAX];
  4761. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4762. return DeleteFileW(wbuf) ? 0 : -1;
  4763. }
  4764. static int
  4765. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4766. {
  4767. wchar_t wbuf[W_PATH_MAX];
  4768. (void)mode;
  4769. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4770. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4771. }
  4772. /* Create substitutes for POSIX functions in Win32. */
  4773. #if defined(GCC_DIAGNOSTIC)
  4774. /* Show no warning in case system functions are not used. */
  4775. #pragma GCC diagnostic push
  4776. #pragma GCC diagnostic ignored "-Wunused-function"
  4777. #endif
  4778. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4779. FUNCTION_MAY_BE_UNUSED
  4780. static DIR *
  4781. mg_opendir(const struct mg_connection *conn, const char *name)
  4782. {
  4783. DIR *dir = NULL;
  4784. wchar_t wpath[W_PATH_MAX];
  4785. DWORD attrs;
  4786. if (name == NULL) {
  4787. SetLastError(ERROR_BAD_ARGUMENTS);
  4788. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4789. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4790. } else {
  4791. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4792. attrs = GetFileAttributesW(wpath);
  4793. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4794. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4795. (void)wcscat(wpath, L"\\*");
  4796. dir->handle = FindFirstFileW(wpath, &dir->info);
  4797. dir->result.d_name[0] = '\0';
  4798. } else {
  4799. mg_free(dir);
  4800. dir = NULL;
  4801. }
  4802. }
  4803. return dir;
  4804. }
  4805. FUNCTION_MAY_BE_UNUSED
  4806. static int
  4807. mg_closedir(DIR *dir)
  4808. {
  4809. int result = 0;
  4810. if (dir != NULL) {
  4811. if (dir->handle != INVALID_HANDLE_VALUE)
  4812. result = FindClose(dir->handle) ? 0 : -1;
  4813. mg_free(dir);
  4814. } else {
  4815. result = -1;
  4816. SetLastError(ERROR_BAD_ARGUMENTS);
  4817. }
  4818. return result;
  4819. }
  4820. FUNCTION_MAY_BE_UNUSED
  4821. static struct dirent *
  4822. mg_readdir(DIR *dir)
  4823. {
  4824. struct dirent *result = 0;
  4825. if (dir) {
  4826. if (dir->handle != INVALID_HANDLE_VALUE) {
  4827. result = &dir->result;
  4828. (void)WideCharToMultiByte(CP_UTF8,
  4829. 0,
  4830. dir->info.cFileName,
  4831. -1,
  4832. result->d_name,
  4833. sizeof(result->d_name),
  4834. NULL,
  4835. NULL);
  4836. if (!FindNextFileW(dir->handle, &dir->info)) {
  4837. (void)FindClose(dir->handle);
  4838. dir->handle = INVALID_HANDLE_VALUE;
  4839. }
  4840. } else {
  4841. SetLastError(ERROR_FILE_NOT_FOUND);
  4842. }
  4843. } else {
  4844. SetLastError(ERROR_BAD_ARGUMENTS);
  4845. }
  4846. return result;
  4847. }
  4848. #if !defined(HAVE_POLL)
  4849. #undef POLLIN
  4850. #undef POLLPRI
  4851. #undef POLLOUT
  4852. #define POLLIN (1) /* Data ready - read will not block. */
  4853. #define POLLPRI (2) /* Priority data ready. */
  4854. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4855. FUNCTION_MAY_BE_UNUSED
  4856. static int
  4857. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4858. {
  4859. struct timeval tv;
  4860. fd_set rset;
  4861. fd_set wset;
  4862. unsigned int i;
  4863. int result;
  4864. SOCKET maxfd = 0;
  4865. memset(&tv, 0, sizeof(tv));
  4866. tv.tv_sec = milliseconds / 1000;
  4867. tv.tv_usec = (milliseconds % 1000) * 1000;
  4868. FD_ZERO(&rset);
  4869. FD_ZERO(&wset);
  4870. for (i = 0; i < n; i++) {
  4871. if (pfd[i].events & POLLIN) {
  4872. FD_SET(pfd[i].fd, &rset);
  4873. }
  4874. if (pfd[i].events & POLLOUT) {
  4875. FD_SET(pfd[i].fd, &wset);
  4876. }
  4877. pfd[i].revents = 0;
  4878. if (pfd[i].fd > maxfd) {
  4879. maxfd = pfd[i].fd;
  4880. }
  4881. }
  4882. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4883. for (i = 0; i < n; i++) {
  4884. if (FD_ISSET(pfd[i].fd, &rset)) {
  4885. pfd[i].revents |= POLLIN;
  4886. }
  4887. if (FD_ISSET(pfd[i].fd, &wset)) {
  4888. pfd[i].revents |= POLLOUT;
  4889. }
  4890. }
  4891. }
  4892. /* We should subtract the time used in select from remaining
  4893. * "milliseconds", in particular if called from mg_poll with a
  4894. * timeout quantum.
  4895. * Unfortunately, the remaining time is not stored in "tv" in all
  4896. * implementations, so the result in "tv" must be considered undefined.
  4897. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4898. return result;
  4899. }
  4900. #endif /* HAVE_POLL */
  4901. #if defined(GCC_DIAGNOSTIC)
  4902. /* Enable unused function warning again */
  4903. #pragma GCC diagnostic pop
  4904. #endif
  4905. static void
  4906. set_close_on_exec(SOCKET sock,
  4907. const struct mg_connection *conn /* may be null */,
  4908. struct mg_context *ctx /* may be null */)
  4909. {
  4910. (void)conn; /* Unused. */
  4911. (void)ctx;
  4912. #if defined(_WIN32_WCE)
  4913. (void)sock;
  4914. #else
  4915. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4916. #endif
  4917. }
  4918. int
  4919. mg_start_thread(mg_thread_func_t f, void *p)
  4920. {
  4921. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4922. /* Compile-time option to control stack size, e.g.
  4923. * -DUSE_STACK_SIZE=16384
  4924. */
  4925. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4926. == ((uintptr_t)(-1L)))
  4927. ? -1
  4928. : 0);
  4929. #else
  4930. return (
  4931. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4932. ? -1
  4933. : 0);
  4934. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4935. }
  4936. /* Start a thread storing the thread context. */
  4937. static int
  4938. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4939. void *p,
  4940. pthread_t *threadidptr)
  4941. {
  4942. uintptr_t uip;
  4943. HANDLE threadhandle;
  4944. int result = -1;
  4945. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4946. threadhandle = (HANDLE)uip;
  4947. if ((uip != 0) && (threadidptr != NULL)) {
  4948. *threadidptr = threadhandle;
  4949. result = 0;
  4950. }
  4951. return result;
  4952. }
  4953. /* Wait for a thread to finish. */
  4954. static int
  4955. mg_join_thread(pthread_t threadid)
  4956. {
  4957. int result;
  4958. DWORD dwevent;
  4959. result = -1;
  4960. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4961. if (dwevent == WAIT_FAILED) {
  4962. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4963. } else {
  4964. if (dwevent == WAIT_OBJECT_0) {
  4965. CloseHandle(threadid);
  4966. result = 0;
  4967. }
  4968. }
  4969. return result;
  4970. }
  4971. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4972. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4973. /* Create substitutes for POSIX functions in Win32. */
  4974. #if defined(GCC_DIAGNOSTIC)
  4975. /* Show no warning in case system functions are not used. */
  4976. #pragma GCC diagnostic push
  4977. #pragma GCC diagnostic ignored "-Wunused-function"
  4978. #endif
  4979. FUNCTION_MAY_BE_UNUSED
  4980. static HANDLE
  4981. dlopen(const char *dll_name, int flags)
  4982. {
  4983. wchar_t wbuf[W_PATH_MAX];
  4984. (void)flags;
  4985. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4986. return LoadLibraryW(wbuf);
  4987. }
  4988. FUNCTION_MAY_BE_UNUSED
  4989. static int
  4990. dlclose(void *handle)
  4991. {
  4992. int result;
  4993. if (FreeLibrary((HMODULE)handle) != 0) {
  4994. result = 0;
  4995. } else {
  4996. result = -1;
  4997. }
  4998. return result;
  4999. }
  5000. #if defined(GCC_DIAGNOSTIC)
  5001. /* Enable unused function warning again */
  5002. #pragma GCC diagnostic pop
  5003. #endif
  5004. #endif
  5005. #if !defined(NO_CGI)
  5006. #define SIGKILL (0)
  5007. static int
  5008. kill(pid_t pid, int sig_num)
  5009. {
  5010. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  5011. (void)CloseHandle((HANDLE)pid);
  5012. return 0;
  5013. }
  5014. #if !defined(WNOHANG)
  5015. #define WNOHANG (1)
  5016. #endif
  5017. static pid_t
  5018. waitpid(pid_t pid, int *status, int flags)
  5019. {
  5020. DWORD timeout = INFINITE;
  5021. DWORD waitres;
  5022. (void)status; /* Currently not used by any client here */
  5023. if ((flags | WNOHANG) == WNOHANG) {
  5024. timeout = 0;
  5025. }
  5026. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  5027. if (waitres == WAIT_OBJECT_0) {
  5028. return pid;
  5029. }
  5030. if (waitres == WAIT_TIMEOUT) {
  5031. return 0;
  5032. }
  5033. return (pid_t)-1;
  5034. }
  5035. static void
  5036. trim_trailing_whitespaces(char *s)
  5037. {
  5038. char *e = s + strlen(s);
  5039. while ((e > s) && isspace((unsigned char)e[-1])) {
  5040. *(--e) = '\0';
  5041. }
  5042. }
  5043. static pid_t
  5044. spawn_process(struct mg_connection *conn,
  5045. const char *prog,
  5046. char *envblk,
  5047. char *envp[],
  5048. int fdin[2],
  5049. int fdout[2],
  5050. int fderr[2],
  5051. const char *dir)
  5052. {
  5053. HANDLE me;
  5054. char *interp;
  5055. char *interp_arg = 0;
  5056. char full_dir[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX];
  5057. int truncated;
  5058. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5059. STARTUPINFOA si;
  5060. PROCESS_INFORMATION pi = {0};
  5061. (void)envp;
  5062. memset(&si, 0, sizeof(si));
  5063. si.cb = sizeof(si);
  5064. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5065. si.wShowWindow = SW_HIDE;
  5066. me = GetCurrentProcess();
  5067. DuplicateHandle(me,
  5068. (HANDLE)_get_osfhandle(fdin[0]),
  5069. me,
  5070. &si.hStdInput,
  5071. 0,
  5072. TRUE,
  5073. DUPLICATE_SAME_ACCESS);
  5074. DuplicateHandle(me,
  5075. (HANDLE)_get_osfhandle(fdout[1]),
  5076. me,
  5077. &si.hStdOutput,
  5078. 0,
  5079. TRUE,
  5080. DUPLICATE_SAME_ACCESS);
  5081. DuplicateHandle(me,
  5082. (HANDLE)_get_osfhandle(fderr[1]),
  5083. me,
  5084. &si.hStdError,
  5085. 0,
  5086. TRUE,
  5087. DUPLICATE_SAME_ACCESS);
  5088. /* Mark handles that should not be inherited. See
  5089. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5090. */
  5091. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5092. HANDLE_FLAG_INHERIT,
  5093. 0);
  5094. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5095. HANDLE_FLAG_INHERIT,
  5096. 0);
  5097. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5098. HANDLE_FLAG_INHERIT,
  5099. 0);
  5100. /* First check, if there is a CGI interpreter configured for all CGI
  5101. * scripts. */
  5102. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5103. if (interp != NULL) {
  5104. /* If there is a configured interpreter, check for additional arguments
  5105. */
  5106. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5107. } else {
  5108. /* Otherwise, the interpreter must be stated in the first line of the
  5109. * CGI script file, after a #! (shebang) mark. */
  5110. buf[0] = buf[1] = '\0';
  5111. /* Get the full script path */
  5112. mg_snprintf(
  5113. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5114. if (truncated) {
  5115. pi.hProcess = (pid_t)-1;
  5116. goto spawn_cleanup;
  5117. }
  5118. /* Open the script file, to read the first line */
  5119. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5120. /* Read the first line of the script into the buffer */
  5121. mg_fgets(buf, sizeof(buf), &file);
  5122. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5123. buf[sizeof(buf) - 1] = '\0';
  5124. }
  5125. if ((buf[0] == '#') && (buf[1] == '!')) {
  5126. trim_trailing_whitespaces(buf + 2);
  5127. } else {
  5128. buf[2] = '\0';
  5129. }
  5130. interp = buf + 2;
  5131. }
  5132. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5133. if (interp[0] != '\0') {
  5134. /* This is an interpreted script file. We must call the interpreter. */
  5135. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5136. mg_snprintf(conn,
  5137. &truncated,
  5138. cmdline,
  5139. sizeof(cmdline),
  5140. "\"%s\" %s \"%s\\%s\"",
  5141. interp,
  5142. interp_arg,
  5143. full_dir,
  5144. prog);
  5145. } else {
  5146. mg_snprintf(conn,
  5147. &truncated,
  5148. cmdline,
  5149. sizeof(cmdline),
  5150. "\"%s\" \"%s\\%s\"",
  5151. interp,
  5152. full_dir,
  5153. prog);
  5154. }
  5155. } else {
  5156. /* This is (probably) a compiled program. We call it directly. */
  5157. mg_snprintf(conn,
  5158. &truncated,
  5159. cmdline,
  5160. sizeof(cmdline),
  5161. "\"%s\\%s\"",
  5162. full_dir,
  5163. prog);
  5164. }
  5165. if (truncated) {
  5166. pi.hProcess = (pid_t)-1;
  5167. goto spawn_cleanup;
  5168. }
  5169. DEBUG_TRACE("Running [%s]", cmdline);
  5170. if (CreateProcessA(NULL,
  5171. cmdline,
  5172. NULL,
  5173. NULL,
  5174. TRUE,
  5175. CREATE_NEW_PROCESS_GROUP,
  5176. envblk,
  5177. NULL,
  5178. &si,
  5179. &pi)
  5180. == 0) {
  5181. mg_cry_internal(
  5182. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5183. pi.hProcess = (pid_t)-1;
  5184. /* goto spawn_cleanup; */
  5185. }
  5186. spawn_cleanup:
  5187. (void)CloseHandle(si.hStdOutput);
  5188. (void)CloseHandle(si.hStdError);
  5189. (void)CloseHandle(si.hStdInput);
  5190. if (pi.hThread != NULL) {
  5191. (void)CloseHandle(pi.hThread);
  5192. }
  5193. return (pid_t)pi.hProcess;
  5194. }
  5195. #endif /* !NO_CGI */
  5196. static int
  5197. set_blocking_mode(SOCKET sock)
  5198. {
  5199. unsigned long non_blocking = 0;
  5200. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5201. }
  5202. static int
  5203. set_non_blocking_mode(SOCKET sock)
  5204. {
  5205. unsigned long non_blocking = 1;
  5206. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5207. }
  5208. #else
  5209. #if !defined(NO_FILESYSTEMS)
  5210. static int
  5211. mg_stat(const struct mg_connection *conn,
  5212. const char *path,
  5213. struct mg_file_stat *filep)
  5214. {
  5215. struct stat st;
  5216. if (!filep) {
  5217. return 0;
  5218. }
  5219. memset(filep, 0, sizeof(*filep));
  5220. if (mg_path_suspicious(conn, path)) {
  5221. return 0;
  5222. }
  5223. if (0 == stat(path, &st)) {
  5224. filep->size = (uint64_t)(st.st_size);
  5225. filep->last_modified = st.st_mtime;
  5226. filep->is_directory = S_ISDIR(st.st_mode);
  5227. return 1;
  5228. }
  5229. return 0;
  5230. }
  5231. #endif /* NO_FILESYSTEMS */
  5232. static void
  5233. set_close_on_exec(int fd,
  5234. const struct mg_connection *conn /* may be null */,
  5235. struct mg_context *ctx /* may be null */)
  5236. {
  5237. #if defined(__ZEPHYR__)
  5238. (void)fd;
  5239. (void)conn;
  5240. (void)ctx;
  5241. #else
  5242. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5243. if (conn || ctx) {
  5244. struct mg_connection fc;
  5245. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5246. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5247. __func__,
  5248. strerror(ERRNO));
  5249. }
  5250. }
  5251. #endif
  5252. }
  5253. int
  5254. mg_start_thread(mg_thread_func_t func, void *param)
  5255. {
  5256. pthread_t thread_id;
  5257. pthread_attr_t attr;
  5258. int result;
  5259. (void)pthread_attr_init(&attr);
  5260. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5261. #if defined(__ZEPHYR__)
  5262. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5263. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5264. /* Compile-time option to control stack size,
  5265. * e.g. -DUSE_STACK_SIZE=16384 */
  5266. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5267. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5268. result = pthread_create(&thread_id, &attr, func, param);
  5269. pthread_attr_destroy(&attr);
  5270. return result;
  5271. }
  5272. /* Start a thread storing the thread context. */
  5273. static int
  5274. mg_start_thread_with_id(mg_thread_func_t func,
  5275. void *param,
  5276. pthread_t *threadidptr)
  5277. {
  5278. pthread_t thread_id;
  5279. pthread_attr_t attr;
  5280. int result;
  5281. (void)pthread_attr_init(&attr);
  5282. #if defined(__ZEPHYR__)
  5283. pthread_attr_setstack(&attr,
  5284. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5285. ZEPHYR_STACK_SIZE);
  5286. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5287. /* Compile-time option to control stack size,
  5288. * e.g. -DUSE_STACK_SIZE=16384 */
  5289. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5290. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5291. result = pthread_create(&thread_id, &attr, func, param);
  5292. pthread_attr_destroy(&attr);
  5293. if ((result == 0) && (threadidptr != NULL)) {
  5294. *threadidptr = thread_id;
  5295. }
  5296. return result;
  5297. }
  5298. /* Wait for a thread to finish. */
  5299. static int
  5300. mg_join_thread(pthread_t threadid)
  5301. {
  5302. int result;
  5303. result = pthread_join(threadid, NULL);
  5304. return result;
  5305. }
  5306. #if !defined(NO_CGI)
  5307. static pid_t
  5308. spawn_process(struct mg_connection *conn,
  5309. const char *prog,
  5310. char *envblk,
  5311. char *envp[],
  5312. int fdin[2],
  5313. int fdout[2],
  5314. int fderr[2],
  5315. const char *dir)
  5316. {
  5317. pid_t pid;
  5318. const char *interp;
  5319. (void)envblk;
  5320. if ((pid = fork()) == -1) {
  5321. /* Parent */
  5322. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5323. } else if (pid != 0) {
  5324. /* Make sure children close parent-side descriptors.
  5325. * The caller will close the child-side immediately. */
  5326. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5327. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5328. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5329. } else {
  5330. /* Child */
  5331. if (chdir(dir) != 0) {
  5332. mg_cry_internal(
  5333. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5334. } else if (dup2(fdin[0], 0) == -1) {
  5335. mg_cry_internal(conn,
  5336. "%s: dup2(%d, 0): %s",
  5337. __func__,
  5338. fdin[0],
  5339. strerror(ERRNO));
  5340. } else if (dup2(fdout[1], 1) == -1) {
  5341. mg_cry_internal(conn,
  5342. "%s: dup2(%d, 1): %s",
  5343. __func__,
  5344. fdout[1],
  5345. strerror(ERRNO));
  5346. } else if (dup2(fderr[1], 2) == -1) {
  5347. mg_cry_internal(conn,
  5348. "%s: dup2(%d, 2): %s",
  5349. __func__,
  5350. fderr[1],
  5351. strerror(ERRNO));
  5352. } else {
  5353. struct sigaction sa;
  5354. /* Keep stderr and stdout in two different pipes.
  5355. * Stdout will be sent back to the client,
  5356. * stderr should go into a server error log. */
  5357. (void)close(fdin[0]);
  5358. (void)close(fdout[1]);
  5359. (void)close(fderr[1]);
  5360. /* Close write end fdin and read end fdout and fderr */
  5361. (void)close(fdin[1]);
  5362. (void)close(fdout[0]);
  5363. (void)close(fderr[0]);
  5364. /* After exec, all signal handlers are restored to their default
  5365. * values, with one exception of SIGCHLD. According to
  5366. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5367. * will leave unchanged after exec if it was set to be ignored.
  5368. * Restore it to default action. */
  5369. memset(&sa, 0, sizeof(sa));
  5370. sa.sa_handler = SIG_DFL;
  5371. sigaction(SIGCHLD, &sa, NULL);
  5372. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5373. if (interp == NULL) {
  5374. /* no interpreter configured, call the programm directly */
  5375. (void)execle(prog, prog, NULL, envp);
  5376. mg_cry_internal(conn,
  5377. "%s: execle(%s): %s",
  5378. __func__,
  5379. prog,
  5380. strerror(ERRNO));
  5381. } else {
  5382. /* call the configured interpreter */
  5383. const char *interp_args =
  5384. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5385. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5386. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5387. } else {
  5388. (void)execle(interp, interp, prog, NULL, envp);
  5389. }
  5390. mg_cry_internal(conn,
  5391. "%s: execle(%s %s): %s",
  5392. __func__,
  5393. interp,
  5394. prog,
  5395. strerror(ERRNO));
  5396. }
  5397. }
  5398. exit(EXIT_FAILURE);
  5399. }
  5400. return pid;
  5401. }
  5402. #endif /* !NO_CGI */
  5403. static int
  5404. set_non_blocking_mode(SOCKET sock)
  5405. {
  5406. int flags = fcntl(sock, F_GETFL, 0);
  5407. if (flags < 0) {
  5408. return -1;
  5409. }
  5410. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5411. return -1;
  5412. }
  5413. return 0;
  5414. }
  5415. static int
  5416. set_blocking_mode(SOCKET sock)
  5417. {
  5418. int flags = fcntl(sock, F_GETFL, 0);
  5419. if (flags < 0) {
  5420. return -1;
  5421. }
  5422. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5423. return -1;
  5424. }
  5425. return 0;
  5426. }
  5427. #endif /* _WIN32 / else */
  5428. /* End of initial operating system specific define block. */
  5429. /* Get a random number (independent of C rand function) */
  5430. static uint64_t
  5431. get_random(void)
  5432. {
  5433. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5434. static uint64_t lcg = 0; /* Linear congruential generator */
  5435. uint64_t now = mg_get_current_time_ns();
  5436. if (lfsr == 0) {
  5437. /* lfsr will be only 0 if has not been initialized,
  5438. * so this code is called only once. */
  5439. lfsr = mg_get_current_time_ns();
  5440. lcg = mg_get_current_time_ns();
  5441. } else {
  5442. /* Get the next step of both random number generators. */
  5443. lfsr = (lfsr >> 1)
  5444. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5445. << 63);
  5446. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5447. }
  5448. /* Combining two pseudo-random number generators and a high resolution
  5449. * part
  5450. * of the current server time will make it hard (impossible?) to guess
  5451. * the
  5452. * next number. */
  5453. return (lfsr ^ lcg ^ now);
  5454. }
  5455. static int
  5456. mg_poll(struct mg_pollfd *pfd,
  5457. unsigned int n,
  5458. int milliseconds,
  5459. stop_flag_t *stop_flag)
  5460. {
  5461. /* Call poll, but only for a maximum time of a few seconds.
  5462. * This will allow to stop the server after some seconds, instead
  5463. * of having to wait for a long socket timeout. */
  5464. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5465. do {
  5466. int result;
  5467. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5468. /* Shut down signal */
  5469. return -2;
  5470. }
  5471. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5472. ms_now = milliseconds;
  5473. }
  5474. result = poll(pfd, n, ms_now);
  5475. if (result != 0) {
  5476. /* Poll returned either success (1) or error (-1).
  5477. * Forward both to the caller. */
  5478. return result;
  5479. }
  5480. /* Poll returned timeout (0). */
  5481. if (milliseconds > 0) {
  5482. milliseconds -= ms_now;
  5483. }
  5484. } while (milliseconds > 0);
  5485. /* timeout: return 0 */
  5486. return 0;
  5487. }
  5488. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5489. * descriptor.
  5490. * Return value:
  5491. * >=0 .. number of bytes successfully written
  5492. * -1 .. timeout
  5493. * -2 .. error
  5494. */
  5495. static int
  5496. push_inner(struct mg_context *ctx,
  5497. FILE *fp,
  5498. SOCKET sock,
  5499. SSL *ssl,
  5500. const char *buf,
  5501. int len,
  5502. double timeout)
  5503. {
  5504. uint64_t start = 0, now = 0, timeout_ns = 0;
  5505. int n, err;
  5506. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5507. #if defined(_WIN32)
  5508. typedef int len_t;
  5509. #else
  5510. typedef size_t len_t;
  5511. #endif
  5512. if (timeout > 0) {
  5513. now = mg_get_current_time_ns();
  5514. start = now;
  5515. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5516. }
  5517. if (ctx == NULL) {
  5518. return -2;
  5519. }
  5520. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5521. if (ssl) {
  5522. return -2;
  5523. }
  5524. #endif
  5525. /* Try to read until it succeeds, fails, times out, or the server
  5526. * shuts down. */
  5527. for (;;) {
  5528. #if !defined(NO_SSL)
  5529. if (ssl != NULL) {
  5530. ERR_clear_error();
  5531. n = SSL_write(ssl, buf, len);
  5532. if (n <= 0) {
  5533. err = SSL_get_error(ssl, n);
  5534. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5535. err = ERRNO;
  5536. } else if ((err == SSL_ERROR_WANT_READ)
  5537. || (err == SSL_ERROR_WANT_WRITE)) {
  5538. n = 0;
  5539. } else {
  5540. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5541. ERR_clear_error();
  5542. return -2;
  5543. }
  5544. ERR_clear_error();
  5545. } else {
  5546. err = 0;
  5547. }
  5548. } else
  5549. #endif
  5550. #if defined(USE_MBEDTLS)
  5551. if (ssl != NULL) {
  5552. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5553. if (n <= 0) {
  5554. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5555. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5556. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5557. n = 0;
  5558. } else {
  5559. fprintf(stderr, "SSL write failed, error %d\n", n);
  5560. return -2;
  5561. }
  5562. } else {
  5563. err = 0;
  5564. }
  5565. } else
  5566. #endif
  5567. if (fp != NULL) {
  5568. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5569. if (ferror(fp)) {
  5570. n = -1;
  5571. err = ERRNO;
  5572. } else {
  5573. err = 0;
  5574. }
  5575. } else {
  5576. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5577. err = (n < 0) ? ERRNO : 0;
  5578. #if defined(_WIN32)
  5579. if (err == WSAEWOULDBLOCK) {
  5580. err = 0;
  5581. n = 0;
  5582. }
  5583. #else
  5584. if (ERROR_TRY_AGAIN(err)) {
  5585. err = 0;
  5586. n = 0;
  5587. }
  5588. #endif
  5589. if (n < 0) {
  5590. /* shutdown of the socket at client side */
  5591. return -2;
  5592. }
  5593. }
  5594. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5595. return -2;
  5596. }
  5597. if ((n > 0) || ((n == 0) && (len == 0))) {
  5598. /* some data has been read, or no data was requested */
  5599. return n;
  5600. }
  5601. if (n < 0) {
  5602. /* socket error - check errno */
  5603. DEBUG_TRACE("send() failed, error %d", err);
  5604. /* TODO (mid): error handling depending on the error code.
  5605. * These codes are different between Windows and Linux.
  5606. * Currently there is no problem with failing send calls,
  5607. * if there is a reproducible situation, it should be
  5608. * investigated in detail.
  5609. */
  5610. return -2;
  5611. }
  5612. /* Only in case n=0 (timeout), repeat calling the write function */
  5613. /* If send failed, wait before retry */
  5614. if (fp != NULL) {
  5615. /* For files, just wait a fixed time.
  5616. * Maybe it helps, maybe not. */
  5617. mg_sleep(5);
  5618. } else {
  5619. /* For sockets, wait for the socket using poll */
  5620. struct mg_pollfd pfd[1];
  5621. int pollres;
  5622. pfd[0].fd = sock;
  5623. pfd[0].events = POLLOUT;
  5624. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5625. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5626. return -2;
  5627. }
  5628. if (pollres > 0) {
  5629. continue;
  5630. }
  5631. }
  5632. if (timeout > 0) {
  5633. now = mg_get_current_time_ns();
  5634. if ((now - start) > timeout_ns) {
  5635. /* Timeout */
  5636. break;
  5637. }
  5638. }
  5639. }
  5640. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5641. used */
  5642. return -1;
  5643. }
  5644. static int
  5645. push_all(struct mg_context *ctx,
  5646. FILE *fp,
  5647. SOCKET sock,
  5648. SSL *ssl,
  5649. const char *buf,
  5650. int len)
  5651. {
  5652. double timeout = -1.0;
  5653. int n, nwritten = 0;
  5654. if (ctx == NULL) {
  5655. return -1;
  5656. }
  5657. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5658. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5659. }
  5660. if (timeout <= 0.0) {
  5661. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5662. }
  5663. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5664. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5665. if (n < 0) {
  5666. if (nwritten == 0) {
  5667. nwritten = -1; /* Propagate the error */
  5668. }
  5669. break;
  5670. } else if (n == 0) {
  5671. break; /* No more data to write */
  5672. } else {
  5673. nwritten += n;
  5674. len -= n;
  5675. }
  5676. }
  5677. return nwritten;
  5678. }
  5679. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5680. * Return value:
  5681. * >=0 .. number of bytes successfully read
  5682. * -1 .. timeout
  5683. * -2 .. error
  5684. */
  5685. static int
  5686. pull_inner(FILE *fp,
  5687. struct mg_connection *conn,
  5688. char *buf,
  5689. int len,
  5690. double timeout)
  5691. {
  5692. int nread, err = 0;
  5693. #if defined(_WIN32)
  5694. typedef int len_t;
  5695. #else
  5696. typedef size_t len_t;
  5697. #endif
  5698. /* We need an additional wait loop around this, because in some cases
  5699. * with TLSwe may get data from the socket but not from SSL_read.
  5700. * In this case we need to repeat at least once.
  5701. */
  5702. if (fp != NULL) {
  5703. #if !defined(_WIN32_WCE)
  5704. /* Use read() instead of fread(), because if we're reading from the
  5705. * CGI pipe, fread() may block until IO buffer is filled up. We
  5706. * cannot afford to block and must pass all read bytes immediately
  5707. * to the client. */
  5708. nread = (int)read(fileno(fp), buf, (size_t)len);
  5709. #else
  5710. /* WinCE does not support CGI pipes */
  5711. nread = (int)fread(buf, 1, (size_t)len, fp);
  5712. #endif
  5713. err = (nread < 0) ? ERRNO : 0;
  5714. if ((nread == 0) && (len > 0)) {
  5715. /* Should get data, but got EOL */
  5716. return -2;
  5717. }
  5718. #if !defined(NO_SSL)
  5719. } else if (conn->ssl != NULL) {
  5720. int ssl_pending;
  5721. struct mg_pollfd pfd[1];
  5722. int pollres;
  5723. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5724. /* We already know there is no more data buffered in conn->buf
  5725. * but there is more available in the SSL layer. So don't poll
  5726. * conn->client.sock yet. */
  5727. if (ssl_pending > len) {
  5728. ssl_pending = len;
  5729. }
  5730. pollres = 1;
  5731. } else {
  5732. pfd[0].fd = conn->client.sock;
  5733. pfd[0].events = POLLIN;
  5734. pollres = mg_poll(pfd,
  5735. 1,
  5736. (int)(timeout * 1000.0),
  5737. &(conn->phys_ctx->stop_flag));
  5738. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5739. return -2;
  5740. }
  5741. }
  5742. if (pollres > 0) {
  5743. ERR_clear_error();
  5744. nread =
  5745. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5746. if (nread <= 0) {
  5747. err = SSL_get_error(conn->ssl, nread);
  5748. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5749. err = ERRNO;
  5750. } else if ((err == SSL_ERROR_WANT_READ)
  5751. || (err == SSL_ERROR_WANT_WRITE)) {
  5752. nread = 0;
  5753. } else {
  5754. /* All errors should return -2 */
  5755. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5756. ERR_clear_error();
  5757. return -2;
  5758. }
  5759. ERR_clear_error();
  5760. } else {
  5761. err = 0;
  5762. }
  5763. } else if (pollres < 0) {
  5764. /* Error */
  5765. return -2;
  5766. } else {
  5767. /* pollres = 0 means timeout */
  5768. nread = 0;
  5769. }
  5770. #endif
  5771. #if defined(USE_MBEDTLS)
  5772. } else if (conn->ssl != NULL) {
  5773. struct pollfd pfd[1];
  5774. int to_read;
  5775. int pollres;
  5776. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5777. if (to_read > 0) {
  5778. /* We already know there is no more data buffered in conn->buf
  5779. * but there is more available in the SSL layer. So don't poll
  5780. * conn->client.sock yet. */
  5781. pollres = 1;
  5782. if (to_read > len)
  5783. to_read = len;
  5784. }
  5785. else {
  5786. pfd[0].fd = conn->client.sock;
  5787. pfd[0].events = POLLIN;
  5788. to_read = len;
  5789. pollres = mg_poll(pfd,
  5790. 1,
  5791. (int)(timeout * 1000.0),
  5792. &(conn->phys_ctx->stop_flag));
  5793. if (conn->phys_ctx->stop_flag) {
  5794. return -2;
  5795. }
  5796. }
  5797. if (pollres > 0) {
  5798. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5799. if (nread <= 0) {
  5800. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5801. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5802. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5803. nread = 0;
  5804. } else {
  5805. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5806. return -2;
  5807. }
  5808. } else {
  5809. err = 0;
  5810. }
  5811. } else if (pollres < 0) {
  5812. /* Error */
  5813. return -2;
  5814. } else {
  5815. /* pollres = 0 means timeout */
  5816. nread = 0;
  5817. }
  5818. #endif
  5819. } else {
  5820. struct mg_pollfd pfd[1];
  5821. int pollres;
  5822. pfd[0].fd = conn->client.sock;
  5823. pfd[0].events = POLLIN;
  5824. pollres = mg_poll(pfd,
  5825. 1,
  5826. (int)(timeout * 1000.0),
  5827. &(conn->phys_ctx->stop_flag));
  5828. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5829. return -2;
  5830. }
  5831. if (pollres > 0) {
  5832. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5833. err = (nread < 0) ? ERRNO : 0;
  5834. if (nread <= 0) {
  5835. /* shutdown of the socket at client side */
  5836. return -2;
  5837. }
  5838. } else if (pollres < 0) {
  5839. /* error callint poll */
  5840. return -2;
  5841. } else {
  5842. /* pollres = 0 means timeout */
  5843. nread = 0;
  5844. }
  5845. }
  5846. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5847. return -2;
  5848. }
  5849. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5850. /* some data has been read, or no data was requested */
  5851. return nread;
  5852. }
  5853. if (nread < 0) {
  5854. /* socket error - check errno */
  5855. #if defined(_WIN32)
  5856. if (err == WSAEWOULDBLOCK) {
  5857. /* TODO (low): check if this is still required */
  5858. /* standard case if called from close_socket_gracefully */
  5859. return -2;
  5860. } else if (err == WSAETIMEDOUT) {
  5861. /* TODO (low): check if this is still required */
  5862. /* timeout is handled by the while loop */
  5863. return 0;
  5864. } else if (err == WSAECONNABORTED) {
  5865. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5866. return -2;
  5867. } else {
  5868. DEBUG_TRACE("recv() failed, error %d", err);
  5869. return -2;
  5870. }
  5871. #else
  5872. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5873. * if the timeout is reached and if the socket was set to non-
  5874. * blocking in close_socket_gracefully, so we can not distinguish
  5875. * here. We have to wait for the timeout in both cases for now.
  5876. */
  5877. if (ERROR_TRY_AGAIN(err)) {
  5878. /* TODO (low): check if this is still required */
  5879. /* EAGAIN/EWOULDBLOCK:
  5880. * standard case if called from close_socket_gracefully
  5881. * => should return -1 */
  5882. /* or timeout occurred
  5883. * => the code must stay in the while loop */
  5884. /* EINTR can be generated on a socket with a timeout set even
  5885. * when SA_RESTART is effective for all relevant signals
  5886. * (see signal(7)).
  5887. * => stay in the while loop */
  5888. } else {
  5889. DEBUG_TRACE("recv() failed, error %d", err);
  5890. return -2;
  5891. }
  5892. #endif
  5893. }
  5894. /* Timeout occurred, but no data available. */
  5895. return -1;
  5896. }
  5897. static int
  5898. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5899. {
  5900. int n, nread = 0;
  5901. double timeout = -1.0;
  5902. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5903. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5904. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5905. }
  5906. if (timeout <= 0.0) {
  5907. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5908. }
  5909. start_time = mg_get_current_time_ns();
  5910. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5911. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5912. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5913. if (n == -2) {
  5914. if (nread == 0) {
  5915. nread = -1; /* Propagate the error */
  5916. }
  5917. break;
  5918. } else if (n == -1) {
  5919. /* timeout */
  5920. if (timeout >= 0.0) {
  5921. now = mg_get_current_time_ns();
  5922. if ((now - start_time) <= timeout_ns) {
  5923. continue;
  5924. }
  5925. }
  5926. break;
  5927. } else if (n == 0) {
  5928. break; /* No more data to read */
  5929. } else {
  5930. nread += n;
  5931. len -= n;
  5932. }
  5933. }
  5934. return nread;
  5935. }
  5936. static void
  5937. discard_unread_request_data(struct mg_connection *conn)
  5938. {
  5939. char buf[MG_BUF_LEN];
  5940. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5941. ;
  5942. }
  5943. static int
  5944. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5945. {
  5946. int64_t content_len, n, buffered_len, nread;
  5947. int64_t len64 =
  5948. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5949. * int, we may not read more
  5950. * bytes */
  5951. const char *body;
  5952. if (conn == NULL) {
  5953. return 0;
  5954. }
  5955. /* If Content-Length is not set for a response with body data,
  5956. * we do not know in advance how much data should be read. */
  5957. content_len = conn->content_len;
  5958. if (content_len < 0) {
  5959. /* The body data is completed when the connection is closed. */
  5960. content_len = INT64_MAX;
  5961. }
  5962. nread = 0;
  5963. if (conn->consumed_content < content_len) {
  5964. /* Adjust number of bytes to read. */
  5965. int64_t left_to_read = content_len - conn->consumed_content;
  5966. if (left_to_read < len64) {
  5967. /* Do not read more than the total content length of the
  5968. * request.
  5969. */
  5970. len64 = left_to_read;
  5971. }
  5972. /* Return buffered data */
  5973. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5974. - conn->consumed_content;
  5975. if (buffered_len > 0) {
  5976. if (len64 < buffered_len) {
  5977. buffered_len = len64;
  5978. }
  5979. body = conn->buf + conn->request_len + conn->consumed_content;
  5980. memcpy(buf, body, (size_t)buffered_len);
  5981. len64 -= buffered_len;
  5982. conn->consumed_content += buffered_len;
  5983. nread += buffered_len;
  5984. buf = (char *)buf + buffered_len;
  5985. }
  5986. /* We have returned all buffered data. Read new data from the remote
  5987. * socket.
  5988. */
  5989. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5990. conn->consumed_content += n;
  5991. nread += n;
  5992. } else {
  5993. nread = ((nread > 0) ? nread : n);
  5994. }
  5995. }
  5996. return (int)nread;
  5997. }
  5998. /* Forward declarations */
  5999. static void handle_request(struct mg_connection *);
  6000. #if defined(USE_HTTP2)
  6001. #if defined(NO_SSL)
  6002. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  6003. #endif
  6004. #define USE_ALPN
  6005. #include "mod_http2.inl"
  6006. /* Not supported with HTTP/2 */
  6007. #define HTTP1_only \
  6008. { \
  6009. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  6010. http2_must_use_http1(conn); \
  6011. return; \
  6012. } \
  6013. }
  6014. #else
  6015. #define HTTP1_only
  6016. #endif
  6017. int
  6018. mg_read(struct mg_connection *conn, void *buf, size_t len)
  6019. {
  6020. if (len > INT_MAX) {
  6021. len = INT_MAX;
  6022. }
  6023. if (conn == NULL) {
  6024. return 0;
  6025. }
  6026. if (conn->is_chunked) {
  6027. size_t all_read = 0;
  6028. while (len > 0) {
  6029. if (conn->is_chunked >= 3) {
  6030. /* No more data left to read */
  6031. return 0;
  6032. }
  6033. if (conn->is_chunked != 1) {
  6034. /* Has error */
  6035. return -1;
  6036. }
  6037. if (conn->consumed_content != conn->content_len) {
  6038. /* copy from the current chunk */
  6039. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  6040. if (read_ret < 1) {
  6041. /* read error */
  6042. conn->is_chunked = 2;
  6043. return -1;
  6044. }
  6045. all_read += (size_t)read_ret;
  6046. len -= (size_t)read_ret;
  6047. if (conn->consumed_content == conn->content_len) {
  6048. /* Add data bytes in the current chunk have been read,
  6049. * so we are expecting \r\n now. */
  6050. char x[2];
  6051. conn->content_len += 2;
  6052. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  6053. || (x[1] != '\n')) {
  6054. /* Protocol violation */
  6055. conn->is_chunked = 2;
  6056. return -1;
  6057. }
  6058. }
  6059. } else {
  6060. /* fetch a new chunk */
  6061. size_t i;
  6062. char lenbuf[64];
  6063. char *end = NULL;
  6064. unsigned long chunkSize = 0;
  6065. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  6066. conn->content_len++;
  6067. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  6068. lenbuf[i] = 0;
  6069. }
  6070. if ((i > 0) && (lenbuf[i] == '\r')
  6071. && (lenbuf[i - 1] != '\r')) {
  6072. continue;
  6073. }
  6074. if ((i > 1) && (lenbuf[i] == '\n')
  6075. && (lenbuf[i - 1] == '\r')) {
  6076. lenbuf[i + 1] = 0;
  6077. chunkSize = strtoul(lenbuf, &end, 16);
  6078. if (chunkSize == 0) {
  6079. /* regular end of content */
  6080. conn->is_chunked = 3;
  6081. }
  6082. break;
  6083. }
  6084. if (!isxdigit((unsigned char)lenbuf[i])) {
  6085. /* illegal character for chunk length */
  6086. conn->is_chunked = 2;
  6087. return -1;
  6088. }
  6089. }
  6090. if ((end == NULL) || (*end != '\r')) {
  6091. /* chunksize not set correctly */
  6092. conn->is_chunked = 2;
  6093. return -1;
  6094. }
  6095. if (chunkSize == 0) {
  6096. /* try discarding trailer for keep-alive */
  6097. conn->content_len += 2;
  6098. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  6099. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  6100. conn->is_chunked = 4;
  6101. }
  6102. break;
  6103. }
  6104. /* append a new chunk */
  6105. conn->content_len += (int64_t)chunkSize;
  6106. }
  6107. }
  6108. return (int)all_read;
  6109. }
  6110. return mg_read_inner(conn, buf, len);
  6111. }
  6112. int
  6113. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  6114. {
  6115. time_t now;
  6116. int n, total, allowed;
  6117. if (conn == NULL) {
  6118. return 0;
  6119. }
  6120. if (len > INT_MAX) {
  6121. return -1;
  6122. }
  6123. /* Mark connection as "data sent" */
  6124. conn->request_state = 10;
  6125. #if defined(USE_HTTP2)
  6126. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  6127. http2_data_frame_head(conn, len, 0);
  6128. }
  6129. #endif
  6130. if (conn->throttle > 0) {
  6131. if ((now = time(NULL)) != conn->last_throttle_time) {
  6132. conn->last_throttle_time = now;
  6133. conn->last_throttle_bytes = 0;
  6134. }
  6135. allowed = conn->throttle - conn->last_throttle_bytes;
  6136. if (allowed > (int)len) {
  6137. allowed = (int)len;
  6138. }
  6139. total = push_all(conn->phys_ctx,
  6140. NULL,
  6141. conn->client.sock,
  6142. conn->ssl,
  6143. (const char *)buf,
  6144. allowed);
  6145. if (total == allowed) {
  6146. buf = (const char *)buf + total;
  6147. conn->last_throttle_bytes += total;
  6148. while ((total < (int)len)
  6149. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6150. allowed = (conn->throttle > ((int)len - total))
  6151. ? (int)len - total
  6152. : conn->throttle;
  6153. n = push_all(conn->phys_ctx,
  6154. NULL,
  6155. conn->client.sock,
  6156. conn->ssl,
  6157. (const char *)buf,
  6158. allowed);
  6159. if (n != allowed) {
  6160. break;
  6161. }
  6162. sleep(1);
  6163. conn->last_throttle_bytes = allowed;
  6164. conn->last_throttle_time = time(NULL);
  6165. buf = (const char *)buf + n;
  6166. total += n;
  6167. }
  6168. }
  6169. } else {
  6170. total = push_all(conn->phys_ctx,
  6171. NULL,
  6172. conn->client.sock,
  6173. conn->ssl,
  6174. (const char *)buf,
  6175. (int)len);
  6176. }
  6177. if (total > 0) {
  6178. conn->num_bytes_sent += total;
  6179. }
  6180. return total;
  6181. }
  6182. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6183. int
  6184. mg_send_chunk(struct mg_connection *conn,
  6185. const char *chunk,
  6186. unsigned int chunk_len)
  6187. {
  6188. char lenbuf[16];
  6189. size_t lenbuf_len;
  6190. int ret;
  6191. int t;
  6192. /* First store the length information in a text buffer. */
  6193. sprintf(lenbuf, "%x\r\n", chunk_len);
  6194. lenbuf_len = strlen(lenbuf);
  6195. /* Then send length information, chunk and terminating \r\n. */
  6196. ret = mg_write(conn, lenbuf, lenbuf_len);
  6197. if (ret != (int)lenbuf_len) {
  6198. return -1;
  6199. }
  6200. t = ret;
  6201. ret = mg_write(conn, chunk, chunk_len);
  6202. if (ret != (int)chunk_len) {
  6203. return -1;
  6204. }
  6205. t += ret;
  6206. ret = mg_write(conn, "\r\n", 2);
  6207. if (ret != 2) {
  6208. return -1;
  6209. }
  6210. t += ret;
  6211. return t;
  6212. }
  6213. #if defined(GCC_DIAGNOSTIC)
  6214. /* This block forwards format strings to printf implementations,
  6215. * so we need to disable the format-nonliteral warning. */
  6216. #pragma GCC diagnostic push
  6217. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6218. #endif
  6219. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6220. static int
  6221. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6222. {
  6223. va_list ap_copy;
  6224. size_t size = MG_BUF_LEN / 4;
  6225. int len = -1;
  6226. *buf = NULL;
  6227. while (len < 0) {
  6228. if (*buf) {
  6229. mg_free(*buf);
  6230. }
  6231. size *= 4;
  6232. *buf = (char *)mg_malloc(size);
  6233. if (!*buf) {
  6234. break;
  6235. }
  6236. va_copy(ap_copy, ap);
  6237. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6238. va_end(ap_copy);
  6239. (*buf)[size - 1] = 0;
  6240. }
  6241. return len;
  6242. }
  6243. /* Print message to buffer. If buffer is large enough to hold the message,
  6244. * return buffer. If buffer is to small, allocate large enough buffer on
  6245. * heap,
  6246. * and return allocated buffer. */
  6247. static int
  6248. alloc_vprintf(char **out_buf,
  6249. char *prealloc_buf,
  6250. size_t prealloc_size,
  6251. const char *fmt,
  6252. va_list ap)
  6253. {
  6254. va_list ap_copy;
  6255. int len;
  6256. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6257. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6258. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6259. * Therefore, we make two passes: on first pass, get required message
  6260. * length.
  6261. * On second pass, actually print the message. */
  6262. va_copy(ap_copy, ap);
  6263. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6264. va_end(ap_copy);
  6265. if (len < 0) {
  6266. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6267. * Switch to alternative code path that uses incremental
  6268. * allocations.
  6269. */
  6270. va_copy(ap_copy, ap);
  6271. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6272. va_end(ap_copy);
  6273. } else if ((size_t)(len) >= prealloc_size) {
  6274. /* The pre-allocated buffer not large enough. */
  6275. /* Allocate a new buffer. */
  6276. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6277. if (!*out_buf) {
  6278. /* Allocation failed. Return -1 as "out of memory" error. */
  6279. return -1;
  6280. }
  6281. /* Buffer allocation successful. Store the string there. */
  6282. va_copy(ap_copy, ap);
  6283. IGNORE_UNUSED_RESULT(
  6284. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6285. va_end(ap_copy);
  6286. } else {
  6287. /* The pre-allocated buffer is large enough.
  6288. * Use it to store the string and return the address. */
  6289. va_copy(ap_copy, ap);
  6290. IGNORE_UNUSED_RESULT(
  6291. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6292. va_end(ap_copy);
  6293. *out_buf = prealloc_buf;
  6294. }
  6295. return len;
  6296. }
  6297. #if defined(GCC_DIAGNOSTIC)
  6298. /* Enable format-nonliteral warning again. */
  6299. #pragma GCC diagnostic pop
  6300. #endif
  6301. static int
  6302. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6303. {
  6304. char mem[MG_BUF_LEN];
  6305. char *buf = NULL;
  6306. int len;
  6307. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6308. len = mg_write(conn, buf, (size_t)len);
  6309. }
  6310. if (buf != mem) {
  6311. mg_free(buf);
  6312. }
  6313. return len;
  6314. }
  6315. int
  6316. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6317. {
  6318. va_list ap;
  6319. int result;
  6320. va_start(ap, fmt);
  6321. result = mg_vprintf(conn, fmt, ap);
  6322. va_end(ap);
  6323. return result;
  6324. }
  6325. int
  6326. mg_url_decode(const char *src,
  6327. int src_len,
  6328. char *dst,
  6329. int dst_len,
  6330. int is_form_url_encoded)
  6331. {
  6332. int i, j, a, b;
  6333. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6334. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6335. if ((i < src_len - 2) && (src[i] == '%')
  6336. && isxdigit((unsigned char)src[i + 1])
  6337. && isxdigit((unsigned char)src[i + 2])) {
  6338. a = tolower((unsigned char)src[i + 1]);
  6339. b = tolower((unsigned char)src[i + 2]);
  6340. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6341. i += 2;
  6342. } else if (is_form_url_encoded && (src[i] == '+')) {
  6343. dst[j] = ' ';
  6344. } else {
  6345. dst[j] = src[i];
  6346. }
  6347. }
  6348. dst[j] = '\0'; /* Null-terminate the destination */
  6349. return (i >= src_len) ? j : -1;
  6350. }
  6351. /* form url decoding of an entire string */
  6352. static void
  6353. url_decode_in_place(char *buf)
  6354. {
  6355. int len = (int)strlen(buf);
  6356. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6357. }
  6358. int
  6359. mg_get_var(const char *data,
  6360. size_t data_len,
  6361. const char *name,
  6362. char *dst,
  6363. size_t dst_len)
  6364. {
  6365. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6366. }
  6367. int
  6368. mg_get_var2(const char *data,
  6369. size_t data_len,
  6370. const char *name,
  6371. char *dst,
  6372. size_t dst_len,
  6373. size_t occurrence)
  6374. {
  6375. const char *p, *e, *s;
  6376. size_t name_len;
  6377. int len;
  6378. if ((dst == NULL) || (dst_len == 0)) {
  6379. len = -2;
  6380. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6381. len = -1;
  6382. dst[0] = '\0';
  6383. } else {
  6384. name_len = strlen(name);
  6385. e = data + data_len;
  6386. len = -1;
  6387. dst[0] = '\0';
  6388. /* data is "var1=val1&var2=val2...". Find variable first */
  6389. for (p = data; p + name_len < e; p++) {
  6390. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6391. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6392. /* Point p to variable value */
  6393. p += name_len + 1;
  6394. /* Point s to the end of the value */
  6395. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6396. if (s == NULL) {
  6397. s = e;
  6398. }
  6399. DEBUG_ASSERT(s >= p);
  6400. if (s < p) {
  6401. return -3;
  6402. }
  6403. /* Decode variable into destination buffer */
  6404. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6405. /* Redirect error code from -1 to -2 (destination buffer too
  6406. * small). */
  6407. if (len == -1) {
  6408. len = -2;
  6409. }
  6410. break;
  6411. }
  6412. }
  6413. }
  6414. return len;
  6415. }
  6416. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6417. int
  6418. mg_split_form_urlencoded(char *data,
  6419. struct mg_header *form_fields,
  6420. unsigned num_form_fields)
  6421. {
  6422. char *b;
  6423. int i;
  6424. int num = 0;
  6425. if (data == NULL) {
  6426. /* parameter error */
  6427. return -1;
  6428. }
  6429. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6430. /* determine the number of expected fields */
  6431. if (data[0] == 0) {
  6432. return 0;
  6433. }
  6434. /* count number of & to return the number of key-value-pairs */
  6435. num = 1;
  6436. while (*data) {
  6437. if (*data == '&') {
  6438. num++;
  6439. }
  6440. data++;
  6441. }
  6442. return num;
  6443. }
  6444. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6445. /* parameter error */
  6446. return -1;
  6447. }
  6448. for (i = 0; i < (int)num_form_fields; i++) {
  6449. /* extract key-value pairs from input data */
  6450. while ((*data == ' ') || (*data == '\t')) {
  6451. /* skip initial spaces */
  6452. data++;
  6453. }
  6454. if (*data == 0) {
  6455. /* end of string reached */
  6456. break;
  6457. }
  6458. form_fields[num].name = data;
  6459. /* find & or = */
  6460. b = data;
  6461. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6462. b++;
  6463. }
  6464. if (*b == 0) {
  6465. /* last key without value */
  6466. form_fields[num].value = NULL;
  6467. } else if (*b == '&') {
  6468. /* mid key without value */
  6469. form_fields[num].value = NULL;
  6470. } else {
  6471. /* terminate string */
  6472. *b = 0;
  6473. /* value starts after '=' */
  6474. data = b + 1;
  6475. form_fields[num].value = data;
  6476. }
  6477. /* new field is stored */
  6478. num++;
  6479. /* find a next key */
  6480. b = strchr(data, '&');
  6481. if (b == 0) {
  6482. /* no more data */
  6483. break;
  6484. } else {
  6485. /* terminate value of last field at '&' */
  6486. *b = 0;
  6487. /* next key-value-pairs starts after '&' */
  6488. data = b + 1;
  6489. }
  6490. }
  6491. /* Decode all values */
  6492. for (i = 0; i < num; i++) {
  6493. if (form_fields[i].name) {
  6494. url_decode_in_place((char *)form_fields[i].name);
  6495. }
  6496. if (form_fields[i].value) {
  6497. url_decode_in_place((char *)form_fields[i].value);
  6498. }
  6499. }
  6500. /* return number of fields found */
  6501. return num;
  6502. }
  6503. /* HCP24: some changes to compare hole var_name */
  6504. int
  6505. mg_get_cookie(const char *cookie_header,
  6506. const char *var_name,
  6507. char *dst,
  6508. size_t dst_size)
  6509. {
  6510. const char *s, *p, *end;
  6511. int name_len, len = -1;
  6512. if ((dst == NULL) || (dst_size == 0)) {
  6513. return -2;
  6514. }
  6515. dst[0] = '\0';
  6516. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6517. return -1;
  6518. }
  6519. name_len = (int)strlen(var_name);
  6520. end = s + strlen(s);
  6521. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6522. if (s[name_len] == '=') {
  6523. /* HCP24: now check is it a substring or a full cookie name */
  6524. if ((s == cookie_header) || (s[-1] == ' ')) {
  6525. s += name_len + 1;
  6526. if ((p = strchr(s, ' ')) == NULL) {
  6527. p = end;
  6528. }
  6529. if (p[-1] == ';') {
  6530. p--;
  6531. }
  6532. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6533. s++;
  6534. p--;
  6535. }
  6536. if ((size_t)(p - s) < dst_size) {
  6537. len = (int)(p - s);
  6538. mg_strlcpy(dst, s, (size_t)len + 1);
  6539. } else {
  6540. len = -3;
  6541. }
  6542. break;
  6543. }
  6544. }
  6545. }
  6546. return len;
  6547. }
  6548. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6549. static void
  6550. base64_encode(const unsigned char *src, int src_len, char *dst)
  6551. {
  6552. static const char *b64 =
  6553. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6554. int i, j, a, b, c;
  6555. for (i = j = 0; i < src_len; i += 3) {
  6556. a = src[i];
  6557. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6558. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6559. dst[j++] = b64[a >> 2];
  6560. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6561. if (i + 1 < src_len) {
  6562. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6563. }
  6564. if (i + 2 < src_len) {
  6565. dst[j++] = b64[c & 63];
  6566. }
  6567. }
  6568. while (j % 4 != 0) {
  6569. dst[j++] = '=';
  6570. }
  6571. dst[j++] = '\0';
  6572. }
  6573. #endif
  6574. #if defined(USE_LUA)
  6575. static unsigned char
  6576. b64reverse(char letter)
  6577. {
  6578. if ((letter >= 'A') && (letter <= 'Z')) {
  6579. return letter - 'A';
  6580. }
  6581. if ((letter >= 'a') && (letter <= 'z')) {
  6582. return letter - 'a' + 26;
  6583. }
  6584. if ((letter >= '0') && (letter <= '9')) {
  6585. return letter - '0' + 52;
  6586. }
  6587. if (letter == '+') {
  6588. return 62;
  6589. }
  6590. if (letter == '/') {
  6591. return 63;
  6592. }
  6593. if (letter == '=') {
  6594. return 255; /* normal end */
  6595. }
  6596. return 254; /* error */
  6597. }
  6598. static int
  6599. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6600. {
  6601. int i;
  6602. unsigned char a, b, c, d;
  6603. *dst_len = 0;
  6604. for (i = 0; i < src_len; i += 4) {
  6605. a = b64reverse(src[i]);
  6606. if (a >= 254) {
  6607. return i;
  6608. }
  6609. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6610. if (b >= 254) {
  6611. return i + 1;
  6612. }
  6613. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6614. if (c == 254) {
  6615. return i + 2;
  6616. }
  6617. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6618. if (d == 254) {
  6619. return i + 3;
  6620. }
  6621. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6622. if (c != 255) {
  6623. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6624. if (d != 255) {
  6625. dst[(*dst_len)++] = (c << 6) + d;
  6626. }
  6627. }
  6628. }
  6629. return -1;
  6630. }
  6631. #endif
  6632. static int
  6633. is_put_or_delete_method(const struct mg_connection *conn)
  6634. {
  6635. if (conn) {
  6636. const char *s = conn->request_info.request_method;
  6637. return (s != NULL)
  6638. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6639. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6640. }
  6641. return 0;
  6642. }
  6643. #if !defined(NO_FILES)
  6644. static int
  6645. extention_matches_script(
  6646. struct mg_connection *conn, /* in: request (must be valid) */
  6647. const char *filename /* in: filename (must be valid) */
  6648. )
  6649. {
  6650. #if !defined(NO_CGI)
  6651. if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], filename)
  6652. > 0) {
  6653. return 1;
  6654. }
  6655. if (match_prefix_strlen(conn->dom_ctx->config[CGI2_EXTENSIONS], filename)
  6656. > 0) {
  6657. return 1;
  6658. }
  6659. #endif
  6660. #if defined(USE_LUA)
  6661. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6662. filename)
  6663. > 0) {
  6664. return 1;
  6665. }
  6666. #endif
  6667. #if defined(USE_DUKTAPE)
  6668. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6669. filename)
  6670. > 0) {
  6671. return 1;
  6672. }
  6673. #endif
  6674. /* filename and conn could be unused, if all preocessor conditions
  6675. * are false (no script language supported). */
  6676. (void)filename;
  6677. (void)conn;
  6678. return 0;
  6679. }
  6680. static int
  6681. extention_matches_template_text(
  6682. struct mg_connection *conn, /* in: request (must be valid) */
  6683. const char *filename /* in: filename (must be valid) */
  6684. )
  6685. {
  6686. #if defined(USE_LUA)
  6687. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6688. filename)
  6689. > 0) {
  6690. return 1;
  6691. }
  6692. #endif
  6693. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6694. > 0) {
  6695. return 1;
  6696. }
  6697. return 0;
  6698. }
  6699. /* For given directory path, substitute it to valid index file.
  6700. * Return 1 if index file has been found, 0 if not found.
  6701. * If the file is found, it's stats is returned in stp. */
  6702. static int
  6703. substitute_index_file(struct mg_connection *conn,
  6704. char *path,
  6705. size_t path_len,
  6706. struct mg_file_stat *filestat)
  6707. {
  6708. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6709. struct vec filename_vec;
  6710. size_t n = strlen(path);
  6711. int found = 0;
  6712. /* The 'path' given to us points to the directory. Remove all trailing
  6713. * directory separator characters from the end of the path, and
  6714. * then append single directory separator character. */
  6715. while ((n > 0) && (path[n - 1] == '/')) {
  6716. n--;
  6717. }
  6718. path[n] = '/';
  6719. /* Traverse index files list. For each entry, append it to the given
  6720. * path and see if the file exists. If it exists, break the loop */
  6721. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6722. /* Ignore too long entries that may overflow path buffer */
  6723. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6724. continue;
  6725. }
  6726. /* Prepare full path to the index file */
  6727. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6728. /* Does it exist? */
  6729. if (mg_stat(conn, path, filestat)) {
  6730. /* Yes it does, break the loop */
  6731. found = 1;
  6732. break;
  6733. }
  6734. }
  6735. /* If no index file exists, restore directory path */
  6736. if (!found) {
  6737. path[n] = '\0';
  6738. }
  6739. return found;
  6740. }
  6741. #endif
  6742. static void
  6743. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6744. char *filename, /* out: filename */
  6745. size_t filename_buf_len, /* in: size of filename buffer */
  6746. struct mg_file_stat *filestat, /* out: file status structure */
  6747. int *is_found, /* out: file found (directly) */
  6748. int *is_script_resource, /* out: handled by a script? */
  6749. int *is_websocket_request, /* out: websocket connetion? */
  6750. int *is_put_or_delete_request, /* out: put/delete a file? */
  6751. int *is_template_text /* out: SSI file or LSP file? */
  6752. )
  6753. {
  6754. char const *accept_encoding;
  6755. #if !defined(NO_FILES)
  6756. const char *uri = conn->request_info.local_uri;
  6757. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6758. const char *rewrite;
  6759. struct vec a, b;
  6760. ptrdiff_t match_len;
  6761. char gz_path[PATH_MAX];
  6762. int truncated;
  6763. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6764. char *tmp_str;
  6765. size_t tmp_str_len, sep_pos;
  6766. int allow_substitute_script_subresources;
  6767. #endif
  6768. #else
  6769. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6770. #endif
  6771. /* Step 1: Set all initially unknown outputs to zero */
  6772. memset(filestat, 0, sizeof(*filestat));
  6773. *filename = 0;
  6774. *is_found = 0;
  6775. *is_script_resource = 0;
  6776. *is_template_text = 0;
  6777. /* Step 2: Check if the request attempts to modify the file system */
  6778. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6779. /* Step 3: Check if it is a websocket request, and modify the document
  6780. * root if required */
  6781. #if defined(USE_WEBSOCKET)
  6782. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6783. #if !defined(NO_FILES)
  6784. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6785. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6786. }
  6787. #endif /* !NO_FILES */
  6788. #else /* USE_WEBSOCKET */
  6789. *is_websocket_request = 0;
  6790. #endif /* USE_WEBSOCKET */
  6791. /* Step 4: Check if gzip encoded response is allowed */
  6792. conn->accept_gzip = 0;
  6793. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6794. if (strstr(accept_encoding, "gzip") != NULL) {
  6795. conn->accept_gzip = 1;
  6796. }
  6797. }
  6798. #if !defined(NO_FILES)
  6799. /* Step 5: If there is no root directory, don't look for files. */
  6800. /* Note that root == NULL is a regular use case here. This occurs,
  6801. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6802. * config is not required. */
  6803. if (root == NULL) {
  6804. /* all file related outputs have already been set to 0, just return
  6805. */
  6806. return;
  6807. }
  6808. /* Step 6: Determine the local file path from the root path and the
  6809. * request uri. */
  6810. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6811. * part of the path one byte on the right. */
  6812. truncated = 0;
  6813. mg_snprintf(
  6814. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6815. if (truncated) {
  6816. goto interpret_cleanup;
  6817. }
  6818. /* Step 7: URI rewriting */
  6819. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6820. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6821. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6822. mg_snprintf(conn,
  6823. &truncated,
  6824. filename,
  6825. filename_buf_len - 1,
  6826. "%.*s%s",
  6827. (int)b.len,
  6828. b.ptr,
  6829. uri + match_len);
  6830. break;
  6831. }
  6832. }
  6833. if (truncated) {
  6834. goto interpret_cleanup;
  6835. }
  6836. /* Step 8: Check if the file exists at the server */
  6837. /* Local file path and name, corresponding to requested URI
  6838. * is now stored in "filename" variable. */
  6839. if (mg_stat(conn, filename, filestat)) {
  6840. int uri_len = (int)strlen(uri);
  6841. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6842. /* 8.1: File exists. */
  6843. *is_found = 1;
  6844. /* 8.2: Check if it is a script type. */
  6845. if (extention_matches_script(conn, filename)) {
  6846. /* The request addresses a CGI resource, Lua script or
  6847. * server-side javascript.
  6848. * The URI corresponds to the script itself (like
  6849. * /path/script.cgi), and there is no additional resource
  6850. * path (like /path/script.cgi/something).
  6851. * Requests that modify (replace or delete) a resource, like
  6852. * PUT and DELETE requests, should replace/delete the script
  6853. * file.
  6854. * Requests that read or write from/to a resource, like GET and
  6855. * POST requests, should call the script and return the
  6856. * generated response. */
  6857. *is_script_resource = (!*is_put_or_delete_request);
  6858. }
  6859. /* 8.3: Check for SSI and LSP files */
  6860. if (extention_matches_template_text(conn, filename)) {
  6861. /* Same as above, but for *.lsp and *.shtml files. */
  6862. /* A "template text" is a file delivered directly to the client,
  6863. * but with some text tags replaced by dynamic content.
  6864. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6865. * (LP, LSP) file. */
  6866. *is_template_text = (!*is_put_or_delete_request);
  6867. }
  6868. /* 8.4: If the request target is a directory, there could be
  6869. * a substitute file (index.html, index.cgi, ...). */
  6870. if (filestat->is_directory && is_uri_end_slash) {
  6871. /* Use a local copy here, since substitute_index_file will
  6872. * change the content of the file status */
  6873. struct mg_file_stat tmp_filestat;
  6874. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6875. if (substitute_index_file(
  6876. conn, filename, filename_buf_len, &tmp_filestat)) {
  6877. /* Substitute file found. Copy stat to the output, then
  6878. * check if the file is a script file */
  6879. *filestat = tmp_filestat;
  6880. if (extention_matches_script(conn, filename)) {
  6881. /* Substitute file is a script file */
  6882. *is_script_resource = 1;
  6883. } else if (extention_matches_template_text(conn, filename)) {
  6884. /* Substitute file is a LSP or SSI file */
  6885. *is_template_text = 1;
  6886. } else {
  6887. /* Substitute file is a regular file */
  6888. *is_script_resource = 0;
  6889. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6890. }
  6891. }
  6892. /* If there is no substitute file, the server could return
  6893. * a directory listing in a later step */
  6894. }
  6895. return;
  6896. }
  6897. /* Step 9: Check for zipped files: */
  6898. /* If we can't find the actual file, look for the file
  6899. * with the same name but a .gz extension. If we find it,
  6900. * use that and set the gzipped flag in the file struct
  6901. * to indicate that the response need to have the content-
  6902. * encoding: gzip header.
  6903. * We can only do this if the browser declares support. */
  6904. if (conn->accept_gzip) {
  6905. mg_snprintf(
  6906. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6907. if (truncated) {
  6908. goto interpret_cleanup;
  6909. }
  6910. if (mg_stat(conn, gz_path, filestat)) {
  6911. if (filestat) {
  6912. filestat->is_gzipped = 1;
  6913. *is_found = 1;
  6914. }
  6915. /* Currently gz files can not be scripts. */
  6916. return;
  6917. }
  6918. }
  6919. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6920. /* Step 10: Script resources may handle sub-resources */
  6921. /* Support PATH_INFO for CGI scripts. */
  6922. tmp_str_len = strlen(filename);
  6923. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6924. if (!tmp_str) {
  6925. /* Out of memory */
  6926. goto interpret_cleanup;
  6927. }
  6928. memcpy(tmp_str, filename, tmp_str_len + 1);
  6929. /* Check config, if index scripts may have sub-resources */
  6930. allow_substitute_script_subresources =
  6931. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6932. "yes");
  6933. sep_pos = tmp_str_len;
  6934. while (sep_pos > 0) {
  6935. sep_pos--;
  6936. if (tmp_str[sep_pos] == '/') {
  6937. int is_script = 0, does_exist = 0;
  6938. tmp_str[sep_pos] = 0;
  6939. if (tmp_str[0]) {
  6940. is_script = extention_matches_script(conn, tmp_str);
  6941. does_exist = mg_stat(conn, tmp_str, filestat);
  6942. }
  6943. if (does_exist && is_script) {
  6944. filename[sep_pos] = 0;
  6945. memmove(filename + sep_pos + 2,
  6946. filename + sep_pos + 1,
  6947. strlen(filename + sep_pos + 1) + 1);
  6948. conn->path_info = filename + sep_pos + 1;
  6949. filename[sep_pos + 1] = '/';
  6950. *is_script_resource = 1;
  6951. *is_found = 1;
  6952. break;
  6953. }
  6954. if (allow_substitute_script_subresources) {
  6955. if (substitute_index_file(
  6956. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6957. /* some intermediate directory has an index file */
  6958. if (extention_matches_script(conn, tmp_str)) {
  6959. size_t script_name_len = strlen(tmp_str);
  6960. /* subres_name read before this memory locatio will be
  6961. overwritten */
  6962. char *subres_name = filename + sep_pos;
  6963. size_t subres_name_len = strlen(subres_name);
  6964. DEBUG_TRACE("Substitute script %s serving path %s",
  6965. tmp_str,
  6966. filename);
  6967. /* this index file is a script */
  6968. if ((script_name_len + subres_name_len + 2)
  6969. >= filename_buf_len) {
  6970. mg_free(tmp_str);
  6971. goto interpret_cleanup;
  6972. }
  6973. conn->path_info =
  6974. filename + script_name_len + 1; /* new target */
  6975. memmove(conn->path_info, subres_name, subres_name_len);
  6976. conn->path_info[subres_name_len] = 0;
  6977. memcpy(filename, tmp_str, script_name_len + 1);
  6978. *is_script_resource = 1;
  6979. *is_found = 1;
  6980. break;
  6981. } else {
  6982. DEBUG_TRACE("Substitute file %s serving path %s",
  6983. tmp_str,
  6984. filename);
  6985. /* non-script files will not have sub-resources */
  6986. filename[sep_pos] = 0;
  6987. conn->path_info = 0;
  6988. *is_script_resource = 0;
  6989. *is_found = 0;
  6990. break;
  6991. }
  6992. }
  6993. }
  6994. tmp_str[sep_pos] = '/';
  6995. }
  6996. }
  6997. mg_free(tmp_str);
  6998. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6999. #endif /* !defined(NO_FILES) */
  7000. return;
  7001. #if !defined(NO_FILES)
  7002. /* Reset all outputs */
  7003. interpret_cleanup:
  7004. memset(filestat, 0, sizeof(*filestat));
  7005. *filename = 0;
  7006. *is_found = 0;
  7007. *is_script_resource = 0;
  7008. *is_websocket_request = 0;
  7009. *is_put_or_delete_request = 0;
  7010. #endif /* !defined(NO_FILES) */
  7011. }
  7012. /* Check whether full request is buffered. Return:
  7013. * -1 if request or response is malformed
  7014. * 0 if request or response is not yet fully buffered
  7015. * >0 actual request length, including last \r\n\r\n */
  7016. static int
  7017. get_http_header_len(const char *buf, int buflen)
  7018. {
  7019. int i;
  7020. for (i = 0; i < buflen; i++) {
  7021. /* Do an unsigned comparison in some conditions below */
  7022. const unsigned char c = (unsigned char)buf[i];
  7023. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7024. && !isprint(c)) {
  7025. /* abort scan as soon as one malformed character is found */
  7026. return -1;
  7027. }
  7028. if (i < buflen - 1) {
  7029. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7030. /* Two newline, no carriage return - not standard compliant,
  7031. * but it should be accepted */
  7032. return i + 2;
  7033. }
  7034. }
  7035. if (i < buflen - 3) {
  7036. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7037. && (buf[i + 3] == '\n')) {
  7038. /* Two \r\n - standard compliant */
  7039. return i + 4;
  7040. }
  7041. }
  7042. }
  7043. return 0;
  7044. }
  7045. #if !defined(NO_CACHING)
  7046. /* Convert month to the month number. Return -1 on error, or month number */
  7047. static int
  7048. get_month_index(const char *s)
  7049. {
  7050. size_t i;
  7051. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7052. if (!strcmp(s, month_names[i])) {
  7053. return (int)i;
  7054. }
  7055. }
  7056. return -1;
  7057. }
  7058. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7059. static time_t
  7060. parse_date_string(const char *datetime)
  7061. {
  7062. char month_str[32] = {0};
  7063. int second, minute, hour, day, month, year;
  7064. time_t result = (time_t)0;
  7065. struct tm tm;
  7066. if ((sscanf(datetime,
  7067. "%d/%3s/%d %d:%d:%d",
  7068. &day,
  7069. month_str,
  7070. &year,
  7071. &hour,
  7072. &minute,
  7073. &second)
  7074. == 6)
  7075. || (sscanf(datetime,
  7076. "%d %3s %d %d:%d:%d",
  7077. &day,
  7078. month_str,
  7079. &year,
  7080. &hour,
  7081. &minute,
  7082. &second)
  7083. == 6)
  7084. || (sscanf(datetime,
  7085. "%*3s, %d %3s %d %d:%d:%d",
  7086. &day,
  7087. month_str,
  7088. &year,
  7089. &hour,
  7090. &minute,
  7091. &second)
  7092. == 6)
  7093. || (sscanf(datetime,
  7094. "%d-%3s-%d %d:%d:%d",
  7095. &day,
  7096. month_str,
  7097. &year,
  7098. &hour,
  7099. &minute,
  7100. &second)
  7101. == 6)) {
  7102. month = get_month_index(month_str);
  7103. if ((month >= 0) && (year >= 1970)) {
  7104. memset(&tm, 0, sizeof(tm));
  7105. tm.tm_year = year - 1900;
  7106. tm.tm_mon = month;
  7107. tm.tm_mday = day;
  7108. tm.tm_hour = hour;
  7109. tm.tm_min = minute;
  7110. tm.tm_sec = second;
  7111. result = timegm(&tm);
  7112. }
  7113. }
  7114. return result;
  7115. }
  7116. #endif /* !NO_CACHING */
  7117. /* Pre-process URIs according to RFC + protect against directory disclosure
  7118. * attacks by removing '..', excessive '/' and '\' characters */
  7119. static void
  7120. remove_dot_segments(char *inout)
  7121. {
  7122. /* Windows backend protection
  7123. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7124. * in URI by slash */
  7125. char *out_end = inout;
  7126. char *in = inout;
  7127. if (!in) {
  7128. /* Param error. */
  7129. return;
  7130. }
  7131. while (*in) {
  7132. if (*in == '\\') {
  7133. *in = '/';
  7134. }
  7135. in++;
  7136. }
  7137. /* Algorithm "remove_dot_segments" from
  7138. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7139. /* Step 1:
  7140. * The input buffer is initialized.
  7141. * The output buffer is initialized to the empty string.
  7142. */
  7143. in = inout;
  7144. /* Step 2:
  7145. * While the input buffer is not empty, loop as follows:
  7146. */
  7147. /* Less than out_end of the inout buffer is used as output, so keep
  7148. * condition: out_end <= in */
  7149. while (*in) {
  7150. /* Step 2a:
  7151. * If the input buffer begins with a prefix of "../" or "./",
  7152. * then remove that prefix from the input buffer;
  7153. */
  7154. if (!strncmp(in, "../", 3)) {
  7155. in += 3;
  7156. } else if (!strncmp(in, "./", 2)) {
  7157. in += 2;
  7158. }
  7159. /* otherwise */
  7160. /* Step 2b:
  7161. * if the input buffer begins with a prefix of "/./" or "/.",
  7162. * where "." is a complete path segment, then replace that
  7163. * prefix with "/" in the input buffer;
  7164. */
  7165. else if (!strncmp(in, "/./", 3)) {
  7166. in += 2;
  7167. } else if (!strcmp(in, "/.")) {
  7168. in[1] = 0;
  7169. }
  7170. /* otherwise */
  7171. /* Step 2c:
  7172. * if the input buffer begins with a prefix of "/../" or "/..",
  7173. * where ".." is a complete path segment, then replace that
  7174. * prefix with "/" in the input buffer and remove the last
  7175. * segment and its preceding "/" (if any) from the output
  7176. * buffer;
  7177. */
  7178. else if (!strncmp(in, "/../", 4)) {
  7179. in += 3;
  7180. if (inout != out_end) {
  7181. /* remove last segment */
  7182. do {
  7183. out_end--;
  7184. } while ((inout != out_end) && (*out_end != '/'));
  7185. }
  7186. } else if (!strcmp(in, "/..")) {
  7187. in[1] = 0;
  7188. if (inout != out_end) {
  7189. /* remove last segment */
  7190. do {
  7191. out_end--;
  7192. } while ((inout != out_end) && (*out_end != '/'));
  7193. }
  7194. }
  7195. /* otherwise */
  7196. /* Step 2d:
  7197. * if the input buffer consists only of "." or "..", then remove
  7198. * that from the input buffer;
  7199. */
  7200. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7201. *in = 0;
  7202. }
  7203. /* otherwise */
  7204. /* Step 2e:
  7205. * move the first path segment in the input buffer to the end of
  7206. * the output buffer, including the initial "/" character (if
  7207. * any) and any subsequent characters up to, but not including,
  7208. * the next "/" character or the end of the input buffer.
  7209. */
  7210. else {
  7211. do {
  7212. *out_end = *in;
  7213. out_end++;
  7214. in++;
  7215. } while ((*in != 0) && (*in != '/'));
  7216. }
  7217. }
  7218. /* Step 3:
  7219. * Finally, the output buffer is returned as the result of
  7220. * remove_dot_segments.
  7221. */
  7222. /* Terminate output */
  7223. *out_end = 0;
  7224. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7225. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7226. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7227. * or "//" anymore.
  7228. */
  7229. out_end = in = inout;
  7230. while (*in) {
  7231. if (*in == '.') {
  7232. /* remove . at the end or preceding of / */
  7233. char *in_ahead = in;
  7234. do {
  7235. in_ahead++;
  7236. } while (*in_ahead == '.');
  7237. if (*in_ahead == '/') {
  7238. in = in_ahead;
  7239. if ((out_end != inout) && (out_end[-1] == '/')) {
  7240. /* remove generated // */
  7241. out_end--;
  7242. }
  7243. } else if (*in_ahead == 0) {
  7244. in = in_ahead;
  7245. } else {
  7246. do {
  7247. *out_end++ = '.';
  7248. in++;
  7249. } while (in != in_ahead);
  7250. }
  7251. } else if (*in == '/') {
  7252. /* replace // by / */
  7253. *out_end++ = '/';
  7254. do {
  7255. in++;
  7256. } while (*in == '/');
  7257. } else {
  7258. *out_end++ = *in;
  7259. in++;
  7260. }
  7261. }
  7262. *out_end = 0;
  7263. }
  7264. static const struct {
  7265. const char *extension;
  7266. size_t ext_len;
  7267. const char *mime_type;
  7268. } builtin_mime_types[] = {
  7269. /* IANA registered MIME types
  7270. * (http://www.iana.org/assignments/media-types)
  7271. * application types */
  7272. {".doc", 4, "application/msword"},
  7273. {".eps", 4, "application/postscript"},
  7274. {".exe", 4, "application/octet-stream"},
  7275. {".js", 3, "application/javascript"},
  7276. {".json", 5, "application/json"},
  7277. {".pdf", 4, "application/pdf"},
  7278. {".ps", 3, "application/postscript"},
  7279. {".rtf", 4, "application/rtf"},
  7280. {".xhtml", 6, "application/xhtml+xml"},
  7281. {".xsl", 4, "application/xml"},
  7282. {".xslt", 5, "application/xml"},
  7283. /* fonts */
  7284. {".ttf", 4, "application/font-sfnt"},
  7285. {".cff", 4, "application/font-sfnt"},
  7286. {".otf", 4, "application/font-sfnt"},
  7287. {".aat", 4, "application/font-sfnt"},
  7288. {".sil", 4, "application/font-sfnt"},
  7289. {".pfr", 4, "application/font-tdpfr"},
  7290. {".woff", 5, "application/font-woff"},
  7291. /* audio */
  7292. {".mp3", 4, "audio/mpeg"},
  7293. {".oga", 4, "audio/ogg"},
  7294. {".ogg", 4, "audio/ogg"},
  7295. /* image */
  7296. {".gif", 4, "image/gif"},
  7297. {".ief", 4, "image/ief"},
  7298. {".jpeg", 5, "image/jpeg"},
  7299. {".jpg", 4, "image/jpeg"},
  7300. {".jpm", 4, "image/jpm"},
  7301. {".jpx", 4, "image/jpx"},
  7302. {".png", 4, "image/png"},
  7303. {".svg", 4, "image/svg+xml"},
  7304. {".tif", 4, "image/tiff"},
  7305. {".tiff", 5, "image/tiff"},
  7306. /* model */
  7307. {".wrl", 4, "model/vrml"},
  7308. /* text */
  7309. {".css", 4, "text/css"},
  7310. {".csv", 4, "text/csv"},
  7311. {".htm", 4, "text/html"},
  7312. {".html", 5, "text/html"},
  7313. {".sgm", 4, "text/sgml"},
  7314. {".shtm", 5, "text/html"},
  7315. {".shtml", 6, "text/html"},
  7316. {".txt", 4, "text/plain"},
  7317. {".xml", 4, "text/xml"},
  7318. /* video */
  7319. {".mov", 4, "video/quicktime"},
  7320. {".mp4", 4, "video/mp4"},
  7321. {".mpeg", 5, "video/mpeg"},
  7322. {".mpg", 4, "video/mpeg"},
  7323. {".ogv", 4, "video/ogg"},
  7324. {".qt", 3, "video/quicktime"},
  7325. /* not registered types
  7326. * (http://reference.sitepoint.com/html/mime-types-full,
  7327. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7328. {".arj", 4, "application/x-arj-compressed"},
  7329. {".gz", 3, "application/x-gunzip"},
  7330. {".rar", 4, "application/x-arj-compressed"},
  7331. {".swf", 4, "application/x-shockwave-flash"},
  7332. {".tar", 4, "application/x-tar"},
  7333. {".tgz", 4, "application/x-tar-gz"},
  7334. {".torrent", 8, "application/x-bittorrent"},
  7335. {".ppt", 4, "application/x-mspowerpoint"},
  7336. {".xls", 4, "application/x-msexcel"},
  7337. {".zip", 4, "application/x-zip-compressed"},
  7338. {".aac",
  7339. 4,
  7340. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7341. {".aif", 4, "audio/x-aif"},
  7342. {".m3u", 4, "audio/x-mpegurl"},
  7343. {".mid", 4, "audio/x-midi"},
  7344. {".ra", 3, "audio/x-pn-realaudio"},
  7345. {".ram", 4, "audio/x-pn-realaudio"},
  7346. {".wav", 4, "audio/x-wav"},
  7347. {".bmp", 4, "image/bmp"},
  7348. {".ico", 4, "image/x-icon"},
  7349. {".pct", 4, "image/x-pct"},
  7350. {".pict", 5, "image/pict"},
  7351. {".rgb", 4, "image/x-rgb"},
  7352. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7353. {".asf", 4, "video/x-ms-asf"},
  7354. {".avi", 4, "video/x-msvideo"},
  7355. {".m4v", 4, "video/x-m4v"},
  7356. {NULL, 0, NULL}};
  7357. const char *
  7358. mg_get_builtin_mime_type(const char *path)
  7359. {
  7360. const char *ext;
  7361. size_t i, path_len;
  7362. path_len = strlen(path);
  7363. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7364. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7365. if ((path_len > builtin_mime_types[i].ext_len)
  7366. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7367. return builtin_mime_types[i].mime_type;
  7368. }
  7369. }
  7370. return "text/plain";
  7371. }
  7372. /* Look at the "path" extension and figure what mime type it has.
  7373. * Store mime type in the vector. */
  7374. static void
  7375. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7376. {
  7377. struct vec ext_vec, mime_vec;
  7378. const char *list, *ext;
  7379. size_t path_len;
  7380. path_len = strlen(path);
  7381. if ((conn == NULL) || (vec == NULL)) {
  7382. if (vec != NULL) {
  7383. memset(vec, '\0', sizeof(struct vec));
  7384. }
  7385. return;
  7386. }
  7387. /* Scan user-defined mime types first, in case user wants to
  7388. * override default mime types. */
  7389. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7390. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7391. /* ext now points to the path suffix */
  7392. ext = path + path_len - ext_vec.len;
  7393. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7394. *vec = mime_vec;
  7395. return;
  7396. }
  7397. }
  7398. vec->ptr = mg_get_builtin_mime_type(path);
  7399. vec->len = strlen(vec->ptr);
  7400. }
  7401. /* Stringify binary data. Output buffer must be twice as big as input,
  7402. * because each byte takes 2 bytes in string representation */
  7403. static void
  7404. bin2str(char *to, const unsigned char *p, size_t len)
  7405. {
  7406. static const char *hex = "0123456789abcdef";
  7407. for (; len--; p++) {
  7408. *to++ = hex[p[0] >> 4];
  7409. *to++ = hex[p[0] & 0x0f];
  7410. }
  7411. *to = '\0';
  7412. }
  7413. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7414. */
  7415. char *
  7416. mg_md5(char buf[33], ...)
  7417. {
  7418. md5_byte_t hash[16];
  7419. const char *p;
  7420. va_list ap;
  7421. md5_state_t ctx;
  7422. md5_init(&ctx);
  7423. va_start(ap, buf);
  7424. while ((p = va_arg(ap, const char *)) != NULL) {
  7425. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7426. }
  7427. va_end(ap);
  7428. md5_finish(&ctx, hash);
  7429. bin2str(buf, hash, sizeof(hash));
  7430. return buf;
  7431. }
  7432. /* Check the user's password, return 1 if OK */
  7433. static int
  7434. check_password(const char *method,
  7435. const char *ha1,
  7436. const char *uri,
  7437. const char *nonce,
  7438. const char *nc,
  7439. const char *cnonce,
  7440. const char *qop,
  7441. const char *response)
  7442. {
  7443. char ha2[32 + 1], expected_response[32 + 1];
  7444. /* Some of the parameters may be NULL */
  7445. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7446. || (qop == NULL) || (response == NULL)) {
  7447. return 0;
  7448. }
  7449. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7450. if (strlen(response) != 32) {
  7451. return 0;
  7452. }
  7453. mg_md5(ha2, method, ":", uri, NULL);
  7454. mg_md5(expected_response,
  7455. ha1,
  7456. ":",
  7457. nonce,
  7458. ":",
  7459. nc,
  7460. ":",
  7461. cnonce,
  7462. ":",
  7463. qop,
  7464. ":",
  7465. ha2,
  7466. NULL);
  7467. return mg_strcasecmp(response, expected_response) == 0;
  7468. }
  7469. #if !defined(NO_FILESYSTEMS)
  7470. /* Use the global passwords file, if specified by auth_gpass option,
  7471. * or search for .htpasswd in the requested directory. */
  7472. static void
  7473. open_auth_file(struct mg_connection *conn,
  7474. const char *path,
  7475. struct mg_file *filep)
  7476. {
  7477. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7478. char name[PATH_MAX];
  7479. const char *p, *e,
  7480. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7481. int truncated;
  7482. if (gpass != NULL) {
  7483. /* Use global passwords file */
  7484. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7485. #if defined(DEBUG)
  7486. /* Use mg_cry_internal here, since gpass has been
  7487. * configured. */
  7488. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7489. #endif
  7490. }
  7491. /* Important: using local struct mg_file to test path for
  7492. * is_directory flag. If filep is used, mg_stat() makes it
  7493. * appear as if auth file was opened.
  7494. * TODO(mid): Check if this is still required after rewriting
  7495. * mg_stat */
  7496. } else if (mg_stat(conn, path, &filep->stat)
  7497. && filep->stat.is_directory) {
  7498. mg_snprintf(conn,
  7499. &truncated,
  7500. name,
  7501. sizeof(name),
  7502. "%s/%s",
  7503. path,
  7504. PASSWORDS_FILE_NAME);
  7505. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7506. #if defined(DEBUG)
  7507. /* Don't use mg_cry_internal here, but only a trace, since
  7508. * this is a typical case. It will occur for every directory
  7509. * without a password file. */
  7510. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7511. #endif
  7512. }
  7513. } else {
  7514. /* Try to find .htpasswd in requested directory. */
  7515. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7516. if (e[0] == '/') {
  7517. break;
  7518. }
  7519. }
  7520. mg_snprintf(conn,
  7521. &truncated,
  7522. name,
  7523. sizeof(name),
  7524. "%.*s/%s",
  7525. (int)(e - p),
  7526. p,
  7527. PASSWORDS_FILE_NAME);
  7528. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7529. #if defined(DEBUG)
  7530. /* Don't use mg_cry_internal here, but only a trace, since
  7531. * this is a typical case. It will occur for every directory
  7532. * without a password file. */
  7533. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7534. #endif
  7535. }
  7536. }
  7537. }
  7538. }
  7539. #endif /* NO_FILESYSTEMS */
  7540. /* Parsed Authorization header */
  7541. struct ah {
  7542. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7543. };
  7544. /* Return 1 on success. Always initializes the ah structure. */
  7545. static int
  7546. parse_auth_header(struct mg_connection *conn,
  7547. char *buf,
  7548. size_t buf_size,
  7549. struct ah *ah)
  7550. {
  7551. char *name, *value, *s;
  7552. const char *auth_header;
  7553. uint64_t nonce;
  7554. if (!ah || !conn) {
  7555. return 0;
  7556. }
  7557. (void)memset(ah, 0, sizeof(*ah));
  7558. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7559. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7560. return 0;
  7561. }
  7562. /* Make modifiable copy of the auth header */
  7563. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7564. s = buf;
  7565. /* Parse authorization header */
  7566. for (;;) {
  7567. /* Gobble initial spaces */
  7568. while (isspace((unsigned char)*s)) {
  7569. s++;
  7570. }
  7571. name = skip_quoted(&s, "=", " ", 0);
  7572. /* Value is either quote-delimited, or ends at first comma or space.
  7573. */
  7574. if (s[0] == '\"') {
  7575. s++;
  7576. value = skip_quoted(&s, "\"", " ", '\\');
  7577. if (s[0] == ',') {
  7578. s++;
  7579. }
  7580. } else {
  7581. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7582. * uses spaces */
  7583. }
  7584. if (*name == '\0') {
  7585. break;
  7586. }
  7587. if (!strcmp(name, "username")) {
  7588. ah->user = value;
  7589. } else if (!strcmp(name, "cnonce")) {
  7590. ah->cnonce = value;
  7591. } else if (!strcmp(name, "response")) {
  7592. ah->response = value;
  7593. } else if (!strcmp(name, "uri")) {
  7594. ah->uri = value;
  7595. } else if (!strcmp(name, "qop")) {
  7596. ah->qop = value;
  7597. } else if (!strcmp(name, "nc")) {
  7598. ah->nc = value;
  7599. } else if (!strcmp(name, "nonce")) {
  7600. ah->nonce = value;
  7601. }
  7602. }
  7603. #if !defined(NO_NONCE_CHECK)
  7604. /* Read the nonce from the response. */
  7605. if (ah->nonce == NULL) {
  7606. return 0;
  7607. }
  7608. s = NULL;
  7609. nonce = strtoull(ah->nonce, &s, 10);
  7610. if ((s == NULL) || (*s != 0)) {
  7611. return 0;
  7612. }
  7613. /* Convert the nonce from the client to a number. */
  7614. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7615. /* The converted number corresponds to the time the nounce has been
  7616. * created. This should not be earlier than the server start. */
  7617. /* Server side nonce check is valuable in all situations but one:
  7618. * if the server restarts frequently, but the client should not see
  7619. * that, so the server should accept nonces from previous starts. */
  7620. /* However, the reasonable default is to not accept a nonce from a
  7621. * previous start, so if anyone changed the access rights between
  7622. * two restarts, a new login is required. */
  7623. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7624. /* nonce is from a previous start of the server and no longer valid
  7625. * (replay attack?) */
  7626. return 0;
  7627. }
  7628. /* Check if the nonce is too high, so it has not (yet) been used by the
  7629. * server. */
  7630. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7631. + conn->dom_ctx->nonce_count)) {
  7632. return 0;
  7633. }
  7634. #else
  7635. (void)nonce;
  7636. #endif
  7637. /* CGI needs it as REMOTE_USER */
  7638. if (ah->user != NULL) {
  7639. conn->request_info.remote_user =
  7640. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7641. } else {
  7642. return 0;
  7643. }
  7644. return 1;
  7645. }
  7646. static const char *
  7647. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7648. {
  7649. if (!filep) {
  7650. return NULL;
  7651. }
  7652. if (filep->access.fp != NULL) {
  7653. return fgets(buf, (int)size, filep->access.fp);
  7654. } else {
  7655. return NULL;
  7656. }
  7657. }
  7658. /* Define the initial recursion depth for procesesing htpasswd files that
  7659. * include other htpasswd
  7660. * (or even the same) files. It is not difficult to provide a file or files
  7661. * s.t. they force civetweb
  7662. * to infinitely recurse and then crash.
  7663. */
  7664. #define INITIAL_DEPTH 9
  7665. #if INITIAL_DEPTH <= 0
  7666. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7667. #endif
  7668. #if !defined(NO_FILESYSTEMS)
  7669. struct read_auth_file_struct {
  7670. struct mg_connection *conn;
  7671. struct ah ah;
  7672. const char *domain;
  7673. char buf[256 + 256 + 40];
  7674. const char *f_user;
  7675. const char *f_domain;
  7676. const char *f_ha1;
  7677. };
  7678. static int
  7679. read_auth_file(struct mg_file *filep,
  7680. struct read_auth_file_struct *workdata,
  7681. int depth)
  7682. {
  7683. int is_authorized = 0;
  7684. struct mg_file fp;
  7685. size_t l;
  7686. if (!filep || !workdata || (0 == depth)) {
  7687. return 0;
  7688. }
  7689. /* Loop over passwords file */
  7690. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7691. l = strlen(workdata->buf);
  7692. while (l > 0) {
  7693. if (isspace((unsigned char)workdata->buf[l - 1])
  7694. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7695. l--;
  7696. workdata->buf[l] = 0;
  7697. } else
  7698. break;
  7699. }
  7700. if (l < 1) {
  7701. continue;
  7702. }
  7703. workdata->f_user = workdata->buf;
  7704. if (workdata->f_user[0] == ':') {
  7705. /* user names may not contain a ':' and may not be empty,
  7706. * so lines starting with ':' may be used for a special purpose
  7707. */
  7708. if (workdata->f_user[1] == '#') {
  7709. /* :# is a comment */
  7710. continue;
  7711. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7712. if (mg_fopen(workdata->conn,
  7713. workdata->f_user + 9,
  7714. MG_FOPEN_MODE_READ,
  7715. &fp)) {
  7716. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7717. (void)mg_fclose(
  7718. &fp.access); /* ignore error on read only file */
  7719. /* No need to continue processing files once we have a
  7720. * match, since nothing will reset it back
  7721. * to 0.
  7722. */
  7723. if (is_authorized) {
  7724. return is_authorized;
  7725. }
  7726. } else {
  7727. mg_cry_internal(workdata->conn,
  7728. "%s: cannot open authorization file: %s",
  7729. __func__,
  7730. workdata->buf);
  7731. }
  7732. continue;
  7733. }
  7734. /* everything is invalid for the moment (might change in the
  7735. * future) */
  7736. mg_cry_internal(workdata->conn,
  7737. "%s: syntax error in authorization file: %s",
  7738. __func__,
  7739. workdata->buf);
  7740. continue;
  7741. }
  7742. workdata->f_domain = strchr(workdata->f_user, ':');
  7743. if (workdata->f_domain == NULL) {
  7744. mg_cry_internal(workdata->conn,
  7745. "%s: syntax error in authorization file: %s",
  7746. __func__,
  7747. workdata->buf);
  7748. continue;
  7749. }
  7750. *(char *)(workdata->f_domain) = 0;
  7751. (workdata->f_domain)++;
  7752. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7753. if (workdata->f_ha1 == NULL) {
  7754. mg_cry_internal(workdata->conn,
  7755. "%s: syntax error in authorization file: %s",
  7756. __func__,
  7757. workdata->buf);
  7758. continue;
  7759. }
  7760. *(char *)(workdata->f_ha1) = 0;
  7761. (workdata->f_ha1)++;
  7762. if (!strcmp(workdata->ah.user, workdata->f_user)
  7763. && !strcmp(workdata->domain, workdata->f_domain)) {
  7764. return check_password(workdata->conn->request_info.request_method,
  7765. workdata->f_ha1,
  7766. workdata->ah.uri,
  7767. workdata->ah.nonce,
  7768. workdata->ah.nc,
  7769. workdata->ah.cnonce,
  7770. workdata->ah.qop,
  7771. workdata->ah.response);
  7772. }
  7773. }
  7774. return is_authorized;
  7775. }
  7776. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7777. static int
  7778. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7779. {
  7780. struct read_auth_file_struct workdata;
  7781. char buf[MG_BUF_LEN];
  7782. if (!conn || !conn->dom_ctx) {
  7783. return 0;
  7784. }
  7785. memset(&workdata, 0, sizeof(workdata));
  7786. workdata.conn = conn;
  7787. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7788. return 0;
  7789. }
  7790. if (realm) {
  7791. workdata.domain = realm;
  7792. } else {
  7793. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7794. }
  7795. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7796. }
  7797. /* Public function to check http digest authentication header */
  7798. int
  7799. mg_check_digest_access_authentication(struct mg_connection *conn,
  7800. const char *realm,
  7801. const char *filename)
  7802. {
  7803. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7804. int auth;
  7805. if (!conn || !filename) {
  7806. return -1;
  7807. }
  7808. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7809. return -2;
  7810. }
  7811. auth = authorize(conn, &file, realm);
  7812. mg_fclose(&file.access);
  7813. return auth;
  7814. }
  7815. #endif /* NO_FILESYSTEMS */
  7816. /* Return 1 if request is authorised, 0 otherwise. */
  7817. static int
  7818. check_authorization(struct mg_connection *conn, const char *path)
  7819. {
  7820. #if !defined(NO_FILESYSTEMS)
  7821. char fname[PATH_MAX];
  7822. struct vec uri_vec, filename_vec;
  7823. const char *list;
  7824. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7825. int authorized = 1, truncated;
  7826. if (!conn || !conn->dom_ctx) {
  7827. return 0;
  7828. }
  7829. list = conn->dom_ctx->config[PROTECT_URI];
  7830. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7831. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7832. mg_snprintf(conn,
  7833. &truncated,
  7834. fname,
  7835. sizeof(fname),
  7836. "%.*s",
  7837. (int)filename_vec.len,
  7838. filename_vec.ptr);
  7839. if (truncated
  7840. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7841. mg_cry_internal(conn,
  7842. "%s: cannot open %s: %s",
  7843. __func__,
  7844. fname,
  7845. strerror(errno));
  7846. }
  7847. break;
  7848. }
  7849. }
  7850. if (!is_file_opened(&file.access)) {
  7851. open_auth_file(conn, path, &file);
  7852. }
  7853. if (is_file_opened(&file.access)) {
  7854. authorized = authorize(conn, &file, NULL);
  7855. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7856. }
  7857. return authorized;
  7858. #else
  7859. (void)conn;
  7860. (void)path;
  7861. return 1;
  7862. #endif /* NO_FILESYSTEMS */
  7863. }
  7864. /* Internal function. Assumes conn is valid */
  7865. static void
  7866. send_authorization_request(struct mg_connection *conn, const char *realm)
  7867. {
  7868. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7869. int trunc = 0;
  7870. char buf[128];
  7871. if (!realm) {
  7872. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7873. }
  7874. mg_lock_context(conn->phys_ctx);
  7875. nonce += conn->dom_ctx->nonce_count;
  7876. ++conn->dom_ctx->nonce_count;
  7877. mg_unlock_context(conn->phys_ctx);
  7878. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7879. conn->must_close = 1;
  7880. /* Create 401 response */
  7881. mg_response_header_start(conn, 401);
  7882. send_no_cache_header(conn);
  7883. send_additional_header(conn);
  7884. mg_response_header_add(conn, "Content-Length", "0", -1);
  7885. /* Content for "WWW-Authenticate" header */
  7886. mg_snprintf(conn,
  7887. &trunc,
  7888. buf,
  7889. sizeof(buf),
  7890. "Digest qop=\"auth\", realm=\"%s\", "
  7891. "nonce=\"%" UINT64_FMT "\"",
  7892. realm,
  7893. nonce);
  7894. if (!trunc) {
  7895. /* !trunc should always be true */
  7896. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7897. }
  7898. /* Send all headers */
  7899. mg_response_header_send(conn);
  7900. }
  7901. /* Interface function. Parameters are provided by the user, so do
  7902. * at least some basic checks.
  7903. */
  7904. int
  7905. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7906. const char *realm)
  7907. {
  7908. if (conn && conn->dom_ctx) {
  7909. send_authorization_request(conn, realm);
  7910. return 0;
  7911. }
  7912. return -1;
  7913. }
  7914. #if !defined(NO_FILES)
  7915. static int
  7916. is_authorized_for_put(struct mg_connection *conn)
  7917. {
  7918. if (conn) {
  7919. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7920. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7921. int ret = 0;
  7922. if (passfile != NULL
  7923. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7924. ret = authorize(conn, &file, NULL);
  7925. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7926. }
  7927. return ret;
  7928. }
  7929. return 0;
  7930. }
  7931. #endif
  7932. int
  7933. mg_modify_passwords_file(const char *fname,
  7934. const char *domain,
  7935. const char *user,
  7936. const char *pass)
  7937. {
  7938. int found, i;
  7939. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7940. FILE *fp, *fp2;
  7941. found = 0;
  7942. fp = fp2 = NULL;
  7943. /* Regard empty password as no password - remove user record. */
  7944. if ((pass != NULL) && (pass[0] == '\0')) {
  7945. pass = NULL;
  7946. }
  7947. /* Other arguments must not be empty */
  7948. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7949. return 0;
  7950. }
  7951. /* Using the given file format, user name and domain must not contain
  7952. * ':'
  7953. */
  7954. if (strchr(user, ':') != NULL) {
  7955. return 0;
  7956. }
  7957. if (strchr(domain, ':') != NULL) {
  7958. return 0;
  7959. }
  7960. /* Do not allow control characters like newline in user name and domain.
  7961. * Do not allow excessively long names either. */
  7962. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7963. if (iscntrl((unsigned char)user[i])) {
  7964. return 0;
  7965. }
  7966. }
  7967. if (user[i]) {
  7968. return 0;
  7969. }
  7970. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7971. if (iscntrl((unsigned char)domain[i])) {
  7972. return 0;
  7973. }
  7974. }
  7975. if (domain[i]) {
  7976. return 0;
  7977. }
  7978. /* The maximum length of the path to the password file is limited */
  7979. if ((strlen(fname) + 4) >= PATH_MAX) {
  7980. return 0;
  7981. }
  7982. /* Create a temporary file name. Length has been checked before. */
  7983. strcpy(tmp, fname);
  7984. strcat(tmp, ".tmp");
  7985. /* Create the file if does not exist */
  7986. /* Use of fopen here is OK, since fname is only ASCII */
  7987. if ((fp = fopen(fname, "a+")) != NULL) {
  7988. (void)fclose(fp);
  7989. }
  7990. /* Open the given file and temporary file */
  7991. if ((fp = fopen(fname, "r")) == NULL) {
  7992. return 0;
  7993. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7994. fclose(fp);
  7995. return 0;
  7996. }
  7997. /* Copy the stuff to temporary file */
  7998. while (fgets(line, sizeof(line), fp) != NULL) {
  7999. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  8000. continue;
  8001. }
  8002. u[255] = 0;
  8003. d[255] = 0;
  8004. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8005. found++;
  8006. if (pass != NULL) {
  8007. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  8008. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  8009. }
  8010. } else {
  8011. fprintf(fp2, "%s", line);
  8012. }
  8013. }
  8014. /* If new user, just add it */
  8015. if (!found && (pass != NULL)) {
  8016. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  8017. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  8018. }
  8019. /* Close files */
  8020. fclose(fp);
  8021. fclose(fp2);
  8022. /* Put the temp file in place of real file */
  8023. IGNORE_UNUSED_RESULT(remove(fname));
  8024. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  8025. return 1;
  8026. }
  8027. static int
  8028. is_valid_port(unsigned long port)
  8029. {
  8030. return (port <= 0xffff);
  8031. }
  8032. static int
  8033. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8034. {
  8035. struct addrinfo hints, *res, *ressave;
  8036. int func_ret = 0;
  8037. int gai_ret;
  8038. memset(&hints, 0, sizeof(struct addrinfo));
  8039. hints.ai_family = af;
  8040. if (!resolve_src) {
  8041. hints.ai_flags = AI_NUMERICHOST;
  8042. }
  8043. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8044. if (gai_ret != 0) {
  8045. /* gai_strerror could be used to convert gai_ret to a string */
  8046. /* POSIX return values: see
  8047. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8048. */
  8049. /* Windows return values: see
  8050. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8051. */
  8052. return 0;
  8053. }
  8054. ressave = res;
  8055. while (res) {
  8056. if ((dstlen >= (size_t)res->ai_addrlen)
  8057. && (res->ai_addr->sa_family == af)) {
  8058. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8059. func_ret = 1;
  8060. }
  8061. res = res->ai_next;
  8062. }
  8063. freeaddrinfo(ressave);
  8064. return func_ret;
  8065. }
  8066. static int
  8067. connect_socket(struct mg_context *ctx /* may be NULL */,
  8068. const char *host,
  8069. int port,
  8070. int use_ssl,
  8071. char *ebuf,
  8072. size_t ebuf_len,
  8073. SOCKET *sock /* output: socket, must not be NULL */,
  8074. union usa *sa /* output: socket address, must not be NULL */
  8075. )
  8076. {
  8077. int ip_ver = 0;
  8078. int conn_ret = -1;
  8079. int sockerr = 0;
  8080. *sock = INVALID_SOCKET;
  8081. memset(sa, 0, sizeof(*sa));
  8082. if (ebuf_len > 0) {
  8083. *ebuf = 0;
  8084. }
  8085. if (host == NULL) {
  8086. mg_snprintf(NULL,
  8087. NULL, /* No truncation check for ebuf */
  8088. ebuf,
  8089. ebuf_len,
  8090. "%s",
  8091. "NULL host");
  8092. return 0;
  8093. }
  8094. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8095. mg_snprintf(NULL,
  8096. NULL, /* No truncation check for ebuf */
  8097. ebuf,
  8098. ebuf_len,
  8099. "%s",
  8100. "invalid port");
  8101. return 0;
  8102. }
  8103. #if !defined(NO_SSL)
  8104. #if !defined(NO_SSL_DL)
  8105. #if defined(OPENSSL_API_1_1)
  8106. if (use_ssl && (TLS_client_method == NULL)) {
  8107. mg_snprintf(NULL,
  8108. NULL, /* No truncation check for ebuf */
  8109. ebuf,
  8110. ebuf_len,
  8111. "%s",
  8112. "SSL is not initialized");
  8113. return 0;
  8114. }
  8115. #else
  8116. if (use_ssl && (SSLv23_client_method == NULL)) {
  8117. mg_snprintf(NULL,
  8118. NULL, /* No truncation check for ebuf */
  8119. ebuf,
  8120. ebuf_len,
  8121. "%s",
  8122. "SSL is not initialized");
  8123. return 0;
  8124. }
  8125. #endif /* OPENSSL_API_1_1 */
  8126. #else
  8127. (void)use_ssl;
  8128. #endif /* NO_SSL_DL */
  8129. #else
  8130. (void)use_ssl;
  8131. #endif /* !defined(NO_SSL) */
  8132. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8133. sa->sin.sin_port = htons((uint16_t)port);
  8134. ip_ver = 4;
  8135. #if defined(USE_IPV6)
  8136. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8137. sa->sin6.sin6_port = htons((uint16_t)port);
  8138. ip_ver = 6;
  8139. } else if (host[0] == '[') {
  8140. /* While getaddrinfo on Windows will work with [::1],
  8141. * getaddrinfo on Linux only works with ::1 (without []). */
  8142. size_t l = strlen(host + 1);
  8143. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8144. if (h) {
  8145. h[l - 1] = 0;
  8146. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8147. sa->sin6.sin6_port = htons((uint16_t)port);
  8148. ip_ver = 6;
  8149. }
  8150. mg_free(h);
  8151. }
  8152. #endif
  8153. }
  8154. if (ip_ver == 0) {
  8155. mg_snprintf(NULL,
  8156. NULL, /* No truncation check for ebuf */
  8157. ebuf,
  8158. ebuf_len,
  8159. "%s",
  8160. "host not found");
  8161. return 0;
  8162. }
  8163. if (ip_ver == 4) {
  8164. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8165. }
  8166. #if defined(USE_IPV6)
  8167. else if (ip_ver == 6) {
  8168. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8169. }
  8170. #endif
  8171. if (*sock == INVALID_SOCKET) {
  8172. mg_snprintf(NULL,
  8173. NULL, /* No truncation check for ebuf */
  8174. ebuf,
  8175. ebuf_len,
  8176. "socket(): %s",
  8177. strerror(ERRNO));
  8178. return 0;
  8179. }
  8180. if (0 != set_non_blocking_mode(*sock)) {
  8181. mg_snprintf(NULL,
  8182. NULL, /* No truncation check for ebuf */
  8183. ebuf,
  8184. ebuf_len,
  8185. "Cannot set socket to non-blocking: %s",
  8186. strerror(ERRNO));
  8187. closesocket(*sock);
  8188. *sock = INVALID_SOCKET;
  8189. return 0;
  8190. }
  8191. set_close_on_exec(*sock, NULL, ctx);
  8192. if (ip_ver == 4) {
  8193. /* connected with IPv4 */
  8194. conn_ret = connect(*sock,
  8195. (struct sockaddr *)((void *)&sa->sin),
  8196. sizeof(sa->sin));
  8197. }
  8198. #if defined(USE_IPV6)
  8199. else if (ip_ver == 6) {
  8200. /* connected with IPv6 */
  8201. conn_ret = connect(*sock,
  8202. (struct sockaddr *)((void *)&sa->sin6),
  8203. sizeof(sa->sin6));
  8204. }
  8205. #endif
  8206. if (conn_ret != 0) {
  8207. sockerr = ERRNO;
  8208. }
  8209. #if defined(_WIN32)
  8210. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8211. #else
  8212. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8213. #endif
  8214. /* Data for getsockopt */
  8215. void *psockerr = &sockerr;
  8216. int ret;
  8217. #if defined(_WIN32)
  8218. int len = (int)sizeof(sockerr);
  8219. #else
  8220. socklen_t len = (socklen_t)sizeof(sockerr);
  8221. #endif
  8222. /* Data for poll */
  8223. struct mg_pollfd pfd[1];
  8224. int pollres;
  8225. int ms_wait = 10000; /* 10 second timeout */
  8226. stop_flag_t nonstop;
  8227. STOP_FLAG_ASSIGN(&nonstop, 0);
  8228. /* For a non-blocking socket, the connect sequence is:
  8229. * 1) call connect (will not block)
  8230. * 2) wait until the socket is ready for writing (select or poll)
  8231. * 3) check connection state with getsockopt
  8232. */
  8233. pfd[0].fd = *sock;
  8234. pfd[0].events = POLLOUT;
  8235. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8236. if (pollres != 1) {
  8237. /* Not connected */
  8238. mg_snprintf(NULL,
  8239. NULL, /* No truncation check for ebuf */
  8240. ebuf,
  8241. ebuf_len,
  8242. "connect(%s:%d): timeout",
  8243. host,
  8244. port);
  8245. closesocket(*sock);
  8246. *sock = INVALID_SOCKET;
  8247. return 0;
  8248. }
  8249. #if defined(_WIN32)
  8250. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8251. #else
  8252. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8253. #endif
  8254. if ((ret == 0) && (sockerr == 0)) {
  8255. conn_ret = 0;
  8256. }
  8257. }
  8258. if (conn_ret != 0) {
  8259. /* Not connected */
  8260. mg_snprintf(NULL,
  8261. NULL, /* No truncation check for ebuf */
  8262. ebuf,
  8263. ebuf_len,
  8264. "connect(%s:%d): error %s",
  8265. host,
  8266. port,
  8267. strerror(sockerr));
  8268. closesocket(*sock);
  8269. *sock = INVALID_SOCKET;
  8270. return 0;
  8271. }
  8272. return 1;
  8273. }
  8274. int
  8275. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8276. {
  8277. static const char *dont_escape = "._-$,;~()";
  8278. static const char *hex = "0123456789abcdef";
  8279. char *pos = dst;
  8280. const char *end = dst + dst_len - 1;
  8281. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8282. if (isalnum((unsigned char)*src)
  8283. || (strchr(dont_escape, *src) != NULL)) {
  8284. *pos = *src;
  8285. } else if (pos + 2 < end) {
  8286. pos[0] = '%';
  8287. pos[1] = hex[(unsigned char)*src >> 4];
  8288. pos[2] = hex[(unsigned char)*src & 0xf];
  8289. pos += 2;
  8290. } else {
  8291. break;
  8292. }
  8293. }
  8294. *pos = '\0';
  8295. return (*src == '\0') ? (int)(pos - dst) : -1;
  8296. }
  8297. /* Return 0 on success, non-zero if an error occurs. */
  8298. static int
  8299. print_dir_entry(struct de *de)
  8300. {
  8301. size_t namesize, escsize, i;
  8302. char *href, *esc, *p;
  8303. char size[64], mod[64];
  8304. #if defined(REENTRANT_TIME)
  8305. struct tm _tm;
  8306. struct tm *tm = &_tm;
  8307. #else
  8308. struct tm *tm;
  8309. #endif
  8310. /* Estimate worst case size for encoding and escaping */
  8311. namesize = strlen(de->file_name) + 1;
  8312. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8313. href = (char *)mg_malloc(namesize * 3 + escsize);
  8314. if (href == NULL) {
  8315. return -1;
  8316. }
  8317. mg_url_encode(de->file_name, href, namesize * 3);
  8318. esc = NULL;
  8319. if (escsize > 0) {
  8320. /* HTML escaping needed */
  8321. esc = href + namesize * 3;
  8322. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8323. mg_strlcpy(p, de->file_name + i, 2);
  8324. if (*p == '&') {
  8325. strcpy(p, "&amp;");
  8326. } else if (*p == '<') {
  8327. strcpy(p, "&lt;");
  8328. } else if (*p == '>') {
  8329. strcpy(p, "&gt;");
  8330. }
  8331. }
  8332. }
  8333. if (de->file.is_directory) {
  8334. mg_snprintf(de->conn,
  8335. NULL, /* Buffer is big enough */
  8336. size,
  8337. sizeof(size),
  8338. "%s",
  8339. "[DIRECTORY]");
  8340. } else {
  8341. /* We use (signed) cast below because MSVC 6 compiler cannot
  8342. * convert unsigned __int64 to double. Sigh. */
  8343. if (de->file.size < 1024) {
  8344. mg_snprintf(de->conn,
  8345. NULL, /* Buffer is big enough */
  8346. size,
  8347. sizeof(size),
  8348. "%d",
  8349. (int)de->file.size);
  8350. } else if (de->file.size < 0x100000) {
  8351. mg_snprintf(de->conn,
  8352. NULL, /* Buffer is big enough */
  8353. size,
  8354. sizeof(size),
  8355. "%.1fk",
  8356. (double)de->file.size / 1024.0);
  8357. } else if (de->file.size < 0x40000000) {
  8358. mg_snprintf(de->conn,
  8359. NULL, /* Buffer is big enough */
  8360. size,
  8361. sizeof(size),
  8362. "%.1fM",
  8363. (double)de->file.size / 1048576);
  8364. } else {
  8365. mg_snprintf(de->conn,
  8366. NULL, /* Buffer is big enough */
  8367. size,
  8368. sizeof(size),
  8369. "%.1fG",
  8370. (double)de->file.size / 1073741824);
  8371. }
  8372. }
  8373. /* Note: mg_snprintf will not cause a buffer overflow above.
  8374. * So, string truncation checks are not required here. */
  8375. #if defined(REENTRANT_TIME)
  8376. localtime_r(&de->file.last_modified, tm);
  8377. #else
  8378. tm = localtime(&de->file.last_modified);
  8379. #endif
  8380. if (tm != NULL) {
  8381. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8382. } else {
  8383. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8384. mod[sizeof(mod) - 1] = '\0';
  8385. }
  8386. mg_printf(de->conn,
  8387. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8388. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8389. href,
  8390. de->file.is_directory ? "/" : "",
  8391. esc ? esc : de->file_name,
  8392. de->file.is_directory ? "/" : "",
  8393. mod,
  8394. size);
  8395. mg_free(href);
  8396. return 0;
  8397. }
  8398. /* This function is called from send_directory() and used for
  8399. * sorting directory entries by size, or name, or modification time.
  8400. * On windows, __cdecl specification is needed in case if project is built
  8401. * with __stdcall convention. qsort always requires __cdels callback. */
  8402. static int WINCDECL
  8403. compare_dir_entries(const void *p1, const void *p2)
  8404. {
  8405. if (p1 && p2) {
  8406. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8407. const char *query_string = a->conn->request_info.query_string;
  8408. int cmp_result = 0;
  8409. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8410. query_string = "n";
  8411. }
  8412. if (a->file.is_directory && !b->file.is_directory) {
  8413. return -1; /* Always put directories on top */
  8414. } else if (!a->file.is_directory && b->file.is_directory) {
  8415. return 1; /* Always put directories on top */
  8416. } else if (*query_string == 'n') {
  8417. cmp_result = strcmp(a->file_name, b->file_name);
  8418. } else if (*query_string == 's') {
  8419. cmp_result = (a->file.size == b->file.size)
  8420. ? 0
  8421. : ((a->file.size > b->file.size) ? 1 : -1);
  8422. } else if (*query_string == 'd') {
  8423. cmp_result =
  8424. (a->file.last_modified == b->file.last_modified)
  8425. ? 0
  8426. : ((a->file.last_modified > b->file.last_modified) ? 1
  8427. : -1);
  8428. }
  8429. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8430. }
  8431. return 0;
  8432. }
  8433. static int
  8434. must_hide_file(struct mg_connection *conn, const char *path)
  8435. {
  8436. if (conn && conn->dom_ctx) {
  8437. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8438. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8439. return (match_prefix_strlen(pw_pattern, path) > 0)
  8440. || (match_prefix_strlen(pattern, path) > 0);
  8441. }
  8442. return 0;
  8443. }
  8444. #if !defined(NO_FILESYSTEMS)
  8445. static int
  8446. scan_directory(struct mg_connection *conn,
  8447. const char *dir,
  8448. void *data,
  8449. int (*cb)(struct de *, void *))
  8450. {
  8451. char path[PATH_MAX];
  8452. struct dirent *dp;
  8453. DIR *dirp;
  8454. struct de de;
  8455. int truncated;
  8456. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8457. return 0;
  8458. } else {
  8459. de.conn = conn;
  8460. while ((dp = mg_readdir(dirp)) != NULL) {
  8461. /* Do not show current dir and hidden files */
  8462. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8463. || must_hide_file(conn, dp->d_name)) {
  8464. continue;
  8465. }
  8466. mg_snprintf(
  8467. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8468. /* If we don't memset stat structure to zero, mtime will have
  8469. * garbage and strftime() will segfault later on in
  8470. * print_dir_entry(). memset is required only if mg_stat()
  8471. * fails. For more details, see
  8472. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8473. memset(&de.file, 0, sizeof(de.file));
  8474. if (truncated) {
  8475. /* If the path is not complete, skip processing. */
  8476. continue;
  8477. }
  8478. if (!mg_stat(conn, path, &de.file)) {
  8479. mg_cry_internal(conn,
  8480. "%s: mg_stat(%s) failed: %s",
  8481. __func__,
  8482. path,
  8483. strerror(ERRNO));
  8484. }
  8485. de.file_name = dp->d_name;
  8486. if (cb(&de, data)) {
  8487. /* stopped */
  8488. break;
  8489. }
  8490. }
  8491. (void)mg_closedir(dirp);
  8492. }
  8493. return 1;
  8494. }
  8495. #endif /* NO_FILESYSTEMS */
  8496. #if !defined(NO_FILES)
  8497. static int
  8498. remove_directory(struct mg_connection *conn, const char *dir)
  8499. {
  8500. char path[PATH_MAX];
  8501. struct dirent *dp;
  8502. DIR *dirp;
  8503. struct de de;
  8504. int truncated;
  8505. int ok = 1;
  8506. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8507. return 0;
  8508. } else {
  8509. de.conn = conn;
  8510. while ((dp = mg_readdir(dirp)) != NULL) {
  8511. /* Do not show current dir (but show hidden files as they will
  8512. * also be removed) */
  8513. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8514. continue;
  8515. }
  8516. mg_snprintf(
  8517. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8518. /* If we don't memset stat structure to zero, mtime will have
  8519. * garbage and strftime() will segfault later on in
  8520. * print_dir_entry(). memset is required only if mg_stat()
  8521. * fails. For more details, see
  8522. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8523. memset(&de.file, 0, sizeof(de.file));
  8524. if (truncated) {
  8525. /* Do not delete anything shorter */
  8526. ok = 0;
  8527. continue;
  8528. }
  8529. if (!mg_stat(conn, path, &de.file)) {
  8530. mg_cry_internal(conn,
  8531. "%s: mg_stat(%s) failed: %s",
  8532. __func__,
  8533. path,
  8534. strerror(ERRNO));
  8535. ok = 0;
  8536. }
  8537. if (de.file.is_directory) {
  8538. if (remove_directory(conn, path) == 0) {
  8539. ok = 0;
  8540. }
  8541. } else {
  8542. /* This will fail file is the file is in memory */
  8543. if (mg_remove(conn, path) == 0) {
  8544. ok = 0;
  8545. }
  8546. }
  8547. }
  8548. (void)mg_closedir(dirp);
  8549. IGNORE_UNUSED_RESULT(rmdir(dir));
  8550. }
  8551. return ok;
  8552. }
  8553. #endif
  8554. struct dir_scan_data {
  8555. struct de *entries;
  8556. size_t num_entries;
  8557. size_t arr_size;
  8558. };
  8559. #if !defined(NO_FILESYSTEMS)
  8560. static int
  8561. dir_scan_callback(struct de *de, void *data)
  8562. {
  8563. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8564. struct de *entries = dsd->entries;
  8565. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8566. entries =
  8567. (struct de *)mg_realloc(entries,
  8568. dsd->arr_size * 2 * sizeof(entries[0]));
  8569. if (entries == NULL) {
  8570. /* stop scan */
  8571. return 1;
  8572. }
  8573. dsd->entries = entries;
  8574. dsd->arr_size *= 2;
  8575. }
  8576. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8577. if (entries[dsd->num_entries].file_name == NULL) {
  8578. /* stop scan */
  8579. return 1;
  8580. }
  8581. entries[dsd->num_entries].file = de->file;
  8582. entries[dsd->num_entries].conn = de->conn;
  8583. dsd->num_entries++;
  8584. return 0;
  8585. }
  8586. static void
  8587. handle_directory_request(struct mg_connection *conn, const char *dir)
  8588. {
  8589. size_t i;
  8590. int sort_direction;
  8591. struct dir_scan_data data = {NULL, 0, 128};
  8592. char date[64], *esc, *p;
  8593. const char *title;
  8594. time_t curtime = time(NULL);
  8595. if (!conn) {
  8596. return;
  8597. }
  8598. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8599. mg_send_http_error(conn,
  8600. 500,
  8601. "Error: Cannot open directory\nopendir(%s): %s",
  8602. dir,
  8603. strerror(ERRNO));
  8604. return;
  8605. }
  8606. gmt_time_string(date, sizeof(date), &curtime);
  8607. esc = NULL;
  8608. title = conn->request_info.local_uri;
  8609. if (title[strcspn(title, "&<>")]) {
  8610. /* HTML escaping needed */
  8611. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8612. if (esc) {
  8613. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8614. mg_strlcpy(p, title + i, 2);
  8615. if (*p == '&') {
  8616. strcpy(p, "&amp;");
  8617. } else if (*p == '<') {
  8618. strcpy(p, "&lt;");
  8619. } else if (*p == '>') {
  8620. strcpy(p, "&gt;");
  8621. }
  8622. }
  8623. } else {
  8624. title = "";
  8625. }
  8626. }
  8627. sort_direction = ((conn->request_info.query_string != NULL)
  8628. && (conn->request_info.query_string[0] != '\0')
  8629. && (conn->request_info.query_string[1] == 'd'))
  8630. ? 'a'
  8631. : 'd';
  8632. conn->must_close = 1;
  8633. /* Create 200 OK response */
  8634. mg_response_header_start(conn, 200);
  8635. send_static_cache_header(conn);
  8636. send_additional_header(conn);
  8637. mg_response_header_add(conn,
  8638. "Content-Type",
  8639. "text/html; charset=utf-8",
  8640. -1);
  8641. /* Send all headers */
  8642. mg_response_header_send(conn);
  8643. /* Body */
  8644. mg_printf(conn,
  8645. "<html><head><title>Index of %s</title>"
  8646. "<style>th {text-align: left;}</style></head>"
  8647. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8648. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8649. "<th><a href=\"?d%c\">Modified</a></th>"
  8650. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8651. "<tr><td colspan=\"3\"><hr></td></tr>",
  8652. esc ? esc : title,
  8653. esc ? esc : title,
  8654. sort_direction,
  8655. sort_direction,
  8656. sort_direction);
  8657. mg_free(esc);
  8658. /* Print first entry - link to a parent directory */
  8659. mg_printf(conn,
  8660. "<tr><td><a href=\"%s\">%s</a></td>"
  8661. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8662. "..",
  8663. "Parent directory",
  8664. "-",
  8665. "-");
  8666. /* Sort and print directory entries */
  8667. if (data.entries != NULL) {
  8668. qsort(data.entries,
  8669. data.num_entries,
  8670. sizeof(data.entries[0]),
  8671. compare_dir_entries);
  8672. for (i = 0; i < data.num_entries; i++) {
  8673. print_dir_entry(&data.entries[i]);
  8674. mg_free(data.entries[i].file_name);
  8675. }
  8676. mg_free(data.entries);
  8677. }
  8678. mg_printf(conn, "%s", "</table></pre></body></html>");
  8679. conn->status_code = 200;
  8680. }
  8681. #endif /* NO_FILESYSTEMS */
  8682. /* Send len bytes from the opened file to the client. */
  8683. static void
  8684. send_file_data(struct mg_connection *conn,
  8685. struct mg_file *filep,
  8686. int64_t offset,
  8687. int64_t len)
  8688. {
  8689. char buf[MG_BUF_LEN];
  8690. int to_read, num_read, num_written;
  8691. int64_t size;
  8692. if (!filep || !conn) {
  8693. return;
  8694. }
  8695. /* Sanity check the offset */
  8696. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8697. : (int64_t)(filep->stat.size);
  8698. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8699. if (len > 0 && filep->access.fp != NULL) {
  8700. /* file stored on disk */
  8701. #if defined(__linux__)
  8702. /* sendfile is only available for Linux */
  8703. if ((conn->ssl == 0) && (conn->throttle == 0)
  8704. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8705. "yes"))) {
  8706. off_t sf_offs = (off_t)offset;
  8707. ssize_t sf_sent;
  8708. int sf_file = fileno(filep->access.fp);
  8709. int loop_cnt = 0;
  8710. do {
  8711. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8712. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8713. size_t sf_tosend =
  8714. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8715. sf_sent =
  8716. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8717. if (sf_sent > 0) {
  8718. len -= sf_sent;
  8719. offset += sf_sent;
  8720. } else if (loop_cnt == 0) {
  8721. /* This file can not be sent using sendfile.
  8722. * This might be the case for pseudo-files in the
  8723. * /sys/ and /proc/ file system.
  8724. * Use the regular user mode copy code instead. */
  8725. break;
  8726. } else if (sf_sent == 0) {
  8727. /* No error, but 0 bytes sent. May be EOF? */
  8728. return;
  8729. }
  8730. loop_cnt++;
  8731. } while ((len > 0) && (sf_sent >= 0));
  8732. if (sf_sent > 0) {
  8733. return; /* OK */
  8734. }
  8735. /* sf_sent<0 means error, thus fall back to the classic way */
  8736. /* This is always the case, if sf_file is not a "normal" file,
  8737. * e.g., for sending data from the output of a CGI process. */
  8738. offset = (int64_t)sf_offs;
  8739. }
  8740. #endif
  8741. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8742. mg_cry_internal(conn,
  8743. "%s: fseeko() failed: %s",
  8744. __func__,
  8745. strerror(ERRNO));
  8746. mg_send_http_error(
  8747. conn,
  8748. 500,
  8749. "%s",
  8750. "Error: Unable to access file at requested position.");
  8751. } else {
  8752. while (len > 0) {
  8753. /* Calculate how much to read from the file in the buffer */
  8754. to_read = sizeof(buf);
  8755. if ((int64_t)to_read > len) {
  8756. to_read = (int)len;
  8757. }
  8758. /* Read from file, exit the loop on error */
  8759. if ((num_read =
  8760. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8761. <= 0) {
  8762. break;
  8763. }
  8764. /* Send read bytes to the client, exit the loop on error */
  8765. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8766. != num_read) {
  8767. break;
  8768. }
  8769. /* Both read and were successful, adjust counters */
  8770. len -= num_written;
  8771. }
  8772. }
  8773. }
  8774. }
  8775. static int
  8776. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8777. {
  8778. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8779. }
  8780. static void
  8781. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8782. {
  8783. if ((filestat != NULL) && (buf != NULL)) {
  8784. mg_snprintf(NULL,
  8785. NULL, /* All calls to construct_etag use 64 byte buffer */
  8786. buf,
  8787. buf_len,
  8788. "\"%lx.%" INT64_FMT "\"",
  8789. (unsigned long)filestat->last_modified,
  8790. filestat->size);
  8791. }
  8792. }
  8793. static void
  8794. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8795. {
  8796. if (filep != NULL && filep->fp != NULL) {
  8797. #if defined(_WIN32)
  8798. (void)conn; /* Unused. */
  8799. #else
  8800. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8801. mg_cry_internal(conn,
  8802. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8803. __func__,
  8804. strerror(ERRNO));
  8805. }
  8806. #endif
  8807. }
  8808. }
  8809. #if defined(USE_ZLIB)
  8810. #include "mod_zlib.inl"
  8811. #endif
  8812. #if !defined(NO_FILESYSTEMS)
  8813. static void
  8814. handle_static_file_request(struct mg_connection *conn,
  8815. const char *path,
  8816. struct mg_file *filep,
  8817. const char *mime_type,
  8818. const char *additional_headers)
  8819. {
  8820. char lm[64], etag[64];
  8821. char range[128]; /* large enough, so there will be no overflow */
  8822. const char *range_hdr;
  8823. int64_t cl, r1, r2;
  8824. struct vec mime_vec;
  8825. int n, truncated;
  8826. char gz_path[PATH_MAX];
  8827. const char *encoding = 0;
  8828. const char *origin_hdr;
  8829. const char *cors_orig_cfg;
  8830. const char *cors1, *cors2;
  8831. int is_head_request;
  8832. #if defined(USE_ZLIB)
  8833. /* Compression is allowed, unless there is a reason not to use
  8834. * compression. If the file is already compressed, too small or a
  8835. * "range" request was made, on the fly compression is not possible. */
  8836. int allow_on_the_fly_compression = 1;
  8837. #endif
  8838. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8839. return;
  8840. }
  8841. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8842. if (mime_type == NULL) {
  8843. get_mime_type(conn, path, &mime_vec);
  8844. } else {
  8845. mime_vec.ptr = mime_type;
  8846. mime_vec.len = strlen(mime_type);
  8847. }
  8848. if (filep->stat.size > INT64_MAX) {
  8849. mg_send_http_error(conn,
  8850. 500,
  8851. "Error: File size is too large to send\n%" INT64_FMT,
  8852. filep->stat.size);
  8853. return;
  8854. }
  8855. cl = (int64_t)filep->stat.size;
  8856. conn->status_code = 200;
  8857. range[0] = '\0';
  8858. #if defined(USE_ZLIB)
  8859. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8860. * it's important to rewrite the filename after resolving
  8861. * the mime type from it, to preserve the actual file's type */
  8862. if (!conn->accept_gzip) {
  8863. allow_on_the_fly_compression = 0;
  8864. }
  8865. #endif
  8866. /* Check if there is a range header */
  8867. range_hdr = mg_get_header(conn, "Range");
  8868. /* For gzipped files, add *.gz */
  8869. if (filep->stat.is_gzipped) {
  8870. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8871. if (truncated) {
  8872. mg_send_http_error(conn,
  8873. 500,
  8874. "Error: Path of zipped file too long (%s)",
  8875. path);
  8876. return;
  8877. }
  8878. path = gz_path;
  8879. encoding = "gzip";
  8880. #if defined(USE_ZLIB)
  8881. /* File is already compressed. No "on the fly" compression. */
  8882. allow_on_the_fly_compression = 0;
  8883. #endif
  8884. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8885. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8886. struct mg_file_stat file_stat;
  8887. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8888. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8889. && !file_stat.is_directory) {
  8890. file_stat.is_gzipped = 1;
  8891. filep->stat = file_stat;
  8892. cl = (int64_t)filep->stat.size;
  8893. path = gz_path;
  8894. encoding = "gzip";
  8895. #if defined(USE_ZLIB)
  8896. /* File is already compressed. No "on the fly" compression. */
  8897. allow_on_the_fly_compression = 0;
  8898. #endif
  8899. }
  8900. }
  8901. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8902. mg_send_http_error(conn,
  8903. 500,
  8904. "Error: Cannot open file\nfopen(%s): %s",
  8905. path,
  8906. strerror(ERRNO));
  8907. return;
  8908. }
  8909. fclose_on_exec(&filep->access, conn);
  8910. /* If "Range" request was made: parse header, send only selected part
  8911. * of the file. */
  8912. r1 = r2 = 0;
  8913. if ((range_hdr != NULL)
  8914. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8915. && (r2 >= 0)) {
  8916. /* actually, range requests don't play well with a pre-gzipped
  8917. * file (since the range is specified in the uncompressed space) */
  8918. if (filep->stat.is_gzipped) {
  8919. mg_send_http_error(
  8920. conn,
  8921. 416, /* 416 = Range Not Satisfiable */
  8922. "%s",
  8923. "Error: Range requests in gzipped files are not supported");
  8924. (void)mg_fclose(
  8925. &filep->access); /* ignore error on read only file */
  8926. return;
  8927. }
  8928. conn->status_code = 206;
  8929. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8930. mg_snprintf(conn,
  8931. NULL, /* range buffer is big enough */
  8932. range,
  8933. sizeof(range),
  8934. "bytes "
  8935. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8936. r1,
  8937. r1 + cl - 1,
  8938. filep->stat.size);
  8939. #if defined(USE_ZLIB)
  8940. /* Do not compress ranges. */
  8941. allow_on_the_fly_compression = 0;
  8942. #endif
  8943. }
  8944. /* Do not compress small files. Small files do not benefit from file
  8945. * compression, but there is still some overhead. */
  8946. #if defined(USE_ZLIB)
  8947. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8948. /* File is below the size limit. */
  8949. allow_on_the_fly_compression = 0;
  8950. }
  8951. #endif
  8952. /* Standard CORS header */
  8953. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8954. origin_hdr = mg_get_header(conn, "Origin");
  8955. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8956. /* Cross-origin resource sharing (CORS), see
  8957. * http://www.html5rocks.com/en/tutorials/cors/,
  8958. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8959. * -
  8960. * preflight is not supported for files. */
  8961. cors1 = "Access-Control-Allow-Origin";
  8962. cors2 = cors_orig_cfg;
  8963. } else {
  8964. cors1 = cors2 = "";
  8965. }
  8966. /* Prepare Etag, and Last-Modified headers. */
  8967. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8968. construct_etag(etag, sizeof(etag), &filep->stat);
  8969. /* Create 2xx (200, 206) response */
  8970. mg_response_header_start(conn, conn->status_code);
  8971. send_static_cache_header(conn);
  8972. send_additional_header(conn);
  8973. mg_response_header_add(conn,
  8974. "Content-Type",
  8975. mime_vec.ptr,
  8976. (int)mime_vec.len);
  8977. if (cors1[0] != 0) {
  8978. mg_response_header_add(conn, cors1, cors2, -1);
  8979. }
  8980. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8981. mg_response_header_add(conn, "Etag", etag, -1);
  8982. #if defined(USE_ZLIB)
  8983. /* On the fly compression allowed */
  8984. if (allow_on_the_fly_compression) {
  8985. /* For on the fly compression, we don't know the content size in
  8986. * advance, so we have to use chunked encoding */
  8987. encoding = "gzip";
  8988. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8989. /* HTTP/2 is always using "chunks" (frames) */
  8990. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8991. }
  8992. } else
  8993. #endif
  8994. {
  8995. /* Without on-the-fly compression, we know the content-length
  8996. * and we can use ranges (with on-the-fly compression we cannot).
  8997. * So we send these response headers only in this case. */
  8998. char len[32];
  8999. int trunc = 0;
  9000. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9001. if (!trunc) {
  9002. mg_response_header_add(conn, "Content-Length", len, -1);
  9003. }
  9004. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9005. }
  9006. if (encoding) {
  9007. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9008. }
  9009. if (range[0] != 0) {
  9010. mg_response_header_add(conn, "Content-Range", range, -1);
  9011. }
  9012. /* The code above does not add any header starting with X- to make
  9013. * sure no one of the additional_headers is included twice */
  9014. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9015. mg_response_header_add_lines(conn, additional_headers);
  9016. }
  9017. /* Send all headers */
  9018. mg_response_header_send(conn);
  9019. if (!is_head_request) {
  9020. #if defined(USE_ZLIB)
  9021. if (allow_on_the_fly_compression) {
  9022. /* Compress and send */
  9023. send_compressed_data(conn, filep);
  9024. } else
  9025. #endif
  9026. {
  9027. /* Send file directly */
  9028. send_file_data(conn, filep, r1, cl);
  9029. }
  9030. }
  9031. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9032. }
  9033. int
  9034. mg_send_file_body(struct mg_connection *conn, const char *path)
  9035. {
  9036. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9037. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9038. return -1;
  9039. }
  9040. fclose_on_exec(&file.access, conn);
  9041. send_file_data(conn, &file, 0, INT64_MAX);
  9042. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9043. return 0; /* >= 0 for OK */
  9044. }
  9045. #endif /* NO_FILESYSTEMS */
  9046. #if !defined(NO_CACHING)
  9047. /* Return True if we should reply 304 Not Modified. */
  9048. static int
  9049. is_not_modified(const struct mg_connection *conn,
  9050. const struct mg_file_stat *filestat)
  9051. {
  9052. char etag[64];
  9053. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9054. const char *inm = mg_get_header(conn, "If-None-Match");
  9055. construct_etag(etag, sizeof(etag), filestat);
  9056. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9057. || ((ims != NULL)
  9058. && (filestat->last_modified <= parse_date_string(ims)));
  9059. }
  9060. static void
  9061. handle_not_modified_static_file_request(struct mg_connection *conn,
  9062. struct mg_file *filep)
  9063. {
  9064. char lm[64], etag[64];
  9065. if ((conn == NULL) || (filep == NULL)) {
  9066. return;
  9067. }
  9068. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9069. construct_etag(etag, sizeof(etag), &filep->stat);
  9070. /* Create 304 "not modified" response */
  9071. mg_response_header_start(conn, 304);
  9072. send_static_cache_header(conn);
  9073. send_additional_header(conn);
  9074. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9075. mg_response_header_add(conn, "Etag", etag, -1);
  9076. /* Send all headers */
  9077. mg_response_header_send(conn);
  9078. }
  9079. #endif
  9080. #if !defined(NO_FILESYSTEMS)
  9081. void
  9082. mg_send_file(struct mg_connection *conn, const char *path)
  9083. {
  9084. mg_send_mime_file2(conn, path, NULL, NULL);
  9085. }
  9086. void
  9087. mg_send_mime_file(struct mg_connection *conn,
  9088. const char *path,
  9089. const char *mime_type)
  9090. {
  9091. mg_send_mime_file2(conn, path, mime_type, NULL);
  9092. }
  9093. void
  9094. mg_send_mime_file2(struct mg_connection *conn,
  9095. const char *path,
  9096. const char *mime_type,
  9097. const char *additional_headers)
  9098. {
  9099. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9100. if (!conn) {
  9101. /* No conn */
  9102. return;
  9103. }
  9104. if (mg_stat(conn, path, &file.stat)) {
  9105. #if !defined(NO_CACHING)
  9106. if (is_not_modified(conn, &file.stat)) {
  9107. /* Send 304 "Not Modified" - this must not send any body data */
  9108. handle_not_modified_static_file_request(conn, &file);
  9109. } else
  9110. #endif /* NO_CACHING */
  9111. if (file.stat.is_directory) {
  9112. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9113. "yes")) {
  9114. handle_directory_request(conn, path);
  9115. } else {
  9116. mg_send_http_error(conn,
  9117. 403,
  9118. "%s",
  9119. "Error: Directory listing denied");
  9120. }
  9121. } else {
  9122. handle_static_file_request(
  9123. conn, path, &file, mime_type, additional_headers);
  9124. }
  9125. } else {
  9126. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9127. }
  9128. }
  9129. /* For a given PUT path, create all intermediate subdirectories.
  9130. * Return 0 if the path itself is a directory.
  9131. * Return 1 if the path leads to a file.
  9132. * Return -1 for if the path is too long.
  9133. * Return -2 if path can not be created.
  9134. */
  9135. static int
  9136. put_dir(struct mg_connection *conn, const char *path)
  9137. {
  9138. char buf[PATH_MAX];
  9139. const char *s, *p;
  9140. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9141. size_t len;
  9142. int res = 1;
  9143. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9144. len = (size_t)(p - path);
  9145. if (len >= sizeof(buf)) {
  9146. /* path too long */
  9147. res = -1;
  9148. break;
  9149. }
  9150. memcpy(buf, path, len);
  9151. buf[len] = '\0';
  9152. /* Try to create intermediate directory */
  9153. DEBUG_TRACE("mkdir(%s)", buf);
  9154. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9155. /* path does not exixt and can not be created */
  9156. res = -2;
  9157. break;
  9158. }
  9159. /* Is path itself a directory? */
  9160. if (p[1] == '\0') {
  9161. res = 0;
  9162. }
  9163. }
  9164. return res;
  9165. }
  9166. static void
  9167. remove_bad_file(const struct mg_connection *conn, const char *path)
  9168. {
  9169. int r = mg_remove(conn, path);
  9170. if (r != 0) {
  9171. mg_cry_internal(conn,
  9172. "%s: Cannot remove invalid file %s",
  9173. __func__,
  9174. path);
  9175. }
  9176. }
  9177. long long
  9178. mg_store_body(struct mg_connection *conn, const char *path)
  9179. {
  9180. char buf[MG_BUF_LEN];
  9181. long long len = 0;
  9182. int ret, n;
  9183. struct mg_file fi;
  9184. if (conn->consumed_content != 0) {
  9185. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9186. return -11;
  9187. }
  9188. ret = put_dir(conn, path);
  9189. if (ret < 0) {
  9190. /* -1 for path too long,
  9191. * -2 for path can not be created. */
  9192. return ret;
  9193. }
  9194. if (ret != 1) {
  9195. /* Return 0 means, path itself is a directory. */
  9196. return 0;
  9197. }
  9198. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9199. return -12;
  9200. }
  9201. ret = mg_read(conn, buf, sizeof(buf));
  9202. while (ret > 0) {
  9203. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9204. if (n != ret) {
  9205. (void)mg_fclose(
  9206. &fi.access); /* File is bad and will be removed anyway. */
  9207. remove_bad_file(conn, path);
  9208. return -13;
  9209. }
  9210. len += ret;
  9211. ret = mg_read(conn, buf, sizeof(buf));
  9212. }
  9213. /* File is open for writing. If fclose fails, there was probably an
  9214. * error flushing the buffer to disk, so the file on disk might be
  9215. * broken. Delete it and return an error to the caller. */
  9216. if (mg_fclose(&fi.access) != 0) {
  9217. remove_bad_file(conn, path);
  9218. return -14;
  9219. }
  9220. return len;
  9221. }
  9222. #endif /* NO_FILESYSTEMS */
  9223. /* Parse a buffer:
  9224. * Forward the string pointer till the end of a word, then
  9225. * terminate it and forward till the begin of the next word.
  9226. */
  9227. static int
  9228. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9229. {
  9230. /* Forward until a space is found - use isgraph here */
  9231. /* See http://www.cplusplus.com/reference/cctype/ */
  9232. while (isgraph((unsigned char)**ppw)) {
  9233. (*ppw)++;
  9234. }
  9235. /* Check end of word */
  9236. if (eol) {
  9237. /* must be a end of line */
  9238. if ((**ppw != '\r') && (**ppw != '\n')) {
  9239. return -1;
  9240. }
  9241. } else {
  9242. /* must be a end of a word, but not a line */
  9243. if (**ppw != ' ') {
  9244. return -1;
  9245. }
  9246. }
  9247. /* Terminate and forward to the next word */
  9248. do {
  9249. **ppw = 0;
  9250. (*ppw)++;
  9251. } while (isspace((unsigned char)**ppw));
  9252. /* Check after term */
  9253. if (!eol) {
  9254. /* if it's not the end of line, there must be a next word */
  9255. if (!isgraph((unsigned char)**ppw)) {
  9256. return -1;
  9257. }
  9258. }
  9259. /* ok */
  9260. return 1;
  9261. }
  9262. /* Parse HTTP headers from the given buffer, advance buf pointer
  9263. * to the point where parsing stopped.
  9264. * All parameters must be valid pointers (not NULL).
  9265. * Return <0 on error. */
  9266. static int
  9267. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9268. {
  9269. int i;
  9270. int num_headers = 0;
  9271. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9272. char *dp = *buf;
  9273. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9274. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9275. dp++;
  9276. }
  9277. if (dp == *buf) {
  9278. /* End of headers reached. */
  9279. break;
  9280. }
  9281. if (*dp != ':') {
  9282. /* This is not a valid field. */
  9283. return -1;
  9284. }
  9285. /* End of header key (*dp == ':') */
  9286. /* Truncate here and set the key name */
  9287. *dp = 0;
  9288. hdr[i].name = *buf;
  9289. /* Skip all spaces */
  9290. do {
  9291. dp++;
  9292. } while ((*dp == ' ') || (*dp == '\t'));
  9293. /* The rest of the line is the value */
  9294. hdr[i].value = dp;
  9295. /* Find end of line */
  9296. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9297. dp++;
  9298. };
  9299. /* eliminate \r */
  9300. if (*dp == '\r') {
  9301. *dp = 0;
  9302. dp++;
  9303. if (*dp != '\n') {
  9304. /* This is not a valid line. */
  9305. return -1;
  9306. }
  9307. }
  9308. /* here *dp is either 0 or '\n' */
  9309. /* in any case, we have a new header */
  9310. num_headers = i + 1;
  9311. if (*dp) {
  9312. *dp = 0;
  9313. dp++;
  9314. *buf = dp;
  9315. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9316. /* This is the end of the header */
  9317. break;
  9318. }
  9319. } else {
  9320. *buf = dp;
  9321. break;
  9322. }
  9323. }
  9324. return num_headers;
  9325. }
  9326. struct mg_http_method_info {
  9327. const char *name;
  9328. int request_has_body;
  9329. int response_has_body;
  9330. int is_safe;
  9331. int is_idempotent;
  9332. int is_cacheable;
  9333. };
  9334. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9335. static const struct mg_http_method_info http_methods[] = {
  9336. /* HTTP (RFC 2616) */
  9337. {"GET", 0, 1, 1, 1, 1},
  9338. {"POST", 1, 1, 0, 0, 0},
  9339. {"PUT", 1, 0, 0, 1, 0},
  9340. {"DELETE", 0, 0, 0, 1, 0},
  9341. {"HEAD", 0, 0, 1, 1, 1},
  9342. {"OPTIONS", 0, 0, 1, 1, 0},
  9343. {"CONNECT", 1, 1, 0, 0, 0},
  9344. /* TRACE method (RFC 2616) is not supported for security reasons */
  9345. /* PATCH method (RFC 5789) */
  9346. {"PATCH", 1, 0, 0, 0, 0},
  9347. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9348. /* WEBDAV (RFC 2518) */
  9349. {"PROPFIND", 0, 1, 1, 1, 0},
  9350. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9351. * Some PROPFIND results MAY be cached, with care,
  9352. * as there is no cache validation mechanism for
  9353. * most properties. This method is both safe and
  9354. * idempotent (see Section 9.1 of [RFC2616]). */
  9355. {"MKCOL", 0, 0, 0, 1, 0},
  9356. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9357. * When MKCOL is invoked without a request body,
  9358. * the newly created collection SHOULD have no
  9359. * members. A MKCOL request message may contain
  9360. * a message body. The precise behavior of a MKCOL
  9361. * request when the body is present is undefined,
  9362. * ... ==> We do not support MKCOL with body data.
  9363. * This method is idempotent, but not safe (see
  9364. * Section 9.1 of [RFC2616]). Responses to this
  9365. * method MUST NOT be cached. */
  9366. /* Unsupported WEBDAV Methods: */
  9367. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  9368. /* + 11 methods from RFC 3253 */
  9369. /* ORDERPATCH (RFC 3648) */
  9370. /* ACL (RFC 3744) */
  9371. /* SEARCH (RFC 5323) */
  9372. /* + MicroSoft extensions
  9373. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9374. /* REPORT method (RFC 3253) */
  9375. {"REPORT", 1, 1, 1, 1, 1},
  9376. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9377. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9378. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9379. * to be useful for REST in case a "GET request with body" is
  9380. * required. */
  9381. {NULL, 0, 0, 0, 0, 0}
  9382. /* end of list */
  9383. };
  9384. static const struct mg_http_method_info *
  9385. get_http_method_info(const char *method)
  9386. {
  9387. /* Check if the method is known to the server. The list of all known
  9388. * HTTP methods can be found here at
  9389. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9390. */
  9391. const struct mg_http_method_info *m = http_methods;
  9392. while (m->name) {
  9393. if (!strcmp(m->name, method)) {
  9394. return m;
  9395. }
  9396. m++;
  9397. }
  9398. return NULL;
  9399. }
  9400. static int
  9401. is_valid_http_method(const char *method)
  9402. {
  9403. return (get_http_method_info(method) != NULL);
  9404. }
  9405. /* Parse HTTP request, fill in mg_request_info structure.
  9406. * This function modifies the buffer by NUL-terminating
  9407. * HTTP request components, header names and header values.
  9408. * Parameters:
  9409. * buf (in/out): pointer to the HTTP header to parse and split
  9410. * len (in): length of HTTP header buffer
  9411. * re (out): parsed header as mg_request_info
  9412. * buf and ri must be valid pointers (not NULL), len>0.
  9413. * Returns <0 on error. */
  9414. static int
  9415. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9416. {
  9417. int request_length;
  9418. int init_skip = 0;
  9419. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9420. * remote_port */
  9421. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9422. NULL;
  9423. ri->num_headers = 0;
  9424. /* RFC says that all initial whitespaces should be ingored */
  9425. /* This included all leading \r and \n (isspace) */
  9426. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9427. while ((len > 0) && isspace((unsigned char)*buf)) {
  9428. buf++;
  9429. len--;
  9430. init_skip++;
  9431. }
  9432. if (len == 0) {
  9433. /* Incomplete request */
  9434. return 0;
  9435. }
  9436. /* Control characters are not allowed, including zero */
  9437. if (iscntrl((unsigned char)*buf)) {
  9438. return -1;
  9439. }
  9440. /* Find end of HTTP header */
  9441. request_length = get_http_header_len(buf, len);
  9442. if (request_length <= 0) {
  9443. return request_length;
  9444. }
  9445. buf[request_length - 1] = '\0';
  9446. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9447. return -1;
  9448. }
  9449. /* The first word has to be the HTTP method */
  9450. ri->request_method = buf;
  9451. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9452. return -1;
  9453. }
  9454. /* Check for a valid http method */
  9455. if (!is_valid_http_method(ri->request_method)) {
  9456. return -1;
  9457. }
  9458. /* The second word is the URI */
  9459. ri->request_uri = buf;
  9460. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9461. return -1;
  9462. }
  9463. /* Next would be the HTTP version */
  9464. ri->http_version = buf;
  9465. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9466. return -1;
  9467. }
  9468. /* Check for a valid HTTP version key */
  9469. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9470. /* Invalid request */
  9471. return -1;
  9472. }
  9473. ri->http_version += 5;
  9474. /* Parse all HTTP headers */
  9475. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9476. if (ri->num_headers < 0) {
  9477. /* Error while parsing headers */
  9478. return -1;
  9479. }
  9480. return request_length + init_skip;
  9481. }
  9482. static int
  9483. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9484. {
  9485. int response_length;
  9486. int init_skip = 0;
  9487. char *tmp, *tmp2;
  9488. long l;
  9489. /* Initialize elements. */
  9490. ri->http_version = ri->status_text = NULL;
  9491. ri->num_headers = ri->status_code = 0;
  9492. /* RFC says that all initial whitespaces should be ingored */
  9493. /* This included all leading \r and \n (isspace) */
  9494. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9495. while ((len > 0) && isspace((unsigned char)*buf)) {
  9496. buf++;
  9497. len--;
  9498. init_skip++;
  9499. }
  9500. if (len == 0) {
  9501. /* Incomplete request */
  9502. return 0;
  9503. }
  9504. /* Control characters are not allowed, including zero */
  9505. if (iscntrl((unsigned char)*buf)) {
  9506. return -1;
  9507. }
  9508. /* Find end of HTTP header */
  9509. response_length = get_http_header_len(buf, len);
  9510. if (response_length <= 0) {
  9511. return response_length;
  9512. }
  9513. buf[response_length - 1] = '\0';
  9514. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9515. return -1;
  9516. }
  9517. /* The first word is the HTTP version */
  9518. /* Check for a valid HTTP version key */
  9519. if (strncmp(buf, "HTTP/", 5) != 0) {
  9520. /* Invalid request */
  9521. return -1;
  9522. }
  9523. buf += 5;
  9524. if (!isgraph((unsigned char)buf[0])) {
  9525. /* Invalid request */
  9526. return -1;
  9527. }
  9528. ri->http_version = buf;
  9529. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9530. return -1;
  9531. }
  9532. /* The second word is the status as a number */
  9533. tmp = buf;
  9534. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9535. return -1;
  9536. }
  9537. l = strtol(tmp, &tmp2, 10);
  9538. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9539. /* Everything else but a 3 digit code is invalid */
  9540. return -1;
  9541. }
  9542. ri->status_code = (int)l;
  9543. /* The rest of the line is the status text */
  9544. ri->status_text = buf;
  9545. /* Find end of status text */
  9546. /* isgraph or isspace = isprint */
  9547. while (isprint((unsigned char)*buf)) {
  9548. buf++;
  9549. }
  9550. if ((*buf != '\r') && (*buf != '\n')) {
  9551. return -1;
  9552. }
  9553. /* Terminate string and forward buf to next line */
  9554. do {
  9555. *buf = 0;
  9556. buf++;
  9557. } while (isspace((unsigned char)*buf));
  9558. /* Parse all HTTP headers */
  9559. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9560. if (ri->num_headers < 0) {
  9561. /* Error while parsing headers */
  9562. return -1;
  9563. }
  9564. return response_length + init_skip;
  9565. }
  9566. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9567. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9568. * buffer (which marks the end of HTTP request). Buffer buf may already
  9569. * have some data. The length of the data is stored in nread.
  9570. * Upon every read operation, increase nread by the number of bytes read. */
  9571. static int
  9572. read_message(FILE *fp,
  9573. struct mg_connection *conn,
  9574. char *buf,
  9575. int bufsiz,
  9576. int *nread)
  9577. {
  9578. int request_len, n = 0;
  9579. struct timespec last_action_time;
  9580. double request_timeout;
  9581. if (!conn) {
  9582. return 0;
  9583. }
  9584. memset(&last_action_time, 0, sizeof(last_action_time));
  9585. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9586. /* value of request_timeout is in seconds, config in milliseconds */
  9587. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9588. } else {
  9589. request_timeout =
  9590. atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  9591. }
  9592. if (conn->handled_requests > 0) {
  9593. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9594. request_timeout =
  9595. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9596. }
  9597. }
  9598. request_len = get_http_header_len(buf, *nread);
  9599. while (request_len == 0) {
  9600. /* Full request not yet received */
  9601. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9602. /* Server is to be stopped. */
  9603. return -1;
  9604. }
  9605. if (*nread >= bufsiz) {
  9606. /* Request too long */
  9607. return -2;
  9608. }
  9609. n = pull_inner(
  9610. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9611. if (n == -2) {
  9612. /* Receive error */
  9613. return -1;
  9614. }
  9615. /* update clock after every read request */
  9616. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9617. if (n > 0) {
  9618. *nread += n;
  9619. request_len = get_http_header_len(buf, *nread);
  9620. }
  9621. if ((request_len == 0) && (request_timeout >= 0)) {
  9622. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9623. > request_timeout) {
  9624. /* Timeout */
  9625. return -1;
  9626. }
  9627. }
  9628. }
  9629. return request_len;
  9630. }
  9631. #if !defined(NO_CGI) || !defined(NO_FILES)
  9632. static int
  9633. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9634. {
  9635. const char *expect;
  9636. char buf[MG_BUF_LEN];
  9637. int success = 0;
  9638. if (!conn) {
  9639. return 0;
  9640. }
  9641. expect = mg_get_header(conn, "Expect");
  9642. DEBUG_ASSERT(fp != NULL);
  9643. if (!fp) {
  9644. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9645. return 0;
  9646. }
  9647. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9648. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9649. */
  9650. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9651. } else {
  9652. if (expect != NULL) {
  9653. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9654. conn->status_code = 100;
  9655. } else {
  9656. conn->status_code = 200;
  9657. }
  9658. DEBUG_ASSERT(conn->consumed_content == 0);
  9659. if (conn->consumed_content != 0) {
  9660. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9661. return 0;
  9662. }
  9663. for (;;) {
  9664. int nread = mg_read(conn, buf, sizeof(buf));
  9665. if (nread <= 0) {
  9666. success = (nread == 0);
  9667. break;
  9668. }
  9669. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9670. break;
  9671. }
  9672. }
  9673. /* Each error code path in this function must send an error */
  9674. if (!success) {
  9675. /* NOTE: Maybe some data has already been sent. */
  9676. /* TODO (low): If some data has been sent, a correct error
  9677. * reply can no longer be sent, so just close the connection */
  9678. mg_send_http_error(conn, 500, "%s", "");
  9679. }
  9680. }
  9681. return success;
  9682. }
  9683. #endif
  9684. #if defined(USE_TIMERS)
  9685. #define TIMER_API static
  9686. #include "timer.inl"
  9687. #endif /* USE_TIMERS */
  9688. #if !defined(NO_CGI)
  9689. /* This structure helps to create an environment for the spawned CGI
  9690. * program.
  9691. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9692. * last element must be NULL.
  9693. * However, on Windows there is a requirement that all these
  9694. * VARIABLE=VALUE\0
  9695. * strings must reside in a contiguous buffer. The end of the buffer is
  9696. * marked by two '\0' characters.
  9697. * We satisfy both worlds: we create an envp array (which is vars), all
  9698. * entries are actually pointers inside buf. */
  9699. struct cgi_environment {
  9700. struct mg_connection *conn;
  9701. /* Data block */
  9702. char *buf; /* Environment buffer */
  9703. size_t buflen; /* Space available in buf */
  9704. size_t bufused; /* Space taken in buf */
  9705. /* Index block */
  9706. char **var; /* char **envp */
  9707. size_t varlen; /* Number of variables available in var */
  9708. size_t varused; /* Number of variables stored in var */
  9709. };
  9710. static void addenv(struct cgi_environment *env,
  9711. PRINTF_FORMAT_STRING(const char *fmt),
  9712. ...) PRINTF_ARGS(2, 3);
  9713. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9714. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9715. static void
  9716. addenv(struct cgi_environment *env, const char *fmt, ...)
  9717. {
  9718. size_t i, n, space;
  9719. int truncated = 0;
  9720. char *added;
  9721. va_list ap;
  9722. if ((env->varlen - env->varused) < 2) {
  9723. mg_cry_internal(env->conn,
  9724. "%s: Cannot register CGI variable [%s]",
  9725. __func__,
  9726. fmt);
  9727. return;
  9728. }
  9729. /* Calculate how much space is left in the buffer */
  9730. space = (env->buflen - env->bufused);
  9731. do {
  9732. /* Space for "\0\0" is always needed. */
  9733. if (space <= 2) {
  9734. /* Allocate new buffer */
  9735. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9736. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9737. if (!added) {
  9738. /* Out of memory */
  9739. mg_cry_internal(
  9740. env->conn,
  9741. "%s: Cannot allocate memory for CGI variable [%s]",
  9742. __func__,
  9743. fmt);
  9744. return;
  9745. }
  9746. /* Retarget pointers */
  9747. env->buf = added;
  9748. env->buflen = n;
  9749. for (i = 0, n = 0; i < env->varused; i++) {
  9750. env->var[i] = added + n;
  9751. n += strlen(added + n) + 1;
  9752. }
  9753. space = (env->buflen - env->bufused);
  9754. }
  9755. /* Make a pointer to the free space int the buffer */
  9756. added = env->buf + env->bufused;
  9757. /* Copy VARIABLE=VALUE\0 string into the free space */
  9758. va_start(ap, fmt);
  9759. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9760. va_end(ap);
  9761. /* Do not add truncated strings to the environment */
  9762. if (truncated) {
  9763. /* Reallocate the buffer */
  9764. space = 0;
  9765. }
  9766. } while (truncated);
  9767. /* Calculate number of bytes added to the environment */
  9768. n = strlen(added) + 1;
  9769. env->bufused += n;
  9770. /* Append a pointer to the added string into the envp array */
  9771. env->var[env->varused] = added;
  9772. env->varused++;
  9773. }
  9774. /* Return 0 on success, non-zero if an error occurs. */
  9775. static int
  9776. prepare_cgi_environment(struct mg_connection *conn,
  9777. const char *prog,
  9778. struct cgi_environment *env)
  9779. {
  9780. const char *s;
  9781. struct vec var_vec;
  9782. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9783. int i, truncated, uri_len;
  9784. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9785. return -1;
  9786. }
  9787. env->conn = conn;
  9788. env->buflen = CGI_ENVIRONMENT_SIZE;
  9789. env->bufused = 0;
  9790. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9791. if (env->buf == NULL) {
  9792. mg_cry_internal(conn,
  9793. "%s: Not enough memory for environmental buffer",
  9794. __func__);
  9795. return -1;
  9796. }
  9797. env->varlen = MAX_CGI_ENVIR_VARS;
  9798. env->varused = 0;
  9799. env->var =
  9800. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9801. if (env->var == NULL) {
  9802. mg_cry_internal(conn,
  9803. "%s: Not enough memory for environmental variables",
  9804. __func__);
  9805. mg_free(env->buf);
  9806. return -1;
  9807. }
  9808. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9809. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9810. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9811. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9812. /* Prepare the environment block */
  9813. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9814. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9815. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9816. addenv(env, "SERVER_PORT=%d", ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)));
  9817. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9818. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9819. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9820. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9821. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9822. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9823. /* SCRIPT_NAME */
  9824. uri_len = (int)strlen(conn->request_info.local_uri);
  9825. if (conn->path_info == NULL) {
  9826. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9827. /* URI: /path_to_script/script.cgi */
  9828. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9829. } else {
  9830. /* URI: /path_to_script/ ... using index.cgi */
  9831. const char *index_file = strrchr(prog, '/');
  9832. if (index_file) {
  9833. addenv(env,
  9834. "SCRIPT_NAME=%s%s",
  9835. conn->request_info.local_uri,
  9836. index_file + 1);
  9837. }
  9838. }
  9839. } else {
  9840. /* URI: /path_to_script/script.cgi/path_info */
  9841. addenv(env,
  9842. "SCRIPT_NAME=%.*s",
  9843. uri_len - (int)strlen(conn->path_info),
  9844. conn->request_info.local_uri);
  9845. }
  9846. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9847. if (conn->path_info == NULL) {
  9848. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9849. } else {
  9850. addenv(env,
  9851. "PATH_TRANSLATED=%s%s",
  9852. conn->dom_ctx->config[DOCUMENT_ROOT],
  9853. conn->path_info);
  9854. }
  9855. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9856. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9857. addenv(env, "CONTENT_TYPE=%s", s);
  9858. }
  9859. if (conn->request_info.query_string != NULL) {
  9860. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9861. }
  9862. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9863. addenv(env, "CONTENT_LENGTH=%s", s);
  9864. }
  9865. if ((s = getenv("PATH")) != NULL) {
  9866. addenv(env, "PATH=%s", s);
  9867. }
  9868. if (conn->path_info != NULL) {
  9869. addenv(env, "PATH_INFO=%s", conn->path_info);
  9870. }
  9871. if (conn->status_code > 0) {
  9872. /* CGI error handler should show the status code */
  9873. addenv(env, "STATUS=%d", conn->status_code);
  9874. }
  9875. #if defined(_WIN32)
  9876. if ((s = getenv("COMSPEC")) != NULL) {
  9877. addenv(env, "COMSPEC=%s", s);
  9878. }
  9879. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9880. addenv(env, "SYSTEMROOT=%s", s);
  9881. }
  9882. if ((s = getenv("SystemDrive")) != NULL) {
  9883. addenv(env, "SystemDrive=%s", s);
  9884. }
  9885. if ((s = getenv("ProgramFiles")) != NULL) {
  9886. addenv(env, "ProgramFiles=%s", s);
  9887. }
  9888. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9889. addenv(env, "ProgramFiles(x86)=%s", s);
  9890. }
  9891. #else
  9892. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9893. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9894. }
  9895. #endif /* _WIN32 */
  9896. if ((s = getenv("PERLLIB")) != NULL) {
  9897. addenv(env, "PERLLIB=%s", s);
  9898. }
  9899. if (conn->request_info.remote_user != NULL) {
  9900. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9901. addenv(env, "%s", "AUTH_TYPE=Digest");
  9902. }
  9903. /* Add all headers as HTTP_* variables */
  9904. for (i = 0; i < conn->request_info.num_headers; i++) {
  9905. (void)mg_snprintf(conn,
  9906. &truncated,
  9907. http_var_name,
  9908. sizeof(http_var_name),
  9909. "HTTP_%s",
  9910. conn->request_info.http_headers[i].name);
  9911. if (truncated) {
  9912. mg_cry_internal(conn,
  9913. "%s: HTTP header variable too long [%s]",
  9914. __func__,
  9915. conn->request_info.http_headers[i].name);
  9916. continue;
  9917. }
  9918. /* Convert variable name into uppercase, and change - to _ */
  9919. for (p = http_var_name; *p != '\0'; p++) {
  9920. if (*p == '-') {
  9921. *p = '_';
  9922. }
  9923. *p = (char)toupper((unsigned char)*p);
  9924. }
  9925. addenv(env,
  9926. "%s=%s",
  9927. http_var_name,
  9928. conn->request_info.http_headers[i].value);
  9929. }
  9930. /* Add user-specified variables */
  9931. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9932. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9933. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9934. }
  9935. env->var[env->varused] = NULL;
  9936. env->buf[env->bufused] = '\0';
  9937. return 0;
  9938. }
  9939. /* Data for CGI process control: PID and number of references */
  9940. struct process_control_data {
  9941. pid_t pid;
  9942. ptrdiff_t references;
  9943. };
  9944. static int
  9945. abort_cgi_process(void *data)
  9946. {
  9947. /* Waitpid checks for child status and won't work for a pid that does
  9948. * not identify a child of the current process. Thus, if the pid is
  9949. * reused, we will not affect a different process. */
  9950. struct process_control_data *proc = (struct process_control_data *)data;
  9951. int status = 0;
  9952. ptrdiff_t refs;
  9953. pid_t ret_pid;
  9954. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9955. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9956. /* Stop child process */
  9957. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9958. kill(proc->pid, SIGABRT);
  9959. /* Wait until process is terminated (don't leave zombies) */
  9960. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9961. ;
  9962. } else {
  9963. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9964. }
  9965. /* Dec reference counter */
  9966. refs = mg_atomic_dec(&proc->references);
  9967. if (refs == 0) {
  9968. /* no more references - free data */
  9969. mg_free(data);
  9970. }
  9971. return 0;
  9972. }
  9973. /* Local (static) function assumes all arguments are valid. */
  9974. static void
  9975. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9976. {
  9977. char *buf;
  9978. size_t buflen;
  9979. int headers_len, data_len, i, truncated;
  9980. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9981. const char *status, *status_text, *connection_state;
  9982. char *pbuf, dir[PATH_MAX], *p;
  9983. struct mg_request_info ri;
  9984. struct cgi_environment blk;
  9985. FILE *in = NULL, *out = NULL, *err = NULL;
  9986. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9987. pid_t pid = (pid_t)-1;
  9988. struct process_control_data *proc = NULL;
  9989. #if defined(USE_TIMERS)
  9990. double cgi_timeout;
  9991. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9992. /* Get timeout in seconds */
  9993. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9994. } else {
  9995. cgi_timeout =
  9996. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9997. }
  9998. #endif
  9999. buf = NULL;
  10000. buflen = conn->phys_ctx->max_request_size;
  10001. i = prepare_cgi_environment(conn, prog, &blk);
  10002. if (i != 0) {
  10003. blk.buf = NULL;
  10004. blk.var = NULL;
  10005. goto done;
  10006. }
  10007. /* CGI must be executed in its own directory. 'dir' must point to the
  10008. * directory containing executable program, 'p' must point to the
  10009. * executable program name relative to 'dir'. */
  10010. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10011. if (truncated) {
  10012. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10013. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10014. goto done;
  10015. }
  10016. if ((p = strrchr(dir, '/')) != NULL) {
  10017. *p++ = '\0';
  10018. } else {
  10019. dir[0] = '.';
  10020. dir[1] = '\0';
  10021. p = (char *)prog;
  10022. }
  10023. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10024. status = strerror(ERRNO);
  10025. mg_cry_internal(
  10026. conn,
  10027. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10028. prog,
  10029. status);
  10030. mg_send_http_error(conn,
  10031. 500,
  10032. "Error: Cannot create CGI pipe: %s",
  10033. status);
  10034. goto done;
  10035. }
  10036. proc = (struct process_control_data *)
  10037. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10038. if (proc == NULL) {
  10039. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10040. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10041. goto done;
  10042. }
  10043. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10044. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  10045. if (pid == (pid_t)-1) {
  10046. status = strerror(ERRNO);
  10047. mg_cry_internal(
  10048. conn,
  10049. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10050. prog,
  10051. status);
  10052. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10053. mg_free(proc);
  10054. proc = NULL;
  10055. goto done;
  10056. }
  10057. /* Store data in shared process_control_data */
  10058. proc->pid = pid;
  10059. proc->references = 1;
  10060. #if defined(USE_TIMERS)
  10061. if (cgi_timeout > 0.0) {
  10062. proc->references = 2;
  10063. // Start a timer for CGI
  10064. timer_add(conn->phys_ctx,
  10065. cgi_timeout /* in seconds */,
  10066. 0.0,
  10067. 1,
  10068. abort_cgi_process,
  10069. (void *)proc,
  10070. NULL);
  10071. }
  10072. #endif
  10073. /* Parent closes only one side of the pipes.
  10074. * If we don't mark them as closed, close() attempt before
  10075. * return from this function throws an exception on Windows.
  10076. * Windows does not like when closed descriptor is closed again. */
  10077. (void)close(fdin[0]);
  10078. (void)close(fdout[1]);
  10079. (void)close(fderr[1]);
  10080. fdin[0] = fdout[1] = fderr[1] = -1;
  10081. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10082. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10083. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10084. status = strerror(ERRNO);
  10085. mg_cry_internal(conn,
  10086. "Error: CGI program \"%s\": Can not open fd: %s",
  10087. prog,
  10088. status);
  10089. mg_send_http_error(conn,
  10090. 500,
  10091. "Error: CGI can not open fd\nfdopen: %s",
  10092. status);
  10093. goto done;
  10094. }
  10095. setbuf(in, NULL);
  10096. setbuf(out, NULL);
  10097. setbuf(err, NULL);
  10098. fout.access.fp = out;
  10099. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10100. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10101. conn->content_len);
  10102. /* This is a POST/PUT request, or another request with body data. */
  10103. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10104. /* Error sending the body data */
  10105. mg_cry_internal(
  10106. conn,
  10107. "Error: CGI program \"%s\": Forward body data failed",
  10108. prog);
  10109. goto done;
  10110. }
  10111. }
  10112. /* Close so child gets an EOF. */
  10113. fclose(in);
  10114. in = NULL;
  10115. fdin[1] = -1;
  10116. /* Now read CGI reply into a buffer. We need to set correct
  10117. * status code, thus we need to see all HTTP headers first.
  10118. * Do not send anything back to client, until we buffer in all
  10119. * HTTP headers. */
  10120. data_len = 0;
  10121. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10122. if (buf == NULL) {
  10123. mg_send_http_error(conn,
  10124. 500,
  10125. "Error: Not enough memory for CGI buffer (%u bytes)",
  10126. (unsigned int)buflen);
  10127. mg_cry_internal(
  10128. conn,
  10129. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10130. "bytes)",
  10131. prog,
  10132. (unsigned int)buflen);
  10133. goto done;
  10134. }
  10135. DEBUG_TRACE("CGI: %s", "wait for response");
  10136. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10137. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10138. if (headers_len <= 0) {
  10139. /* Could not parse the CGI response. Check if some error message on
  10140. * stderr. */
  10141. i = pull_all(err, conn, buf, (int)buflen);
  10142. if (i > 0) {
  10143. /* CGI program explicitly sent an error */
  10144. /* Write the error message to the internal log */
  10145. mg_cry_internal(conn,
  10146. "Error: CGI program \"%s\" sent error "
  10147. "message: [%.*s]",
  10148. prog,
  10149. i,
  10150. buf);
  10151. /* Don't send the error message back to the client */
  10152. mg_send_http_error(conn,
  10153. 500,
  10154. "Error: CGI program \"%s\" failed.",
  10155. prog);
  10156. } else {
  10157. /* CGI program did not explicitly send an error, but a broken
  10158. * respon header */
  10159. mg_cry_internal(conn,
  10160. "Error: CGI program sent malformed or too big "
  10161. "(>%u bytes) HTTP headers: [%.*s]",
  10162. (unsigned)buflen,
  10163. data_len,
  10164. buf);
  10165. mg_send_http_error(conn,
  10166. 500,
  10167. "Error: CGI program sent malformed or too big "
  10168. "(>%u bytes) HTTP headers: [%.*s]",
  10169. (unsigned)buflen,
  10170. data_len,
  10171. buf);
  10172. }
  10173. /* in both cases, abort processing CGI */
  10174. goto done;
  10175. }
  10176. pbuf = buf;
  10177. buf[headers_len - 1] = '\0';
  10178. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10179. /* Make up and send the status line */
  10180. status_text = "OK";
  10181. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10182. != NULL) {
  10183. conn->status_code = atoi(status);
  10184. status_text = status;
  10185. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10186. status_text++;
  10187. }
  10188. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10189. != NULL) {
  10190. conn->status_code = 307;
  10191. } else {
  10192. conn->status_code = 200;
  10193. }
  10194. connection_state =
  10195. get_header(ri.http_headers, ri.num_headers, "Connection");
  10196. if (!header_has_option(connection_state, "keep-alive")) {
  10197. conn->must_close = 1;
  10198. }
  10199. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10200. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10201. /* Send headers */
  10202. for (i = 0; i < ri.num_headers; i++) {
  10203. DEBUG_TRACE("CGI header: %s: %s",
  10204. ri.http_headers[i].name,
  10205. ri.http_headers[i].value);
  10206. mg_printf(conn,
  10207. "%s: %s\r\n",
  10208. ri.http_headers[i].name,
  10209. ri.http_headers[i].value);
  10210. }
  10211. mg_write(conn, "\r\n", 2);
  10212. /* Send chunk of data that may have been read after the headers */
  10213. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10214. /* Read the rest of CGI output and send to the client */
  10215. DEBUG_TRACE("CGI: %s", "forward all data");
  10216. send_file_data(conn, &fout, 0, INT64_MAX);
  10217. DEBUG_TRACE("CGI: %s", "all data sent");
  10218. done:
  10219. mg_free(blk.var);
  10220. mg_free(blk.buf);
  10221. if (pid != (pid_t)-1) {
  10222. abort_cgi_process((void *)proc);
  10223. }
  10224. if (fdin[0] != -1) {
  10225. close(fdin[0]);
  10226. }
  10227. if (fdout[1] != -1) {
  10228. close(fdout[1]);
  10229. }
  10230. if (fderr[1] != -1) {
  10231. close(fderr[1]);
  10232. }
  10233. if (in != NULL) {
  10234. fclose(in);
  10235. } else if (fdin[1] != -1) {
  10236. close(fdin[1]);
  10237. }
  10238. if (out != NULL) {
  10239. fclose(out);
  10240. } else if (fdout[0] != -1) {
  10241. close(fdout[0]);
  10242. }
  10243. if (err != NULL) {
  10244. fclose(err);
  10245. } else if (fderr[0] != -1) {
  10246. close(fderr[0]);
  10247. }
  10248. mg_free(buf);
  10249. }
  10250. #endif /* !NO_CGI */
  10251. #if !defined(NO_FILES)
  10252. static void
  10253. mkcol(struct mg_connection *conn, const char *path)
  10254. {
  10255. int rc, body_len;
  10256. struct de de;
  10257. if (conn == NULL) {
  10258. return;
  10259. }
  10260. /* TODO (mid): Check the mg_send_http_error situations in this function
  10261. */
  10262. memset(&de.file, 0, sizeof(de.file));
  10263. if (!mg_stat(conn, path, &de.file)) {
  10264. mg_cry_internal(conn,
  10265. "%s: mg_stat(%s) failed: %s",
  10266. __func__,
  10267. path,
  10268. strerror(ERRNO));
  10269. }
  10270. if (de.file.last_modified) {
  10271. /* TODO (mid): This check does not seem to make any sense ! */
  10272. /* TODO (mid): Add a webdav unit test first, before changing
  10273. * anything here. */
  10274. mg_send_http_error(
  10275. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10276. return;
  10277. }
  10278. body_len = conn->data_len - conn->request_len;
  10279. if (body_len > 0) {
  10280. mg_send_http_error(
  10281. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10282. return;
  10283. }
  10284. rc = mg_mkdir(conn, path, 0755);
  10285. if (rc == 0) {
  10286. /* Create 201 "Created" response */
  10287. mg_response_header_start(conn, 201);
  10288. send_static_cache_header(conn);
  10289. send_additional_header(conn);
  10290. mg_response_header_add(conn, "Content-Length", "0", -1);
  10291. /* Send all headers - there is no body */
  10292. mg_response_header_send(conn);
  10293. } else {
  10294. if (errno == EEXIST) {
  10295. mg_send_http_error(
  10296. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10297. } else if (errno == EACCES) {
  10298. mg_send_http_error(
  10299. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10300. } else if (errno == ENOENT) {
  10301. mg_send_http_error(
  10302. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10303. } else {
  10304. mg_send_http_error(
  10305. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10306. }
  10307. }
  10308. }
  10309. static void
  10310. put_file(struct mg_connection *conn, const char *path)
  10311. {
  10312. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10313. const char *range;
  10314. int64_t r1, r2;
  10315. int rc;
  10316. if (conn == NULL) {
  10317. return;
  10318. }
  10319. if (mg_stat(conn, path, &file.stat)) {
  10320. /* File already exists */
  10321. conn->status_code = 200;
  10322. if (file.stat.is_directory) {
  10323. /* This is an already existing directory,
  10324. * so there is nothing to do for the server. */
  10325. rc = 0;
  10326. } else {
  10327. /* File exists and is not a directory. */
  10328. /* Can it be replaced? */
  10329. /* Check if the server may write this file */
  10330. if (access(path, W_OK) == 0) {
  10331. /* Access granted */
  10332. rc = 1;
  10333. } else {
  10334. mg_send_http_error(
  10335. conn,
  10336. 403,
  10337. "Error: Put not possible\nReplacing %s is not allowed",
  10338. path);
  10339. return;
  10340. }
  10341. }
  10342. } else {
  10343. /* File should be created */
  10344. conn->status_code = 201;
  10345. rc = put_dir(conn, path);
  10346. }
  10347. if (rc == 0) {
  10348. /* put_dir returns 0 if path is a directory */
  10349. /* Create response */
  10350. mg_response_header_start(conn, conn->status_code);
  10351. send_no_cache_header(conn);
  10352. send_additional_header(conn);
  10353. mg_response_header_add(conn, "Content-Length", "0", -1);
  10354. /* Send all headers - there is no body */
  10355. mg_response_header_send(conn);
  10356. /* Request to create a directory has been fulfilled successfully.
  10357. * No need to put a file. */
  10358. return;
  10359. }
  10360. if (rc == -1) {
  10361. /* put_dir returns -1 if the path is too long */
  10362. mg_send_http_error(conn,
  10363. 414,
  10364. "Error: Path too long\nput_dir(%s): %s",
  10365. path,
  10366. strerror(ERRNO));
  10367. return;
  10368. }
  10369. if (rc == -2) {
  10370. /* put_dir returns -2 if the directory can not be created */
  10371. mg_send_http_error(conn,
  10372. 500,
  10373. "Error: Can not create directory\nput_dir(%s): %s",
  10374. path,
  10375. strerror(ERRNO));
  10376. return;
  10377. }
  10378. /* A file should be created or overwritten. */
  10379. /* Currently CivetWeb does not nead read+write access. */
  10380. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10381. || file.access.fp == NULL) {
  10382. (void)mg_fclose(&file.access);
  10383. mg_send_http_error(conn,
  10384. 500,
  10385. "Error: Can not create file\nfopen(%s): %s",
  10386. path,
  10387. strerror(ERRNO));
  10388. return;
  10389. }
  10390. fclose_on_exec(&file.access, conn);
  10391. range = mg_get_header(conn, "Content-Range");
  10392. r1 = r2 = 0;
  10393. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10394. conn->status_code = 206; /* Partial content */
  10395. fseeko(file.access.fp, r1, SEEK_SET);
  10396. }
  10397. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10398. /* forward_body_data failed.
  10399. * The error code has already been sent to the client,
  10400. * and conn->status_code is already set. */
  10401. (void)mg_fclose(&file.access);
  10402. return;
  10403. }
  10404. if (mg_fclose(&file.access) != 0) {
  10405. /* fclose failed. This might have different reasons, but a likely
  10406. * one is "no space on disk", http 507. */
  10407. conn->status_code = 507;
  10408. }
  10409. /* Create response (status_code has been set before) */
  10410. mg_response_header_start(conn, conn->status_code);
  10411. send_no_cache_header(conn);
  10412. send_additional_header(conn);
  10413. mg_response_header_add(conn, "Content-Length", "0", -1);
  10414. /* Send all headers - there is no body */
  10415. mg_response_header_send(conn);
  10416. }
  10417. static void
  10418. delete_file(struct mg_connection *conn, const char *path)
  10419. {
  10420. struct de de;
  10421. memset(&de.file, 0, sizeof(de.file));
  10422. if (!mg_stat(conn, path, &de.file)) {
  10423. /* mg_stat returns 0 if the file does not exist */
  10424. mg_send_http_error(conn,
  10425. 404,
  10426. "Error: Cannot delete file\nFile %s not found",
  10427. path);
  10428. return;
  10429. }
  10430. if (de.file.is_directory) {
  10431. if (remove_directory(conn, path)) {
  10432. /* Delete is successful: Return 204 without content. */
  10433. mg_send_http_error(conn, 204, "%s", "");
  10434. } else {
  10435. /* Delete is not successful: Return 500 (Server error). */
  10436. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10437. }
  10438. return;
  10439. }
  10440. /* This is an existing file (not a directory).
  10441. * Check if write permission is granted. */
  10442. if (access(path, W_OK) != 0) {
  10443. /* File is read only */
  10444. mg_send_http_error(
  10445. conn,
  10446. 403,
  10447. "Error: Delete not possible\nDeleting %s is not allowed",
  10448. path);
  10449. return;
  10450. }
  10451. /* Try to delete it. */
  10452. if (mg_remove(conn, path) == 0) {
  10453. /* Delete was successful: Return 204 without content. */
  10454. mg_response_header_start(conn, 204);
  10455. send_no_cache_header(conn);
  10456. send_additional_header(conn);
  10457. mg_response_header_add(conn, "Content-Length", "0", -1);
  10458. mg_response_header_send(conn);
  10459. } else {
  10460. /* Delete not successful (file locked). */
  10461. mg_send_http_error(conn,
  10462. 423,
  10463. "Error: Cannot delete file\nremove(%s): %s",
  10464. path,
  10465. strerror(ERRNO));
  10466. }
  10467. }
  10468. #endif /* !NO_FILES */
  10469. #if !defined(NO_FILESYSTEMS)
  10470. static void
  10471. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10472. static void
  10473. do_ssi_include(struct mg_connection *conn,
  10474. const char *ssi,
  10475. char *tag,
  10476. int include_level)
  10477. {
  10478. char file_name[MG_BUF_LEN], path[512], *p;
  10479. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10480. size_t len;
  10481. int truncated = 0;
  10482. if (conn == NULL) {
  10483. return;
  10484. }
  10485. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10486. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10487. * always < MG_BUF_LEN. */
  10488. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10489. /* File name is relative to the webserver root */
  10490. file_name[511] = 0;
  10491. (void)mg_snprintf(conn,
  10492. &truncated,
  10493. path,
  10494. sizeof(path),
  10495. "%s/%s",
  10496. conn->dom_ctx->config[DOCUMENT_ROOT],
  10497. file_name);
  10498. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10499. /* File name is relative to the webserver working directory
  10500. * or it is absolute system path */
  10501. file_name[511] = 0;
  10502. (void)
  10503. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10504. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10505. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10506. /* File name is relative to the currect document */
  10507. file_name[511] = 0;
  10508. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10509. if (!truncated) {
  10510. if ((p = strrchr(path, '/')) != NULL) {
  10511. p[1] = '\0';
  10512. }
  10513. len = strlen(path);
  10514. (void)mg_snprintf(conn,
  10515. &truncated,
  10516. path + len,
  10517. sizeof(path) - len,
  10518. "%s",
  10519. file_name);
  10520. }
  10521. } else {
  10522. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10523. return;
  10524. }
  10525. if (truncated) {
  10526. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10527. return;
  10528. }
  10529. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10530. mg_cry_internal(conn,
  10531. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10532. tag,
  10533. path,
  10534. strerror(ERRNO));
  10535. } else {
  10536. fclose_on_exec(&file.access, conn);
  10537. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10538. > 0) {
  10539. send_ssi_file(conn, path, &file, include_level + 1);
  10540. } else {
  10541. send_file_data(conn, &file, 0, INT64_MAX);
  10542. }
  10543. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10544. }
  10545. }
  10546. #if !defined(NO_POPEN)
  10547. static void
  10548. do_ssi_exec(struct mg_connection *conn, char *tag)
  10549. {
  10550. char cmd[1024] = "";
  10551. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10552. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10553. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10554. } else {
  10555. cmd[1023] = 0;
  10556. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10557. mg_cry_internal(conn,
  10558. "Cannot SSI #exec: [%s]: %s",
  10559. cmd,
  10560. strerror(ERRNO));
  10561. } else {
  10562. send_file_data(conn, &file, 0, INT64_MAX);
  10563. pclose(file.access.fp);
  10564. }
  10565. }
  10566. }
  10567. #endif /* !NO_POPEN */
  10568. static int
  10569. mg_fgetc(struct mg_file *filep)
  10570. {
  10571. if (filep == NULL) {
  10572. return EOF;
  10573. }
  10574. if (filep->access.fp != NULL) {
  10575. return fgetc(filep->access.fp);
  10576. } else {
  10577. return EOF;
  10578. }
  10579. }
  10580. static void
  10581. send_ssi_file(struct mg_connection *conn,
  10582. const char *path,
  10583. struct mg_file *filep,
  10584. int include_level)
  10585. {
  10586. char buf[MG_BUF_LEN];
  10587. int ch, len, in_tag, in_ssi_tag;
  10588. if (include_level > 10) {
  10589. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10590. return;
  10591. }
  10592. in_tag = in_ssi_tag = len = 0;
  10593. /* Read file, byte by byte, and look for SSI include tags */
  10594. while ((ch = mg_fgetc(filep)) != EOF) {
  10595. if (in_tag) {
  10596. /* We are in a tag, either SSI tag or html tag */
  10597. if (ch == '>') {
  10598. /* Tag is closing */
  10599. buf[len++] = '>';
  10600. if (in_ssi_tag) {
  10601. /* Handle SSI tag */
  10602. buf[len] = 0;
  10603. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10604. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10605. #if !defined(NO_POPEN)
  10606. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10607. do_ssi_exec(conn, buf + 9);
  10608. #endif /* !NO_POPEN */
  10609. } else {
  10610. mg_cry_internal(conn,
  10611. "%s: unknown SSI "
  10612. "command: \"%s\"",
  10613. path,
  10614. buf);
  10615. }
  10616. len = 0;
  10617. in_ssi_tag = in_tag = 0;
  10618. } else {
  10619. /* Not an SSI tag */
  10620. /* Flush buffer */
  10621. (void)mg_write(conn, buf, (size_t)len);
  10622. len = 0;
  10623. in_tag = 0;
  10624. }
  10625. } else {
  10626. /* Tag is still open */
  10627. buf[len++] = (char)(ch & 0xff);
  10628. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10629. /* All SSI tags start with <!--# */
  10630. in_ssi_tag = 1;
  10631. }
  10632. if ((len + 2) > (int)sizeof(buf)) {
  10633. /* Tag to long for buffer */
  10634. mg_cry_internal(conn, "%s: tag is too large", path);
  10635. return;
  10636. }
  10637. }
  10638. } else {
  10639. /* We are not in a tag yet. */
  10640. if (ch == '<') {
  10641. /* Tag is opening */
  10642. in_tag = 1;
  10643. if (len > 0) {
  10644. /* Flush current buffer.
  10645. * Buffer is filled with "len" bytes. */
  10646. (void)mg_write(conn, buf, (size_t)len);
  10647. }
  10648. /* Store the < */
  10649. len = 1;
  10650. buf[0] = '<';
  10651. } else {
  10652. /* No Tag */
  10653. /* Add data to buffer */
  10654. buf[len++] = (char)(ch & 0xff);
  10655. /* Flush if buffer is full */
  10656. if (len == (int)sizeof(buf)) {
  10657. mg_write(conn, buf, (size_t)len);
  10658. len = 0;
  10659. }
  10660. }
  10661. }
  10662. }
  10663. /* Send the rest of buffered data */
  10664. if (len > 0) {
  10665. mg_write(conn, buf, (size_t)len);
  10666. }
  10667. }
  10668. static void
  10669. handle_ssi_file_request(struct mg_connection *conn,
  10670. const char *path,
  10671. struct mg_file *filep)
  10672. {
  10673. char date[64];
  10674. time_t curtime = time(NULL);
  10675. const char *cors_orig_cfg;
  10676. const char *cors1, *cors2;
  10677. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10678. return;
  10679. }
  10680. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10681. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10682. /* Cross-origin resource sharing (CORS). */
  10683. cors1 = "Access-Control-Allow-Origin";
  10684. cors2 = cors_orig_cfg;
  10685. } else {
  10686. cors1 = cors2 = "";
  10687. }
  10688. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10689. /* File exists (precondition for calling this function),
  10690. * but can not be opened by the server. */
  10691. mg_send_http_error(conn,
  10692. 500,
  10693. "Error: Cannot read file\nfopen(%s): %s",
  10694. path,
  10695. strerror(ERRNO));
  10696. } else {
  10697. /* Set "must_close" for HTTP/1.x, since we do not know the
  10698. * content length */
  10699. conn->must_close = 1;
  10700. gmt_time_string(date, sizeof(date), &curtime);
  10701. fclose_on_exec(&filep->access, conn);
  10702. /* 200 OK response */
  10703. mg_response_header_start(conn, 200);
  10704. send_no_cache_header(conn);
  10705. send_additional_header(conn);
  10706. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10707. if (cors1[0]) {
  10708. mg_response_header_add(conn, cors1, cors2, -1);
  10709. }
  10710. mg_response_header_send(conn);
  10711. /* Header sent, now send body */
  10712. send_ssi_file(conn, path, filep, 0);
  10713. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10714. }
  10715. }
  10716. #endif /* NO_FILESYSTEMS */
  10717. #if !defined(NO_FILES)
  10718. static void
  10719. send_options(struct mg_connection *conn)
  10720. {
  10721. if (!conn) {
  10722. return;
  10723. }
  10724. /* We do not set a "Cache-Control" header here, but leave the default.
  10725. * Since browsers do not send an OPTIONS request, we can not test the
  10726. * effect anyway. */
  10727. mg_response_header_start(conn, 200);
  10728. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10729. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10730. /* Use the same as before */
  10731. mg_response_header_add(
  10732. conn,
  10733. "Allow",
  10734. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10735. -1);
  10736. mg_response_header_add(conn, "DAV", "1", -1);
  10737. } else {
  10738. /* TODO: Check this later for HTTP/2 */
  10739. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10740. }
  10741. send_additional_header(conn);
  10742. mg_response_header_send(conn);
  10743. }
  10744. /* Writes PROPFIND properties for a collection element */
  10745. static int
  10746. print_props(struct mg_connection *conn,
  10747. const char *uri,
  10748. const char *name,
  10749. struct mg_file_stat *filep)
  10750. {
  10751. size_t href_size, i, j;
  10752. int len;
  10753. char *href, mtime[64];
  10754. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10755. return 0;
  10756. }
  10757. /* Estimate worst case size for encoding */
  10758. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10759. href = (char *)mg_malloc(href_size);
  10760. if (href == NULL) {
  10761. return 0;
  10762. }
  10763. len = mg_url_encode(uri, href, href_size);
  10764. if (len >= 0) {
  10765. /* Append an extra string */
  10766. mg_url_encode(name, href + len, href_size - (size_t)len);
  10767. }
  10768. /* Directory separator should be preserved. */
  10769. for (i = j = 0; href[i]; j++) {
  10770. if (!strncmp(href + i, "%2f", 3)) {
  10771. href[j] = '/';
  10772. i += 3;
  10773. } else {
  10774. href[j] = href[i++];
  10775. }
  10776. }
  10777. href[j] = '\0';
  10778. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10779. mg_printf(conn,
  10780. "<d:response>"
  10781. "<d:href>%s</d:href>"
  10782. "<d:propstat>"
  10783. "<d:prop>"
  10784. "<d:resourcetype>%s</d:resourcetype>"
  10785. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10786. "<d:getlastmodified>%s</d:getlastmodified>"
  10787. "</d:prop>"
  10788. "<d:status>HTTP/1.1 200 OK</d:status>"
  10789. "</d:propstat>"
  10790. "</d:response>\n",
  10791. href,
  10792. filep->is_directory ? "<d:collection/>" : "",
  10793. filep->size,
  10794. mtime);
  10795. mg_free(href);
  10796. return 1;
  10797. }
  10798. static int
  10799. print_dav_dir_entry(struct de *de, void *data)
  10800. {
  10801. struct mg_connection *conn = (struct mg_connection *)data;
  10802. if (!de || !conn
  10803. || !print_props(
  10804. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10805. /* stop scan */
  10806. return 1;
  10807. }
  10808. return 0;
  10809. }
  10810. static void
  10811. handle_propfind(struct mg_connection *conn,
  10812. const char *path,
  10813. struct mg_file_stat *filep)
  10814. {
  10815. const char *depth = mg_get_header(conn, "Depth");
  10816. char date[64];
  10817. time_t curtime = time(NULL);
  10818. gmt_time_string(date, sizeof(date), &curtime);
  10819. if (!conn || !path || !filep || !conn->dom_ctx) {
  10820. return;
  10821. }
  10822. conn->must_close = 1;
  10823. /* return 207 "Multi-Status" */
  10824. mg_response_header_start(conn, 207);
  10825. send_static_cache_header(conn);
  10826. send_additional_header(conn);
  10827. mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10828. mg_response_header_send(conn);
  10829. /* Content */
  10830. mg_printf(conn,
  10831. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10832. "<d:multistatus xmlns:d='DAV:'>\n");
  10833. /* Print properties for the requested resource itself */
  10834. print_props(conn, conn->request_info.local_uri, "", filep);
  10835. /* If it is a directory, print directory entries too if Depth is not 0
  10836. */
  10837. if (filep->is_directory
  10838. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10839. "yes")
  10840. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10841. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10842. }
  10843. mg_printf(conn, "%s\n", "</d:multistatus>");
  10844. }
  10845. #endif
  10846. void
  10847. mg_lock_connection(struct mg_connection *conn)
  10848. {
  10849. if (conn) {
  10850. (void)pthread_mutex_lock(&conn->mutex);
  10851. }
  10852. }
  10853. void
  10854. mg_unlock_connection(struct mg_connection *conn)
  10855. {
  10856. if (conn) {
  10857. (void)pthread_mutex_unlock(&conn->mutex);
  10858. }
  10859. }
  10860. void
  10861. mg_lock_context(struct mg_context *ctx)
  10862. {
  10863. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10864. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10865. }
  10866. }
  10867. void
  10868. mg_unlock_context(struct mg_context *ctx)
  10869. {
  10870. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10871. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10872. }
  10873. }
  10874. #if defined(USE_LUA)
  10875. #include "mod_lua.inl"
  10876. #endif /* USE_LUA */
  10877. #if defined(USE_DUKTAPE)
  10878. #include "mod_duktape.inl"
  10879. #endif /* USE_DUKTAPE */
  10880. #if defined(USE_WEBSOCKET)
  10881. #if !defined(NO_SSL_DL)
  10882. #define SHA_API static
  10883. #include "sha1.inl"
  10884. #endif
  10885. static int
  10886. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10887. {
  10888. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10889. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10890. SHA_CTX sha_ctx;
  10891. int truncated;
  10892. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10893. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10894. if (truncated) {
  10895. conn->must_close = 1;
  10896. return 0;
  10897. }
  10898. DEBUG_TRACE("%s", "Send websocket handshake");
  10899. SHA1_Init(&sha_ctx);
  10900. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10901. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10902. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10903. mg_printf(conn,
  10904. "HTTP/1.1 101 Switching Protocols\r\n"
  10905. "Upgrade: websocket\r\n"
  10906. "Connection: Upgrade\r\n"
  10907. "Sec-WebSocket-Accept: %s\r\n",
  10908. b64_sha);
  10909. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10910. // Send negotiated compression extension parameters
  10911. websocket_deflate_response(conn);
  10912. #endif
  10913. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10914. mg_printf(conn,
  10915. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10916. conn->request_info.acceptedWebSocketSubprotocol);
  10917. } else {
  10918. mg_printf(conn, "%s", "\r\n");
  10919. }
  10920. return 1;
  10921. }
  10922. #if !defined(MG_MAX_UNANSWERED_PING)
  10923. /* Configuration of the maximum number of websocket PINGs that might
  10924. * stay unanswered before the connection is considered broken.
  10925. * Note: The name of this define may still change (until it is
  10926. * defined as a compile parameter in a documentation).
  10927. */
  10928. #define MG_MAX_UNANSWERED_PING (5)
  10929. #endif
  10930. static void
  10931. read_websocket(struct mg_connection *conn,
  10932. mg_websocket_data_handler ws_data_handler,
  10933. void *callback_data)
  10934. {
  10935. /* Pointer to the beginning of the portion of the incoming websocket
  10936. * message queue.
  10937. * The original websocket upgrade request is never removed, so the queue
  10938. * begins after it. */
  10939. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10940. int n, error, exit_by_callback;
  10941. int ret;
  10942. /* body_len is the length of the entire queue in bytes
  10943. * len is the length of the current message
  10944. * data_len is the length of the current message's data payload
  10945. * header_len is the length of the current message's header */
  10946. size_t i, len, mask_len = 0, header_len, body_len;
  10947. uint64_t data_len = 0;
  10948. /* "The masking key is a 32-bit value chosen at random by the client."
  10949. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10950. */
  10951. unsigned char mask[4];
  10952. /* data points to the place where the message is stored when passed to
  10953. * the websocket_data callback. This is either mem on the stack, or a
  10954. * dynamically allocated buffer if it is too large. */
  10955. unsigned char mem[4096];
  10956. unsigned char mop; /* mask flag and opcode */
  10957. /* Variables used for connection monitoring */
  10958. double timeout = -1.0;
  10959. int enable_ping_pong = 0;
  10960. int ping_count = 0;
  10961. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10962. enable_ping_pong =
  10963. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10964. "yes");
  10965. }
  10966. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10967. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10968. }
  10969. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10970. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10971. }
  10972. if (timeout <= 0.0) {
  10973. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  10974. }
  10975. /* Enter data processing loop */
  10976. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10977. conn->request_info.remote_addr,
  10978. conn->request_info.remote_port);
  10979. conn->in_websocket_handling = 1;
  10980. mg_set_thread_name("wsock");
  10981. /* Loop continuously, reading messages from the socket, invoking the
  10982. * callback, and waiting repeatedly until an error occurs. */
  10983. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10984. && (!conn->must_close)) {
  10985. header_len = 0;
  10986. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10987. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10988. len = buf[1] & 127;
  10989. mask_len = (buf[1] & 128) ? 4 : 0;
  10990. if ((len < 126) && (body_len >= mask_len)) {
  10991. /* inline 7-bit length field */
  10992. data_len = len;
  10993. header_len = 2 + mask_len;
  10994. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10995. /* 16-bit length field */
  10996. header_len = 4 + mask_len;
  10997. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10998. } else if (body_len >= (10 + mask_len)) {
  10999. /* 64-bit length field */
  11000. uint32_t l1, l2;
  11001. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11002. memcpy(&l2, &buf[6], 4);
  11003. header_len = 10 + mask_len;
  11004. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11005. if (data_len > (uint64_t)0x7FFF0000ul) {
  11006. /* no can do */
  11007. mg_cry_internal(
  11008. conn,
  11009. "%s",
  11010. "websocket out of memory; closing connection");
  11011. break;
  11012. }
  11013. }
  11014. }
  11015. if ((header_len > 0) && (body_len >= header_len)) {
  11016. /* Allocate space to hold websocket payload */
  11017. unsigned char *data = mem;
  11018. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11019. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11020. conn->phys_ctx);
  11021. if (data == NULL) {
  11022. /* Allocation failed, exit the loop and then close the
  11023. * connection */
  11024. mg_cry_internal(
  11025. conn,
  11026. "%s",
  11027. "websocket out of memory; closing connection");
  11028. break;
  11029. }
  11030. }
  11031. /* Copy the mask before we shift the queue and destroy it */
  11032. if (mask_len > 0) {
  11033. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11034. } else {
  11035. memset(mask, 0, sizeof(mask));
  11036. }
  11037. /* Read frame payload from the first message in the queue into
  11038. * data and advance the queue by moving the memory in place. */
  11039. DEBUG_ASSERT(body_len >= header_len);
  11040. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11041. mop = buf[0]; /* current mask and opcode */
  11042. /* Overflow case */
  11043. len = body_len - header_len;
  11044. memcpy(data, buf + header_len, len);
  11045. error = 0;
  11046. while ((uint64_t)len < data_len) {
  11047. n = pull_inner(NULL,
  11048. conn,
  11049. (char *)(data + len),
  11050. (int)(data_len - len),
  11051. timeout);
  11052. if (n <= -2) {
  11053. error = 1;
  11054. break;
  11055. } else if (n > 0) {
  11056. len += (size_t)n;
  11057. } else {
  11058. /* Timeout: should retry */
  11059. /* TODO: retry condition */
  11060. }
  11061. }
  11062. if (error) {
  11063. mg_cry_internal(
  11064. conn,
  11065. "%s",
  11066. "Websocket pull failed; closing connection");
  11067. if (data != mem) {
  11068. mg_free(data);
  11069. }
  11070. break;
  11071. }
  11072. conn->data_len = conn->request_len;
  11073. } else {
  11074. mop = buf[0]; /* current mask and opcode, overwritten by
  11075. * memmove() */
  11076. /* Length of the message being read at the front of the
  11077. * queue. Cast to 31 bit is OK, since we limited
  11078. * data_len before. */
  11079. len = (size_t)data_len + header_len;
  11080. /* Copy the data payload into the data pointer for the
  11081. * callback. Cast to 31 bit is OK, since we
  11082. * limited data_len */
  11083. memcpy(data, buf + header_len, (size_t)data_len);
  11084. /* Move the queue forward len bytes */
  11085. memmove(buf, buf + len, body_len - len);
  11086. /* Mark the queue as advanced */
  11087. conn->data_len -= (int)len;
  11088. }
  11089. /* Apply mask if necessary */
  11090. if (mask_len > 0) {
  11091. for (i = 0; i < (size_t)data_len; i++) {
  11092. data[i] ^= mask[i & 3];
  11093. }
  11094. }
  11095. exit_by_callback = 0;
  11096. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11097. /* filter PONG messages */
  11098. DEBUG_TRACE("PONG from %s:%u",
  11099. conn->request_info.remote_addr,
  11100. conn->request_info.remote_port);
  11101. /* No unanwered PINGs left */
  11102. ping_count = 0;
  11103. } else if (enable_ping_pong
  11104. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11105. /* reply PING messages */
  11106. DEBUG_TRACE("Reply PING from %s:%u",
  11107. conn->request_info.remote_addr,
  11108. conn->request_info.remote_port);
  11109. ret = mg_websocket_write(conn,
  11110. MG_WEBSOCKET_OPCODE_PONG,
  11111. (char *)data,
  11112. (size_t)data_len);
  11113. if (ret <= 0) {
  11114. /* Error: send failed */
  11115. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11116. break;
  11117. }
  11118. } else {
  11119. /* Exit the loop if callback signals to exit (server side),
  11120. * or "connection close" opcode received (client side). */
  11121. if (ws_data_handler != NULL) {
  11122. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11123. if (mop & 0x40) {
  11124. /* Inflate the data received if bit RSV1 is set. */
  11125. if (!conn->websocket_deflate_initialized) {
  11126. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11127. exit_by_callback = 1;
  11128. }
  11129. if (!exit_by_callback) {
  11130. size_t inflate_buf_size_old = 0;
  11131. size_t inflate_buf_size =
  11132. data_len
  11133. * 4; // Initial guess of the inflated message
  11134. // size. We double the memory when needed.
  11135. Bytef *inflated;
  11136. Bytef *new_mem;
  11137. conn->websocket_inflate_state.avail_in =
  11138. (uInt)(data_len + 4);
  11139. conn->websocket_inflate_state.next_in = data;
  11140. // Add trailing 0x00 0x00 0xff 0xff bytes
  11141. data[data_len] = '\x00';
  11142. data[data_len + 1] = '\x00';
  11143. data[data_len + 2] = '\xff';
  11144. data[data_len + 3] = '\xff';
  11145. do {
  11146. if (inflate_buf_size_old == 0) {
  11147. new_mem = mg_calloc(inflate_buf_size,
  11148. sizeof(Bytef));
  11149. } else {
  11150. inflate_buf_size *= 2;
  11151. new_mem =
  11152. mg_realloc(inflated, inflate_buf_size);
  11153. }
  11154. if (new_mem == NULL) {
  11155. mg_cry_internal(
  11156. conn,
  11157. "Out of memory: Cannot allocate "
  11158. "inflate buffer of %i bytes",
  11159. inflate_buf_size);
  11160. exit_by_callback = 1;
  11161. break;
  11162. }
  11163. inflated = new_mem;
  11164. conn->websocket_inflate_state.avail_out =
  11165. (uInt)(inflate_buf_size
  11166. - inflate_buf_size_old);
  11167. conn->websocket_inflate_state.next_out =
  11168. inflated + inflate_buf_size_old;
  11169. int ret =
  11170. inflate(&conn->websocket_inflate_state,
  11171. Z_SYNC_FLUSH);
  11172. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11173. || ret == Z_MEM_ERROR || ret < 0) {
  11174. mg_cry_internal(
  11175. conn,
  11176. "ZLIB inflate error: %i %s",
  11177. ret,
  11178. (conn->websocket_inflate_state.msg
  11179. ? conn->websocket_inflate_state.msg
  11180. : "<no error message>"));
  11181. exit_by_callback = 1;
  11182. break;
  11183. }
  11184. inflate_buf_size_old = inflate_buf_size;
  11185. } while (conn->websocket_inflate_state.avail_out
  11186. == 0);
  11187. inflate_buf_size -=
  11188. conn->websocket_inflate_state.avail_out;
  11189. if (!ws_data_handler(conn,
  11190. mop,
  11191. (char *)inflated,
  11192. inflate_buf_size,
  11193. callback_data)) {
  11194. exit_by_callback = 1;
  11195. }
  11196. mg_free(inflated);
  11197. }
  11198. } else
  11199. #endif
  11200. if (!ws_data_handler(conn,
  11201. mop,
  11202. (char *)data,
  11203. (size_t)data_len,
  11204. callback_data)) {
  11205. exit_by_callback = 1;
  11206. }
  11207. }
  11208. }
  11209. /* It a buffer has been allocated, free it again */
  11210. if (data != mem) {
  11211. mg_free(data);
  11212. }
  11213. if (exit_by_callback) {
  11214. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11215. conn->request_info.remote_addr,
  11216. conn->request_info.remote_port);
  11217. break;
  11218. }
  11219. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11220. /* Opcode == 8, connection close */
  11221. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11222. conn->request_info.remote_addr,
  11223. conn->request_info.remote_port);
  11224. break;
  11225. }
  11226. /* Not breaking the loop, process next websocket frame. */
  11227. } else {
  11228. /* Read from the socket into the next available location in the
  11229. * message queue. */
  11230. n = pull_inner(NULL,
  11231. conn,
  11232. conn->buf + conn->data_len,
  11233. conn->buf_size - conn->data_len,
  11234. timeout);
  11235. if (n <= -2) {
  11236. /* Error, no bytes read */
  11237. DEBUG_TRACE("PULL from %s:%u failed",
  11238. conn->request_info.remote_addr,
  11239. conn->request_info.remote_port);
  11240. break;
  11241. }
  11242. if (n > 0) {
  11243. conn->data_len += n;
  11244. /* Reset open PING count */
  11245. ping_count = 0;
  11246. } else {
  11247. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11248. && (!conn->must_close)) {
  11249. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11250. /* Stop sending PING */
  11251. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11252. "- closing connection",
  11253. ping_count,
  11254. conn->request_info.remote_addr,
  11255. conn->request_info.remote_port);
  11256. break;
  11257. }
  11258. if (enable_ping_pong) {
  11259. /* Send Websocket PING message */
  11260. DEBUG_TRACE("PING to %s:%u",
  11261. conn->request_info.remote_addr,
  11262. conn->request_info.remote_port);
  11263. ret = mg_websocket_write(conn,
  11264. MG_WEBSOCKET_OPCODE_PING,
  11265. NULL,
  11266. 0);
  11267. if (ret <= 0) {
  11268. /* Error: send failed */
  11269. DEBUG_TRACE("Send PING failed (%i)", ret);
  11270. break;
  11271. }
  11272. ping_count++;
  11273. }
  11274. }
  11275. /* Timeout: should retry */
  11276. /* TODO: get timeout def */
  11277. }
  11278. }
  11279. }
  11280. /* Leave data processing loop */
  11281. mg_set_thread_name("worker");
  11282. conn->in_websocket_handling = 0;
  11283. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11284. conn->request_info.remote_addr,
  11285. conn->request_info.remote_port);
  11286. }
  11287. static int
  11288. mg_websocket_write_exec(struct mg_connection *conn,
  11289. int opcode,
  11290. const char *data,
  11291. size_t dataLen,
  11292. uint32_t masking_key)
  11293. {
  11294. unsigned char header[14];
  11295. size_t headerLen;
  11296. int retval;
  11297. #if defined(GCC_DIAGNOSTIC)
  11298. /* Disable spurious conversion warning for GCC */
  11299. #pragma GCC diagnostic push
  11300. #pragma GCC diagnostic ignored "-Wconversion"
  11301. #endif
  11302. /* Note that POSIX/Winsock's send() is threadsafe
  11303. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11304. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11305. * push(), although that is only a problem if the packet is large or
  11306. * outgoing buffer is full). */
  11307. /* TODO: Check if this lock should be moved to user land.
  11308. * Currently the server sets this lock for websockets, but
  11309. * not for any other connection. It must be set for every
  11310. * conn read/written by more than one thread, no matter if
  11311. * it is a websocket or regular connection. */
  11312. (void)mg_lock_connection(conn);
  11313. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11314. size_t deflated_size;
  11315. Bytef *deflated;
  11316. // Deflate websocket messages over 100kb
  11317. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11318. if (use_deflate) {
  11319. if (!conn->websocket_deflate_initialized) {
  11320. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11321. return 0;
  11322. }
  11323. // Deflating the message
  11324. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11325. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11326. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11327. deflated_size = compressBound((uLong)dataLen);
  11328. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11329. if (deflated == NULL) {
  11330. mg_cry_internal(
  11331. conn,
  11332. "Out of memory: Cannot allocate deflate buffer of %i bytes",
  11333. deflated_size);
  11334. mg_unlock_connection(conn);
  11335. return -1;
  11336. }
  11337. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11338. conn->websocket_deflate_state.next_out = deflated;
  11339. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11340. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11341. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11342. } else
  11343. #endif
  11344. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11345. #if defined(GCC_DIAGNOSTIC)
  11346. #pragma GCC diagnostic pop
  11347. #endif
  11348. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11349. if (dataLen < 126) {
  11350. /* inline 7-bit length field */
  11351. header[1] = (unsigned char)dataLen;
  11352. headerLen = 2;
  11353. } else if (dataLen <= 0xFFFF) {
  11354. /* 16-bit length field */
  11355. uint16_t len = htons((uint16_t)dataLen);
  11356. header[1] = 126;
  11357. memcpy(header + 2, &len, 2);
  11358. headerLen = 4;
  11359. } else {
  11360. /* 64-bit length field */
  11361. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11362. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11363. header[1] = 127;
  11364. memcpy(header + 2, &len1, 4);
  11365. memcpy(header + 6, &len2, 4);
  11366. headerLen = 10;
  11367. }
  11368. if (masking_key) {
  11369. /* add mask */
  11370. header[1] |= 0x80;
  11371. memcpy(header + headerLen, &masking_key, 4);
  11372. headerLen += 4;
  11373. }
  11374. retval = mg_write(conn, header, headerLen);
  11375. if (retval != (int)headerLen) {
  11376. /* Did not send complete header */
  11377. retval = -1;
  11378. } else {
  11379. if (dataLen > 0) {
  11380. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11381. if (use_deflate) {
  11382. retval = mg_write(conn, deflated, dataLen);
  11383. mg_free(deflated);
  11384. } else
  11385. #endif
  11386. retval = mg_write(conn, data, dataLen);
  11387. }
  11388. /* if dataLen == 0, the header length (2) is returned */
  11389. }
  11390. /* TODO: Remove this unlock as well, when lock is removed. */
  11391. mg_unlock_connection(conn);
  11392. return retval;
  11393. }
  11394. int
  11395. mg_websocket_write(struct mg_connection *conn,
  11396. int opcode,
  11397. const char *data,
  11398. size_t dataLen)
  11399. {
  11400. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11401. }
  11402. static void
  11403. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11404. {
  11405. size_t i = 0;
  11406. i = 0;
  11407. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11408. /* Convert in 32 bit words, if data is 4 byte aligned */
  11409. while (i < (in_len - 3)) {
  11410. *(uint32_t *)(void *)(out + i) =
  11411. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11412. i += 4;
  11413. }
  11414. }
  11415. if (i != in_len) {
  11416. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11417. while (i < in_len) {
  11418. *(uint8_t *)(void *)(out + i) =
  11419. *(uint8_t *)(void *)(in + i)
  11420. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11421. i++;
  11422. }
  11423. }
  11424. }
  11425. int
  11426. mg_websocket_client_write(struct mg_connection *conn,
  11427. int opcode,
  11428. const char *data,
  11429. size_t dataLen)
  11430. {
  11431. int retval = -1;
  11432. char *masked_data =
  11433. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11434. uint32_t masking_key = 0;
  11435. if (masked_data == NULL) {
  11436. /* Return -1 in an error case */
  11437. mg_cry_internal(conn,
  11438. "%s",
  11439. "Cannot allocate buffer for masked websocket response: "
  11440. "Out of memory");
  11441. return -1;
  11442. }
  11443. do {
  11444. /* Get a masking key - but not 0 */
  11445. masking_key = (uint32_t)get_random();
  11446. } while (masking_key == 0);
  11447. mask_data(data, dataLen, masking_key, masked_data);
  11448. retval = mg_websocket_write_exec(
  11449. conn, opcode, masked_data, dataLen, masking_key);
  11450. mg_free(masked_data);
  11451. return retval;
  11452. }
  11453. static void
  11454. handle_websocket_request(struct mg_connection *conn,
  11455. const char *path,
  11456. int is_callback_resource,
  11457. struct mg_websocket_subprotocols *subprotocols,
  11458. mg_websocket_connect_handler ws_connect_handler,
  11459. mg_websocket_ready_handler ws_ready_handler,
  11460. mg_websocket_data_handler ws_data_handler,
  11461. mg_websocket_close_handler ws_close_handler,
  11462. void *cbData)
  11463. {
  11464. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11465. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11466. ptrdiff_t lua_websock = 0;
  11467. #if !defined(USE_LUA)
  11468. (void)path;
  11469. #endif
  11470. /* Step 1: Check websocket protocol version. */
  11471. /* Step 1.1: Check Sec-WebSocket-Key. */
  11472. if (!websock_key) {
  11473. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11474. * requires a Sec-WebSocket-Key header.
  11475. */
  11476. /* It could be the hixie draft version
  11477. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11478. */
  11479. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11480. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11481. char key3[8];
  11482. if ((key1 != NULL) && (key2 != NULL)) {
  11483. /* This version uses 8 byte body data in a GET request */
  11484. conn->content_len = 8;
  11485. if (8 == mg_read(conn, key3, 8)) {
  11486. /* This is the hixie version */
  11487. mg_send_http_error(conn,
  11488. 426,
  11489. "%s",
  11490. "Protocol upgrade to RFC 6455 required");
  11491. return;
  11492. }
  11493. }
  11494. /* This is an unknown version */
  11495. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11496. return;
  11497. }
  11498. /* Step 1.2: Check websocket protocol version. */
  11499. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11500. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11501. /* Reject wrong versions */
  11502. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11503. return;
  11504. }
  11505. /* Step 1.3: Could check for "Host", but we do not really nead this
  11506. * value for anything, so just ignore it. */
  11507. /* Step 2: If a callback is responsible, call it. */
  11508. if (is_callback_resource) {
  11509. /* Step 2.1 check and select subprotocol */
  11510. const char *protocols[64]; // max 64 headers
  11511. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11512. "Sec-WebSocket-Protocol",
  11513. protocols,
  11514. 64);
  11515. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11516. int cnt = 0;
  11517. int idx;
  11518. unsigned long len;
  11519. const char *sep, *curSubProtocol,
  11520. *acceptedWebSocketSubprotocol = NULL;
  11521. /* look for matching subprotocol */
  11522. do {
  11523. const char *protocol = protocols[cnt];
  11524. do {
  11525. sep = strchr(protocol, ',');
  11526. curSubProtocol = protocol;
  11527. len = sep ? (unsigned long)(sep - protocol)
  11528. : (unsigned long)strlen(protocol);
  11529. while (sep && isspace((unsigned char)*++sep))
  11530. ; // ignore leading whitespaces
  11531. protocol = sep;
  11532. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11533. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11534. && (strncmp(curSubProtocol,
  11535. subprotocols->subprotocols[idx],
  11536. len)
  11537. == 0)) {
  11538. acceptedWebSocketSubprotocol =
  11539. subprotocols->subprotocols[idx];
  11540. break;
  11541. }
  11542. }
  11543. } while (sep && !acceptedWebSocketSubprotocol);
  11544. } while (++cnt < nbSubprotocolHeader
  11545. && !acceptedWebSocketSubprotocol);
  11546. conn->request_info.acceptedWebSocketSubprotocol =
  11547. acceptedWebSocketSubprotocol;
  11548. } else if (nbSubprotocolHeader > 0) {
  11549. /* keep legacy behavior */
  11550. const char *protocol = protocols[0];
  11551. /* The protocol is a comma separated list of names. */
  11552. /* The server must only return one value from this list. */
  11553. /* First check if it is a list or just a single value. */
  11554. const char *sep = strrchr(protocol, ',');
  11555. if (sep == NULL) {
  11556. /* Just a single protocol -> accept it. */
  11557. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11558. } else {
  11559. /* Multiple protocols -> accept the last one. */
  11560. /* This is just a quick fix if the client offers multiple
  11561. * protocols. The handler should have a list of accepted
  11562. * protocols on his own
  11563. * and use it to select one protocol among those the client
  11564. * has
  11565. * offered.
  11566. */
  11567. while (isspace((unsigned char)*++sep)) {
  11568. ; /* ignore leading whitespaces */
  11569. }
  11570. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11571. }
  11572. }
  11573. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11574. websocket_deflate_negotiate(conn);
  11575. #endif
  11576. if ((ws_connect_handler != NULL)
  11577. && (ws_connect_handler(conn, cbData) != 0)) {
  11578. /* C callback has returned non-zero, do not proceed with
  11579. * handshake.
  11580. */
  11581. /* Note that C callbacks are no longer called when Lua is
  11582. * responsible, so C can no longer filter callbacks for Lua. */
  11583. return;
  11584. }
  11585. }
  11586. #if defined(USE_LUA)
  11587. /* Step 3: No callback. Check if Lua is responsible. */
  11588. else {
  11589. /* Step 3.1: Check if Lua is responsible. */
  11590. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11591. lua_websock = match_prefix_strlen(
  11592. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11593. }
  11594. if (lua_websock) {
  11595. /* Step 3.2: Lua is responsible: call it. */
  11596. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11597. if (!conn->lua_websocket_state) {
  11598. /* Lua rejected the new client */
  11599. return;
  11600. }
  11601. }
  11602. }
  11603. #endif
  11604. /* Step 4: Check if there is a responsible websocket handler. */
  11605. if (!is_callback_resource && !lua_websock) {
  11606. /* There is no callback, and Lua is not responsible either. */
  11607. /* Reply with a 404 Not Found. We are still at a standard
  11608. * HTTP request here, before the websocket handshake, so
  11609. * we can still send standard HTTP error replies. */
  11610. mg_send_http_error(conn, 404, "%s", "Not found");
  11611. return;
  11612. }
  11613. /* Step 5: The websocket connection has been accepted */
  11614. if (!send_websocket_handshake(conn, websock_key)) {
  11615. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11616. return;
  11617. }
  11618. /* Step 6: Call the ready handler */
  11619. if (is_callback_resource) {
  11620. if (ws_ready_handler != NULL) {
  11621. ws_ready_handler(conn, cbData);
  11622. }
  11623. #if defined(USE_LUA)
  11624. } else if (lua_websock) {
  11625. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11626. /* the ready handler returned false */
  11627. return;
  11628. }
  11629. #endif
  11630. }
  11631. /* Step 7: Enter the read loop */
  11632. if (is_callback_resource) {
  11633. read_websocket(conn, ws_data_handler, cbData);
  11634. #if defined(USE_LUA)
  11635. } else if (lua_websock) {
  11636. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11637. #endif
  11638. }
  11639. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11640. /* Step 8: Close the deflate & inflate buffers */
  11641. if (conn->websocket_deflate_initialized) {
  11642. deflateEnd(&conn->websocket_deflate_state);
  11643. inflateEnd(&conn->websocket_inflate_state);
  11644. }
  11645. #endif
  11646. /* Step 9: Call the close handler */
  11647. if (ws_close_handler) {
  11648. ws_close_handler(conn, cbData);
  11649. }
  11650. }
  11651. #endif /* !USE_WEBSOCKET */
  11652. /* Is upgrade request:
  11653. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11654. * 1 = upgrade to websocket
  11655. * 2 = upgrade to HTTP/2
  11656. * -1 = upgrade to unknown protocol
  11657. */
  11658. static int
  11659. should_switch_to_protocol(const struct mg_connection *conn)
  11660. {
  11661. const char *upgrade, *connection;
  11662. /* A websocket protocoll has the following HTTP headers:
  11663. *
  11664. * Connection: Upgrade
  11665. * Upgrade: Websocket
  11666. */
  11667. connection = mg_get_header(conn, "Connection");
  11668. if (connection == NULL) {
  11669. return PROTOCOL_TYPE_HTTP1;
  11670. }
  11671. if (!mg_strcasestr(connection, "upgrade")) {
  11672. return PROTOCOL_TYPE_HTTP1;
  11673. }
  11674. upgrade = mg_get_header(conn, "Upgrade");
  11675. if (upgrade == NULL) {
  11676. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11677. return -1;
  11678. }
  11679. /* Upgrade to ... */
  11680. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11681. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11682. * "Sec-WebSocket-Version" are also required.
  11683. * Don't check them here, since even an unsupported websocket protocol
  11684. * request still IS a websocket request (in contrast to a standard HTTP
  11685. * request). It will fail later in handle_websocket_request.
  11686. */
  11687. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11688. }
  11689. if (0 != mg_strcasestr(upgrade, "h2")) {
  11690. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11691. }
  11692. /* Upgrade to another protocol */
  11693. return -1;
  11694. }
  11695. static int
  11696. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11697. {
  11698. int n;
  11699. unsigned int a, b, c, d, slash;
  11700. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11701. slash = 32;
  11702. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11703. n = 0;
  11704. }
  11705. }
  11706. if ((n > 0) && ((size_t)n == vec->len)) {
  11707. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11708. /* IPv4 format */
  11709. if (sa->sa.sa_family == AF_INET) {
  11710. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11711. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11712. | ((uint32_t)c << 8) | (uint32_t)d;
  11713. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11714. return (ip & mask) == net;
  11715. }
  11716. return 0;
  11717. }
  11718. }
  11719. #if defined(USE_IPV6)
  11720. else {
  11721. char ad[50];
  11722. const char *p;
  11723. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11724. slash = 128;
  11725. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11726. n = 0;
  11727. }
  11728. }
  11729. if ((n <= 0) && no_strict) {
  11730. /* no square brackets? */
  11731. p = strchr(vec->ptr, '/');
  11732. if (p && (p < (vec->ptr + vec->len))) {
  11733. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11734. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11735. n += (int)(p - vec->ptr);
  11736. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11737. } else {
  11738. n = 0;
  11739. }
  11740. } else if (vec->len < sizeof(ad)) {
  11741. n = (int)vec->len;
  11742. slash = 128;
  11743. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11744. }
  11745. }
  11746. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11747. p = ad;
  11748. c = 0;
  11749. /* zone indexes are unsupported, at least two colons are needed */
  11750. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11751. if (*(p++) == ':') {
  11752. c++;
  11753. }
  11754. }
  11755. if ((*p == '\0') && (c >= 2)) {
  11756. struct sockaddr_in6 sin6;
  11757. unsigned int i;
  11758. /* for strict validation, an actual IPv6 argument is needed */
  11759. if (sa->sa.sa_family != AF_INET6) {
  11760. return 0;
  11761. }
  11762. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11763. /* IPv6 format */
  11764. for (i = 0; i < 16; i++) {
  11765. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11766. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11767. uint8_t mask = 0;
  11768. if (8 * i + 8 < slash) {
  11769. mask = 0xFFu;
  11770. } else if (8 * i < slash) {
  11771. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11772. }
  11773. if ((ip & mask) != net) {
  11774. return 0;
  11775. }
  11776. }
  11777. return 1;
  11778. }
  11779. }
  11780. }
  11781. }
  11782. #else
  11783. (void)no_strict;
  11784. #endif
  11785. /* malformed */
  11786. return -1;
  11787. }
  11788. static int
  11789. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11790. {
  11791. int throttle = 0;
  11792. struct vec vec, val;
  11793. char mult;
  11794. double v;
  11795. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11796. mult = ',';
  11797. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11798. || (v < 0)
  11799. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11800. && (mult != ','))) {
  11801. continue;
  11802. }
  11803. v *= (lowercase(&mult) == 'k')
  11804. ? 1024
  11805. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11806. if (vec.len == 1 && vec.ptr[0] == '*') {
  11807. throttle = (int)v;
  11808. } else {
  11809. int matched = parse_match_net(&vec, rsa, 0);
  11810. if (matched >= 0) {
  11811. /* a valid IP subnet */
  11812. if (matched) {
  11813. throttle = (int)v;
  11814. }
  11815. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11816. throttle = (int)v;
  11817. }
  11818. }
  11819. }
  11820. return throttle;
  11821. }
  11822. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11823. #include "handle_form.inl"
  11824. static int
  11825. get_first_ssl_listener_index(const struct mg_context *ctx)
  11826. {
  11827. unsigned int i;
  11828. int idx = -1;
  11829. if (ctx) {
  11830. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11831. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11832. }
  11833. }
  11834. return idx;
  11835. }
  11836. /* Return host (without port) */
  11837. static void
  11838. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11839. {
  11840. const char *host_header =
  11841. get_header(ri->http_headers, ri->num_headers, "Host");
  11842. host->ptr = NULL;
  11843. host->len = 0;
  11844. if (host_header != NULL) {
  11845. char *pos;
  11846. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11847. * is found. */
  11848. if (*host_header == '[') {
  11849. pos = strchr(host_header, ']');
  11850. if (!pos) {
  11851. /* Malformed hostname starts with '[', but no ']' found */
  11852. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11853. return;
  11854. }
  11855. /* terminate after ']' */
  11856. host->ptr = host_header;
  11857. host->len = (size_t)(pos + 1 - host_header);
  11858. } else {
  11859. /* Otherwise, a ':' separates hostname and port number */
  11860. pos = strchr(host_header, ':');
  11861. if (pos != NULL) {
  11862. host->len = (size_t)(pos - host_header);
  11863. } else {
  11864. host->len = strlen(host_header);
  11865. }
  11866. host->ptr = host_header;
  11867. }
  11868. }
  11869. }
  11870. static int
  11871. switch_domain_context(struct mg_connection *conn)
  11872. {
  11873. struct vec host;
  11874. get_host_from_request_info(&host, &conn->request_info);
  11875. if (host.ptr) {
  11876. if (conn->ssl) {
  11877. /* This is a HTTPS connection, maybe we have a hostname
  11878. * from SNI (set in ssl_servername_callback). */
  11879. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11880. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11881. /* We are not using the default domain */
  11882. if ((strlen(sslhost) != host.len)
  11883. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11884. /* Mismatch between SNI domain and HTTP domain */
  11885. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11886. sslhost,
  11887. (int)host.len,
  11888. host.ptr);
  11889. return 0;
  11890. }
  11891. }
  11892. } else {
  11893. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11894. while (dom) {
  11895. if ((strlen(dom->config[AUTHENTICATION_DOMAIN]) == host.len)
  11896. && !mg_strncasecmp(host.ptr,
  11897. dom->config[AUTHENTICATION_DOMAIN],
  11898. host.len)) {
  11899. /* Found matching domain */
  11900. DEBUG_TRACE("HTTP domain %s found",
  11901. dom->config[AUTHENTICATION_DOMAIN]);
  11902. /* TODO: Check if this is a HTTP or HTTPS domain */
  11903. conn->dom_ctx = dom;
  11904. break;
  11905. }
  11906. mg_lock_context(conn->phys_ctx);
  11907. dom = dom->next;
  11908. mg_unlock_context(conn->phys_ctx);
  11909. }
  11910. }
  11911. } else {
  11912. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11913. return 1;
  11914. }
  11915. DEBUG_TRACE("HTTP%s Host: %.*s",
  11916. conn->ssl ? "S" : "",
  11917. (int)host.len,
  11918. host.ptr);
  11919. return 1;
  11920. }
  11921. static int mg_construct_local_link(const struct mg_connection *conn,
  11922. char *buf,
  11923. size_t buflen,
  11924. const char *define_proto,
  11925. int define_port,
  11926. const char *define_uri);
  11927. static void
  11928. redirect_to_https_port(struct mg_connection *conn, int port)
  11929. {
  11930. char target_url[MG_BUF_LEN];
  11931. int truncated = 0;
  11932. const char *expect_proto =
  11933. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11934. /* Use "308 Permanent Redirect" */
  11935. int redirect_code = 308;
  11936. /* In any case, close the current connection */
  11937. conn->must_close = 1;
  11938. /* Send host, port, uri and (if it exists) ?query_string */
  11939. if (mg_construct_local_link(
  11940. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11941. < 0) {
  11942. truncated = 1;
  11943. } else if (conn->request_info.query_string != NULL) {
  11944. size_t slen1 = strlen(target_url);
  11945. size_t slen2 = strlen(conn->request_info.query_string);
  11946. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11947. target_url[slen1] = '?';
  11948. memcpy(target_url + slen1 + 1,
  11949. conn->request_info.query_string,
  11950. slen2);
  11951. target_url[slen1 + slen2 + 1] = 0;
  11952. } else {
  11953. truncated = 1;
  11954. }
  11955. }
  11956. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11957. * is used as buffer size) */
  11958. if (truncated) {
  11959. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11960. return;
  11961. }
  11962. /* Use redirect helper function */
  11963. mg_send_http_redirect(conn, target_url, redirect_code);
  11964. }
  11965. static void
  11966. mg_set_handler_type(struct mg_context *phys_ctx,
  11967. struct mg_domain_context *dom_ctx,
  11968. const char *uri,
  11969. int handler_type,
  11970. int is_delete_request,
  11971. mg_request_handler handler,
  11972. struct mg_websocket_subprotocols *subprotocols,
  11973. mg_websocket_connect_handler connect_handler,
  11974. mg_websocket_ready_handler ready_handler,
  11975. mg_websocket_data_handler data_handler,
  11976. mg_websocket_close_handler close_handler,
  11977. mg_authorization_handler auth_handler,
  11978. void *cbdata)
  11979. {
  11980. struct mg_handler_info *tmp_rh, **lastref;
  11981. size_t urilen = strlen(uri);
  11982. if (handler_type == WEBSOCKET_HANDLER) {
  11983. DEBUG_ASSERT(handler == NULL);
  11984. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11985. || ready_handler != NULL || data_handler != NULL
  11986. || close_handler != NULL);
  11987. DEBUG_ASSERT(auth_handler == NULL);
  11988. if (handler != NULL) {
  11989. return;
  11990. }
  11991. if (!is_delete_request && (connect_handler == NULL)
  11992. && (ready_handler == NULL) && (data_handler == NULL)
  11993. && (close_handler == NULL)) {
  11994. return;
  11995. }
  11996. if (auth_handler != NULL) {
  11997. return;
  11998. }
  11999. } else if (handler_type == REQUEST_HANDLER) {
  12000. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12001. && data_handler == NULL && close_handler == NULL);
  12002. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12003. DEBUG_ASSERT(auth_handler == NULL);
  12004. if ((connect_handler != NULL) || (ready_handler != NULL)
  12005. || (data_handler != NULL) || (close_handler != NULL)) {
  12006. return;
  12007. }
  12008. if (!is_delete_request && (handler == NULL)) {
  12009. return;
  12010. }
  12011. if (auth_handler != NULL) {
  12012. return;
  12013. }
  12014. } else { /* AUTH_HANDLER */
  12015. DEBUG_ASSERT(handler == NULL);
  12016. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12017. && data_handler == NULL && close_handler == NULL);
  12018. DEBUG_ASSERT(auth_handler != NULL);
  12019. if (handler != NULL) {
  12020. return;
  12021. }
  12022. if ((connect_handler != NULL) || (ready_handler != NULL)
  12023. || (data_handler != NULL) || (close_handler != NULL)) {
  12024. return;
  12025. }
  12026. if (!is_delete_request && (auth_handler == NULL)) {
  12027. return;
  12028. }
  12029. }
  12030. if (!phys_ctx || !dom_ctx) {
  12031. return;
  12032. }
  12033. mg_lock_context(phys_ctx);
  12034. /* first try to find an existing handler */
  12035. do {
  12036. lastref = &(dom_ctx->handlers);
  12037. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12038. tmp_rh = tmp_rh->next) {
  12039. if (tmp_rh->handler_type == handler_type
  12040. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12041. if (!is_delete_request) {
  12042. /* update existing handler */
  12043. if (handler_type == REQUEST_HANDLER) {
  12044. /* Wait for end of use before updating */
  12045. if (tmp_rh->refcount) {
  12046. mg_unlock_context(phys_ctx);
  12047. mg_sleep(1);
  12048. mg_lock_context(phys_ctx);
  12049. /* tmp_rh might have been freed, search again. */
  12050. break;
  12051. }
  12052. /* Ok, the handler is no more use -> Update it */
  12053. tmp_rh->handler = handler;
  12054. } else if (handler_type == WEBSOCKET_HANDLER) {
  12055. tmp_rh->subprotocols = subprotocols;
  12056. tmp_rh->connect_handler = connect_handler;
  12057. tmp_rh->ready_handler = ready_handler;
  12058. tmp_rh->data_handler = data_handler;
  12059. tmp_rh->close_handler = close_handler;
  12060. } else { /* AUTH_HANDLER */
  12061. tmp_rh->auth_handler = auth_handler;
  12062. }
  12063. tmp_rh->cbdata = cbdata;
  12064. } else {
  12065. /* remove existing handler */
  12066. if (handler_type == REQUEST_HANDLER) {
  12067. /* Wait for end of use before removing */
  12068. if (tmp_rh->refcount) {
  12069. tmp_rh->removing = 1;
  12070. mg_unlock_context(phys_ctx);
  12071. mg_sleep(1);
  12072. mg_lock_context(phys_ctx);
  12073. /* tmp_rh might have been freed, search again. */
  12074. break;
  12075. }
  12076. /* Ok, the handler is no more used */
  12077. }
  12078. *lastref = tmp_rh->next;
  12079. mg_free(tmp_rh->uri);
  12080. mg_free(tmp_rh);
  12081. }
  12082. mg_unlock_context(phys_ctx);
  12083. return;
  12084. }
  12085. lastref = &(tmp_rh->next);
  12086. }
  12087. } while (tmp_rh != NULL);
  12088. if (is_delete_request) {
  12089. /* no handler to set, this was a remove request to a non-existing
  12090. * handler */
  12091. mg_unlock_context(phys_ctx);
  12092. return;
  12093. }
  12094. tmp_rh =
  12095. (struct mg_handler_info *)mg_calloc_ctx(1,
  12096. sizeof(struct mg_handler_info),
  12097. phys_ctx);
  12098. if (tmp_rh == NULL) {
  12099. mg_unlock_context(phys_ctx);
  12100. mg_cry_ctx_internal(phys_ctx,
  12101. "%s",
  12102. "Cannot create new request handler struct, OOM");
  12103. return;
  12104. }
  12105. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12106. if (!tmp_rh->uri) {
  12107. mg_unlock_context(phys_ctx);
  12108. mg_free(tmp_rh);
  12109. mg_cry_ctx_internal(phys_ctx,
  12110. "%s",
  12111. "Cannot create new request handler struct, OOM");
  12112. return;
  12113. }
  12114. tmp_rh->uri_len = urilen;
  12115. if (handler_type == REQUEST_HANDLER) {
  12116. tmp_rh->refcount = 0;
  12117. tmp_rh->removing = 0;
  12118. tmp_rh->handler = handler;
  12119. } else if (handler_type == WEBSOCKET_HANDLER) {
  12120. tmp_rh->subprotocols = subprotocols;
  12121. tmp_rh->connect_handler = connect_handler;
  12122. tmp_rh->ready_handler = ready_handler;
  12123. tmp_rh->data_handler = data_handler;
  12124. tmp_rh->close_handler = close_handler;
  12125. } else { /* AUTH_HANDLER */
  12126. tmp_rh->auth_handler = auth_handler;
  12127. }
  12128. tmp_rh->cbdata = cbdata;
  12129. tmp_rh->handler_type = handler_type;
  12130. tmp_rh->next = NULL;
  12131. *lastref = tmp_rh;
  12132. mg_unlock_context(phys_ctx);
  12133. }
  12134. void
  12135. mg_set_request_handler(struct mg_context *ctx,
  12136. const char *uri,
  12137. mg_request_handler handler,
  12138. void *cbdata)
  12139. {
  12140. mg_set_handler_type(ctx,
  12141. &(ctx->dd),
  12142. uri,
  12143. REQUEST_HANDLER,
  12144. handler == NULL,
  12145. handler,
  12146. NULL,
  12147. NULL,
  12148. NULL,
  12149. NULL,
  12150. NULL,
  12151. NULL,
  12152. cbdata);
  12153. }
  12154. void
  12155. mg_set_websocket_handler(struct mg_context *ctx,
  12156. const char *uri,
  12157. mg_websocket_connect_handler connect_handler,
  12158. mg_websocket_ready_handler ready_handler,
  12159. mg_websocket_data_handler data_handler,
  12160. mg_websocket_close_handler close_handler,
  12161. void *cbdata)
  12162. {
  12163. mg_set_websocket_handler_with_subprotocols(ctx,
  12164. uri,
  12165. NULL,
  12166. connect_handler,
  12167. ready_handler,
  12168. data_handler,
  12169. close_handler,
  12170. cbdata);
  12171. }
  12172. void
  12173. mg_set_websocket_handler_with_subprotocols(
  12174. struct mg_context *ctx,
  12175. const char *uri,
  12176. struct mg_websocket_subprotocols *subprotocols,
  12177. mg_websocket_connect_handler connect_handler,
  12178. mg_websocket_ready_handler ready_handler,
  12179. mg_websocket_data_handler data_handler,
  12180. mg_websocket_close_handler close_handler,
  12181. void *cbdata)
  12182. {
  12183. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12184. && (data_handler == NULL)
  12185. && (close_handler == NULL);
  12186. mg_set_handler_type(ctx,
  12187. &(ctx->dd),
  12188. uri,
  12189. WEBSOCKET_HANDLER,
  12190. is_delete_request,
  12191. NULL,
  12192. subprotocols,
  12193. connect_handler,
  12194. ready_handler,
  12195. data_handler,
  12196. close_handler,
  12197. NULL,
  12198. cbdata);
  12199. }
  12200. void
  12201. mg_set_auth_handler(struct mg_context *ctx,
  12202. const char *uri,
  12203. mg_authorization_handler handler,
  12204. void *cbdata)
  12205. {
  12206. mg_set_handler_type(ctx,
  12207. &(ctx->dd),
  12208. uri,
  12209. AUTH_HANDLER,
  12210. handler == NULL,
  12211. NULL,
  12212. NULL,
  12213. NULL,
  12214. NULL,
  12215. NULL,
  12216. NULL,
  12217. handler,
  12218. cbdata);
  12219. }
  12220. static int
  12221. get_request_handler(struct mg_connection *conn,
  12222. int handler_type,
  12223. mg_request_handler *handler,
  12224. struct mg_websocket_subprotocols **subprotocols,
  12225. mg_websocket_connect_handler *connect_handler,
  12226. mg_websocket_ready_handler *ready_handler,
  12227. mg_websocket_data_handler *data_handler,
  12228. mg_websocket_close_handler *close_handler,
  12229. mg_authorization_handler *auth_handler,
  12230. void **cbdata,
  12231. struct mg_handler_info **handler_info)
  12232. {
  12233. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12234. if (request_info) {
  12235. const char *uri = request_info->local_uri;
  12236. size_t urilen = strlen(uri);
  12237. struct mg_handler_info *tmp_rh;
  12238. int step, matched;
  12239. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12240. return 0;
  12241. }
  12242. mg_lock_context(conn->phys_ctx);
  12243. for (step = 0; step < 3; step++) {
  12244. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12245. tmp_rh = tmp_rh->next) {
  12246. if (tmp_rh->handler_type != handler_type) {
  12247. continue;
  12248. }
  12249. if (step == 0) {
  12250. /* first try for an exact match */
  12251. matched = (tmp_rh->uri_len == urilen)
  12252. && (strcmp(tmp_rh->uri, uri) == 0);
  12253. } else if (step == 1) {
  12254. /* next try for a partial match, we will accept
  12255. uri/something */
  12256. matched =
  12257. (tmp_rh->uri_len < urilen)
  12258. && (uri[tmp_rh->uri_len] == '/')
  12259. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12260. } else {
  12261. /* finally try for pattern match */
  12262. matched =
  12263. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12264. }
  12265. if (matched) {
  12266. if (handler_type == WEBSOCKET_HANDLER) {
  12267. *subprotocols = tmp_rh->subprotocols;
  12268. *connect_handler = tmp_rh->connect_handler;
  12269. *ready_handler = tmp_rh->ready_handler;
  12270. *data_handler = tmp_rh->data_handler;
  12271. *close_handler = tmp_rh->close_handler;
  12272. } else if (handler_type == REQUEST_HANDLER) {
  12273. if (tmp_rh->removing) {
  12274. /* Treat as none found */
  12275. step = 2;
  12276. break;
  12277. }
  12278. *handler = tmp_rh->handler;
  12279. /* Acquire handler and give it back */
  12280. tmp_rh->refcount++;
  12281. *handler_info = tmp_rh;
  12282. } else { /* AUTH_HANDLER */
  12283. *auth_handler = tmp_rh->auth_handler;
  12284. }
  12285. *cbdata = tmp_rh->cbdata;
  12286. mg_unlock_context(conn->phys_ctx);
  12287. return 1;
  12288. }
  12289. }
  12290. }
  12291. mg_unlock_context(conn->phys_ctx);
  12292. }
  12293. return 0; /* none found */
  12294. }
  12295. /* Check if the script file is in a path, allowed for script files.
  12296. * This can be used if uploading files is possible not only for the server
  12297. * admin, and the upload mechanism does not check the file extension.
  12298. */
  12299. static int
  12300. is_in_script_path(const struct mg_connection *conn, const char *path)
  12301. {
  12302. /* TODO (Feature): Add config value for allowed script path.
  12303. * Default: All allowed. */
  12304. (void)conn;
  12305. (void)path;
  12306. return 1;
  12307. }
  12308. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12309. static int
  12310. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12311. int bits,
  12312. char *data,
  12313. size_t len,
  12314. void *cbdata)
  12315. {
  12316. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12317. if (pcallbacks->websocket_data) {
  12318. return pcallbacks->websocket_data(conn, bits, data, len);
  12319. }
  12320. /* No handler set - assume "OK" */
  12321. return 1;
  12322. }
  12323. static void
  12324. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12325. void *cbdata)
  12326. {
  12327. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12328. if (pcallbacks->connection_close) {
  12329. pcallbacks->connection_close(conn);
  12330. }
  12331. }
  12332. #endif
  12333. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12334. */
  12335. static void
  12336. release_handler_ref(struct mg_connection *conn,
  12337. struct mg_handler_info *handler_info)
  12338. {
  12339. if (handler_info != NULL) {
  12340. /* Use context lock for ref counter */
  12341. mg_lock_context(conn->phys_ctx);
  12342. handler_info->refcount--;
  12343. mg_unlock_context(conn->phys_ctx);
  12344. }
  12345. }
  12346. /* This is the heart of the Civetweb's logic.
  12347. * This function is called when the request is read, parsed and validated,
  12348. * and Civetweb must decide what action to take: serve a file, or
  12349. * a directory, or call embedded function, etcetera. */
  12350. static void
  12351. handle_request(struct mg_connection *conn)
  12352. {
  12353. struct mg_request_info *ri = &conn->request_info;
  12354. char path[PATH_MAX];
  12355. int uri_len, ssl_index;
  12356. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12357. is_put_or_delete_request = 0, is_callback_resource = 0,
  12358. is_template_text_file = 0;
  12359. int i;
  12360. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12361. mg_request_handler callback_handler = NULL;
  12362. struct mg_handler_info *handler_info = NULL;
  12363. struct mg_websocket_subprotocols *subprotocols;
  12364. mg_websocket_connect_handler ws_connect_handler = NULL;
  12365. mg_websocket_ready_handler ws_ready_handler = NULL;
  12366. mg_websocket_data_handler ws_data_handler = NULL;
  12367. mg_websocket_close_handler ws_close_handler = NULL;
  12368. void *callback_data = NULL;
  12369. mg_authorization_handler auth_handler = NULL;
  12370. void *auth_callback_data = NULL;
  12371. int handler_type;
  12372. time_t curtime = time(NULL);
  12373. char date[64];
  12374. path[0] = 0;
  12375. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12376. conn->request_state = 0;
  12377. /* 1. get the request url */
  12378. /* 1.1. split into url and query string */
  12379. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12380. != NULL) {
  12381. *((char *)conn->request_info.query_string++) = '\0';
  12382. }
  12383. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12384. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12385. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12386. if (ssl_index >= 0) {
  12387. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12388. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12389. redirect_to_https_port(conn, port);
  12390. } else {
  12391. /* A http to https forward port has been specified,
  12392. * but no https port to forward to. */
  12393. mg_send_http_error(conn,
  12394. 503,
  12395. "%s",
  12396. "Error: SSL forward not configured properly");
  12397. mg_cry_internal(conn,
  12398. "%s",
  12399. "Can not redirect to SSL, no SSL port available");
  12400. }
  12401. return;
  12402. }
  12403. uri_len = (int)strlen(ri->local_uri);
  12404. /* 1.3. decode url (if config says so) */
  12405. if (should_decode_url(conn)) {
  12406. mg_url_decode(
  12407. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12408. if (conn->request_info.query_string) {
  12409. url_decode_in_place((char *)conn->request_info.query_string);
  12410. }
  12411. }
  12412. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12413. * not possible */
  12414. remove_dot_segments((char *)ri->local_uri);
  12415. /* step 1. completed, the url is known now */
  12416. uri_len = (int)strlen(ri->local_uri);
  12417. DEBUG_TRACE("URL: %s", ri->local_uri);
  12418. /* 2. if this ip has limited speed, set it for this connection */
  12419. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12420. &conn->client.rsa,
  12421. ri->local_uri);
  12422. /* 3. call a "handle everything" callback, if registered */
  12423. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12424. /* Note that since V1.7 the "begin_request" function is called
  12425. * before an authorization check. If an authorization check is
  12426. * required, use a request_handler instead. */
  12427. i = conn->phys_ctx->callbacks.begin_request(conn);
  12428. if (i > 0) {
  12429. /* callback already processed the request. Store the
  12430. return value as a status code for the access log. */
  12431. conn->status_code = i;
  12432. if (!conn->must_close) {
  12433. discard_unread_request_data(conn);
  12434. }
  12435. return;
  12436. } else if (i == 0) {
  12437. /* civetweb should process the request */
  12438. } else {
  12439. /* unspecified - may change with the next version */
  12440. return;
  12441. }
  12442. }
  12443. /* request not yet handled by a handler or redirect, so the request
  12444. * is processed here */
  12445. /* 4. Check for CORS preflight requests and handle them (if configured).
  12446. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12447. */
  12448. if (!strcmp(ri->request_method, "OPTIONS")) {
  12449. /* Send a response to CORS preflights only if
  12450. * access_control_allow_methods is not NULL and not an empty string.
  12451. * In this case, scripts can still handle CORS. */
  12452. const char *cors_meth_cfg =
  12453. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12454. const char *cors_orig_cfg =
  12455. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12456. const char *cors_origin =
  12457. get_header(ri->http_headers, ri->num_headers, "Origin");
  12458. const char *cors_acrm = get_header(ri->http_headers,
  12459. ri->num_headers,
  12460. "Access-Control-Request-Method");
  12461. /* Todo: check if cors_origin is in cors_orig_cfg.
  12462. * Or, let the client check this. */
  12463. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12464. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12465. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12466. /* This is a valid CORS preflight, and the server is configured
  12467. * to handle it automatically. */
  12468. const char *cors_acrh =
  12469. get_header(ri->http_headers,
  12470. ri->num_headers,
  12471. "Access-Control-Request-Headers");
  12472. gmt_time_string(date, sizeof(date), &curtime);
  12473. mg_printf(conn,
  12474. "HTTP/1.1 200 OK\r\n"
  12475. "Date: %s\r\n"
  12476. "Access-Control-Allow-Origin: %s\r\n"
  12477. "Access-Control-Allow-Methods: %s\r\n"
  12478. "Content-Length: 0\r\n"
  12479. "Connection: %s\r\n",
  12480. date,
  12481. cors_orig_cfg,
  12482. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12483. suggest_connection_header(conn));
  12484. if (cors_acrh != NULL) {
  12485. /* CORS request is asking for additional headers */
  12486. const char *cors_hdr_cfg =
  12487. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12488. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12489. /* Allow only if access_control_allow_headers is
  12490. * not NULL and not an empty string. If this
  12491. * configuration is set to *, allow everything.
  12492. * Otherwise this configuration must be a list
  12493. * of allowed HTTP header names. */
  12494. mg_printf(conn,
  12495. "Access-Control-Allow-Headers: %s\r\n",
  12496. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12497. : cors_hdr_cfg));
  12498. }
  12499. }
  12500. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12501. mg_printf(conn, "\r\n");
  12502. return;
  12503. }
  12504. }
  12505. /* 5. interpret the url to find out how the request must be handled
  12506. */
  12507. /* 5.1. first test, if the request targets the regular http(s)://
  12508. * protocol namespace or the websocket ws(s):// protocol namespace.
  12509. */
  12510. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12511. #if defined(USE_WEBSOCKET)
  12512. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12513. #else
  12514. handler_type = REQUEST_HANDLER;
  12515. #endif /* defined(USE_WEBSOCKET) */
  12516. if (is_websocket_request) {
  12517. HTTP1_only;
  12518. }
  12519. /* 5.2. check if the request will be handled by a callback */
  12520. if (get_request_handler(conn,
  12521. handler_type,
  12522. &callback_handler,
  12523. &subprotocols,
  12524. &ws_connect_handler,
  12525. &ws_ready_handler,
  12526. &ws_data_handler,
  12527. &ws_close_handler,
  12528. NULL,
  12529. &callback_data,
  12530. &handler_info)) {
  12531. /* 5.2.1. A callback will handle this request. All requests
  12532. * handled by a callback have to be considered as requests
  12533. * to a script resource. */
  12534. is_callback_resource = 1;
  12535. is_script_resource = 1;
  12536. is_put_or_delete_request = is_put_or_delete_method(conn);
  12537. } else {
  12538. no_callback_resource:
  12539. /* 5.2.2. No callback is responsible for this request. The URI
  12540. * addresses a file based resource (static content or Lua/cgi
  12541. * scripts in the file system). */
  12542. is_callback_resource = 0;
  12543. interpret_uri(conn,
  12544. path,
  12545. sizeof(path),
  12546. &file.stat,
  12547. &is_found,
  12548. &is_script_resource,
  12549. &is_websocket_request,
  12550. &is_put_or_delete_request,
  12551. &is_template_text_file);
  12552. }
  12553. /* 6. authorization check */
  12554. /* 6.1. a custom authorization handler is installed */
  12555. if (get_request_handler(conn,
  12556. AUTH_HANDLER,
  12557. NULL,
  12558. NULL,
  12559. NULL,
  12560. NULL,
  12561. NULL,
  12562. NULL,
  12563. &auth_handler,
  12564. &auth_callback_data,
  12565. NULL)) {
  12566. if (!auth_handler(conn, auth_callback_data)) {
  12567. /* Callback handler will not be used anymore. Release it */
  12568. release_handler_ref(conn, handler_info);
  12569. return;
  12570. }
  12571. } else if (is_put_or_delete_request && !is_script_resource
  12572. && !is_callback_resource) {
  12573. HTTP1_only;
  12574. /* 6.2. this request is a PUT/DELETE to a real file */
  12575. /* 6.2.1. thus, the server must have real files */
  12576. #if defined(NO_FILES)
  12577. if (1) {
  12578. #else
  12579. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12580. #endif
  12581. /* This code path will not be called for request handlers */
  12582. DEBUG_ASSERT(handler_info == NULL);
  12583. /* This server does not have any real files, thus the
  12584. * PUT/DELETE methods are not valid. */
  12585. mg_send_http_error(conn,
  12586. 405,
  12587. "%s method not allowed",
  12588. conn->request_info.request_method);
  12589. return;
  12590. }
  12591. #if !defined(NO_FILES)
  12592. /* 6.2.2. Check if put authorization for static files is
  12593. * available.
  12594. */
  12595. if (!is_authorized_for_put(conn)) {
  12596. send_authorization_request(conn, NULL);
  12597. return;
  12598. }
  12599. #endif
  12600. } else {
  12601. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12602. * or it is a PUT or DELETE request to a resource that does not
  12603. * correspond to a file. Check authorization. */
  12604. if (!check_authorization(conn, path)) {
  12605. send_authorization_request(conn, NULL);
  12606. /* Callback handler will not be used anymore. Release it */
  12607. release_handler_ref(conn, handler_info);
  12608. return;
  12609. }
  12610. }
  12611. /* request is authorized or does not need authorization */
  12612. /* 7. check if there are request handlers for this uri */
  12613. if (is_callback_resource) {
  12614. HTTP1_only;
  12615. if (!is_websocket_request) {
  12616. i = callback_handler(conn, callback_data);
  12617. /* Callback handler will not be used anymore. Release it */
  12618. release_handler_ref(conn, handler_info);
  12619. if (i > 0) {
  12620. /* Do nothing, callback has served the request. Store
  12621. * then return value as status code for the log and discard
  12622. * all data from the client not used by the callback. */
  12623. conn->status_code = i;
  12624. if (!conn->must_close) {
  12625. discard_unread_request_data(conn);
  12626. }
  12627. } else {
  12628. /* The handler did NOT handle the request. */
  12629. /* Some proper reactions would be:
  12630. * a) close the connections without sending anything
  12631. * b) send a 404 not found
  12632. * c) try if there is a file matching the URI
  12633. * It would be possible to do a, b or c in the callback
  12634. * implementation, and return 1 - we cannot do anything
  12635. * here, that is not possible in the callback.
  12636. *
  12637. * TODO: What would be the best reaction here?
  12638. * (Note: The reaction may change, if there is a better
  12639. * idea.)
  12640. */
  12641. /* For the moment, use option c: We look for a proper file,
  12642. * but since a file request is not always a script resource,
  12643. * the authorization check might be different. */
  12644. interpret_uri(conn,
  12645. path,
  12646. sizeof(path),
  12647. &file.stat,
  12648. &is_found,
  12649. &is_script_resource,
  12650. &is_websocket_request,
  12651. &is_put_or_delete_request,
  12652. &is_template_text_file);
  12653. callback_handler = NULL;
  12654. /* Here we are at a dead end:
  12655. * According to URI matching, a callback should be
  12656. * responsible for handling the request,
  12657. * we called it, but the callback declared itself
  12658. * not responsible.
  12659. * We use a goto here, to get out of this dead end,
  12660. * and continue with the default handling.
  12661. * A goto here is simpler and better to understand
  12662. * than some curious loop. */
  12663. goto no_callback_resource;
  12664. }
  12665. } else {
  12666. #if defined(USE_WEBSOCKET)
  12667. handle_websocket_request(conn,
  12668. path,
  12669. is_callback_resource,
  12670. subprotocols,
  12671. ws_connect_handler,
  12672. ws_ready_handler,
  12673. ws_data_handler,
  12674. ws_close_handler,
  12675. callback_data);
  12676. #endif
  12677. }
  12678. return;
  12679. }
  12680. /* 8. handle websocket requests */
  12681. #if defined(USE_WEBSOCKET)
  12682. if (is_websocket_request) {
  12683. HTTP1_only;
  12684. if (is_script_resource) {
  12685. if (is_in_script_path(conn, path)) {
  12686. /* Websocket Lua script */
  12687. handle_websocket_request(conn,
  12688. path,
  12689. 0 /* Lua Script */,
  12690. NULL,
  12691. NULL,
  12692. NULL,
  12693. NULL,
  12694. NULL,
  12695. conn->phys_ctx->user_data);
  12696. } else {
  12697. /* Script was in an illegal path */
  12698. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12699. }
  12700. } else {
  12701. mg_send_http_error(conn, 404, "%s", "Not found");
  12702. }
  12703. return;
  12704. } else
  12705. #endif
  12706. #if defined(NO_FILES)
  12707. /* 9a. In case the server uses only callbacks, this uri is
  12708. * unknown.
  12709. * Then, all request handling ends here. */
  12710. mg_send_http_error(conn, 404, "%s", "Not Found");
  12711. #else
  12712. /* 9b. This request is either for a static file or resource handled
  12713. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12714. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12715. mg_send_http_error(conn, 404, "%s", "Not Found");
  12716. return;
  12717. }
  12718. /* 10. Request is handled by a script */
  12719. if (is_script_resource) {
  12720. HTTP1_only;
  12721. handle_file_based_request(conn, path, &file);
  12722. return;
  12723. }
  12724. /* 11. Handle put/delete/mkcol requests */
  12725. if (is_put_or_delete_request) {
  12726. HTTP1_only;
  12727. /* 11.1. PUT method */
  12728. if (!strcmp(ri->request_method, "PUT")) {
  12729. put_file(conn, path);
  12730. return;
  12731. }
  12732. /* 11.2. DELETE method */
  12733. if (!strcmp(ri->request_method, "DELETE")) {
  12734. delete_file(conn, path);
  12735. return;
  12736. }
  12737. /* 11.3. MKCOL method */
  12738. if (!strcmp(ri->request_method, "MKCOL")) {
  12739. mkcol(conn, path);
  12740. return;
  12741. }
  12742. /* 11.4. PATCH method
  12743. * This method is not supported for static resources,
  12744. * only for scripts (Lua, CGI) and callbacks. */
  12745. mg_send_http_error(conn,
  12746. 405,
  12747. "%s method not allowed",
  12748. conn->request_info.request_method);
  12749. return;
  12750. }
  12751. /* 11. File does not exist, or it was configured that it should be
  12752. * hidden */
  12753. if (!is_found || (must_hide_file(conn, path))) {
  12754. mg_send_http_error(conn, 404, "%s", "Not found");
  12755. return;
  12756. }
  12757. /* 12. Directory uris should end with a slash */
  12758. if (file.stat.is_directory && (uri_len > 0)
  12759. && (ri->local_uri[uri_len - 1] != '/')) {
  12760. size_t len = strlen(ri->request_uri);
  12761. char *new_path = mg_malloc_ctx(len + 2, conn->phys_ctx);
  12762. if (!new_path) {
  12763. mg_send_http_error(conn, 500, "out or memory");
  12764. } else {
  12765. memcpy(new_path, ri->request_uri, len);
  12766. new_path[len] = '/';
  12767. new_path[len + 1] = 0;
  12768. mg_send_http_redirect(conn, new_path, 301);
  12769. }
  12770. return;
  12771. }
  12772. /* 13. Handle other methods than GET/HEAD */
  12773. /* 13.1. Handle PROPFIND */
  12774. if (!strcmp(ri->request_method, "PROPFIND")) {
  12775. handle_propfind(conn, path, &file.stat);
  12776. return;
  12777. }
  12778. /* 13.2. Handle OPTIONS for files */
  12779. if (!strcmp(ri->request_method, "OPTIONS")) {
  12780. /* This standard handler is only used for real files.
  12781. * Scripts should support the OPTIONS method themselves, to allow a
  12782. * maximum flexibility.
  12783. * Lua and CGI scripts may fully support CORS this way (including
  12784. * preflights). */
  12785. send_options(conn);
  12786. return;
  12787. }
  12788. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12789. if ((0 != strcmp(ri->request_method, "GET"))
  12790. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12791. mg_send_http_error(conn,
  12792. 405,
  12793. "%s method not allowed",
  12794. conn->request_info.request_method);
  12795. return;
  12796. }
  12797. /* 14. directories */
  12798. if (file.stat.is_directory) {
  12799. /* Substitute files have already been handled above. */
  12800. /* Here we can either generate and send a directory listing,
  12801. * or send an "access denied" error. */
  12802. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12803. "yes")) {
  12804. handle_directory_request(conn, path);
  12805. } else {
  12806. mg_send_http_error(conn,
  12807. 403,
  12808. "%s",
  12809. "Error: Directory listing denied");
  12810. }
  12811. return;
  12812. }
  12813. /* 15. Files with search/replace patterns: LSP and SSI */
  12814. if (is_template_text_file) {
  12815. HTTP1_only;
  12816. handle_file_based_request(conn, path, &file);
  12817. return;
  12818. }
  12819. /* 16. Static file - maybe cached */
  12820. #if !defined(NO_CACHING)
  12821. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12822. /* Send 304 "Not Modified" - this must not send any body data */
  12823. handle_not_modified_static_file_request(conn, &file);
  12824. return;
  12825. }
  12826. #endif /* !NO_CACHING */
  12827. /* 17. Static file - not cached */
  12828. handle_static_file_request(conn, path, &file, NULL, NULL);
  12829. #endif /* !defined(NO_FILES) */
  12830. }
  12831. #if !defined(NO_FILESYSTEMS)
  12832. static void
  12833. handle_file_based_request(struct mg_connection *conn,
  12834. const char *path,
  12835. struct mg_file *file)
  12836. {
  12837. if (!conn || !conn->dom_ctx) {
  12838. return;
  12839. }
  12840. if (0) {
  12841. #if defined(USE_LUA)
  12842. } else if (match_prefix_strlen(
  12843. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS], path)
  12844. > 0) {
  12845. if (is_in_script_path(conn, path)) {
  12846. /* Lua server page: an SSI like page containing mostly plain
  12847. * html code plus some tags with server generated contents. */
  12848. handle_lsp_request(conn, path, file, NULL);
  12849. } else {
  12850. /* Script was in an illegal path */
  12851. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12852. }
  12853. } else if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12854. path)
  12855. > 0) {
  12856. if (is_in_script_path(conn, path)) {
  12857. /* Lua in-server module script: a CGI like script used to
  12858. * generate
  12859. * the
  12860. * entire reply. */
  12861. mg_exec_lua_script(conn, path, NULL);
  12862. } else {
  12863. /* Script was in an illegal path */
  12864. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12865. }
  12866. #endif
  12867. #if defined(USE_DUKTAPE)
  12868. } else if (match_prefix_strlen(
  12869. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS], path)
  12870. > 0) {
  12871. if (is_in_script_path(conn, path)) {
  12872. /* Call duktape to generate the page */
  12873. mg_exec_duktape_script(conn, path);
  12874. } else {
  12875. /* Script was in an illegal path */
  12876. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12877. }
  12878. #endif
  12879. #if !defined(NO_CGI)
  12880. } else if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], path)
  12881. > 0) {
  12882. if (is_in_script_path(conn, path)) {
  12883. /* CGI scripts may support all HTTP methods */
  12884. handle_cgi_request(conn, path);
  12885. } else {
  12886. /* Script was in an illegal path */
  12887. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12888. }
  12889. #endif /* !NO_CGI */
  12890. } else if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  12891. > 0) {
  12892. if (is_in_script_path(conn, path)) {
  12893. handle_ssi_file_request(conn, path, file);
  12894. } else {
  12895. /* Script was in an illegal path */
  12896. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12897. }
  12898. #if !defined(NO_CACHING)
  12899. } else if ((!conn->in_error_handler)
  12900. && is_not_modified(conn, &file->stat)) {
  12901. /* Send 304 "Not Modified" - this must not send any body data */
  12902. handle_not_modified_static_file_request(conn, file);
  12903. #endif /* !NO_CACHING */
  12904. } else {
  12905. handle_static_file_request(conn, path, file, NULL, NULL);
  12906. }
  12907. }
  12908. #endif /* NO_FILESYSTEMS */
  12909. static void
  12910. close_all_listening_sockets(struct mg_context *ctx)
  12911. {
  12912. unsigned int i;
  12913. if (!ctx) {
  12914. return;
  12915. }
  12916. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12917. closesocket(ctx->listening_sockets[i].sock);
  12918. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12919. }
  12920. mg_free(ctx->listening_sockets);
  12921. ctx->listening_sockets = NULL;
  12922. mg_free(ctx->listening_socket_fds);
  12923. ctx->listening_socket_fds = NULL;
  12924. }
  12925. /* Valid listening port specification is: [ip_address:]port[s]
  12926. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12927. * Examples for IPv6: [::]:80, [::1]:80,
  12928. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12929. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12930. * In order to bind to both, IPv4 and IPv6, you can either add
  12931. * both ports using 8080,[::]:8080, or the short form +8080.
  12932. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12933. * one only accepting IPv4 the other only IPv6. +8080 creates
  12934. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12935. * environment, they might work differently, or might not work
  12936. * at all - it must be tested what options work best in the
  12937. * relevant network environment.
  12938. */
  12939. static int
  12940. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12941. {
  12942. unsigned int a, b, c, d;
  12943. unsigned port;
  12944. unsigned long portUL;
  12945. int ch, len;
  12946. const char *cb;
  12947. char *endptr;
  12948. #if defined(USE_IPV6)
  12949. char buf[100] = {0};
  12950. #endif
  12951. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12952. * Also, all-zeroes in the socket address means binding to all addresses
  12953. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12954. memset(so, 0, sizeof(*so));
  12955. so->lsa.sin.sin_family = AF_INET;
  12956. *ip_version = 0;
  12957. /* Initialize len as invalid. */
  12958. port = 0;
  12959. len = 0;
  12960. /* Test for different ways to format this string */
  12961. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12962. == 5) {
  12963. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12964. so->lsa.sin.sin_addr.s_addr =
  12965. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12966. so->lsa.sin.sin_port = htons((uint16_t)port);
  12967. *ip_version = 4;
  12968. #if defined(USE_IPV6)
  12969. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12970. && ((size_t)len <= vec->len)
  12971. && mg_inet_pton(
  12972. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12973. /* IPv6 address, examples: see above */
  12974. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12975. */
  12976. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12977. *ip_version = 6;
  12978. #endif
  12979. } else if ((vec->ptr[0] == '+')
  12980. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12981. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12982. /* Add 1 to len for the + character we skipped before */
  12983. len++;
  12984. #if defined(USE_IPV6)
  12985. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12986. so->lsa.sin6.sin6_family = AF_INET6;
  12987. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12988. *ip_version = 4 + 6;
  12989. #else
  12990. /* Bind to IPv4 only, since IPv6 is not built in. */
  12991. so->lsa.sin.sin_port = htons((uint16_t)port);
  12992. *ip_version = 4;
  12993. #endif
  12994. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12995. && (vec->ptr != endptr)) {
  12996. len = (int)(endptr - vec->ptr);
  12997. port = (uint16_t)portUL;
  12998. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12999. so->lsa.sin.sin_port = htons((uint16_t)port);
  13000. *ip_version = 4;
  13001. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13002. /* String could be a hostname. This check algotithm
  13003. * will only work for RFC 952 compliant hostnames,
  13004. * starting with a letter, containing only letters,
  13005. * digits and hyphen ('-'). Newer specs may allow
  13006. * more, but this is not guaranteed here, since it
  13007. * may interfere with rules for port option lists. */
  13008. /* According to RFC 1035, hostnames are restricted to 255 characters
  13009. * in total (63 between two dots). */
  13010. char hostname[256];
  13011. size_t hostnlen = (size_t)(cb - vec->ptr);
  13012. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13013. /* This would be invalid in any case */
  13014. *ip_version = 0;
  13015. return 0;
  13016. }
  13017. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13018. if (mg_inet_pton(
  13019. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13020. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13021. *ip_version = 4;
  13022. so->lsa.sin.sin_port = htons((uint16_t)port);
  13023. len += (int)(hostnlen + 1);
  13024. } else {
  13025. len = 0;
  13026. }
  13027. #if defined(USE_IPV6)
  13028. } else if (mg_inet_pton(AF_INET6,
  13029. hostname,
  13030. &so->lsa.sin6,
  13031. sizeof(so->lsa.sin6),
  13032. 1)) {
  13033. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13034. *ip_version = 6;
  13035. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13036. len += (int)(hostnlen + 1);
  13037. } else {
  13038. len = 0;
  13039. }
  13040. #endif
  13041. } else {
  13042. len = 0;
  13043. }
  13044. } else {
  13045. /* Parsing failure. */
  13046. len = 0;
  13047. }
  13048. /* sscanf and the option splitting code ensure the following condition
  13049. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13050. if ((len > 0) && is_valid_port(port)
  13051. && (((size_t)len == vec->len) || ((size_t)(len + 1) == vec->len))) {
  13052. /* Next character after the port number */
  13053. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13054. so->is_ssl = (ch == 's');
  13055. so->ssl_redir = (ch == 'r');
  13056. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13057. return 1;
  13058. }
  13059. }
  13060. /* Reset ip_version to 0 if there is an error */
  13061. *ip_version = 0;
  13062. return 0;
  13063. }
  13064. /* Is there any SSL port in use? */
  13065. static int
  13066. is_ssl_port_used(const char *ports)
  13067. {
  13068. if (ports) {
  13069. /* There are several different allowed syntax variants:
  13070. * - "80" for a single port using every network interface
  13071. * - "localhost:80" for a single port using only localhost
  13072. * - "80,localhost:8080" for two ports, one bound to localhost
  13073. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13074. * to IPv4 localhost, one to IPv6 localhost
  13075. * - "+80" use port 80 for IPv4 and IPv6
  13076. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13077. * for both: IPv4 and IPv4
  13078. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13079. * additionally port 8080 bound to localhost connections
  13080. *
  13081. * If we just look for 's' anywhere in the string, "localhost:80"
  13082. * will be detected as SSL (false positive).
  13083. * Looking for 's' after a digit may cause false positives in
  13084. * "my24service:8080".
  13085. * Looking from 's' backward if there are only ':' and numbers
  13086. * before will not work for "24service:8080" (non SSL, port 8080)
  13087. * or "24s" (SSL, port 24).
  13088. *
  13089. * Remark: Initially hostnames were not allowed to start with a
  13090. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13091. * Section 2.1).
  13092. *
  13093. * To get this correct, the entire string must be parsed as a whole,
  13094. * reading it as a list element for element and parsing with an
  13095. * algorithm equivalent to parse_port_string.
  13096. *
  13097. * In fact, we use local interface names here, not arbitrary
  13098. * hostnames, so in most cases the only name will be "localhost".
  13099. *
  13100. * So, for now, we use this simple algorithm, that may still return
  13101. * a false positive in bizarre cases.
  13102. */
  13103. int i;
  13104. int portslen = (int)strlen(ports);
  13105. char prevIsNumber = 0;
  13106. for (i = 0; i < portslen; i++) {
  13107. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13108. return 1;
  13109. }
  13110. if (ports[i] >= '0' && ports[i] <= '9') {
  13111. prevIsNumber = 1;
  13112. } else {
  13113. prevIsNumber = 0;
  13114. }
  13115. }
  13116. }
  13117. return 0;
  13118. }
  13119. static int
  13120. set_ports_option(struct mg_context *phys_ctx)
  13121. {
  13122. const char *list;
  13123. int on = 1;
  13124. #if defined(USE_IPV6)
  13125. int off = 0;
  13126. #endif
  13127. struct vec vec;
  13128. struct socket so, *ptr;
  13129. struct mg_pollfd *pfd;
  13130. union usa usa;
  13131. socklen_t len;
  13132. int ip_version;
  13133. int portsTotal = 0;
  13134. int portsOk = 0;
  13135. const char *opt_txt;
  13136. long opt_listen_backlog;
  13137. if (!phys_ctx) {
  13138. return 0;
  13139. }
  13140. memset(&so, 0, sizeof(so));
  13141. memset(&usa, 0, sizeof(usa));
  13142. len = sizeof(usa);
  13143. list = phys_ctx->dd.config[LISTENING_PORTS];
  13144. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13145. portsTotal++;
  13146. if (!parse_port_string(&vec, &so, &ip_version)) {
  13147. mg_cry_ctx_internal(
  13148. phys_ctx,
  13149. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13150. (int)vec.len,
  13151. vec.ptr,
  13152. portsTotal,
  13153. "[IP_ADDRESS:]PORT[s|r]");
  13154. continue;
  13155. }
  13156. #if !defined(NO_SSL)
  13157. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13158. mg_cry_ctx_internal(phys_ctx,
  13159. "Cannot add SSL socket (entry %i)",
  13160. portsTotal);
  13161. continue;
  13162. }
  13163. #endif
  13164. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  13165. == INVALID_SOCKET) {
  13166. mg_cry_ctx_internal(phys_ctx,
  13167. "cannot create socket (entry %i)",
  13168. portsTotal);
  13169. continue;
  13170. }
  13171. #if defined(_WIN32)
  13172. /* Windows SO_REUSEADDR lets many procs binds to a
  13173. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13174. * if someone already has the socket -- DTL */
  13175. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13176. * Windows might need a few seconds before
  13177. * the same port can be used again in the
  13178. * same process, so a short Sleep may be
  13179. * required between mg_stop and mg_start.
  13180. */
  13181. if (setsockopt(so.sock,
  13182. SOL_SOCKET,
  13183. SO_EXCLUSIVEADDRUSE,
  13184. (SOCK_OPT_TYPE)&on,
  13185. sizeof(on))
  13186. != 0) {
  13187. /* Set reuse option, but don't abort on errors. */
  13188. mg_cry_ctx_internal(
  13189. phys_ctx,
  13190. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13191. portsTotal);
  13192. }
  13193. #else
  13194. if (setsockopt(so.sock,
  13195. SOL_SOCKET,
  13196. SO_REUSEADDR,
  13197. (SOCK_OPT_TYPE)&on,
  13198. sizeof(on))
  13199. != 0) {
  13200. /* Set reuse option, but don't abort on errors. */
  13201. mg_cry_ctx_internal(
  13202. phys_ctx,
  13203. "cannot set socket option SO_REUSEADDR (entry %i)",
  13204. portsTotal);
  13205. }
  13206. #endif
  13207. if (ip_version > 4) {
  13208. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13209. #if defined(USE_IPV6)
  13210. if (ip_version > 6) {
  13211. if (so.lsa.sa.sa_family == AF_INET6
  13212. && setsockopt(so.sock,
  13213. IPPROTO_IPV6,
  13214. IPV6_V6ONLY,
  13215. (void *)&off,
  13216. sizeof(off))
  13217. != 0) {
  13218. /* Set IPv6 only option, but don't abort on errors. */
  13219. mg_cry_ctx_internal(phys_ctx,
  13220. "cannot set socket option "
  13221. "IPV6_V6ONLY=off (entry %i)",
  13222. portsTotal);
  13223. }
  13224. } else {
  13225. if (so.lsa.sa.sa_family == AF_INET6
  13226. && setsockopt(so.sock,
  13227. IPPROTO_IPV6,
  13228. IPV6_V6ONLY,
  13229. (void *)&on,
  13230. sizeof(on))
  13231. != 0) {
  13232. /* Set IPv6 only option, but don't abort on errors. */
  13233. mg_cry_ctx_internal(phys_ctx,
  13234. "cannot set socket option "
  13235. "IPV6_V6ONLY=on (entry %i)",
  13236. portsTotal);
  13237. }
  13238. }
  13239. #else
  13240. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13241. closesocket(so.sock);
  13242. so.sock = INVALID_SOCKET;
  13243. continue;
  13244. #endif
  13245. }
  13246. if (so.lsa.sa.sa_family == AF_INET) {
  13247. len = sizeof(so.lsa.sin);
  13248. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13249. mg_cry_ctx_internal(phys_ctx,
  13250. "cannot bind to %.*s: %d (%s)",
  13251. (int)vec.len,
  13252. vec.ptr,
  13253. (int)ERRNO,
  13254. strerror(errno));
  13255. closesocket(so.sock);
  13256. so.sock = INVALID_SOCKET;
  13257. continue;
  13258. }
  13259. }
  13260. #if defined(USE_IPV6)
  13261. else if (so.lsa.sa.sa_family == AF_INET6) {
  13262. len = sizeof(so.lsa.sin6);
  13263. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13264. mg_cry_ctx_internal(phys_ctx,
  13265. "cannot bind to IPv6 %.*s: %d (%s)",
  13266. (int)vec.len,
  13267. vec.ptr,
  13268. (int)ERRNO,
  13269. strerror(errno));
  13270. closesocket(so.sock);
  13271. so.sock = INVALID_SOCKET;
  13272. continue;
  13273. }
  13274. }
  13275. #endif
  13276. else {
  13277. mg_cry_ctx_internal(
  13278. phys_ctx,
  13279. "cannot bind: address family not supported (entry %i)",
  13280. portsTotal);
  13281. closesocket(so.sock);
  13282. so.sock = INVALID_SOCKET;
  13283. continue;
  13284. }
  13285. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13286. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13287. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13288. mg_cry_ctx_internal(phys_ctx,
  13289. "%s value \"%s\" is invalid",
  13290. config_options[LISTEN_BACKLOG_SIZE].name,
  13291. opt_txt);
  13292. closesocket(so.sock);
  13293. so.sock = INVALID_SOCKET;
  13294. continue;
  13295. }
  13296. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13297. mg_cry_ctx_internal(phys_ctx,
  13298. "cannot listen to %.*s: %d (%s)",
  13299. (int)vec.len,
  13300. vec.ptr,
  13301. (int)ERRNO,
  13302. strerror(errno));
  13303. closesocket(so.sock);
  13304. so.sock = INVALID_SOCKET;
  13305. continue;
  13306. }
  13307. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13308. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13309. int err = (int)ERRNO;
  13310. mg_cry_ctx_internal(phys_ctx,
  13311. "call to getsockname failed %.*s: %d (%s)",
  13312. (int)vec.len,
  13313. vec.ptr,
  13314. err,
  13315. strerror(errno));
  13316. closesocket(so.sock);
  13317. so.sock = INVALID_SOCKET;
  13318. continue;
  13319. }
  13320. /* Update lsa port in case of random free ports */
  13321. #if defined(USE_IPV6)
  13322. if (so.lsa.sa.sa_family == AF_INET6) {
  13323. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13324. } else
  13325. #endif
  13326. {
  13327. so.lsa.sin.sin_port = usa.sin.sin_port;
  13328. }
  13329. if ((ptr = (struct socket *)
  13330. mg_realloc_ctx(phys_ctx->listening_sockets,
  13331. (phys_ctx->num_listening_sockets + 1)
  13332. * sizeof(phys_ctx->listening_sockets[0]),
  13333. phys_ctx))
  13334. == NULL) {
  13335. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13336. closesocket(so.sock);
  13337. so.sock = INVALID_SOCKET;
  13338. continue;
  13339. }
  13340. if ((pfd = (struct mg_pollfd *)
  13341. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13342. (phys_ctx->num_listening_sockets + 1)
  13343. * sizeof(phys_ctx->listening_socket_fds[0]),
  13344. phys_ctx))
  13345. == NULL) {
  13346. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13347. closesocket(so.sock);
  13348. so.sock = INVALID_SOCKET;
  13349. mg_free(ptr);
  13350. continue;
  13351. }
  13352. set_close_on_exec(so.sock, NULL, phys_ctx);
  13353. phys_ctx->listening_sockets = ptr;
  13354. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13355. phys_ctx->listening_socket_fds = pfd;
  13356. phys_ctx->num_listening_sockets++;
  13357. portsOk++;
  13358. }
  13359. if (portsOk != portsTotal) {
  13360. close_all_listening_sockets(phys_ctx);
  13361. portsOk = 0;
  13362. }
  13363. return portsOk;
  13364. }
  13365. static const char *
  13366. header_val(const struct mg_connection *conn, const char *header)
  13367. {
  13368. const char *header_value;
  13369. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13370. return "-";
  13371. } else {
  13372. return header_value;
  13373. }
  13374. }
  13375. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13376. static void log_access(const struct mg_connection *conn);
  13377. #include "external_log_access.inl"
  13378. #elif !defined(NO_FILESYSTEMS)
  13379. static void
  13380. log_access(const struct mg_connection *conn)
  13381. {
  13382. const struct mg_request_info *ri;
  13383. struct mg_file fi;
  13384. char date[64], src_addr[IP_ADDR_STR_LEN];
  13385. struct tm *tm;
  13386. const char *referer;
  13387. const char *user_agent;
  13388. char buf[4096];
  13389. if (!conn || !conn->dom_ctx) {
  13390. return;
  13391. }
  13392. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13393. if (mg_fopen(conn,
  13394. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13395. MG_FOPEN_MODE_APPEND,
  13396. &fi)
  13397. == 0) {
  13398. fi.access.fp = NULL;
  13399. }
  13400. } else {
  13401. fi.access.fp = NULL;
  13402. }
  13403. /* Log is written to a file and/or a callback. If both are not set,
  13404. * executing the rest of the function is pointless. */
  13405. if ((fi.access.fp == NULL)
  13406. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13407. return;
  13408. }
  13409. tm = localtime(&conn->conn_birth_time);
  13410. if (tm != NULL) {
  13411. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13412. } else {
  13413. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13414. date[sizeof(date) - 1] = '\0';
  13415. }
  13416. ri = &conn->request_info;
  13417. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13418. referer = header_val(conn, "Referer");
  13419. user_agent = header_val(conn, "User-Agent");
  13420. mg_snprintf(conn,
  13421. NULL, /* Ignore truncation in access log */
  13422. buf,
  13423. sizeof(buf),
  13424. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13425. src_addr,
  13426. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13427. date,
  13428. ri->request_method ? ri->request_method : "-",
  13429. ri->request_uri ? ri->request_uri : "-",
  13430. ri->query_string ? "?" : "",
  13431. ri->query_string ? ri->query_string : "",
  13432. ri->http_version,
  13433. conn->status_code,
  13434. conn->num_bytes_sent,
  13435. referer,
  13436. user_agent);
  13437. if (conn->phys_ctx->callbacks.log_access) {
  13438. conn->phys_ctx->callbacks.log_access(conn, buf);
  13439. }
  13440. if (fi.access.fp) {
  13441. int ok = 1;
  13442. flockfile(fi.access.fp);
  13443. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13444. ok = 0;
  13445. }
  13446. if (fflush(fi.access.fp) != 0) {
  13447. ok = 0;
  13448. }
  13449. funlockfile(fi.access.fp);
  13450. if (mg_fclose(&fi.access) != 0) {
  13451. ok = 0;
  13452. }
  13453. if (!ok) {
  13454. mg_cry_internal(conn,
  13455. "Error writing log file %s",
  13456. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13457. }
  13458. }
  13459. }
  13460. #else
  13461. #error Must either enable filesystems or provide a custom log_access implementation
  13462. #endif /* Externally provided function */
  13463. /* Verify given socket address against the ACL.
  13464. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13465. */
  13466. static int
  13467. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13468. {
  13469. int allowed, flag, matched;
  13470. struct vec vec;
  13471. if (phys_ctx) {
  13472. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13473. /* If any ACL is set, deny by default */
  13474. allowed = (list == NULL) ? '+' : '-';
  13475. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13476. flag = vec.ptr[0];
  13477. matched = -1;
  13478. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13479. vec.ptr++;
  13480. vec.len--;
  13481. matched = parse_match_net(&vec, sa, 1);
  13482. }
  13483. if (matched < 0) {
  13484. mg_cry_ctx_internal(phys_ctx,
  13485. "%s: subnet must be [+|-]IP-addr[/x]",
  13486. __func__);
  13487. return -1;
  13488. }
  13489. if (matched) {
  13490. allowed = flag;
  13491. }
  13492. }
  13493. return allowed == '+';
  13494. }
  13495. return -1;
  13496. }
  13497. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13498. static int
  13499. set_uid_option(struct mg_context *phys_ctx)
  13500. {
  13501. int success = 0;
  13502. if (phys_ctx) {
  13503. /* We are currently running as curr_uid. */
  13504. const uid_t curr_uid = getuid();
  13505. /* If set, we want to run as run_as_user. */
  13506. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13507. const struct passwd *to_pw = NULL;
  13508. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13509. /* run_as_user does not exist on the system. We can't proceed
  13510. * further. */
  13511. mg_cry_ctx_internal(phys_ctx,
  13512. "%s: unknown user [%s]",
  13513. __func__,
  13514. run_as_user);
  13515. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13516. /* There was either no request to change user, or we're already
  13517. * running as run_as_user. Nothing else to do.
  13518. */
  13519. success = 1;
  13520. } else {
  13521. /* Valid change request. */
  13522. if (setgid(to_pw->pw_gid) == -1) {
  13523. mg_cry_ctx_internal(phys_ctx,
  13524. "%s: setgid(%s): %s",
  13525. __func__,
  13526. run_as_user,
  13527. strerror(errno));
  13528. } else if (setgroups(0, NULL) == -1) {
  13529. mg_cry_ctx_internal(phys_ctx,
  13530. "%s: setgroups(): %s",
  13531. __func__,
  13532. strerror(errno));
  13533. } else if (setuid(to_pw->pw_uid) == -1) {
  13534. mg_cry_ctx_internal(phys_ctx,
  13535. "%s: setuid(%s): %s",
  13536. __func__,
  13537. run_as_user,
  13538. strerror(errno));
  13539. } else {
  13540. success = 1;
  13541. }
  13542. }
  13543. }
  13544. return success;
  13545. }
  13546. #endif /* !_WIN32 */
  13547. static void
  13548. tls_dtor(void *key)
  13549. {
  13550. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13551. /* key == pthread_getspecific(sTlsKey); */
  13552. if (tls) {
  13553. if (tls->is_master == 2) {
  13554. tls->is_master = -3; /* Mark memory as dead */
  13555. mg_free(tls);
  13556. }
  13557. }
  13558. pthread_setspecific(sTlsKey, NULL);
  13559. }
  13560. #if !defined(NO_SSL)
  13561. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13562. struct mg_domain_context *dom_ctx,
  13563. const char *pem,
  13564. const char *chain);
  13565. static const char *ssl_error(void);
  13566. static int
  13567. refresh_trust(struct mg_connection *conn)
  13568. {
  13569. struct stat cert_buf;
  13570. int64_t t = 0;
  13571. const char *pem;
  13572. const char *chain;
  13573. int should_verify_peer;
  13574. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13575. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13576. * refresh_trust still can not work. */
  13577. return 0;
  13578. }
  13579. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13580. if (chain == NULL) {
  13581. /* pem is not NULL here */
  13582. chain = pem;
  13583. }
  13584. if (*chain == 0) {
  13585. chain = NULL;
  13586. }
  13587. if (stat(pem, &cert_buf) != -1) {
  13588. t = (int64_t)cert_buf.st_mtime;
  13589. }
  13590. mg_lock_context(conn->phys_ctx);
  13591. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13592. conn->dom_ctx->ssl_cert_last_mtime = t;
  13593. should_verify_peer = 0;
  13594. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13595. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13596. == 0) {
  13597. should_verify_peer = 1;
  13598. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13599. "optional")
  13600. == 0) {
  13601. should_verify_peer = 1;
  13602. }
  13603. }
  13604. if (should_verify_peer) {
  13605. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13606. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13607. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13608. ca_file,
  13609. ca_path)
  13610. != 1) {
  13611. mg_unlock_context(conn->phys_ctx);
  13612. mg_cry_ctx_internal(
  13613. conn->phys_ctx,
  13614. "SSL_CTX_load_verify_locations error: %s "
  13615. "ssl_verify_peer requires setting "
  13616. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13617. "present in "
  13618. "the .conf file?",
  13619. ssl_error());
  13620. return 0;
  13621. }
  13622. }
  13623. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13624. mg_unlock_context(conn->phys_ctx);
  13625. return 0;
  13626. }
  13627. }
  13628. mg_unlock_context(conn->phys_ctx);
  13629. return 1;
  13630. }
  13631. #if defined(OPENSSL_API_1_1)
  13632. #else
  13633. static pthread_mutex_t *ssl_mutexes;
  13634. #endif /* OPENSSL_API_1_1 */
  13635. static int
  13636. sslize(struct mg_connection *conn,
  13637. int (*func)(SSL *),
  13638. const struct mg_client_options *client_options)
  13639. {
  13640. int ret, err;
  13641. int short_trust;
  13642. unsigned timeout = 1024;
  13643. unsigned i;
  13644. if (!conn) {
  13645. return 0;
  13646. }
  13647. short_trust =
  13648. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13649. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13650. if (short_trust) {
  13651. int trust_ret = refresh_trust(conn);
  13652. if (!trust_ret) {
  13653. return trust_ret;
  13654. }
  13655. }
  13656. mg_lock_context(conn->phys_ctx);
  13657. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13658. mg_unlock_context(conn->phys_ctx);
  13659. if (conn->ssl == NULL) {
  13660. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13661. OPENSSL_REMOVE_THREAD_STATE();
  13662. return 0;
  13663. }
  13664. SSL_set_app_data(conn->ssl, (char *)conn);
  13665. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13666. if (ret != 1) {
  13667. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13668. SSL_free(conn->ssl);
  13669. conn->ssl = NULL;
  13670. OPENSSL_REMOVE_THREAD_STATE();
  13671. return 0;
  13672. }
  13673. if (client_options) {
  13674. if (client_options->host_name) {
  13675. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13676. }
  13677. }
  13678. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13679. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13680. /* NOTE: The loop below acts as a back-off, so we can end
  13681. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13682. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13683. if (to >= 0) {
  13684. timeout = (unsigned)to;
  13685. }
  13686. }
  13687. /* SSL functions may fail and require to be called again:
  13688. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13689. * Here "func" could be SSL_connect or SSL_accept. */
  13690. for (i = 0; i <= timeout; i += 50) {
  13691. ERR_clear_error();
  13692. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13693. ret = func(conn->ssl);
  13694. if (ret != 1) {
  13695. err = SSL_get_error(conn->ssl, ret);
  13696. if ((err == SSL_ERROR_WANT_CONNECT)
  13697. || (err == SSL_ERROR_WANT_ACCEPT)
  13698. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13699. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13700. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13701. /* Don't wait if the server is going to be stopped. */
  13702. break;
  13703. }
  13704. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13705. /* Simply retry the function call. */
  13706. mg_sleep(50);
  13707. } else {
  13708. /* Need to retry the function call "later".
  13709. * See https://linux.die.net/man/3/ssl_get_error
  13710. * This is typical for non-blocking sockets. */
  13711. struct mg_pollfd pfd;
  13712. int pollres;
  13713. pfd.fd = conn->client.sock;
  13714. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13715. || (err == SSL_ERROR_WANT_WRITE))
  13716. ? POLLOUT
  13717. : POLLIN;
  13718. pollres =
  13719. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13720. if (pollres < 0) {
  13721. /* Break if error occured (-1)
  13722. * or server shutdown (-2) */
  13723. break;
  13724. }
  13725. }
  13726. } else if (err == SSL_ERROR_SYSCALL) {
  13727. /* This is an IO error. Look at errno. */
  13728. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13729. break;
  13730. } else {
  13731. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13732. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13733. break;
  13734. }
  13735. } else {
  13736. /* success */
  13737. break;
  13738. }
  13739. }
  13740. ERR_clear_error();
  13741. if (ret != 1) {
  13742. SSL_free(conn->ssl);
  13743. conn->ssl = NULL;
  13744. OPENSSL_REMOVE_THREAD_STATE();
  13745. return 0;
  13746. }
  13747. return 1;
  13748. }
  13749. /* Return OpenSSL error message (from CRYPTO lib) */
  13750. static const char *
  13751. ssl_error(void)
  13752. {
  13753. unsigned long err;
  13754. err = ERR_get_error();
  13755. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13756. }
  13757. static int
  13758. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13759. {
  13760. int i;
  13761. const char hexdigit[] = "0123456789abcdef";
  13762. if ((memlen <= 0) || (buflen <= 0)) {
  13763. return 0;
  13764. }
  13765. if (buflen < (3 * memlen)) {
  13766. return 0;
  13767. }
  13768. for (i = 0; i < memlen; i++) {
  13769. if (i > 0) {
  13770. buf[3 * i - 1] = ' ';
  13771. }
  13772. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13773. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13774. }
  13775. buf[3 * memlen - 1] = 0;
  13776. return 1;
  13777. }
  13778. static int
  13779. ssl_get_client_cert_info(const struct mg_connection *conn,
  13780. struct mg_client_cert *client_cert)
  13781. {
  13782. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13783. if (cert) {
  13784. char str_buf[1024];
  13785. unsigned char buf[256];
  13786. char *str_serial = NULL;
  13787. unsigned int ulen;
  13788. int ilen;
  13789. unsigned char *tmp_buf;
  13790. unsigned char *tmp_p;
  13791. /* Handle to algorithm used for fingerprint */
  13792. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13793. /* Get Subject and issuer */
  13794. X509_NAME *subj = X509_get_subject_name(cert);
  13795. X509_NAME *iss = X509_get_issuer_name(cert);
  13796. /* Get serial number */
  13797. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13798. /* Translate serial number to a hex string */
  13799. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13800. if (serial_bn) {
  13801. str_serial = BN_bn2hex(serial_bn);
  13802. BN_free(serial_bn);
  13803. }
  13804. client_cert->serial =
  13805. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13806. /* Translate subject and issuer to a string */
  13807. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13808. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13809. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13810. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13811. /* Calculate SHA1 fingerprint and store as a hex string */
  13812. ulen = 0;
  13813. /* ASN1_digest is deprecated. Do the calculation manually,
  13814. * using EVP_Digest. */
  13815. ilen = i2d_X509(cert, NULL);
  13816. tmp_buf = (ilen > 0)
  13817. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13818. conn->phys_ctx)
  13819. : NULL;
  13820. if (tmp_buf) {
  13821. tmp_p = tmp_buf;
  13822. (void)i2d_X509(cert, &tmp_p);
  13823. if (!EVP_Digest(
  13824. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13825. ulen = 0;
  13826. }
  13827. mg_free(tmp_buf);
  13828. }
  13829. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13830. *str_buf = 0;
  13831. }
  13832. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13833. client_cert->peer_cert = (void *)cert;
  13834. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13835. * see https://linux.die.net/man/3/bn_bn2hex */
  13836. OPENSSL_free(str_serial);
  13837. return 1;
  13838. }
  13839. return 0;
  13840. }
  13841. #if defined(OPENSSL_API_1_1)
  13842. #else
  13843. static void
  13844. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13845. {
  13846. (void)line;
  13847. (void)file;
  13848. if (mode & 1) {
  13849. /* 1 is CRYPTO_LOCK */
  13850. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13851. } else {
  13852. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13853. }
  13854. }
  13855. #endif /* OPENSSL_API_1_1 */
  13856. #if !defined(NO_SSL_DL)
  13857. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13858. static void *
  13859. load_tls_dll(char *ebuf,
  13860. size_t ebuf_len,
  13861. const char *dll_name,
  13862. struct ssl_func *sw,
  13863. int *feature_missing)
  13864. {
  13865. union {
  13866. void *p;
  13867. void (*fp)(void);
  13868. } u;
  13869. void *dll_handle;
  13870. struct ssl_func *fp;
  13871. int ok;
  13872. int truncated = 0;
  13873. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13874. mg_snprintf(NULL,
  13875. NULL, /* No truncation check for ebuf */
  13876. ebuf,
  13877. ebuf_len,
  13878. "%s: cannot load %s",
  13879. __func__,
  13880. dll_name);
  13881. return NULL;
  13882. }
  13883. ok = 1;
  13884. for (fp = sw; fp->name != NULL; fp++) {
  13885. #if defined(_WIN32)
  13886. /* GetProcAddress() returns pointer to function */
  13887. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13888. #else
  13889. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13890. * pointers to function pointers. We need to use a union to make a
  13891. * cast. */
  13892. u.p = dlsym(dll_handle, fp->name);
  13893. #endif /* _WIN32 */
  13894. /* Set pointer (might be NULL) */
  13895. fp->ptr = u.fp;
  13896. if (u.fp == NULL) {
  13897. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13898. if (feature_missing) {
  13899. feature_missing[fp->required]++;
  13900. }
  13901. if (fp->required == TLS_Mandatory) {
  13902. /* Mandatory function is missing */
  13903. if (ok) {
  13904. /* This is the first missing function.
  13905. * Create a new error message. */
  13906. mg_snprintf(NULL,
  13907. &truncated,
  13908. ebuf,
  13909. ebuf_len,
  13910. "%s: %s: cannot find %s",
  13911. __func__,
  13912. dll_name,
  13913. fp->name);
  13914. ok = 0;
  13915. } else {
  13916. /* This is yet anothermissing function.
  13917. * Append existing error message. */
  13918. size_t cur_len = strlen(ebuf);
  13919. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13920. mg_snprintf(NULL,
  13921. &truncated,
  13922. ebuf + cur_len,
  13923. ebuf_len - cur_len - 3,
  13924. ", %s",
  13925. fp->name);
  13926. if (truncated) {
  13927. /* If truncated, add "..." */
  13928. strcat(ebuf, "...");
  13929. }
  13930. }
  13931. }
  13932. }
  13933. }
  13934. }
  13935. if (!ok) {
  13936. (void)dlclose(dll_handle);
  13937. return NULL;
  13938. }
  13939. return dll_handle;
  13940. }
  13941. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13942. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13943. #endif /* NO_SSL_DL */
  13944. #if defined(SSL_ALREADY_INITIALIZED)
  13945. static volatile ptrdiff_t cryptolib_users =
  13946. 1; /* Reference counter for crypto library. */
  13947. #else
  13948. static volatile ptrdiff_t cryptolib_users =
  13949. 0; /* Reference counter for crypto library. */
  13950. #endif
  13951. static int
  13952. initialize_ssl(char *ebuf, size_t ebuf_len)
  13953. {
  13954. #if !defined(OPENSSL_API_1_1)
  13955. int i, num_locks;
  13956. size_t size;
  13957. #endif
  13958. if (ebuf_len > 0) {
  13959. ebuf[0] = 0;
  13960. }
  13961. #if !defined(NO_SSL_DL)
  13962. if (!cryptolib_dll_handle) {
  13963. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13964. cryptolib_dll_handle = load_tls_dll(
  13965. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13966. if (!cryptolib_dll_handle) {
  13967. mg_snprintf(NULL,
  13968. NULL, /* No truncation check for ebuf */
  13969. ebuf,
  13970. ebuf_len,
  13971. "%s: error loading library %s",
  13972. __func__,
  13973. CRYPTO_LIB);
  13974. DEBUG_TRACE("%s", ebuf);
  13975. return 0;
  13976. }
  13977. }
  13978. #endif /* NO_SSL_DL */
  13979. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13980. return 1;
  13981. }
  13982. #if !defined(OPENSSL_API_1_1)
  13983. /* Initialize locking callbacks, needed for thread safety.
  13984. * http://www.openssl.org/support/faq.html#PROG1
  13985. */
  13986. num_locks = CRYPTO_num_locks();
  13987. if (num_locks < 0) {
  13988. num_locks = 0;
  13989. }
  13990. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13991. /* allocate mutex array, if required */
  13992. if (num_locks == 0) {
  13993. /* No mutex array required */
  13994. ssl_mutexes = NULL;
  13995. } else {
  13996. /* Mutex array required - allocate it */
  13997. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13998. /* Check OOM */
  13999. if (ssl_mutexes == NULL) {
  14000. mg_snprintf(NULL,
  14001. NULL, /* No truncation check for ebuf */
  14002. ebuf,
  14003. ebuf_len,
  14004. "%s: cannot allocate mutexes: %s",
  14005. __func__,
  14006. ssl_error());
  14007. DEBUG_TRACE("%s", ebuf);
  14008. return 0;
  14009. }
  14010. /* initialize mutex array */
  14011. for (i = 0; i < num_locks; i++) {
  14012. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14013. mg_snprintf(NULL,
  14014. NULL, /* No truncation check for ebuf */
  14015. ebuf,
  14016. ebuf_len,
  14017. "%s: error initializing mutex %i of %i",
  14018. __func__,
  14019. i,
  14020. num_locks);
  14021. DEBUG_TRACE("%s", ebuf);
  14022. mg_free(ssl_mutexes);
  14023. return 0;
  14024. }
  14025. }
  14026. }
  14027. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14028. CRYPTO_set_id_callback(&mg_current_thread_id);
  14029. #endif /* OPENSSL_API_1_1 */
  14030. #if !defined(NO_SSL_DL)
  14031. if (!ssllib_dll_handle) {
  14032. ssllib_dll_handle =
  14033. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14034. if (!ssllib_dll_handle) {
  14035. #if !defined(OPENSSL_API_1_1)
  14036. mg_free(ssl_mutexes);
  14037. #endif
  14038. DEBUG_TRACE("%s", ebuf);
  14039. return 0;
  14040. }
  14041. }
  14042. #endif /* NO_SSL_DL */
  14043. #if defined(OPENSSL_API_1_1)
  14044. /* Initialize SSL library */
  14045. OPENSSL_init_ssl(0, NULL);
  14046. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14047. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14048. NULL);
  14049. #else
  14050. /* Initialize SSL library */
  14051. SSL_library_init();
  14052. SSL_load_error_strings();
  14053. #endif
  14054. return 1;
  14055. }
  14056. static int
  14057. ssl_use_pem_file(struct mg_context *phys_ctx,
  14058. struct mg_domain_context *dom_ctx,
  14059. const char *pem,
  14060. const char *chain)
  14061. {
  14062. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14063. mg_cry_ctx_internal(phys_ctx,
  14064. "%s: cannot open certificate file %s: %s",
  14065. __func__,
  14066. pem,
  14067. ssl_error());
  14068. return 0;
  14069. }
  14070. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14071. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14072. mg_cry_ctx_internal(phys_ctx,
  14073. "%s: cannot open private key file %s: %s",
  14074. __func__,
  14075. pem,
  14076. ssl_error());
  14077. return 0;
  14078. }
  14079. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14080. mg_cry_ctx_internal(phys_ctx,
  14081. "%s: certificate and private key do not match: %s",
  14082. __func__,
  14083. pem);
  14084. return 0;
  14085. }
  14086. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14087. * chain files that contain private keys and certificates in
  14088. * SSL_CTX_use_certificate_chain_file.
  14089. * The CivetWeb-Server used pem-Files that contained both information.
  14090. * In order to make wolfSSL work, it is split in two files.
  14091. * One file that contains key and certificate used by the server and
  14092. * an optional chain file for the ssl stack.
  14093. */
  14094. if (chain) {
  14095. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14096. mg_cry_ctx_internal(phys_ctx,
  14097. "%s: cannot use certificate chain file %s: %s",
  14098. __func__,
  14099. chain,
  14100. ssl_error());
  14101. return 0;
  14102. }
  14103. }
  14104. return 1;
  14105. }
  14106. #if defined(OPENSSL_API_1_1)
  14107. static unsigned long
  14108. ssl_get_protocol(int version_id)
  14109. {
  14110. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14111. if (version_id > 0)
  14112. ret |= SSL_OP_NO_SSLv2;
  14113. if (version_id > 1)
  14114. ret |= SSL_OP_NO_SSLv3;
  14115. if (version_id > 2)
  14116. ret |= SSL_OP_NO_TLSv1;
  14117. if (version_id > 3)
  14118. ret |= SSL_OP_NO_TLSv1_1;
  14119. if (version_id > 4)
  14120. ret |= SSL_OP_NO_TLSv1_2;
  14121. #if defined(SSL_OP_NO_TLSv1_3)
  14122. if (version_id > 5)
  14123. ret |= SSL_OP_NO_TLSv1_3;
  14124. #endif
  14125. return ret;
  14126. }
  14127. #else
  14128. static long
  14129. ssl_get_protocol(int version_id)
  14130. {
  14131. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14132. if (version_id > 0)
  14133. ret |= SSL_OP_NO_SSLv2;
  14134. if (version_id > 1)
  14135. ret |= SSL_OP_NO_SSLv3;
  14136. if (version_id > 2)
  14137. ret |= SSL_OP_NO_TLSv1;
  14138. if (version_id > 3)
  14139. ret |= SSL_OP_NO_TLSv1_1;
  14140. if (version_id > 4)
  14141. ret |= SSL_OP_NO_TLSv1_2;
  14142. #if defined(SSL_OP_NO_TLSv1_3)
  14143. if (version_id > 5)
  14144. ret |= SSL_OP_NO_TLSv1_3;
  14145. #endif
  14146. return (long)ret;
  14147. }
  14148. #endif /* OPENSSL_API_1_1 */
  14149. /* SSL callback documentation:
  14150. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14151. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14152. * https://linux.die.net/man/3/ssl_set_info_callback */
  14153. /* Note: There is no "const" for the first argument in the documentation
  14154. * examples, however some (maybe most, but not all) headers of OpenSSL
  14155. * versions / OpenSSL compatibility layers have it. Having a different
  14156. * definition will cause a warning in C and an error in C++. Use "const SSL
  14157. * *", while automatical conversion from "SSL *" works for all compilers,
  14158. * but not other way around */
  14159. static void
  14160. ssl_info_callback(const SSL *ssl, int what, int ret)
  14161. {
  14162. (void)ret;
  14163. if (what & SSL_CB_HANDSHAKE_START) {
  14164. SSL_get_app_data(ssl);
  14165. }
  14166. if (what & SSL_CB_HANDSHAKE_DONE) {
  14167. /* TODO: check for openSSL 1.1 */
  14168. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14169. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14170. }
  14171. }
  14172. static int
  14173. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14174. {
  14175. #if defined(GCC_DIAGNOSTIC)
  14176. #pragma GCC diagnostic push
  14177. #pragma GCC diagnostic ignored "-Wcast-align"
  14178. #endif /* defined(GCC_DIAGNOSTIC) */
  14179. /* We used an aligned pointer in SSL_set_app_data */
  14180. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14181. #if defined(GCC_DIAGNOSTIC)
  14182. #pragma GCC diagnostic pop
  14183. #endif /* defined(GCC_DIAGNOSTIC) */
  14184. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14185. (void)ad;
  14186. (void)arg;
  14187. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14188. DEBUG_ASSERT(0);
  14189. return SSL_TLSEXT_ERR_NOACK;
  14190. }
  14191. conn->dom_ctx = &(conn->phys_ctx->dd);
  14192. /* Old clients (Win XP) will not support SNI. Then, there
  14193. * is no server name available in the request - we can
  14194. * only work with the default certificate.
  14195. * Multiple HTTPS hosts on one IP+port are only possible
  14196. * with a certificate containing all alternative names.
  14197. */
  14198. if ((servername == NULL) || (*servername == 0)) {
  14199. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14200. mg_lock_context(conn->phys_ctx);
  14201. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14202. mg_unlock_context(conn->phys_ctx);
  14203. return SSL_TLSEXT_ERR_NOACK;
  14204. }
  14205. DEBUG_TRACE("TLS connection to host %s", servername);
  14206. while (conn->dom_ctx) {
  14207. if (!mg_strcasecmp(servername,
  14208. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14209. /* Found matching domain */
  14210. DEBUG_TRACE("TLS domain %s found",
  14211. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14212. break;
  14213. }
  14214. mg_lock_context(conn->phys_ctx);
  14215. conn->dom_ctx = conn->dom_ctx->next;
  14216. mg_unlock_context(conn->phys_ctx);
  14217. }
  14218. if (conn->dom_ctx == NULL) {
  14219. /* Default domain */
  14220. DEBUG_TRACE("TLS default domain %s used",
  14221. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14222. conn->dom_ctx = &(conn->phys_ctx->dd);
  14223. }
  14224. mg_lock_context(conn->phys_ctx);
  14225. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14226. mg_unlock_context(conn->phys_ctx);
  14227. return SSL_TLSEXT_ERR_OK;
  14228. }
  14229. #if defined(USE_ALPN)
  14230. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14231. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14232. alpn_proto_list + 3 + 8,
  14233. NULL};
  14234. #if defined(USE_HTTP2)
  14235. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14236. alpn_proto_list + 3,
  14237. alpn_proto_list + 3 + 8,
  14238. NULL};
  14239. #endif
  14240. static int
  14241. alpn_select_cb(SSL *ssl,
  14242. const unsigned char **out,
  14243. unsigned char *outlen,
  14244. const unsigned char *in,
  14245. unsigned int inlen,
  14246. void *arg)
  14247. {
  14248. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14249. unsigned int i, j, enable_http2 = 0;
  14250. const char **alpn_proto_order = alpn_proto_order_http1;
  14251. struct mg_workerTLS *tls =
  14252. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14253. (void)ssl;
  14254. if (tls == NULL) {
  14255. /* Need to store protocol in Thread Local Storage */
  14256. /* If there is no Thread Local Storage, don't use ALPN */
  14257. return SSL_TLSEXT_ERR_NOACK;
  14258. }
  14259. #if defined(USE_HTTP2)
  14260. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14261. if (enable_http2) {
  14262. alpn_proto_order = alpn_proto_order_http2;
  14263. }
  14264. #endif
  14265. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14266. /* check all accepted protocols in this order */
  14267. const char *alpn_proto = alpn_proto_order[j];
  14268. /* search input for matching protocol */
  14269. for (i = 0; i < inlen; i++) {
  14270. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14271. *out = in + i + 1;
  14272. *outlen = in[i];
  14273. tls->alpn_proto = alpn_proto;
  14274. return SSL_TLSEXT_ERR_OK;
  14275. }
  14276. }
  14277. }
  14278. /* Nothing found */
  14279. return SSL_TLSEXT_ERR_NOACK;
  14280. }
  14281. static int
  14282. next_protos_advertised_cb(SSL *ssl,
  14283. const unsigned char **data,
  14284. unsigned int *len,
  14285. void *arg)
  14286. {
  14287. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14288. *data = (const unsigned char *)alpn_proto_list;
  14289. *len = (unsigned int)strlen((const char *)data);
  14290. (void)ssl;
  14291. (void)dom_ctx;
  14292. return SSL_TLSEXT_ERR_OK;
  14293. }
  14294. static int
  14295. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14296. {
  14297. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14298. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14299. (const unsigned char *)alpn_proto_list,
  14300. alpn_len);
  14301. if (ret != 0) {
  14302. mg_cry_ctx_internal(phys_ctx,
  14303. "SSL_CTX_set_alpn_protos error: %s",
  14304. ssl_error());
  14305. }
  14306. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14307. alpn_select_cb,
  14308. (void *)dom_ctx);
  14309. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14310. next_protos_advertised_cb,
  14311. (void *)dom_ctx);
  14312. return ret;
  14313. }
  14314. #endif
  14315. /* Setup SSL CTX as required by CivetWeb */
  14316. static int
  14317. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14318. struct mg_domain_context *dom_ctx,
  14319. const char *pem,
  14320. const char *chain)
  14321. {
  14322. int callback_ret;
  14323. int should_verify_peer;
  14324. int peer_certificate_optional;
  14325. const char *ca_path;
  14326. const char *ca_file;
  14327. int use_default_verify_paths;
  14328. int verify_depth;
  14329. struct timespec now_mt;
  14330. md5_byte_t ssl_context_id[16];
  14331. md5_state_t md5state;
  14332. int protocol_ver;
  14333. int ssl_cache_timeout;
  14334. #if defined(OPENSSL_API_1_1)
  14335. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14336. mg_cry_ctx_internal(phys_ctx,
  14337. "SSL_CTX_new (server) error: %s",
  14338. ssl_error());
  14339. return 0;
  14340. }
  14341. #else
  14342. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14343. mg_cry_ctx_internal(phys_ctx,
  14344. "SSL_CTX_new (server) error: %s",
  14345. ssl_error());
  14346. return 0;
  14347. }
  14348. #endif /* OPENSSL_API_1_1 */
  14349. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14350. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14351. | SSL_OP_NO_TLSv1_1);
  14352. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14353. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14354. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14355. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14356. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14357. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14358. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14359. #if defined(SSL_OP_NO_RENEGOTIATION)
  14360. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14361. #endif
  14362. #if !defined(NO_SSL_DL)
  14363. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14364. #endif /* NO_SSL_DL */
  14365. /* In SSL documentation examples callback defined without const
  14366. * specifier 'void (*)(SSL *, int, int)' See:
  14367. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14368. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14369. * But in the source code const SSL is used:
  14370. * 'void (*)(const SSL *, int, int)' See:
  14371. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14372. * Problem about wrong documentation described, but not resolved:
  14373. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14374. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14375. * But when compiled with modern C++ compiler, correct const should be
  14376. * provided
  14377. */
  14378. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14379. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14380. ssl_servername_callback);
  14381. /* If a callback has been specified, call it. */
  14382. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14383. ? 0
  14384. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14385. phys_ctx->user_data));
  14386. /* If callback returns 0, civetweb sets up the SSL certificate.
  14387. * If it returns 1, civetweb assumes the calback already did this.
  14388. * If it returns -1, initializing ssl fails. */
  14389. if (callback_ret < 0) {
  14390. mg_cry_ctx_internal(phys_ctx,
  14391. "SSL callback returned error: %i",
  14392. callback_ret);
  14393. return 0;
  14394. }
  14395. if (callback_ret > 0) {
  14396. /* Callback did everything. */
  14397. return 1;
  14398. }
  14399. /* If a domain callback has been specified, call it. */
  14400. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14401. ? 0
  14402. : (phys_ctx->callbacks.init_ssl_domain(
  14403. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14404. dom_ctx->ssl_ctx,
  14405. phys_ctx->user_data));
  14406. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14407. * If it returns 1, civetweb assumes the calback already did this.
  14408. * If it returns -1, initializing ssl fails. */
  14409. if (callback_ret < 0) {
  14410. mg_cry_ctx_internal(phys_ctx,
  14411. "Domain SSL callback returned error: %i",
  14412. callback_ret);
  14413. return 0;
  14414. }
  14415. if (callback_ret > 0) {
  14416. /* Domain callback did everything. */
  14417. return 1;
  14418. }
  14419. /* Use some combination of start time, domain and port as a SSL
  14420. * context ID. This should be unique on the current machine. */
  14421. md5_init(&md5state);
  14422. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14423. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14424. md5_append(&md5state,
  14425. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14426. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14427. md5_append(&md5state,
  14428. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14429. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14430. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14431. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14432. md5_finish(&md5state, ssl_context_id);
  14433. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14434. (unsigned char *)ssl_context_id,
  14435. sizeof(ssl_context_id));
  14436. if (pem != NULL) {
  14437. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14438. return 0;
  14439. }
  14440. }
  14441. /* Should we support client certificates? */
  14442. /* Default is "no". */
  14443. should_verify_peer = 0;
  14444. peer_certificate_optional = 0;
  14445. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14446. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14447. /* Yes, they are mandatory */
  14448. should_verify_peer = 1;
  14449. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14450. "optional")
  14451. == 0) {
  14452. /* Yes, they are optional */
  14453. should_verify_peer = 1;
  14454. peer_certificate_optional = 1;
  14455. }
  14456. }
  14457. use_default_verify_paths =
  14458. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14459. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14460. == 0);
  14461. if (should_verify_peer) {
  14462. ca_path = dom_ctx->config[SSL_CA_PATH];
  14463. ca_file = dom_ctx->config[SSL_CA_FILE];
  14464. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14465. != 1) {
  14466. mg_cry_ctx_internal(phys_ctx,
  14467. "SSL_CTX_load_verify_locations error: %s "
  14468. "ssl_verify_peer requires setting "
  14469. "either ssl_ca_path or ssl_ca_file. "
  14470. "Is any of them present in the "
  14471. ".conf file?",
  14472. ssl_error());
  14473. return 0;
  14474. }
  14475. if (peer_certificate_optional) {
  14476. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14477. } else {
  14478. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14479. SSL_VERIFY_PEER
  14480. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14481. NULL);
  14482. }
  14483. if (use_default_verify_paths
  14484. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14485. mg_cry_ctx_internal(phys_ctx,
  14486. "SSL_CTX_set_default_verify_paths error: %s",
  14487. ssl_error());
  14488. return 0;
  14489. }
  14490. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14491. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14492. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14493. }
  14494. }
  14495. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14496. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14497. dom_ctx->config[SSL_CIPHER_LIST])
  14498. != 1) {
  14499. mg_cry_ctx_internal(phys_ctx,
  14500. "SSL_CTX_set_cipher_list error: %s",
  14501. ssl_error());
  14502. }
  14503. }
  14504. /* SSL session caching */
  14505. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14506. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14507. : 0);
  14508. if (ssl_cache_timeout > 0) {
  14509. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14510. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14511. * default */
  14512. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14513. }
  14514. #if defined(USE_ALPN)
  14515. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14516. #if !defined(NO_SSL_DL)
  14517. if (!tls_feature_missing[TLS_ALPN])
  14518. #endif
  14519. {
  14520. init_alpn(phys_ctx, dom_ctx);
  14521. }
  14522. #endif
  14523. return 1;
  14524. }
  14525. /* Check if SSL is required.
  14526. * If so, dynamically load SSL library
  14527. * and set up ctx->ssl_ctx pointer. */
  14528. static int
  14529. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14530. {
  14531. void *ssl_ctx = 0;
  14532. int callback_ret;
  14533. const char *pem;
  14534. const char *chain;
  14535. char ebuf[128];
  14536. if (!phys_ctx) {
  14537. return 0;
  14538. }
  14539. if (!dom_ctx) {
  14540. dom_ctx = &(phys_ctx->dd);
  14541. }
  14542. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14543. /* No SSL port is set. No need to setup SSL. */
  14544. return 1;
  14545. }
  14546. /* Check for external SSL_CTX */
  14547. callback_ret =
  14548. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14549. ? 0
  14550. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14551. phys_ctx->user_data));
  14552. if (callback_ret < 0) {
  14553. /* Callback exists and returns <0: Initializing failed. */
  14554. mg_cry_ctx_internal(phys_ctx,
  14555. "external_ssl_ctx callback returned error: %i",
  14556. callback_ret);
  14557. return 0;
  14558. } else if (callback_ret > 0) {
  14559. /* Callback exists and returns >0: Initializing complete,
  14560. * civetweb should not modify the SSL context. */
  14561. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14562. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14563. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14564. return 0;
  14565. }
  14566. return 1;
  14567. }
  14568. /* If the callback does not exist or return 0, civetweb must initialize
  14569. * the SSL context. Handle "domain" callback next. */
  14570. /* Check for external domain SSL_CTX callback. */
  14571. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14572. ? 0
  14573. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14574. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14575. &ssl_ctx,
  14576. phys_ctx->user_data));
  14577. if (callback_ret < 0) {
  14578. /* Callback < 0: Error. Abort init. */
  14579. mg_cry_ctx_internal(
  14580. phys_ctx,
  14581. "external_ssl_ctx_domain callback returned error: %i",
  14582. callback_ret);
  14583. return 0;
  14584. } else if (callback_ret > 0) {
  14585. /* Callback > 0: Consider init done. */
  14586. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14587. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14588. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14589. return 0;
  14590. }
  14591. return 1;
  14592. }
  14593. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14594. * 0, CivetWeb should continue initializing SSL */
  14595. /* If PEM file is not specified and the init_ssl callbacks
  14596. * are not specified, setup will fail. */
  14597. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14598. && (phys_ctx->callbacks.init_ssl == NULL)
  14599. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14600. /* No certificate and no init_ssl callbacks:
  14601. * Essential data to set up TLS is missing.
  14602. */
  14603. mg_cry_ctx_internal(phys_ctx,
  14604. "Initializing SSL failed: -%s is not set",
  14605. config_options[SSL_CERTIFICATE].name);
  14606. return 0;
  14607. }
  14608. /* If a certificate chain is configured, use it. */
  14609. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14610. if (chain == NULL) {
  14611. /* Default: certificate chain in PEM file */
  14612. chain = pem;
  14613. }
  14614. if ((chain != NULL) && (*chain == 0)) {
  14615. /* If the chain is an empty string, don't use it. */
  14616. chain = NULL;
  14617. }
  14618. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14619. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14620. return 0;
  14621. }
  14622. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14623. }
  14624. static void
  14625. uninitialize_ssl(void)
  14626. {
  14627. #if defined(OPENSSL_API_1_1)
  14628. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14629. /* Shutdown according to
  14630. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14631. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14632. */
  14633. CONF_modules_unload(1);
  14634. #else
  14635. int i;
  14636. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14637. /* Shutdown according to
  14638. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14639. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14640. */
  14641. CRYPTO_set_locking_callback(NULL);
  14642. CRYPTO_set_id_callback(NULL);
  14643. ENGINE_cleanup();
  14644. CONF_modules_unload(1);
  14645. ERR_free_strings();
  14646. EVP_cleanup();
  14647. CRYPTO_cleanup_all_ex_data();
  14648. OPENSSL_REMOVE_THREAD_STATE();
  14649. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14650. pthread_mutex_destroy(&ssl_mutexes[i]);
  14651. }
  14652. mg_free(ssl_mutexes);
  14653. ssl_mutexes = NULL;
  14654. #endif /* OPENSSL_API_1_1 */
  14655. }
  14656. }
  14657. #endif /* !NO_SSL */
  14658. #if defined(USE_MBEDTLS)
  14659. /* Check if SSL is required.
  14660. * If so, set up ctx->ssl_ctx pointer. */
  14661. static int
  14662. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14663. {
  14664. if (!phys_ctx) {
  14665. return 0;
  14666. }
  14667. if (!dom_ctx) {
  14668. dom_ctx = &(phys_ctx->dd);
  14669. }
  14670. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14671. /* No SSL port is set. No need to setup SSL. */
  14672. return 1;
  14673. }
  14674. dom_ctx->ssl_ctx = mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14675. if (dom_ctx->ssl_ctx == NULL) {
  14676. fprintf(stderr, "ssl_ctx malloc failed\n");
  14677. return 0;
  14678. }
  14679. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14680. == 0
  14681. ? 1
  14682. : 0;
  14683. }
  14684. #endif /* USE_MBEDTLS */
  14685. #if !defined(NO_FILESYSTEMS)
  14686. static int
  14687. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14688. {
  14689. if (phys_ctx) {
  14690. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14691. const char *path;
  14692. struct mg_connection fc;
  14693. if (!dom_ctx) {
  14694. dom_ctx = &(phys_ctx->dd);
  14695. }
  14696. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14697. if ((path != NULL)
  14698. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14699. mg_cry_ctx_internal(phys_ctx,
  14700. "Cannot open %s: %s",
  14701. path,
  14702. strerror(ERRNO));
  14703. return 0;
  14704. }
  14705. return 1;
  14706. }
  14707. return 0;
  14708. }
  14709. #endif /* NO_FILESYSTEMS */
  14710. static int
  14711. set_acl_option(struct mg_context *phys_ctx)
  14712. {
  14713. union usa sa;
  14714. memset(&sa, 0, sizeof(sa));
  14715. #if defined(USE_IPV6)
  14716. sa.sin6.sin6_family = AF_INET6;
  14717. #else
  14718. sa.sin.sin_family = AF_INET;
  14719. #endif
  14720. return check_acl(phys_ctx, &sa) != -1;
  14721. }
  14722. static void
  14723. reset_per_request_attributes(struct mg_connection *conn)
  14724. {
  14725. if (!conn) {
  14726. return;
  14727. }
  14728. conn->num_bytes_sent = conn->consumed_content = 0;
  14729. conn->path_info = NULL;
  14730. conn->status_code = -1;
  14731. conn->content_len = -1;
  14732. conn->is_chunked = 0;
  14733. conn->must_close = 0;
  14734. conn->request_len = 0;
  14735. conn->request_state = 0;
  14736. conn->throttle = 0;
  14737. conn->accept_gzip = 0;
  14738. conn->response_info.content_length = conn->request_info.content_length = -1;
  14739. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14740. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14741. conn->response_info.status_text = NULL;
  14742. conn->response_info.status_code = 0;
  14743. conn->request_info.remote_user = NULL;
  14744. conn->request_info.request_method = NULL;
  14745. conn->request_info.request_uri = NULL;
  14746. conn->request_info.local_uri = NULL;
  14747. #if defined(MG_LEGACY_INTERFACE)
  14748. /* Legacy before split into local_uri and request_uri */
  14749. conn->request_info.uri = NULL;
  14750. #endif
  14751. }
  14752. static int
  14753. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14754. {
  14755. if (setsockopt(sock,
  14756. IPPROTO_TCP,
  14757. TCP_NODELAY,
  14758. (SOCK_OPT_TYPE)&nodelay_on,
  14759. sizeof(nodelay_on))
  14760. != 0) {
  14761. /* Error */
  14762. return 1;
  14763. }
  14764. /* OK */
  14765. return 0;
  14766. }
  14767. #if !defined(__ZEPHYR__)
  14768. static void
  14769. close_socket_gracefully(struct mg_connection *conn)
  14770. {
  14771. #if defined(_WIN32)
  14772. char buf[MG_BUF_LEN];
  14773. int n;
  14774. #endif
  14775. struct linger linger;
  14776. int error_code = 0;
  14777. int linger_timeout = -2;
  14778. socklen_t opt_len = sizeof(error_code);
  14779. if (!conn) {
  14780. return;
  14781. }
  14782. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14783. * "Note that enabling a nonzero timeout on a nonblocking socket
  14784. * is not recommended.", so set it to blocking now */
  14785. set_blocking_mode(conn->client.sock);
  14786. /* Send FIN to the client */
  14787. shutdown(conn->client.sock, SHUTDOWN_WR);
  14788. #if defined(_WIN32)
  14789. /* Read and discard pending incoming data. If we do not do that and
  14790. * close
  14791. * the socket, the data in the send buffer may be discarded. This
  14792. * behaviour is seen on Windows, when client keeps sending data
  14793. * when server decides to close the connection; then when client
  14794. * does recv() it gets no data back. */
  14795. do {
  14796. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14797. } while (n > 0);
  14798. #endif
  14799. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14800. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14801. }
  14802. /* Set linger option according to configuration */
  14803. if (linger_timeout >= 0) {
  14804. /* Set linger option to avoid socket hanging out after close. This
  14805. * prevent ephemeral port exhaust problem under high QPS. */
  14806. linger.l_onoff = 1;
  14807. #if defined(_MSC_VER)
  14808. #pragma warning(push)
  14809. #pragma warning(disable : 4244)
  14810. #endif
  14811. #if defined(GCC_DIAGNOSTIC)
  14812. #pragma GCC diagnostic push
  14813. #pragma GCC diagnostic ignored "-Wconversion"
  14814. #endif
  14815. /* Data type of linger structure elements may differ,
  14816. * so we don't know what cast we need here.
  14817. * Disable type conversion warnings. */
  14818. linger.l_linger = (linger_timeout + 999) / 1000;
  14819. #if defined(GCC_DIAGNOSTIC)
  14820. #pragma GCC diagnostic pop
  14821. #endif
  14822. #if defined(_MSC_VER)
  14823. #pragma warning(pop)
  14824. #endif
  14825. } else {
  14826. linger.l_onoff = 0;
  14827. linger.l_linger = 0;
  14828. }
  14829. if (linger_timeout < -1) {
  14830. /* Default: don't configure any linger */
  14831. } else if (getsockopt(conn->client.sock,
  14832. SOL_SOCKET,
  14833. SO_ERROR,
  14834. #if defined(_WIN32) /* WinSock uses different data type here */
  14835. (char *)&error_code,
  14836. #else
  14837. &error_code,
  14838. #endif
  14839. &opt_len)
  14840. != 0) {
  14841. /* Cannot determine if socket is already closed. This should
  14842. * not occur and never did in a test. Log an error message
  14843. * and continue. */
  14844. mg_cry_internal(conn,
  14845. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14846. __func__,
  14847. strerror(ERRNO));
  14848. #if defined(_WIN32)
  14849. } else if (error_code == WSAECONNRESET) {
  14850. #else
  14851. } else if (error_code == ECONNRESET) {
  14852. #endif
  14853. /* Socket already closed by client/peer, close socket without linger
  14854. */
  14855. } else {
  14856. /* Set linger timeout */
  14857. if (setsockopt(conn->client.sock,
  14858. SOL_SOCKET,
  14859. SO_LINGER,
  14860. (char *)&linger,
  14861. sizeof(linger))
  14862. != 0) {
  14863. mg_cry_internal(
  14864. conn,
  14865. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14866. __func__,
  14867. linger.l_onoff,
  14868. linger.l_linger,
  14869. strerror(ERRNO));
  14870. }
  14871. }
  14872. /* Now we know that our FIN is ACK-ed, safe to close */
  14873. closesocket(conn->client.sock);
  14874. conn->client.sock = INVALID_SOCKET;
  14875. }
  14876. #endif
  14877. static void
  14878. close_connection(struct mg_connection *conn)
  14879. {
  14880. #if defined(USE_SERVER_STATS)
  14881. conn->conn_state = 6; /* to close */
  14882. #endif
  14883. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14884. if (conn->lua_websocket_state) {
  14885. lua_websocket_close(conn, conn->lua_websocket_state);
  14886. conn->lua_websocket_state = NULL;
  14887. }
  14888. #endif
  14889. mg_lock_connection(conn);
  14890. /* Set close flag, so keep-alive loops will stop */
  14891. conn->must_close = 1;
  14892. /* call the connection_close callback if assigned */
  14893. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14894. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14895. conn->phys_ctx->callbacks.connection_close(conn);
  14896. }
  14897. }
  14898. /* Reset user data, after close callback is called.
  14899. * Do not reuse it. If the user needs a destructor,
  14900. * it must be done in the connection_close callback. */
  14901. mg_set_user_connection_data(conn, NULL);
  14902. #if defined(USE_SERVER_STATS)
  14903. conn->conn_state = 7; /* closing */
  14904. #endif
  14905. #if defined(USE_MBEDTLS)
  14906. if (conn->ssl != NULL) {
  14907. mbed_ssl_close(conn->ssl);
  14908. mg_free(conn->ssl);
  14909. conn->ssl = NULL;
  14910. }
  14911. #endif
  14912. #if !defined(NO_SSL)
  14913. if (conn->ssl != NULL) {
  14914. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14915. */
  14916. SSL_shutdown(conn->ssl);
  14917. SSL_free(conn->ssl);
  14918. OPENSSL_REMOVE_THREAD_STATE();
  14919. conn->ssl = NULL;
  14920. }
  14921. #endif
  14922. if (conn->client.sock != INVALID_SOCKET) {
  14923. #if defined(__ZEPHYR__)
  14924. closesocket(conn->client.sock);
  14925. #else
  14926. close_socket_gracefully(conn);
  14927. #endif
  14928. conn->client.sock = INVALID_SOCKET;
  14929. }
  14930. mg_unlock_connection(conn);
  14931. #if defined(USE_SERVER_STATS)
  14932. conn->conn_state = 8; /* closed */
  14933. #endif
  14934. }
  14935. void
  14936. mg_close_connection(struct mg_connection *conn)
  14937. {
  14938. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14939. return;
  14940. }
  14941. #if defined(USE_WEBSOCKET)
  14942. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14943. if (conn->in_websocket_handling) {
  14944. /* Set close flag, so the server thread can exit. */
  14945. conn->must_close = 1;
  14946. return;
  14947. }
  14948. }
  14949. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14950. unsigned int i;
  14951. /* client context: loops must end */
  14952. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14953. conn->must_close = 1;
  14954. /* We need to get the client thread out of the select/recv call
  14955. * here. */
  14956. /* Since we use a sleep quantum of some seconds to check for recv
  14957. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14958. /* join worker thread */
  14959. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14960. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14961. }
  14962. }
  14963. #endif /* defined(USE_WEBSOCKET) */
  14964. close_connection(conn);
  14965. #if !defined(NO_SSL)
  14966. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14967. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14968. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14969. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14970. }
  14971. #endif
  14972. #if defined(USE_WEBSOCKET)
  14973. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14974. mg_free(conn->phys_ctx->worker_threadids);
  14975. (void)pthread_mutex_destroy(&conn->mutex);
  14976. mg_free(conn);
  14977. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14978. (void)pthread_mutex_destroy(&conn->mutex);
  14979. mg_free(conn);
  14980. }
  14981. #else
  14982. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14983. (void)pthread_mutex_destroy(&conn->mutex);
  14984. mg_free(conn);
  14985. }
  14986. #endif /* defined(USE_WEBSOCKET) */
  14987. }
  14988. static struct mg_connection *
  14989. mg_connect_client_impl(const struct mg_client_options *client_options,
  14990. int use_ssl,
  14991. char *ebuf,
  14992. size_t ebuf_len)
  14993. {
  14994. struct mg_connection *conn = NULL;
  14995. SOCKET sock;
  14996. union usa sa;
  14997. struct sockaddr *psa;
  14998. socklen_t len;
  14999. unsigned max_req_size =
  15000. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15001. /* Size of structures, aligned to 8 bytes */
  15002. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15003. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15004. conn =
  15005. (struct mg_connection *)mg_calloc(1,
  15006. conn_size + ctx_size + max_req_size);
  15007. if (conn == NULL) {
  15008. mg_snprintf(NULL,
  15009. NULL, /* No truncation check for ebuf */
  15010. ebuf,
  15011. ebuf_len,
  15012. "calloc(): %s",
  15013. strerror(ERRNO));
  15014. return NULL;
  15015. }
  15016. #if defined(GCC_DIAGNOSTIC)
  15017. #pragma GCC diagnostic push
  15018. #pragma GCC diagnostic ignored "-Wcast-align"
  15019. #endif /* defined(GCC_DIAGNOSTIC) */
  15020. /* conn_size is aligned to 8 bytes */
  15021. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15022. #if defined(GCC_DIAGNOSTIC)
  15023. #pragma GCC diagnostic pop
  15024. #endif /* defined(GCC_DIAGNOSTIC) */
  15025. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15026. conn->buf_size = (int)max_req_size;
  15027. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15028. conn->dom_ctx = &(conn->phys_ctx->dd);
  15029. if (!connect_socket(conn->phys_ctx,
  15030. client_options->host,
  15031. client_options->port,
  15032. use_ssl,
  15033. ebuf,
  15034. ebuf_len,
  15035. &sock,
  15036. &sa)) {
  15037. /* ebuf is set by connect_socket,
  15038. * free all memory and return NULL; */
  15039. mg_free(conn);
  15040. return NULL;
  15041. }
  15042. #if !defined(NO_SSL)
  15043. #if defined(OPENSSL_API_1_1)
  15044. if (use_ssl
  15045. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15046. == NULL) {
  15047. mg_snprintf(NULL,
  15048. NULL, /* No truncation check for ebuf */
  15049. ebuf,
  15050. ebuf_len,
  15051. "SSL_CTX_new error: %s",
  15052. ssl_error());
  15053. closesocket(sock);
  15054. mg_free(conn);
  15055. return NULL;
  15056. }
  15057. #else
  15058. if (use_ssl
  15059. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15060. == NULL) {
  15061. mg_snprintf(NULL,
  15062. NULL, /* No truncation check for ebuf */
  15063. ebuf,
  15064. ebuf_len,
  15065. "SSL_CTX_new error: %s",
  15066. ssl_error());
  15067. closesocket(sock);
  15068. mg_free(conn);
  15069. return NULL;
  15070. }
  15071. #endif /* OPENSSL_API_1_1 */
  15072. #endif /* NO_SSL */
  15073. #if defined(USE_IPV6)
  15074. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15075. : sizeof(conn->client.rsa.sin6);
  15076. psa = (sa.sa.sa_family == AF_INET)
  15077. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15078. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15079. #else
  15080. len = sizeof(conn->client.rsa.sin);
  15081. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15082. #endif
  15083. conn->client.sock = sock;
  15084. conn->client.lsa = sa;
  15085. if (getsockname(sock, psa, &len) != 0) {
  15086. mg_cry_internal(conn,
  15087. "%s: getsockname() failed: %s",
  15088. __func__,
  15089. strerror(ERRNO));
  15090. }
  15091. conn->client.is_ssl = use_ssl ? 1 : 0;
  15092. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15093. mg_snprintf(NULL,
  15094. NULL, /* No truncation check for ebuf */
  15095. ebuf,
  15096. ebuf_len,
  15097. "Can not create mutex");
  15098. #if !defined(NO_SSL)
  15099. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15100. #endif
  15101. closesocket(sock);
  15102. mg_free(conn);
  15103. return NULL;
  15104. }
  15105. #if !defined(NO_SSL)
  15106. if (use_ssl) {
  15107. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15108. * SSL_CTX_set_verify call is needed to switch off server
  15109. * certificate checking, which is off by default in OpenSSL and
  15110. * on in yaSSL. */
  15111. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15112. * SSL_VERIFY_PEER, verify_ssl_server); */
  15113. if (client_options->client_cert) {
  15114. if (!ssl_use_pem_file(conn->phys_ctx,
  15115. conn->dom_ctx,
  15116. client_options->client_cert,
  15117. NULL)) {
  15118. mg_snprintf(NULL,
  15119. NULL, /* No truncation check for ebuf */
  15120. ebuf,
  15121. ebuf_len,
  15122. "Can not use SSL client certificate");
  15123. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15124. closesocket(sock);
  15125. mg_free(conn);
  15126. return NULL;
  15127. }
  15128. }
  15129. if (client_options->server_cert) {
  15130. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15131. client_options->server_cert,
  15132. NULL)
  15133. != 1) {
  15134. mg_cry_internal(conn,
  15135. "SSL_CTX_load_verify_locations error: %s ",
  15136. ssl_error());
  15137. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15138. closesocket(sock);
  15139. mg_free(conn);
  15140. return NULL;
  15141. }
  15142. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15143. } else {
  15144. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15145. }
  15146. if (!sslize(conn, SSL_connect, client_options)) {
  15147. mg_snprintf(NULL,
  15148. NULL, /* No truncation check for ebuf */
  15149. ebuf,
  15150. ebuf_len,
  15151. "SSL connection error");
  15152. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15153. closesocket(sock);
  15154. mg_free(conn);
  15155. return NULL;
  15156. }
  15157. }
  15158. #endif
  15159. return conn;
  15160. }
  15161. CIVETWEB_API struct mg_connection *
  15162. mg_connect_client_secure(const struct mg_client_options *client_options,
  15163. char *error_buffer,
  15164. size_t error_buffer_size)
  15165. {
  15166. return mg_connect_client_impl(client_options,
  15167. 1,
  15168. error_buffer,
  15169. error_buffer_size);
  15170. }
  15171. struct mg_connection *
  15172. mg_connect_client(const char *host,
  15173. int port,
  15174. int use_ssl,
  15175. char *error_buffer,
  15176. size_t error_buffer_size)
  15177. {
  15178. struct mg_client_options opts;
  15179. memset(&opts, 0, sizeof(opts));
  15180. opts.host = host;
  15181. opts.port = port;
  15182. return mg_connect_client_impl(&opts,
  15183. use_ssl,
  15184. error_buffer,
  15185. error_buffer_size);
  15186. }
  15187. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15188. struct mg_connection *
  15189. mg_connect_client2(const char *host,
  15190. const char *protocol,
  15191. int port,
  15192. const char *path,
  15193. struct mg_init_data *init,
  15194. struct mg_error_data *error)
  15195. {
  15196. int is_ssl, is_ws;
  15197. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15198. if (error != NULL) {
  15199. error->code = 0;
  15200. if (error->text_buffer_size > 0) {
  15201. *error->text = 0;
  15202. }
  15203. }
  15204. if ((host == NULL) || (protocol == NULL)) {
  15205. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15206. mg_snprintf(NULL,
  15207. NULL, /* No truncation check for error buffers */
  15208. error->text,
  15209. error->text_buffer_size,
  15210. "%s",
  15211. "Invalid parameters");
  15212. }
  15213. return NULL;
  15214. }
  15215. /* check all known protocolls */
  15216. if (!mg_strcasecmp(protocol, "http")) {
  15217. is_ssl = 0;
  15218. is_ws = 0;
  15219. } else if (!mg_strcasecmp(protocol, "https")) {
  15220. is_ssl = 1;
  15221. is_ws = 0;
  15222. #if defined(USE_WEBSOCKET)
  15223. } else if (!mg_strcasecmp(protocol, "ws")) {
  15224. is_ssl = 0;
  15225. is_ws = 1;
  15226. } else if (!mg_strcasecmp(protocol, "wss")) {
  15227. is_ssl = 1;
  15228. is_ws = 1;
  15229. #endif
  15230. } else {
  15231. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15232. mg_snprintf(NULL,
  15233. NULL, /* No truncation check for error buffers */
  15234. error->text,
  15235. error->text_buffer_size,
  15236. "Protocol %s not supported",
  15237. protocol);
  15238. }
  15239. return NULL;
  15240. }
  15241. /* TODO: The current implementation here just calls the old
  15242. * implementations, without using any new options. This is just a first
  15243. * step to test the new interfaces. */
  15244. #if defined(USE_WEBSOCKET)
  15245. if (is_ws) {
  15246. /* TODO: implement all options */
  15247. return mg_connect_websocket_client(
  15248. host,
  15249. port,
  15250. is_ssl,
  15251. ((error != NULL) ? error->text : NULL),
  15252. ((error != NULL) ? error->text_buffer_size : 0),
  15253. (path ? path : ""),
  15254. NULL /* TODO: origin */,
  15255. experimental_websocket_client_data_wrapper,
  15256. experimental_websocket_client_close_wrapper,
  15257. (void *)init->callbacks);
  15258. }
  15259. #endif
  15260. /* TODO: all additional options */
  15261. struct mg_client_options opts;
  15262. memset(&opts, 0, sizeof(opts));
  15263. opts.host = host;
  15264. opts.port = port;
  15265. return mg_connect_client_impl(&opts,
  15266. is_ssl,
  15267. ((error != NULL) ? error->text : NULL),
  15268. ((error != NULL) ? error->text_buffer_size
  15269. : 0));
  15270. }
  15271. #endif
  15272. static const struct {
  15273. const char *proto;
  15274. size_t proto_len;
  15275. unsigned default_port;
  15276. } abs_uri_protocols[] = {{"http://", 7, 80},
  15277. {"https://", 8, 443},
  15278. {"ws://", 5, 80},
  15279. {"wss://", 6, 443},
  15280. {NULL, 0, 0}};
  15281. /* Check if the uri is valid.
  15282. * return 0 for invalid uri,
  15283. * return 1 for *,
  15284. * return 2 for relative uri,
  15285. * return 3 for absolute uri without port,
  15286. * return 4 for absolute uri with port */
  15287. static int
  15288. get_uri_type(const char *uri)
  15289. {
  15290. int i;
  15291. const char *hostend, *portbegin;
  15292. char *portend;
  15293. unsigned long port;
  15294. /* According to the HTTP standard
  15295. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15296. * URI can be an asterisk (*) or should start with slash (relative uri),
  15297. * or it should start with the protocol (absolute uri). */
  15298. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15299. /* asterisk */
  15300. return 1;
  15301. }
  15302. /* Valid URIs according to RFC 3986
  15303. * (https://www.ietf.org/rfc/rfc3986.txt)
  15304. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15305. * and unreserved characters A-Z a-z 0-9 and -._~
  15306. * and % encoded symbols.
  15307. */
  15308. for (i = 0; uri[i] != 0; i++) {
  15309. if (uri[i] < 33) {
  15310. /* control characters and spaces are invalid */
  15311. return 0;
  15312. }
  15313. /* Allow everything else here (See #894) */
  15314. }
  15315. /* A relative uri starts with a / character */
  15316. if (uri[0] == '/') {
  15317. /* relative uri */
  15318. return 2;
  15319. }
  15320. /* It could be an absolute uri: */
  15321. /* This function only checks if the uri is valid, not if it is
  15322. * addressing the current server. So civetweb can also be used
  15323. * as a proxy server. */
  15324. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15325. if (mg_strncasecmp(uri,
  15326. abs_uri_protocols[i].proto,
  15327. abs_uri_protocols[i].proto_len)
  15328. == 0) {
  15329. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15330. if (!hostend) {
  15331. return 0;
  15332. }
  15333. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15334. if (!portbegin) {
  15335. return 3;
  15336. }
  15337. port = strtoul(portbegin + 1, &portend, 10);
  15338. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15339. return 0;
  15340. }
  15341. return 4;
  15342. }
  15343. }
  15344. return 0;
  15345. }
  15346. /* Return NULL or the relative uri at the current server */
  15347. static const char *
  15348. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15349. {
  15350. const char *server_domain;
  15351. size_t server_domain_len;
  15352. size_t request_domain_len = 0;
  15353. unsigned long port = 0;
  15354. int i, auth_domain_check_enabled;
  15355. const char *hostbegin = NULL;
  15356. const char *hostend = NULL;
  15357. const char *portbegin;
  15358. char *portend;
  15359. auth_domain_check_enabled =
  15360. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15361. /* DNS is case insensitive, so use case insensitive string compare here
  15362. */
  15363. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15364. if (mg_strncasecmp(uri,
  15365. abs_uri_protocols[i].proto,
  15366. abs_uri_protocols[i].proto_len)
  15367. == 0) {
  15368. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15369. hostend = strchr(hostbegin, '/');
  15370. if (!hostend) {
  15371. return 0;
  15372. }
  15373. portbegin = strchr(hostbegin, ':');
  15374. if ((!portbegin) || (portbegin > hostend)) {
  15375. port = abs_uri_protocols[i].default_port;
  15376. request_domain_len = (size_t)(hostend - hostbegin);
  15377. } else {
  15378. port = strtoul(portbegin + 1, &portend, 10);
  15379. if ((portend != hostend) || (port <= 0)
  15380. || !is_valid_port(port)) {
  15381. return 0;
  15382. }
  15383. request_domain_len = (size_t)(portbegin - hostbegin);
  15384. }
  15385. /* protocol found, port set */
  15386. break;
  15387. }
  15388. }
  15389. if (!port) {
  15390. /* port remains 0 if the protocol is not found */
  15391. return 0;
  15392. }
  15393. /* Check if the request is directed to a different server. */
  15394. /* First check if the port is the same. */
  15395. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15396. /* Request is directed to a different port */
  15397. return 0;
  15398. }
  15399. /* Finally check if the server corresponds to the authentication
  15400. * domain of the server (the server domain).
  15401. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15402. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15403. * but do not allow substrings (like
  15404. * http://notmydomain.com/path/file.ext
  15405. * or http://mydomain.com.fake/path/file.ext).
  15406. */
  15407. if (auth_domain_check_enabled) {
  15408. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15409. server_domain_len = strlen(server_domain);
  15410. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15411. return 0;
  15412. }
  15413. if ((request_domain_len == server_domain_len)
  15414. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15415. /* Request is directed to this server - full name match. */
  15416. } else {
  15417. if (request_domain_len < (server_domain_len + 2)) {
  15418. /* Request is directed to another server: The server name
  15419. * is longer than the request name.
  15420. * Drop this case here to avoid overflows in the
  15421. * following checks. */
  15422. return 0;
  15423. }
  15424. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15425. /* Request is directed to another server: It could be a
  15426. * substring
  15427. * like notmyserver.com */
  15428. return 0;
  15429. }
  15430. if (0
  15431. != memcmp(server_domain,
  15432. hostbegin + request_domain_len - server_domain_len,
  15433. server_domain_len)) {
  15434. /* Request is directed to another server:
  15435. * The server name is different. */
  15436. return 0;
  15437. }
  15438. }
  15439. }
  15440. return hostend;
  15441. }
  15442. static int
  15443. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15444. {
  15445. if (ebuf_len > 0) {
  15446. ebuf[0] = '\0';
  15447. }
  15448. *err = 0;
  15449. reset_per_request_attributes(conn);
  15450. if (!conn) {
  15451. mg_snprintf(conn,
  15452. NULL, /* No truncation check for ebuf */
  15453. ebuf,
  15454. ebuf_len,
  15455. "%s",
  15456. "Internal error");
  15457. *err = 500;
  15458. return 0;
  15459. }
  15460. /* Set the time the request was received. This value should be used for
  15461. * timeouts. */
  15462. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15463. conn->request_len =
  15464. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15465. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15466. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15467. mg_snprintf(conn,
  15468. NULL, /* No truncation check for ebuf */
  15469. ebuf,
  15470. ebuf_len,
  15471. "%s",
  15472. "Invalid message size");
  15473. *err = 500;
  15474. return 0;
  15475. }
  15476. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15477. mg_snprintf(conn,
  15478. NULL, /* No truncation check for ebuf */
  15479. ebuf,
  15480. ebuf_len,
  15481. "%s",
  15482. "Message too large");
  15483. *err = 413;
  15484. return 0;
  15485. }
  15486. if (conn->request_len <= 0) {
  15487. if (conn->data_len > 0) {
  15488. mg_snprintf(conn,
  15489. NULL, /* No truncation check for ebuf */
  15490. ebuf,
  15491. ebuf_len,
  15492. "%s",
  15493. "Malformed message");
  15494. *err = 400;
  15495. } else {
  15496. /* Server did not recv anything -> just close the connection */
  15497. conn->must_close = 1;
  15498. mg_snprintf(conn,
  15499. NULL, /* No truncation check for ebuf */
  15500. ebuf,
  15501. ebuf_len,
  15502. "%s",
  15503. "No data received");
  15504. *err = 0;
  15505. }
  15506. return 0;
  15507. }
  15508. return 1;
  15509. }
  15510. static int
  15511. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15512. {
  15513. const char *cl;
  15514. conn->connection_type =
  15515. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15516. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15517. return 0;
  15518. }
  15519. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15520. <= 0) {
  15521. mg_snprintf(conn,
  15522. NULL, /* No truncation check for ebuf */
  15523. ebuf,
  15524. ebuf_len,
  15525. "%s",
  15526. "Bad request");
  15527. *err = 400;
  15528. return 0;
  15529. }
  15530. /* Message is a valid request */
  15531. if (!switch_domain_context(conn)) {
  15532. mg_snprintf(conn,
  15533. NULL, /* No truncation check for ebuf */
  15534. ebuf,
  15535. ebuf_len,
  15536. "%s",
  15537. "Bad request: Host mismatch");
  15538. *err = 400;
  15539. return 0;
  15540. }
  15541. if (((cl = get_header(conn->request_info.http_headers,
  15542. conn->request_info.num_headers,
  15543. "Transfer-Encoding"))
  15544. != NULL)
  15545. && mg_strcasecmp(cl, "identity")) {
  15546. if (mg_strcasecmp(cl, "chunked")) {
  15547. mg_snprintf(conn,
  15548. NULL, /* No truncation check for ebuf */
  15549. ebuf,
  15550. ebuf_len,
  15551. "%s",
  15552. "Bad request");
  15553. *err = 400;
  15554. return 0;
  15555. }
  15556. conn->is_chunked = 1;
  15557. conn->content_len = 0; /* not yet read */
  15558. } else if ((cl = get_header(conn->request_info.http_headers,
  15559. conn->request_info.num_headers,
  15560. "Content-Length"))
  15561. != NULL) {
  15562. /* Request has content length set */
  15563. char *endptr = NULL;
  15564. conn->content_len = strtoll(cl, &endptr, 10);
  15565. if ((endptr == cl) || (conn->content_len < 0)) {
  15566. mg_snprintf(conn,
  15567. NULL, /* No truncation check for ebuf */
  15568. ebuf,
  15569. ebuf_len,
  15570. "%s",
  15571. "Bad request");
  15572. *err = 411;
  15573. return 0;
  15574. }
  15575. /* Publish the content length back to the request info. */
  15576. conn->request_info.content_length = conn->content_len;
  15577. } else {
  15578. /* There is no exception, see RFC7230. */
  15579. conn->content_len = 0;
  15580. }
  15581. return 1;
  15582. }
  15583. /* conn is assumed to be valid in this internal function */
  15584. static int
  15585. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15586. {
  15587. const char *cl;
  15588. conn->connection_type =
  15589. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15590. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15591. return 0;
  15592. }
  15593. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15594. <= 0) {
  15595. mg_snprintf(conn,
  15596. NULL, /* No truncation check for ebuf */
  15597. ebuf,
  15598. ebuf_len,
  15599. "%s",
  15600. "Bad response");
  15601. *err = 400;
  15602. return 0;
  15603. }
  15604. /* Message is a valid response */
  15605. if (((cl = get_header(conn->response_info.http_headers,
  15606. conn->response_info.num_headers,
  15607. "Transfer-Encoding"))
  15608. != NULL)
  15609. && mg_strcasecmp(cl, "identity")) {
  15610. if (mg_strcasecmp(cl, "chunked")) {
  15611. mg_snprintf(conn,
  15612. NULL, /* No truncation check for ebuf */
  15613. ebuf,
  15614. ebuf_len,
  15615. "%s",
  15616. "Bad request");
  15617. *err = 400;
  15618. return 0;
  15619. }
  15620. conn->is_chunked = 1;
  15621. conn->content_len = 0; /* not yet read */
  15622. } else if ((cl = get_header(conn->response_info.http_headers,
  15623. conn->response_info.num_headers,
  15624. "Content-Length"))
  15625. != NULL) {
  15626. char *endptr = NULL;
  15627. conn->content_len = strtoll(cl, &endptr, 10);
  15628. if ((endptr == cl) || (conn->content_len < 0)) {
  15629. mg_snprintf(conn,
  15630. NULL, /* No truncation check for ebuf */
  15631. ebuf,
  15632. ebuf_len,
  15633. "%s",
  15634. "Bad request");
  15635. *err = 411;
  15636. return 0;
  15637. }
  15638. /* Publish the content length back to the response info. */
  15639. conn->response_info.content_length = conn->content_len;
  15640. /* TODO: check if it is still used in response_info */
  15641. conn->request_info.content_length = conn->content_len;
  15642. /* TODO: we should also consider HEAD method */
  15643. if (conn->response_info.status_code == 304) {
  15644. conn->content_len = 0;
  15645. }
  15646. } else {
  15647. /* TODO: we should also consider HEAD method */
  15648. if (((conn->response_info.status_code >= 100)
  15649. && (conn->response_info.status_code <= 199))
  15650. || (conn->response_info.status_code == 204)
  15651. || (conn->response_info.status_code == 304)) {
  15652. conn->content_len = 0;
  15653. } else {
  15654. conn->content_len = -1; /* unknown content length */
  15655. }
  15656. }
  15657. return 1;
  15658. }
  15659. int
  15660. mg_get_response(struct mg_connection *conn,
  15661. char *ebuf,
  15662. size_t ebuf_len,
  15663. int timeout)
  15664. {
  15665. int err, ret;
  15666. char txt[32]; /* will not overflow */
  15667. char *save_timeout;
  15668. char *new_timeout;
  15669. if (ebuf_len > 0) {
  15670. ebuf[0] = '\0';
  15671. }
  15672. if (!conn) {
  15673. mg_snprintf(conn,
  15674. NULL, /* No truncation check for ebuf */
  15675. ebuf,
  15676. ebuf_len,
  15677. "%s",
  15678. "Parameter error");
  15679. return -1;
  15680. }
  15681. /* Reset the previous responses */
  15682. conn->data_len = 0;
  15683. /* Implementation of API function for HTTP clients */
  15684. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15685. if (timeout >= 0) {
  15686. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15687. new_timeout = txt;
  15688. } else {
  15689. new_timeout = NULL;
  15690. }
  15691. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15692. ret = get_response(conn, ebuf, ebuf_len, &err);
  15693. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15694. #if defined(MG_LEGACY_INTERFACE)
  15695. /* TODO: 1) uri is deprecated;
  15696. * 2) here, ri.uri is the http response code */
  15697. conn->request_info.uri = conn->request_info.request_uri;
  15698. #endif
  15699. conn->request_info.local_uri = conn->request_info.request_uri;
  15700. /* TODO (mid): Define proper return values - maybe return length?
  15701. * For the first test use <0 for error and >0 for OK */
  15702. return (ret == 0) ? -1 : +1;
  15703. }
  15704. struct mg_connection *
  15705. mg_download(const char *host,
  15706. int port,
  15707. int use_ssl,
  15708. char *ebuf,
  15709. size_t ebuf_len,
  15710. const char *fmt,
  15711. ...)
  15712. {
  15713. struct mg_connection *conn;
  15714. va_list ap;
  15715. int i;
  15716. int reqerr;
  15717. if (ebuf_len > 0) {
  15718. ebuf[0] = '\0';
  15719. }
  15720. va_start(ap, fmt);
  15721. /* open a connection */
  15722. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15723. if (conn != NULL) {
  15724. i = mg_vprintf(conn, fmt, ap);
  15725. if (i <= 0) {
  15726. mg_snprintf(conn,
  15727. NULL, /* No truncation check for ebuf */
  15728. ebuf,
  15729. ebuf_len,
  15730. "%s",
  15731. "Error sending request");
  15732. } else {
  15733. /* make sure the buffer is clear */
  15734. conn->data_len = 0;
  15735. get_response(conn, ebuf, ebuf_len, &reqerr);
  15736. #if defined(MG_LEGACY_INTERFACE)
  15737. /* TODO: 1) uri is deprecated;
  15738. * 2) here, ri.uri is the http response code */
  15739. conn->request_info.uri = conn->request_info.request_uri;
  15740. #endif
  15741. conn->request_info.local_uri = conn->request_info.request_uri;
  15742. }
  15743. }
  15744. /* if an error occurred, close the connection */
  15745. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15746. mg_close_connection(conn);
  15747. conn = NULL;
  15748. }
  15749. va_end(ap);
  15750. return conn;
  15751. }
  15752. struct websocket_client_thread_data {
  15753. struct mg_connection *conn;
  15754. mg_websocket_data_handler data_handler;
  15755. mg_websocket_close_handler close_handler;
  15756. void *callback_data;
  15757. };
  15758. #if defined(USE_WEBSOCKET)
  15759. #if defined(_WIN32)
  15760. static unsigned __stdcall websocket_client_thread(void *data)
  15761. #else
  15762. static void *
  15763. websocket_client_thread(void *data)
  15764. #endif
  15765. {
  15766. struct websocket_client_thread_data *cdata =
  15767. (struct websocket_client_thread_data *)data;
  15768. void *user_thread_ptr = NULL;
  15769. #if !defined(_WIN32)
  15770. struct sigaction sa;
  15771. /* Ignore SIGPIPE */
  15772. memset(&sa, 0, sizeof(sa));
  15773. sa.sa_handler = SIG_IGN;
  15774. sigaction(SIGPIPE, &sa, NULL);
  15775. #endif
  15776. mg_set_thread_name("ws-clnt");
  15777. if (cdata->conn->phys_ctx) {
  15778. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15779. /* 3 indicates a websocket client thread */
  15780. /* TODO: check if conn->phys_ctx can be set */
  15781. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15782. cdata->conn->phys_ctx, 3);
  15783. }
  15784. }
  15785. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15786. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15787. if (cdata->close_handler != NULL) {
  15788. cdata->close_handler(cdata->conn, cdata->callback_data);
  15789. }
  15790. /* The websocket_client context has only this thread. If it runs out,
  15791. set the stop_flag to 2 (= "stopped"). */
  15792. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15793. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15794. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15795. 3,
  15796. user_thread_ptr);
  15797. }
  15798. mg_free((void *)cdata);
  15799. #if defined(_WIN32)
  15800. return 0;
  15801. #else
  15802. return NULL;
  15803. #endif
  15804. }
  15805. #endif
  15806. static struct mg_connection *
  15807. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15808. int use_ssl,
  15809. char *error_buffer,
  15810. size_t error_buffer_size,
  15811. const char *path,
  15812. const char *origin,
  15813. mg_websocket_data_handler data_func,
  15814. mg_websocket_close_handler close_func,
  15815. void *user_data)
  15816. {
  15817. struct mg_connection *conn = NULL;
  15818. #if defined(USE_WEBSOCKET)
  15819. struct websocket_client_thread_data *thread_data;
  15820. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15821. const char *handshake_req;
  15822. const char *host = client_options->host;
  15823. int i;
  15824. if (origin != NULL) {
  15825. handshake_req = "GET %s HTTP/1.1\r\n"
  15826. "Host: %s\r\n"
  15827. "Upgrade: websocket\r\n"
  15828. "Connection: Upgrade\r\n"
  15829. "Sec-WebSocket-Key: %s\r\n"
  15830. "Sec-WebSocket-Version: 13\r\n"
  15831. "Origin: %s\r\n"
  15832. "\r\n";
  15833. } else {
  15834. handshake_req = "GET %s HTTP/1.1\r\n"
  15835. "Host: %s\r\n"
  15836. "Upgrade: websocket\r\n"
  15837. "Connection: Upgrade\r\n"
  15838. "Sec-WebSocket-Key: %s\r\n"
  15839. "Sec-WebSocket-Version: 13\r\n"
  15840. "\r\n";
  15841. }
  15842. #if defined(__clang__)
  15843. #pragma clang diagnostic push
  15844. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15845. #endif
  15846. /* Establish the client connection and request upgrade */
  15847. conn = mg_connect_client_impl(client_options,
  15848. use_ssl,
  15849. error_buffer,
  15850. error_buffer_size);
  15851. /* Connection object will be null if something goes wrong */
  15852. if (conn == NULL) {
  15853. /* error_buffer should be already filled ... */
  15854. if (!error_buffer[0]) {
  15855. /* ... if not add an error message */
  15856. mg_snprintf(conn,
  15857. NULL, /* No truncation check for ebuf */
  15858. error_buffer,
  15859. error_buffer_size,
  15860. "Unexpected error");
  15861. }
  15862. return NULL;
  15863. }
  15864. i = mg_printf(conn, handshake_req, path, host, magic, origin);
  15865. if (i <= 0) {
  15866. mg_snprintf(conn,
  15867. NULL, /* No truncation check for ebuf */
  15868. error_buffer,
  15869. error_buffer_size,
  15870. "%s",
  15871. "Error sending request");
  15872. mg_close_connection(conn);
  15873. return NULL;
  15874. }
  15875. conn->data_len = 0;
  15876. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15877. mg_close_connection(conn);
  15878. return NULL;
  15879. }
  15880. conn->request_info.local_uri = conn->request_info.request_uri;
  15881. #if defined(__clang__)
  15882. #pragma clang diagnostic pop
  15883. #endif
  15884. if (conn->response_info.status_code != 101) {
  15885. /* We sent an "upgrade" request. For a correct websocket
  15886. * protocol handshake, we expect a "101 Continue" response.
  15887. * Otherwise it is a protocol violation. Maybe the HTTP
  15888. * Server does not know websockets. */
  15889. if (!*error_buffer) {
  15890. /* set an error, if not yet set */
  15891. mg_snprintf(conn,
  15892. NULL, /* No truncation check for ebuf */
  15893. error_buffer,
  15894. error_buffer_size,
  15895. "Unexpected server reply");
  15896. }
  15897. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15898. mg_close_connection(conn);
  15899. return NULL;
  15900. }
  15901. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15902. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15903. if (!thread_data) {
  15904. DEBUG_TRACE("%s\r\n", "Out of memory");
  15905. mg_close_connection(conn);
  15906. return NULL;
  15907. }
  15908. thread_data->conn = conn;
  15909. thread_data->data_handler = data_func;
  15910. thread_data->close_handler = close_func;
  15911. thread_data->callback_data = user_data;
  15912. conn->phys_ctx->worker_threadids =
  15913. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15914. if (!conn->phys_ctx->worker_threadids) {
  15915. DEBUG_TRACE("%s\r\n", "Out of memory");
  15916. mg_free(thread_data);
  15917. mg_close_connection(conn);
  15918. return NULL;
  15919. }
  15920. /* Now upgrade to ws/wss client context */
  15921. conn->phys_ctx->user_data = user_data;
  15922. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15923. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15924. /* Start a thread to read the websocket client connection
  15925. * This thread will automatically stop when mg_disconnect is
  15926. * called on the client connection */
  15927. if (mg_start_thread_with_id(websocket_client_thread,
  15928. thread_data,
  15929. conn->phys_ctx->worker_threadids)
  15930. != 0) {
  15931. conn->phys_ctx->cfg_worker_threads = 0;
  15932. mg_free(thread_data);
  15933. mg_close_connection(conn);
  15934. conn = NULL;
  15935. DEBUG_TRACE("%s",
  15936. "Websocket client connect thread could not be started\r\n");
  15937. }
  15938. #else
  15939. /* Appease "unused parameter" warnings */
  15940. (void)client_options;
  15941. (void)use_ssl;
  15942. (void)error_buffer;
  15943. (void)error_buffer_size;
  15944. (void)path;
  15945. (void)origin;
  15946. (void)user_data;
  15947. (void)data_func;
  15948. (void)close_func;
  15949. #endif
  15950. return conn;
  15951. }
  15952. struct mg_connection *
  15953. mg_connect_websocket_client(const char *host,
  15954. int port,
  15955. int use_ssl,
  15956. char *error_buffer,
  15957. size_t error_buffer_size,
  15958. const char *path,
  15959. const char *origin,
  15960. mg_websocket_data_handler data_func,
  15961. mg_websocket_close_handler close_func,
  15962. void *user_data)
  15963. {
  15964. struct mg_client_options client_options;
  15965. memset(&client_options, 0, sizeof(client_options));
  15966. client_options.host = host;
  15967. client_options.port = port;
  15968. return mg_connect_websocket_client_impl(&client_options,
  15969. use_ssl,
  15970. error_buffer,
  15971. error_buffer_size,
  15972. path,
  15973. origin,
  15974. data_func,
  15975. close_func,
  15976. user_data);
  15977. }
  15978. struct mg_connection *
  15979. mg_connect_websocket_client_secure(
  15980. const struct mg_client_options *client_options,
  15981. char *error_buffer,
  15982. size_t error_buffer_size,
  15983. const char *path,
  15984. const char *origin,
  15985. mg_websocket_data_handler data_func,
  15986. mg_websocket_close_handler close_func,
  15987. void *user_data)
  15988. {
  15989. if (!client_options) {
  15990. return NULL;
  15991. }
  15992. return mg_connect_websocket_client_impl(client_options,
  15993. 1,
  15994. error_buffer,
  15995. error_buffer_size,
  15996. path,
  15997. origin,
  15998. data_func,
  15999. close_func,
  16000. user_data);
  16001. }
  16002. /* Prepare connection data structure */
  16003. static void
  16004. init_connection(struct mg_connection *conn)
  16005. {
  16006. /* Is keep alive allowed by the server */
  16007. int keep_alive_enabled =
  16008. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16009. if (!keep_alive_enabled) {
  16010. conn->must_close = 1;
  16011. }
  16012. /* Important: on new connection, reset the receiving buffer. Credit
  16013. * goes to crule42. */
  16014. conn->data_len = 0;
  16015. conn->handled_requests = 0;
  16016. conn->connection_type = CONNECTION_TYPE_INVALID;
  16017. mg_set_user_connection_data(conn, NULL);
  16018. #if defined(USE_SERVER_STATS)
  16019. conn->conn_state = 2; /* init */
  16020. #endif
  16021. /* call the init_connection callback if assigned */
  16022. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16023. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16024. void *conn_data = NULL;
  16025. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16026. mg_set_user_connection_data(conn, conn_data);
  16027. }
  16028. }
  16029. }
  16030. /* Process a connection - may handle multiple requests
  16031. * using the same connection.
  16032. * Must be called with a valid connection (conn and
  16033. * conn->phys_ctx must be valid).
  16034. */
  16035. static void
  16036. process_new_connection(struct mg_connection *conn)
  16037. {
  16038. struct mg_request_info *ri = &conn->request_info;
  16039. int keep_alive, discard_len;
  16040. char ebuf[100];
  16041. const char *hostend;
  16042. int reqerr, uri_type;
  16043. #if defined(USE_SERVER_STATS)
  16044. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16045. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16046. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16047. #endif
  16048. DEBUG_TRACE("Start processing connection from %s",
  16049. conn->request_info.remote_addr);
  16050. /* Loop over multiple requests sent using the same connection
  16051. * (while "keep alive"). */
  16052. do {
  16053. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16054. conn->handled_requests + 1);
  16055. #if defined(USE_SERVER_STATS)
  16056. conn->conn_state = 3; /* ready */
  16057. #endif
  16058. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16059. /* The request sent by the client could not be understood by
  16060. * the server, or it was incomplete or a timeout. Send an
  16061. * error message and close the connection. */
  16062. if (reqerr > 0) {
  16063. DEBUG_ASSERT(ebuf[0] != '\0');
  16064. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16065. }
  16066. } else if (strcmp(ri->http_version, "1.0")
  16067. && strcmp(ri->http_version, "1.1")) {
  16068. /* HTTP/2 is not allowed here */
  16069. mg_snprintf(conn,
  16070. NULL, /* No truncation check for ebuf */
  16071. ebuf,
  16072. sizeof(ebuf),
  16073. "Bad HTTP version: [%s]",
  16074. ri->http_version);
  16075. mg_send_http_error(conn, 505, "%s", ebuf);
  16076. }
  16077. if (ebuf[0] == '\0') {
  16078. uri_type = get_uri_type(conn->request_info.request_uri);
  16079. switch (uri_type) {
  16080. case 1:
  16081. /* Asterisk */
  16082. conn->request_info.local_uri = 0;
  16083. /* TODO: Deal with '*'. */
  16084. break;
  16085. case 2:
  16086. /* relative uri */
  16087. conn->request_info.local_uri = conn->request_info.request_uri;
  16088. break;
  16089. case 3:
  16090. case 4:
  16091. /* absolute uri (with/without port) */
  16092. hostend = get_rel_url_at_current_server(
  16093. conn->request_info.request_uri, conn);
  16094. if (hostend) {
  16095. conn->request_info.local_uri = hostend;
  16096. } else {
  16097. conn->request_info.local_uri = NULL;
  16098. }
  16099. break;
  16100. default:
  16101. mg_snprintf(conn,
  16102. NULL, /* No truncation check for ebuf */
  16103. ebuf,
  16104. sizeof(ebuf),
  16105. "Invalid URI");
  16106. mg_send_http_error(conn, 400, "%s", ebuf);
  16107. conn->request_info.local_uri = NULL;
  16108. break;
  16109. }
  16110. #if defined(MG_LEGACY_INTERFACE)
  16111. /* Legacy before split into local_uri and request_uri */
  16112. conn->request_info.uri = conn->request_info.local_uri;
  16113. #endif
  16114. }
  16115. if (ebuf[0] != '\0') {
  16116. conn->protocol_type = -1;
  16117. } else {
  16118. /* HTTP/1 allows protocol upgrade */
  16119. conn->protocol_type = should_switch_to_protocol(conn);
  16120. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16121. /* This will occur, if a HTTP/1.1 request should be upgraded
  16122. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16123. * Since most (all?) major browsers only support HTTP/2 using
  16124. * ALPN, this is hard to test and very low priority.
  16125. * Deactivate it (at least for now).
  16126. */
  16127. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16128. }
  16129. }
  16130. DEBUG_TRACE("http: %s, error: %s",
  16131. (ri->http_version ? ri->http_version : "none"),
  16132. (ebuf[0] ? ebuf : "none"));
  16133. if (ebuf[0] == '\0') {
  16134. if (conn->request_info.local_uri) {
  16135. /* handle request to local server */
  16136. #if defined(USE_SERVER_STATS)
  16137. conn->conn_state = 4; /* processing */
  16138. #endif
  16139. handle_request(conn);
  16140. #if defined(USE_SERVER_STATS)
  16141. conn->conn_state = 5; /* processed */
  16142. mg_atomic_add64(&(conn->phys_ctx->total_data_read),
  16143. conn->consumed_content);
  16144. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  16145. conn->num_bytes_sent);
  16146. #endif
  16147. DEBUG_TRACE("%s", "handle_request done");
  16148. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16149. conn->phys_ctx->callbacks.end_request(conn,
  16150. conn->status_code);
  16151. DEBUG_TRACE("%s", "end_request callback done");
  16152. }
  16153. log_access(conn);
  16154. } else {
  16155. /* TODO: handle non-local request (PROXY) */
  16156. conn->must_close = 1;
  16157. }
  16158. } else {
  16159. conn->must_close = 1;
  16160. }
  16161. /* Response complete. Free header buffer */
  16162. free_buffered_response_header_list(conn);
  16163. if (ri->remote_user != NULL) {
  16164. mg_free((void *)ri->remote_user);
  16165. /* Important! When having connections with and without auth
  16166. * would cause double free and then crash */
  16167. ri->remote_user = NULL;
  16168. }
  16169. /* NOTE(lsm): order is important here. should_keep_alive() call
  16170. * is using parsed request, which will be invalid after
  16171. * memmove's below.
  16172. * Therefore, memorize should_keep_alive() result now for later
  16173. * use in loop exit condition. */
  16174. /* Enable it only if this request is completely discardable. */
  16175. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16176. && should_keep_alive(conn) && (conn->content_len >= 0)
  16177. && (conn->request_len > 0)
  16178. && ((conn->is_chunked == 4)
  16179. || (!conn->is_chunked
  16180. && ((conn->consumed_content == conn->content_len)
  16181. || ((conn->request_len + conn->content_len)
  16182. <= conn->data_len))))
  16183. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16184. if (keep_alive) {
  16185. /* Discard all buffered data for this request */
  16186. discard_len =
  16187. ((conn->request_len + conn->content_len) < conn->data_len)
  16188. ? (int)(conn->request_len + conn->content_len)
  16189. : conn->data_len;
  16190. conn->data_len -= discard_len;
  16191. if (conn->data_len > 0) {
  16192. DEBUG_TRACE("discard_len = %d", discard_len);
  16193. memmove(conn->buf,
  16194. conn->buf + discard_len,
  16195. (size_t)conn->data_len);
  16196. }
  16197. }
  16198. DEBUG_ASSERT(conn->data_len >= 0);
  16199. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16200. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16201. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16202. (long int)conn->data_len,
  16203. (long int)conn->buf_size);
  16204. break;
  16205. }
  16206. conn->handled_requests++;
  16207. } while (keep_alive);
  16208. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16209. conn->request_info.remote_addr,
  16210. difftime(time(NULL), conn->conn_birth_time));
  16211. close_connection(conn);
  16212. #if defined(USE_SERVER_STATS)
  16213. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16214. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16215. #endif
  16216. }
  16217. #if defined(ALTERNATIVE_QUEUE)
  16218. static void
  16219. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16220. {
  16221. unsigned int i;
  16222. while (!ctx->stop_flag) {
  16223. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16224. /* find a free worker slot and signal it */
  16225. if (ctx->client_socks[i].in_use == 2) {
  16226. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16227. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16228. ctx->client_socks[i] = *sp;
  16229. ctx->client_socks[i].in_use = 1;
  16230. /* socket has been moved to the consumer */
  16231. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16232. (void)event_signal(ctx->client_wait_events[i]);
  16233. return;
  16234. }
  16235. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16236. }
  16237. }
  16238. /* queue is full */
  16239. mg_sleep(1);
  16240. }
  16241. /* must consume */
  16242. set_blocking_mode(sp->sock);
  16243. closesocket(sp->sock);
  16244. }
  16245. static int
  16246. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16247. {
  16248. DEBUG_TRACE("%s", "going idle");
  16249. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16250. ctx->client_socks[thread_index].in_use = 2;
  16251. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16252. event_wait(ctx->client_wait_events[thread_index]);
  16253. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16254. *sp = ctx->client_socks[thread_index];
  16255. if (ctx->stop_flag) {
  16256. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16257. if (sp->in_use == 1) {
  16258. /* must consume */
  16259. set_blocking_mode(sp->sock);
  16260. closesocket(sp->sock);
  16261. }
  16262. return 0;
  16263. }
  16264. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16265. if (sp->in_use == 1) {
  16266. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16267. return 1;
  16268. }
  16269. /* must not reach here */
  16270. DEBUG_ASSERT(0);
  16271. return 0;
  16272. }
  16273. #else /* ALTERNATIVE_QUEUE */
  16274. /* Worker threads take accepted socket from the queue */
  16275. static int
  16276. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16277. {
  16278. (void)thread_index;
  16279. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16280. DEBUG_TRACE("%s", "going idle");
  16281. /* If the queue is empty, wait. We're idle at this point. */
  16282. while ((ctx->sq_head == ctx->sq_tail)
  16283. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16284. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16285. }
  16286. /* If we're stopping, sq_head may be equal to sq_tail. */
  16287. if (ctx->sq_head > ctx->sq_tail) {
  16288. /* Copy socket from the queue and increment tail */
  16289. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16290. ctx->sq_tail++;
  16291. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16292. /* Wrap pointers if needed */
  16293. while (ctx->sq_tail > ctx->sq_size) {
  16294. ctx->sq_tail -= ctx->sq_size;
  16295. ctx->sq_head -= ctx->sq_size;
  16296. }
  16297. }
  16298. (void)pthread_cond_signal(&ctx->sq_empty);
  16299. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16300. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16301. }
  16302. /* Master thread adds accepted socket to a queue */
  16303. static void
  16304. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16305. {
  16306. int queue_filled;
  16307. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16308. queue_filled = ctx->sq_head - ctx->sq_tail;
  16309. /* If the queue is full, wait */
  16310. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16311. && (queue_filled >= ctx->sq_size)) {
  16312. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16313. #if defined(USE_SERVER_STATS)
  16314. if (queue_filled > ctx->sq_max_fill) {
  16315. ctx->sq_max_fill = queue_filled;
  16316. }
  16317. #endif
  16318. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16319. ctx->sq_blocked = 0; /* Not blocked now */
  16320. queue_filled = ctx->sq_head - ctx->sq_tail;
  16321. }
  16322. if (queue_filled < ctx->sq_size) {
  16323. /* Copy socket to the queue and increment head */
  16324. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16325. ctx->sq_head++;
  16326. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16327. }
  16328. queue_filled = ctx->sq_head - ctx->sq_tail;
  16329. #if defined(USE_SERVER_STATS)
  16330. if (queue_filled > ctx->sq_max_fill) {
  16331. ctx->sq_max_fill = queue_filled;
  16332. }
  16333. #endif
  16334. (void)pthread_cond_signal(&ctx->sq_full);
  16335. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16336. }
  16337. #endif /* ALTERNATIVE_QUEUE */
  16338. static void
  16339. worker_thread_run(struct mg_connection *conn)
  16340. {
  16341. struct mg_context *ctx = conn->phys_ctx;
  16342. int thread_index;
  16343. struct mg_workerTLS tls;
  16344. mg_set_thread_name("worker");
  16345. tls.is_master = 0;
  16346. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16347. #if defined(_WIN32)
  16348. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16349. #endif
  16350. /* Initialize thread local storage before calling any callback */
  16351. pthread_setspecific(sTlsKey, &tls);
  16352. /* Check if there is a user callback */
  16353. if (ctx->callbacks.init_thread) {
  16354. /* call init_thread for a worker thread (type 1), and store the
  16355. * return value */
  16356. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16357. } else {
  16358. /* No callback: set user pointer to NULL */
  16359. tls.user_ptr = NULL;
  16360. }
  16361. /* Connection structure has been pre-allocated */
  16362. thread_index = (int)(conn - ctx->worker_connections);
  16363. if ((thread_index < 0)
  16364. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16365. mg_cry_ctx_internal(ctx,
  16366. "Internal error: Invalid worker index %i",
  16367. thread_index);
  16368. return;
  16369. }
  16370. /* Request buffers are not pre-allocated. They are private to the
  16371. * request and do not contain any state information that might be
  16372. * of interest to anyone observing a server status. */
  16373. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16374. if (conn->buf == NULL) {
  16375. mg_cry_ctx_internal(
  16376. ctx,
  16377. "Out of memory: Cannot allocate buffer for worker %i",
  16378. thread_index);
  16379. return;
  16380. }
  16381. conn->buf_size = (int)ctx->max_request_size;
  16382. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16383. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16384. conn->request_info.user_data = ctx->user_data;
  16385. /* Allocate a mutex for this connection to allow communication both
  16386. * within the request handler and from elsewhere in the application
  16387. */
  16388. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16389. mg_free(conn->buf);
  16390. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16391. return;
  16392. }
  16393. #if defined(USE_SERVER_STATS)
  16394. conn->conn_state = 1; /* not consumed */
  16395. #endif
  16396. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16397. * signal sq_empty condvar to wake up the master waiting in
  16398. * produce_socket() */
  16399. while (consume_socket(ctx, &conn->client, thread_index)) {
  16400. /* New connections must start with new protocol negotiation */
  16401. tls.alpn_proto = NULL;
  16402. #if defined(USE_SERVER_STATS)
  16403. conn->conn_close_time = 0;
  16404. #endif
  16405. conn->conn_birth_time = time(NULL);
  16406. /* Fill in IP, port info early so even if SSL setup below fails,
  16407. * error handler would have the corresponding info.
  16408. * Thanks to Johannes Winkelmann for the patch.
  16409. */
  16410. conn->request_info.remote_port =
  16411. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16412. sockaddr_to_string(conn->request_info.remote_addr,
  16413. sizeof(conn->request_info.remote_addr),
  16414. &conn->client.rsa);
  16415. DEBUG_TRACE("Start processing connection from %s",
  16416. conn->request_info.remote_addr);
  16417. conn->request_info.is_ssl = conn->client.is_ssl;
  16418. if (conn->client.is_ssl) {
  16419. #if defined(USE_MBEDTLS)
  16420. /* HTTPS connection */
  16421. if (mbed_ssl_accept(&conn->ssl,
  16422. conn->dom_ctx->ssl_ctx,
  16423. &conn->client.sock)
  16424. == 0) {
  16425. /* conn->dom_ctx is set in get_request */
  16426. /* process HTTPS connection */
  16427. init_connection(conn);
  16428. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16429. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16430. process_new_connection(conn);
  16431. } else {
  16432. /* make sure the connection is cleaned up on SSL failure */
  16433. close_connection(conn);
  16434. }
  16435. #endif
  16436. #if !defined(NO_SSL)
  16437. /* HTTPS connection */
  16438. if (sslize(conn, SSL_accept, NULL)) {
  16439. /* conn->dom_ctx is set in get_request */
  16440. /* Get SSL client certificate information (if set) */
  16441. struct mg_client_cert client_cert;
  16442. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16443. conn->request_info.client_cert = &client_cert;
  16444. }
  16445. /* process HTTPS connection */
  16446. #if defined(USE_HTTP2)
  16447. if ((tls.alpn_proto != NULL)
  16448. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16449. /* process HTTPS/2 connection */
  16450. init_connection(conn);
  16451. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16452. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16453. conn->content_len =
  16454. -1; /* content length is not predefined */
  16455. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16456. process_new_http2_connection(conn);
  16457. } else
  16458. #endif
  16459. {
  16460. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16461. init_connection(conn);
  16462. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16463. /* Start with HTTP, WS will be an "upgrade" request later */
  16464. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16465. process_new_connection(conn);
  16466. }
  16467. /* Free client certificate info */
  16468. if (conn->request_info.client_cert) {
  16469. mg_free((void *)(conn->request_info.client_cert->subject));
  16470. mg_free((void *)(conn->request_info.client_cert->issuer));
  16471. mg_free((void *)(conn->request_info.client_cert->serial));
  16472. mg_free((void *)(conn->request_info.client_cert->finger));
  16473. /* Free certificate memory */
  16474. X509_free(
  16475. (X509 *)conn->request_info.client_cert->peer_cert);
  16476. conn->request_info.client_cert->peer_cert = 0;
  16477. conn->request_info.client_cert->subject = 0;
  16478. conn->request_info.client_cert->issuer = 0;
  16479. conn->request_info.client_cert->serial = 0;
  16480. conn->request_info.client_cert->finger = 0;
  16481. conn->request_info.client_cert = 0;
  16482. }
  16483. } else {
  16484. /* make sure the connection is cleaned up on SSL failure */
  16485. close_connection(conn);
  16486. }
  16487. #endif
  16488. } else {
  16489. /* process HTTP connection */
  16490. init_connection(conn);
  16491. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16492. /* Start with HTTP, WS will be an "upgrade" request later */
  16493. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16494. process_new_connection(conn);
  16495. }
  16496. DEBUG_TRACE("%s", "Connection closed");
  16497. #if defined(USE_SERVER_STATS)
  16498. conn->conn_close_time = time(NULL);
  16499. #endif
  16500. }
  16501. /* Call exit thread user callback */
  16502. if (ctx->callbacks.exit_thread) {
  16503. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16504. }
  16505. /* delete thread local storage objects */
  16506. pthread_setspecific(sTlsKey, NULL);
  16507. #if defined(_WIN32)
  16508. CloseHandle(tls.pthread_cond_helper_mutex);
  16509. #endif
  16510. pthread_mutex_destroy(&conn->mutex);
  16511. /* Free the request buffer. */
  16512. conn->buf_size = 0;
  16513. mg_free(conn->buf);
  16514. conn->buf = NULL;
  16515. #if defined(USE_SERVER_STATS)
  16516. conn->conn_state = 9; /* done */
  16517. #endif
  16518. DEBUG_TRACE("%s", "exiting");
  16519. }
  16520. /* Threads have different return types on Windows and Unix. */
  16521. #if defined(_WIN32)
  16522. static unsigned __stdcall worker_thread(void *thread_func_param)
  16523. {
  16524. worker_thread_run((struct mg_connection *)thread_func_param);
  16525. return 0;
  16526. }
  16527. #else
  16528. static void *
  16529. worker_thread(void *thread_func_param)
  16530. {
  16531. #if !defined(__ZEPHYR__)
  16532. struct sigaction sa;
  16533. /* Ignore SIGPIPE */
  16534. memset(&sa, 0, sizeof(sa));
  16535. sa.sa_handler = SIG_IGN;
  16536. sigaction(SIGPIPE, &sa, NULL);
  16537. #endif
  16538. worker_thread_run((struct mg_connection *)thread_func_param);
  16539. return NULL;
  16540. }
  16541. #endif /* _WIN32 */
  16542. /* This is an internal function, thus all arguments are expected to be
  16543. * valid - a NULL check is not required. */
  16544. static void
  16545. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16546. {
  16547. struct socket so;
  16548. char src_addr[IP_ADDR_STR_LEN];
  16549. socklen_t len = sizeof(so.rsa);
  16550. #if !defined(__ZEPHYR__)
  16551. int on = 1;
  16552. #endif
  16553. memset(&so, 0, sizeof(so));
  16554. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16555. == INVALID_SOCKET) {
  16556. } else if (check_acl(ctx, &so.rsa) != 1) {
  16557. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16558. mg_cry_ctx_internal(ctx,
  16559. "%s: %s is not allowed to connect",
  16560. __func__,
  16561. src_addr);
  16562. closesocket(so.sock);
  16563. } else {
  16564. /* Put so socket structure into the queue */
  16565. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16566. set_close_on_exec(so.sock, NULL, ctx);
  16567. so.is_ssl = listener->is_ssl;
  16568. so.ssl_redir = listener->ssl_redir;
  16569. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16570. mg_cry_ctx_internal(ctx,
  16571. "%s: getsockname() failed: %s",
  16572. __func__,
  16573. strerror(ERRNO));
  16574. }
  16575. #if !defined(__ZEPHYR__)
  16576. /* Set TCP keep-alive. This is needed because if HTTP-level
  16577. * keep-alive
  16578. * is enabled, and client resets the connection, server won't get
  16579. * TCP FIN or RST and will keep the connection open forever. With
  16580. * TCP keep-alive, next keep-alive handshake will figure out that
  16581. * the client is down and will close the server end.
  16582. * Thanks to Igor Klopov who suggested the patch. */
  16583. if (setsockopt(so.sock,
  16584. SOL_SOCKET,
  16585. SO_KEEPALIVE,
  16586. (SOCK_OPT_TYPE)&on,
  16587. sizeof(on))
  16588. != 0) {
  16589. mg_cry_ctx_internal(
  16590. ctx,
  16591. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16592. __func__,
  16593. strerror(ERRNO));
  16594. }
  16595. #endif
  16596. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16597. * to effectively fill up the underlying IP packet payload and
  16598. * reduce the overhead of sending lots of small buffers. However
  16599. * this hurts the server's throughput (ie. operations per second)
  16600. * when HTTP 1.1 persistent connections are used and the responses
  16601. * are relatively small (eg. less than 1400 bytes).
  16602. */
  16603. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16604. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16605. if (set_tcp_nodelay(so.sock, 1) != 0) {
  16606. mg_cry_ctx_internal(
  16607. ctx,
  16608. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16609. __func__,
  16610. strerror(ERRNO));
  16611. }
  16612. }
  16613. /* The "non blocking" property should already be
  16614. * inherited from the parent socket. Set it for
  16615. * non-compliant socket implementations. */
  16616. set_non_blocking_mode(so.sock);
  16617. so.in_use = 0;
  16618. produce_socket(ctx, &so);
  16619. }
  16620. }
  16621. static void
  16622. master_thread_run(struct mg_context *ctx)
  16623. {
  16624. struct mg_workerTLS tls;
  16625. struct mg_pollfd *pfd;
  16626. unsigned int i;
  16627. unsigned int workerthreadcount;
  16628. if (!ctx) {
  16629. return;
  16630. }
  16631. mg_set_thread_name("master");
  16632. /* Increase priority of the master thread */
  16633. #if defined(_WIN32)
  16634. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16635. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16636. int min_prio = sched_get_priority_min(SCHED_RR);
  16637. int max_prio = sched_get_priority_max(SCHED_RR);
  16638. if ((min_prio >= 0) && (max_prio >= 0)
  16639. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16640. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16641. struct sched_param sched_param = {0};
  16642. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16643. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16644. }
  16645. #endif
  16646. /* Initialize thread local storage */
  16647. #if defined(_WIN32)
  16648. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16649. #endif
  16650. tls.is_master = 1;
  16651. pthread_setspecific(sTlsKey, &tls);
  16652. if (ctx->callbacks.init_thread) {
  16653. /* Callback for the master thread (type 0) */
  16654. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16655. } else {
  16656. tls.user_ptr = NULL;
  16657. }
  16658. /* Server starts *now* */
  16659. ctx->start_time = time(NULL);
  16660. /* Start the server */
  16661. pfd = ctx->listening_socket_fds;
  16662. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16663. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16664. pfd[i].fd = ctx->listening_sockets[i].sock;
  16665. pfd[i].events = POLLIN;
  16666. }
  16667. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16668. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16669. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16670. * successful poll, and POLLIN is defined as
  16671. * (POLLRDNORM | POLLRDBAND)
  16672. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16673. * pfd[i].revents == POLLIN. */
  16674. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16675. && (pfd[i].revents & POLLIN)) {
  16676. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16677. }
  16678. }
  16679. }
  16680. }
  16681. /* Here stop_flag is 1 - Initiate shutdown. */
  16682. DEBUG_TRACE("%s", "stopping workers");
  16683. /* Stop signal received: somebody called mg_stop. Quit. */
  16684. close_all_listening_sockets(ctx);
  16685. /* Wakeup workers that are waiting for connections to handle. */
  16686. #if defined(ALTERNATIVE_QUEUE)
  16687. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16688. event_signal(ctx->client_wait_events[i]);
  16689. }
  16690. #else
  16691. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16692. pthread_cond_broadcast(&ctx->sq_full);
  16693. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16694. #endif
  16695. /* Join all worker threads to avoid leaking threads. */
  16696. workerthreadcount = ctx->cfg_worker_threads;
  16697. for (i = 0; i < workerthreadcount; i++) {
  16698. if (ctx->worker_threadids[i] != 0) {
  16699. mg_join_thread(ctx->worker_threadids[i]);
  16700. }
  16701. }
  16702. #if defined(USE_LUA)
  16703. /* Free Lua state of lua background task */
  16704. if (ctx->lua_background_state) {
  16705. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16706. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  16707. if (lua_istable(lstate, -1)) {
  16708. reg_boolean(lstate, "shutdown", 1);
  16709. lua_pop(lstate, 1);
  16710. mg_sleep(2);
  16711. }
  16712. lua_close(lstate);
  16713. ctx->lua_background_state = 0;
  16714. }
  16715. #endif
  16716. DEBUG_TRACE("%s", "exiting");
  16717. /* call exit thread callback */
  16718. if (ctx->callbacks.exit_thread) {
  16719. /* Callback for the master thread (type 0) */
  16720. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16721. }
  16722. #if defined(_WIN32)
  16723. CloseHandle(tls.pthread_cond_helper_mutex);
  16724. #endif
  16725. pthread_setspecific(sTlsKey, NULL);
  16726. /* Signal mg_stop() that we're done.
  16727. * WARNING: This must be the very last thing this
  16728. * thread does, as ctx becomes invalid after this line. */
  16729. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16730. }
  16731. /* Threads have different return types on Windows and Unix. */
  16732. #if defined(_WIN32)
  16733. static unsigned __stdcall master_thread(void *thread_func_param)
  16734. {
  16735. master_thread_run((struct mg_context *)thread_func_param);
  16736. return 0;
  16737. }
  16738. #else
  16739. static void *
  16740. master_thread(void *thread_func_param)
  16741. {
  16742. #if !defined(__ZEPHYR__)
  16743. struct sigaction sa;
  16744. /* Ignore SIGPIPE */
  16745. memset(&sa, 0, sizeof(sa));
  16746. sa.sa_handler = SIG_IGN;
  16747. sigaction(SIGPIPE, &sa, NULL);
  16748. #endif
  16749. master_thread_run((struct mg_context *)thread_func_param);
  16750. return NULL;
  16751. }
  16752. #endif /* _WIN32 */
  16753. static void
  16754. free_context(struct mg_context *ctx)
  16755. {
  16756. int i;
  16757. struct mg_handler_info *tmp_rh;
  16758. if (ctx == NULL) {
  16759. return;
  16760. }
  16761. /* Call user callback */
  16762. if (ctx->callbacks.exit_context) {
  16763. ctx->callbacks.exit_context(ctx);
  16764. }
  16765. /* All threads exited, no sync is needed. Destroy thread mutex and
  16766. * condvars
  16767. */
  16768. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16769. #if defined(ALTERNATIVE_QUEUE)
  16770. mg_free(ctx->client_socks);
  16771. if (ctx->client_wait_events != NULL) {
  16772. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16773. event_destroy(ctx->client_wait_events[i]);
  16774. }
  16775. mg_free(ctx->client_wait_events);
  16776. }
  16777. #else
  16778. (void)pthread_cond_destroy(&ctx->sq_empty);
  16779. (void)pthread_cond_destroy(&ctx->sq_full);
  16780. mg_free(ctx->squeue);
  16781. #endif
  16782. /* Destroy other context global data structures mutex */
  16783. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16784. /* Deallocate config parameters */
  16785. for (i = 0; i < NUM_OPTIONS; i++) {
  16786. if (ctx->dd.config[i] != NULL) {
  16787. #if defined(_MSC_VER)
  16788. #pragma warning(suppress : 6001)
  16789. #endif
  16790. mg_free(ctx->dd.config[i]);
  16791. }
  16792. }
  16793. /* Deallocate request handlers */
  16794. while (ctx->dd.handlers) {
  16795. tmp_rh = ctx->dd.handlers;
  16796. ctx->dd.handlers = tmp_rh->next;
  16797. mg_free(tmp_rh->uri);
  16798. mg_free(tmp_rh);
  16799. }
  16800. #if defined(USE_MBEDTLS)
  16801. if (ctx->dd.ssl_ctx != NULL) {
  16802. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  16803. mg_free(ctx->dd.ssl_ctx);
  16804. ctx->dd.ssl_ctx = NULL;
  16805. }
  16806. #endif
  16807. #if !defined(NO_SSL)
  16808. /* Deallocate SSL context */
  16809. if (ctx->dd.ssl_ctx != NULL) {
  16810. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16811. int callback_ret =
  16812. (ctx->callbacks.external_ssl_ctx == NULL)
  16813. ? 0
  16814. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16815. if (callback_ret == 0) {
  16816. SSL_CTX_free(ctx->dd.ssl_ctx);
  16817. }
  16818. /* else: ignore error and ommit SSL_CTX_free in case
  16819. * callback_ret is 1 */
  16820. }
  16821. #endif /* !NO_SSL */
  16822. /* Deallocate worker thread ID array */
  16823. mg_free(ctx->worker_threadids);
  16824. /* Deallocate worker thread ID array */
  16825. mg_free(ctx->worker_connections);
  16826. /* deallocate system name string */
  16827. mg_free(ctx->systemName);
  16828. /* Deallocate context itself */
  16829. mg_free(ctx);
  16830. }
  16831. void
  16832. mg_stop(struct mg_context *ctx)
  16833. {
  16834. pthread_t mt;
  16835. if (!ctx) {
  16836. return;
  16837. }
  16838. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16839. * two threads is not allowed. */
  16840. mt = ctx->masterthreadid;
  16841. if (mt == 0) {
  16842. return;
  16843. }
  16844. ctx->masterthreadid = 0;
  16845. /* Set stop flag, so all threads know they have to exit. */
  16846. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16847. /* Join timer thread */
  16848. #if defined(USE_TIMERS)
  16849. timers_exit(ctx);
  16850. #endif
  16851. /* Wait until everything has stopped. */
  16852. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16853. (void)mg_sleep(10);
  16854. }
  16855. /* Wait to stop master thread */
  16856. mg_join_thread(mt);
  16857. /* Close remaining Lua states */
  16858. #if defined(USE_LUA)
  16859. lua_ctx_exit(ctx);
  16860. #endif
  16861. /* Free memory */
  16862. free_context(ctx);
  16863. }
  16864. static void
  16865. get_system_name(char **sysName)
  16866. {
  16867. #if defined(_WIN32)
  16868. #if defined(_WIN32_WCE)
  16869. *sysName = mg_strdup("WinCE");
  16870. #else
  16871. char name[128];
  16872. DWORD dwVersion = 0;
  16873. DWORD dwMajorVersion = 0;
  16874. DWORD dwMinorVersion = 0;
  16875. DWORD dwBuild = 0;
  16876. BOOL wowRet, isWoW = FALSE;
  16877. #if defined(_MSC_VER)
  16878. #pragma warning(push)
  16879. /* GetVersion was declared deprecated */
  16880. #pragma warning(disable : 4996)
  16881. #endif
  16882. dwVersion = GetVersion();
  16883. #if defined(_MSC_VER)
  16884. #pragma warning(pop)
  16885. #endif
  16886. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16887. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16888. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16889. (void)dwBuild;
  16890. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16891. sprintf(name,
  16892. "Windows %u.%u%s",
  16893. (unsigned)dwMajorVersion,
  16894. (unsigned)dwMinorVersion,
  16895. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16896. *sysName = mg_strdup(name);
  16897. #endif
  16898. #elif defined(__ZEPHYR__)
  16899. *sysName = mg_strdup("Zephyr OS");
  16900. #else
  16901. struct utsname name;
  16902. memset(&name, 0, sizeof(name));
  16903. uname(&name);
  16904. *sysName = mg_strdup(name.sysname);
  16905. #endif
  16906. }
  16907. static void
  16908. legacy_init(const char **options)
  16909. {
  16910. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16911. if (options) {
  16912. const char **run_options = options;
  16913. const char *optname = config_options[LISTENING_PORTS].name;
  16914. /* Try to find the "listening_ports" option */
  16915. while (*run_options) {
  16916. if (!strcmp(*run_options, optname)) {
  16917. ports_option = run_options[1];
  16918. }
  16919. run_options += 2;
  16920. }
  16921. }
  16922. if (is_ssl_port_used(ports_option)) {
  16923. /* Initialize with SSL support */
  16924. mg_init_library(MG_FEATURES_TLS);
  16925. } else {
  16926. /* Initialize without SSL support */
  16927. mg_init_library(MG_FEATURES_DEFAULT);
  16928. }
  16929. }
  16930. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16931. static
  16932. #endif
  16933. struct mg_context *
  16934. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16935. {
  16936. struct mg_context *ctx;
  16937. const char *name, *value, *default_value;
  16938. int idx, ok, workerthreadcount;
  16939. unsigned int i;
  16940. int itmp;
  16941. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16942. const char **options =
  16943. ((init != NULL) ? (init->configuration_options) : (NULL));
  16944. struct mg_workerTLS tls;
  16945. if (error != NULL) {
  16946. error->code = 0;
  16947. if (error->text_buffer_size > 0) {
  16948. *error->text = 0;
  16949. }
  16950. }
  16951. if (mg_init_library_called == 0) {
  16952. /* Legacy INIT, if mg_start is called without mg_init_library.
  16953. * Note: This will cause a memory leak when unloading the library.
  16954. */
  16955. legacy_init(options);
  16956. }
  16957. if (mg_init_library_called == 0) {
  16958. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16959. mg_snprintf(NULL,
  16960. NULL, /* No truncation check for error buffers */
  16961. error->text,
  16962. error->text_buffer_size,
  16963. "%s",
  16964. "Library uninitialized");
  16965. }
  16966. return NULL;
  16967. }
  16968. /* Allocate context and initialize reasonable general case defaults. */
  16969. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16970. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16971. mg_snprintf(NULL,
  16972. NULL, /* No truncation check for error buffers */
  16973. error->text,
  16974. error->text_buffer_size,
  16975. "%s",
  16976. "Out of memory");
  16977. }
  16978. return NULL;
  16979. }
  16980. /* Random number generator will initialize at the first call */
  16981. ctx->dd.auth_nonce_mask =
  16982. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16983. /* Save started thread index to reuse in other external API calls
  16984. * For the sake of thread synchronization all non-civetweb threads
  16985. * can be considered as single external thread */
  16986. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16987. tls.is_master = -1; /* Thread calling mg_start */
  16988. tls.thread_idx = ctx->starter_thread_idx;
  16989. #if defined(_WIN32)
  16990. tls.pthread_cond_helper_mutex = NULL;
  16991. #endif
  16992. pthread_setspecific(sTlsKey, &tls);
  16993. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16994. #if !defined(ALTERNATIVE_QUEUE)
  16995. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16996. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16997. ctx->sq_blocked = 0;
  16998. #endif
  16999. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17000. if (!ok) {
  17001. const char *err_msg =
  17002. "Cannot initialize thread synchronization objects";
  17003. /* Fatal error - abort start. However, this situation should never
  17004. * occur in practice. */
  17005. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17006. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17007. mg_snprintf(NULL,
  17008. NULL, /* No truncation check for error buffers */
  17009. error->text,
  17010. error->text_buffer_size,
  17011. "%s",
  17012. err_msg);
  17013. }
  17014. mg_free(ctx);
  17015. pthread_setspecific(sTlsKey, NULL);
  17016. return NULL;
  17017. }
  17018. if ((init != NULL) && (init->callbacks != NULL)) {
  17019. /* Set all callbacks except exit_context. */
  17020. ctx->callbacks = *init->callbacks;
  17021. exit_callback = init->callbacks->exit_context;
  17022. /* The exit callback is activated once the context is successfully
  17023. * created. It should not be called, if an incomplete context object
  17024. * is deleted during a failed initialization. */
  17025. ctx->callbacks.exit_context = 0;
  17026. }
  17027. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17028. ctx->dd.handlers = NULL;
  17029. ctx->dd.next = NULL;
  17030. #if defined(USE_LUA)
  17031. lua_ctx_init(ctx);
  17032. #endif
  17033. /* Store options */
  17034. while (options && (name = *options++) != NULL) {
  17035. if ((idx = get_option_index(name)) == -1) {
  17036. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17037. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17038. mg_snprintf(NULL,
  17039. NULL, /* No truncation check for error buffers */
  17040. error->text,
  17041. error->text_buffer_size,
  17042. "Invalid configuration option: %s",
  17043. name);
  17044. }
  17045. free_context(ctx);
  17046. pthread_setspecific(sTlsKey, NULL);
  17047. return NULL;
  17048. } else if ((value = *options++) == NULL) {
  17049. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17050. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17051. mg_snprintf(NULL,
  17052. NULL, /* No truncation check for error buffers */
  17053. error->text,
  17054. error->text_buffer_size,
  17055. "Invalid configuration option value: %s",
  17056. name);
  17057. }
  17058. free_context(ctx);
  17059. pthread_setspecific(sTlsKey, NULL);
  17060. return NULL;
  17061. }
  17062. if (ctx->dd.config[idx] != NULL) {
  17063. /* A duplicate configuration option is not an error - the last
  17064. * option value will be used. */
  17065. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17066. mg_free(ctx->dd.config[idx]);
  17067. }
  17068. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17069. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17070. }
  17071. /* Set default value if needed */
  17072. for (i = 0; config_options[i].name != NULL; i++) {
  17073. default_value = config_options[i].default_value;
  17074. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17075. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17076. }
  17077. }
  17078. /* Request size option */
  17079. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17080. if (itmp < 1024) {
  17081. mg_cry_ctx_internal(ctx,
  17082. "%s too small",
  17083. config_options[MAX_REQUEST_SIZE].name);
  17084. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17085. mg_snprintf(NULL,
  17086. NULL, /* No truncation check for error buffers */
  17087. error->text,
  17088. error->text_buffer_size,
  17089. "Invalid configuration option value: %s",
  17090. config_options[MAX_REQUEST_SIZE].name);
  17091. }
  17092. free_context(ctx);
  17093. pthread_setspecific(sTlsKey, NULL);
  17094. return NULL;
  17095. }
  17096. ctx->max_request_size = (unsigned)itmp;
  17097. /* Queue length */
  17098. #if !defined(ALTERNATIVE_QUEUE)
  17099. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17100. if (itmp < 1) {
  17101. mg_cry_ctx_internal(ctx,
  17102. "%s too small",
  17103. config_options[CONNECTION_QUEUE_SIZE].name);
  17104. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17105. mg_snprintf(NULL,
  17106. NULL, /* No truncation check for error buffers */
  17107. error->text,
  17108. error->text_buffer_size,
  17109. "Invalid configuration option value: %s",
  17110. config_options[CONNECTION_QUEUE_SIZE].name);
  17111. }
  17112. free_context(ctx);
  17113. pthread_setspecific(sTlsKey, NULL);
  17114. return NULL;
  17115. }
  17116. ctx->squeue =
  17117. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17118. if (ctx->squeue == NULL) {
  17119. mg_cry_ctx_internal(ctx,
  17120. "Out of memory: Cannot allocate %s",
  17121. config_options[CONNECTION_QUEUE_SIZE].name);
  17122. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17123. mg_snprintf(NULL,
  17124. NULL, /* No truncation check for error buffers */
  17125. error->text,
  17126. error->text_buffer_size,
  17127. "Out of memory: Cannot allocate %s",
  17128. config_options[CONNECTION_QUEUE_SIZE].name);
  17129. }
  17130. free_context(ctx);
  17131. pthread_setspecific(sTlsKey, NULL);
  17132. return NULL;
  17133. }
  17134. ctx->sq_size = itmp;
  17135. #endif
  17136. /* Worker thread count option */
  17137. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17138. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17139. if (workerthreadcount <= 0) {
  17140. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17141. } else {
  17142. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17143. }
  17144. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17145. mg_snprintf(NULL,
  17146. NULL, /* No truncation check for error buffers */
  17147. error->text,
  17148. error->text_buffer_size,
  17149. "Invalid configuration option value: %s",
  17150. config_options[NUM_THREADS].name);
  17151. }
  17152. free_context(ctx);
  17153. pthread_setspecific(sTlsKey, NULL);
  17154. return NULL;
  17155. }
  17156. /* Document root */
  17157. #if defined(NO_FILES)
  17158. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17159. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17160. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17161. mg_snprintf(NULL,
  17162. NULL, /* No truncation check for error buffers */
  17163. error->text,
  17164. error->text_buffer_size,
  17165. "Invalid configuration option value: %s",
  17166. config_options[DOCUMENT_ROOT].name);
  17167. }
  17168. free_context(ctx);
  17169. pthread_setspecific(sTlsKey, NULL);
  17170. return NULL;
  17171. }
  17172. #endif
  17173. get_system_name(&ctx->systemName);
  17174. #if defined(USE_LUA)
  17175. /* If a Lua background script has been configured, start it. */
  17176. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17177. char ebuf[256];
  17178. struct vec opt_vec;
  17179. struct vec eq_vec;
  17180. const char *sparams;
  17181. lua_State *state = mg_prepare_lua_context_script(
  17182. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17183. if (!state) {
  17184. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  17185. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17186. mg_snprintf(NULL,
  17187. NULL, /* No truncation check for error buffers */
  17188. error->text,
  17189. error->text_buffer_size,
  17190. "Error in script %s: %s",
  17191. config_options[DOCUMENT_ROOT].name,
  17192. ebuf);
  17193. }
  17194. free_context(ctx);
  17195. pthread_setspecific(sTlsKey, NULL);
  17196. return NULL;
  17197. }
  17198. ctx->lua_background_state = (void *)state;
  17199. lua_newtable(state);
  17200. reg_boolean(state, "shutdown", 0);
  17201. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17202. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  17203. reg_llstring(
  17204. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17205. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17206. break;
  17207. }
  17208. lua_setglobal(state, LUABACKGROUNDPARAMS);
  17209. } else {
  17210. ctx->lua_background_state = 0;
  17211. }
  17212. #endif
  17213. /* Step by step initialization of ctx - depending on build options */
  17214. #if !defined(NO_FILESYSTEMS)
  17215. if (!set_gpass_option(ctx, NULL)) {
  17216. const char *err_msg = "Invalid global password file";
  17217. /* Fatal error - abort start. */
  17218. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17219. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17220. mg_snprintf(NULL,
  17221. NULL, /* No truncation check for error buffers */
  17222. error->text,
  17223. error->text_buffer_size,
  17224. "%s",
  17225. err_msg);
  17226. }
  17227. free_context(ctx);
  17228. pthread_setspecific(sTlsKey, NULL);
  17229. return NULL;
  17230. }
  17231. #endif
  17232. #if defined(USE_MBEDTLS)
  17233. if (!mg_sslctx_init(ctx, NULL)) {
  17234. const char *err_msg = "Error initializing SSL context";
  17235. /* Fatal error - abort start. */
  17236. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17237. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17238. mg_snprintf(NULL,
  17239. NULL, /* No truncation check for error buffers */
  17240. error->text,
  17241. error->text_buffer_size,
  17242. "%s",
  17243. err_msg);
  17244. }
  17245. free_context(ctx);
  17246. pthread_setspecific(sTlsKey, NULL);
  17247. return NULL;
  17248. }
  17249. #endif
  17250. #if !defined(NO_SSL)
  17251. if (!init_ssl_ctx(ctx, NULL)) {
  17252. const char *err_msg = "Error initializing SSL context";
  17253. /* Fatal error - abort start. */
  17254. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17255. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17256. mg_snprintf(NULL,
  17257. NULL, /* No truncation check for error buffers */
  17258. error->text,
  17259. error->text_buffer_size,
  17260. "%s",
  17261. err_msg);
  17262. }
  17263. free_context(ctx);
  17264. pthread_setspecific(sTlsKey, NULL);
  17265. return NULL;
  17266. }
  17267. #endif
  17268. if (!set_ports_option(ctx)) {
  17269. const char *err_msg = "Failed to setup server ports";
  17270. /* Fatal error - abort start. */
  17271. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17272. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17273. mg_snprintf(NULL,
  17274. NULL, /* No truncation check for error buffers */
  17275. error->text,
  17276. error->text_buffer_size,
  17277. "%s",
  17278. err_msg);
  17279. }
  17280. free_context(ctx);
  17281. pthread_setspecific(sTlsKey, NULL);
  17282. return NULL;
  17283. }
  17284. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17285. if (!set_uid_option(ctx)) {
  17286. const char *err_msg = "Failed to run as configured user";
  17287. /* Fatal error - abort start. */
  17288. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17289. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17290. mg_snprintf(NULL,
  17291. NULL, /* No truncation check for error buffers */
  17292. error->text,
  17293. error->text_buffer_size,
  17294. "%s",
  17295. err_msg);
  17296. }
  17297. free_context(ctx);
  17298. pthread_setspecific(sTlsKey, NULL);
  17299. return NULL;
  17300. }
  17301. #endif
  17302. if (!set_acl_option(ctx)) {
  17303. const char *err_msg = "Failed to setup access control list";
  17304. /* Fatal error - abort start. */
  17305. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17306. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17307. mg_snprintf(NULL,
  17308. NULL, /* No truncation check for error buffers */
  17309. error->text,
  17310. error->text_buffer_size,
  17311. "%s",
  17312. err_msg);
  17313. }
  17314. free_context(ctx);
  17315. pthread_setspecific(sTlsKey, NULL);
  17316. return NULL;
  17317. }
  17318. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17319. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17320. sizeof(pthread_t),
  17321. ctx);
  17322. if (ctx->worker_threadids == NULL) {
  17323. const char *err_msg = "Not enough memory for worker thread ID array";
  17324. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17325. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17326. mg_snprintf(NULL,
  17327. NULL, /* No truncation check for error buffers */
  17328. error->text,
  17329. error->text_buffer_size,
  17330. "%s",
  17331. err_msg);
  17332. }
  17333. free_context(ctx);
  17334. pthread_setspecific(sTlsKey, NULL);
  17335. return NULL;
  17336. }
  17337. ctx->worker_connections =
  17338. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17339. sizeof(struct mg_connection),
  17340. ctx);
  17341. if (ctx->worker_connections == NULL) {
  17342. const char *err_msg =
  17343. "Not enough memory for worker thread connection array";
  17344. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17345. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17346. mg_snprintf(NULL,
  17347. NULL, /* No truncation check for error buffers */
  17348. error->text,
  17349. error->text_buffer_size,
  17350. "%s",
  17351. err_msg);
  17352. }
  17353. free_context(ctx);
  17354. pthread_setspecific(sTlsKey, NULL);
  17355. return NULL;
  17356. }
  17357. #if defined(ALTERNATIVE_QUEUE)
  17358. ctx->client_wait_events =
  17359. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17360. sizeof(ctx->client_wait_events[0]),
  17361. ctx);
  17362. if (ctx->client_wait_events == NULL) {
  17363. const char *err_msg = "Not enough memory for worker event array";
  17364. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17365. mg_free(ctx->worker_threadids);
  17366. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17367. mg_snprintf(NULL,
  17368. NULL, /* No truncation check for error buffers */
  17369. error->text,
  17370. error->text_buffer_size,
  17371. "%s",
  17372. err_msg);
  17373. }
  17374. free_context(ctx);
  17375. pthread_setspecific(sTlsKey, NULL);
  17376. return NULL;
  17377. }
  17378. ctx->client_socks =
  17379. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17380. sizeof(ctx->client_socks[0]),
  17381. ctx);
  17382. if (ctx->client_socks == NULL) {
  17383. const char *err_msg = "Not enough memory for worker socket array";
  17384. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17385. mg_free(ctx->client_wait_events);
  17386. mg_free(ctx->worker_threadids);
  17387. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17388. mg_snprintf(NULL,
  17389. NULL, /* No truncation check for error buffers */
  17390. error->text,
  17391. error->text_buffer_size,
  17392. "%s",
  17393. err_msg);
  17394. }
  17395. free_context(ctx);
  17396. pthread_setspecific(sTlsKey, NULL);
  17397. return NULL;
  17398. }
  17399. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17400. ctx->client_wait_events[i] = event_create();
  17401. if (ctx->client_wait_events[i] == 0) {
  17402. const char *err_msg = "Error creating worker event %i";
  17403. mg_cry_ctx_internal(ctx, err_msg, i);
  17404. while (i > 0) {
  17405. i--;
  17406. event_destroy(ctx->client_wait_events[i]);
  17407. }
  17408. mg_free(ctx->client_socks);
  17409. mg_free(ctx->client_wait_events);
  17410. mg_free(ctx->worker_threadids);
  17411. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17412. mg_snprintf(NULL,
  17413. NULL, /* No truncation check for error buffers */
  17414. error->text,
  17415. error->text_buffer_size,
  17416. err_msg,
  17417. i);
  17418. }
  17419. free_context(ctx);
  17420. pthread_setspecific(sTlsKey, NULL);
  17421. return NULL;
  17422. }
  17423. }
  17424. #endif
  17425. #if defined(USE_TIMERS)
  17426. if (timers_init(ctx) != 0) {
  17427. const char *err_msg = "Error creating timers";
  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. /* Context has been created - init user libraries */
  17443. if (ctx->callbacks.init_context) {
  17444. ctx->callbacks.init_context(ctx);
  17445. }
  17446. /* From now, the context is successfully created.
  17447. * When it is destroyed, the exit callback should be called. */
  17448. ctx->callbacks.exit_context = exit_callback;
  17449. ctx->context_type = CONTEXT_SERVER; /* server context */
  17450. /* Start worker threads */
  17451. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17452. /* worker_thread sets up the other fields */
  17453. ctx->worker_connections[i].phys_ctx = ctx;
  17454. if (mg_start_thread_with_id(worker_thread,
  17455. &ctx->worker_connections[i],
  17456. &ctx->worker_threadids[i])
  17457. != 0) {
  17458. long error_no = (long)ERRNO;
  17459. /* thread was not created */
  17460. if (i > 0) {
  17461. /* If the second, third, ... thread cannot be created, set a
  17462. * warning, but keep running. */
  17463. mg_cry_ctx_internal(ctx,
  17464. "Cannot start worker thread %i: error %ld",
  17465. i + 1,
  17466. error_no);
  17467. /* If the server initialization should stop here, all
  17468. * threads that have already been created must be stopped
  17469. * first, before any free_context(ctx) call.
  17470. */
  17471. } else {
  17472. /* If the first worker thread cannot be created, stop
  17473. * initialization and free the entire server context. */
  17474. mg_cry_ctx_internal(ctx,
  17475. "Cannot create threads: error %ld",
  17476. error_no);
  17477. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17478. mg_snprintf(
  17479. NULL,
  17480. NULL, /* No truncation check for error buffers */
  17481. error->text,
  17482. error->text_buffer_size,
  17483. "Cannot create first worker thread: error %ld",
  17484. error_no);
  17485. }
  17486. free_context(ctx);
  17487. pthread_setspecific(sTlsKey, NULL);
  17488. return NULL;
  17489. }
  17490. break;
  17491. }
  17492. }
  17493. /* Start master (listening) thread */
  17494. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17495. pthread_setspecific(sTlsKey, NULL);
  17496. return ctx;
  17497. }
  17498. struct mg_context *
  17499. mg_start(const struct mg_callbacks *callbacks,
  17500. void *user_data,
  17501. const char **options)
  17502. {
  17503. struct mg_init_data init = {0};
  17504. init.callbacks = callbacks;
  17505. init.user_data = user_data;
  17506. init.configuration_options = options;
  17507. return mg_start2(&init, NULL);
  17508. }
  17509. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17510. /* Add an additional domain to an already running web server. */
  17511. int
  17512. mg_start_domain2(struct mg_context *ctx,
  17513. const char **options,
  17514. struct mg_error_data *error)
  17515. {
  17516. const char *name;
  17517. const char *value;
  17518. const char *default_value;
  17519. struct mg_domain_context *new_dom;
  17520. struct mg_domain_context *dom;
  17521. int idx, i;
  17522. if (error != NULL) {
  17523. error->code = 0;
  17524. if (error->text_buffer_size > 0) {
  17525. *error->text = 0;
  17526. }
  17527. }
  17528. if ((ctx == NULL) || (options == NULL)) {
  17529. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17530. mg_snprintf(NULL,
  17531. NULL, /* No truncation check for error buffers */
  17532. error->text,
  17533. error->text_buffer_size,
  17534. "%s",
  17535. "Invalid parameters");
  17536. }
  17537. return -1;
  17538. }
  17539. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17540. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17541. mg_snprintf(NULL,
  17542. NULL, /* No truncation check for error buffers */
  17543. error->text,
  17544. error->text_buffer_size,
  17545. "%s",
  17546. "Server already stopped");
  17547. }
  17548. return -1;
  17549. }
  17550. new_dom = (struct mg_domain_context *)
  17551. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17552. if (!new_dom) {
  17553. /* Out of memory */
  17554. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17555. mg_snprintf(NULL,
  17556. NULL, /* No truncation check for error buffers */
  17557. error->text,
  17558. error->text_buffer_size,
  17559. "%s",
  17560. "Out or memory");
  17561. }
  17562. return -6;
  17563. }
  17564. /* Store options - TODO: unite duplicate code */
  17565. while (options && (name = *options++) != NULL) {
  17566. if ((idx = get_option_index(name)) == -1) {
  17567. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17568. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17569. mg_snprintf(NULL,
  17570. NULL, /* No truncation check for error buffers */
  17571. error->text,
  17572. error->text_buffer_size,
  17573. "Invalid option: %s",
  17574. name);
  17575. }
  17576. mg_free(new_dom);
  17577. return -2;
  17578. } else if ((value = *options++) == NULL) {
  17579. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17580. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17581. mg_snprintf(NULL,
  17582. NULL, /* No truncation check for error buffers */
  17583. error->text,
  17584. error->text_buffer_size,
  17585. "Invalid option value: %s",
  17586. name);
  17587. }
  17588. mg_free(new_dom);
  17589. return -2;
  17590. }
  17591. if (new_dom->config[idx] != NULL) {
  17592. /* Duplicate option: Later values overwrite earlier ones. */
  17593. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17594. mg_free(new_dom->config[idx]);
  17595. }
  17596. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17597. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17598. }
  17599. /* Authentication domain is mandatory */
  17600. /* TODO: Maybe use a new option hostname? */
  17601. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17602. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17603. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17604. mg_snprintf(NULL,
  17605. NULL, /* No truncation check for error buffers */
  17606. error->text,
  17607. error->text_buffer_size,
  17608. "Mandatory option %s missing",
  17609. config_options[AUTHENTICATION_DOMAIN].name);
  17610. }
  17611. mg_free(new_dom);
  17612. return -4;
  17613. }
  17614. /* Set default value if needed. Take the config value from
  17615. * ctx as a default value. */
  17616. for (i = 0; config_options[i].name != NULL; i++) {
  17617. default_value = ctx->dd.config[i];
  17618. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17619. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17620. }
  17621. }
  17622. new_dom->handlers = NULL;
  17623. new_dom->next = NULL;
  17624. new_dom->nonce_count = 0;
  17625. new_dom->auth_nonce_mask =
  17626. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17627. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17628. new_dom->shared_lua_websockets = NULL;
  17629. #endif
  17630. #if !defined(NO_SSL)
  17631. if (!init_ssl_ctx(ctx, new_dom)) {
  17632. /* Init SSL failed */
  17633. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17634. mg_snprintf(NULL,
  17635. NULL, /* No truncation check for error buffers */
  17636. error->text,
  17637. error->text_buffer_size,
  17638. "%s",
  17639. "Initializing SSL context failed");
  17640. }
  17641. mg_free(new_dom);
  17642. return -3;
  17643. }
  17644. #endif
  17645. /* Add element to linked list. */
  17646. mg_lock_context(ctx);
  17647. idx = 0;
  17648. dom = &(ctx->dd);
  17649. for (;;) {
  17650. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17651. dom->config[AUTHENTICATION_DOMAIN])) {
  17652. /* Domain collision */
  17653. mg_cry_ctx_internal(ctx,
  17654. "domain %s already in use",
  17655. new_dom->config[AUTHENTICATION_DOMAIN]);
  17656. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17657. mg_snprintf(NULL,
  17658. NULL, /* No truncation check for error buffers */
  17659. error->text,
  17660. error->text_buffer_size,
  17661. "Domain %s specified by %s is already in use",
  17662. new_dom->config[AUTHENTICATION_DOMAIN],
  17663. config_options[AUTHENTICATION_DOMAIN].name);
  17664. }
  17665. mg_free(new_dom);
  17666. mg_unlock_context(ctx);
  17667. return -5;
  17668. }
  17669. /* Count number of domains */
  17670. idx++;
  17671. if (dom->next == NULL) {
  17672. dom->next = new_dom;
  17673. break;
  17674. }
  17675. dom = dom->next;
  17676. }
  17677. mg_unlock_context(ctx);
  17678. /* Return domain number */
  17679. return idx;
  17680. }
  17681. int
  17682. mg_start_domain(struct mg_context *ctx, const char **options)
  17683. {
  17684. return mg_start_domain2(ctx, options, NULL);
  17685. }
  17686. #endif
  17687. /* Feature check API function */
  17688. unsigned
  17689. mg_check_feature(unsigned feature)
  17690. {
  17691. static const unsigned feature_set = 0
  17692. /* Set bits for available features according to API documentation.
  17693. * This bit mask is created at compile time, according to the active
  17694. * preprocessor defines. It is a single const value at runtime. */
  17695. #if !defined(NO_FILES)
  17696. | MG_FEATURES_FILES
  17697. #endif
  17698. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  17699. | MG_FEATURES_SSL
  17700. #endif
  17701. #if !defined(NO_CGI)
  17702. | MG_FEATURES_CGI
  17703. #endif
  17704. #if defined(USE_IPV6)
  17705. | MG_FEATURES_IPV6
  17706. #endif
  17707. #if defined(USE_WEBSOCKET)
  17708. | MG_FEATURES_WEBSOCKET
  17709. #endif
  17710. #if defined(USE_LUA)
  17711. | MG_FEATURES_LUA
  17712. #endif
  17713. #if defined(USE_DUKTAPE)
  17714. | MG_FEATURES_SSJS
  17715. #endif
  17716. #if !defined(NO_CACHING)
  17717. | MG_FEATURES_CACHE
  17718. #endif
  17719. #if defined(USE_SERVER_STATS)
  17720. | MG_FEATURES_STATS
  17721. #endif
  17722. #if defined(USE_ZLIB)
  17723. | MG_FEATURES_COMPRESSION
  17724. #endif
  17725. /* Set some extra bits not defined in the API documentation.
  17726. * These bits may change without further notice. */
  17727. #if defined(MG_LEGACY_INTERFACE)
  17728. | 0x00008000u
  17729. #endif
  17730. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17731. | 0x00004000u
  17732. #endif
  17733. #if defined(MEMORY_DEBUGGING)
  17734. | 0x00001000u
  17735. #endif
  17736. #if defined(USE_TIMERS)
  17737. | 0x00020000u
  17738. #endif
  17739. #if !defined(NO_NONCE_CHECK)
  17740. | 0x00040000u
  17741. #endif
  17742. #if !defined(NO_POPEN)
  17743. | 0x00080000u
  17744. #endif
  17745. ;
  17746. return (feature & feature_set);
  17747. }
  17748. static size_t
  17749. mg_str_append(char **dst, char *end, const char *src)
  17750. {
  17751. size_t len = strlen(src);
  17752. if (*dst != end) {
  17753. /* Append src if enough space, or close dst. */
  17754. if ((size_t)(end - *dst) > len) {
  17755. strcpy(*dst, src);
  17756. *dst += len;
  17757. } else {
  17758. *dst = end;
  17759. }
  17760. }
  17761. return len;
  17762. }
  17763. /* Get system information. It can be printed or stored by the caller.
  17764. * Return the size of available information. */
  17765. int
  17766. mg_get_system_info(char *buffer, int buflen)
  17767. {
  17768. char *end, *append_eoobj = NULL, block[256];
  17769. size_t system_info_length = 0;
  17770. #if defined(_WIN32)
  17771. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17772. #else
  17773. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17774. #endif
  17775. if ((buffer == NULL) || (buflen < 1)) {
  17776. buflen = 0;
  17777. end = buffer;
  17778. } else {
  17779. *buffer = 0;
  17780. end = buffer + buflen;
  17781. }
  17782. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17783. /* has enough space to append eoobj */
  17784. append_eoobj = buffer;
  17785. if (end) {
  17786. end -= sizeof(eoobj) - 1;
  17787. }
  17788. }
  17789. system_info_length += mg_str_append(&buffer, end, "{");
  17790. /* Server version */
  17791. {
  17792. const char *version = mg_version();
  17793. mg_snprintf(NULL,
  17794. NULL,
  17795. block,
  17796. sizeof(block),
  17797. "%s\"version\" : \"%s\"",
  17798. eol,
  17799. version);
  17800. system_info_length += mg_str_append(&buffer, end, block);
  17801. }
  17802. /* System info */
  17803. {
  17804. #if defined(_WIN32)
  17805. DWORD dwVersion = 0;
  17806. DWORD dwMajorVersion = 0;
  17807. DWORD dwMinorVersion = 0;
  17808. SYSTEM_INFO si;
  17809. GetSystemInfo(&si);
  17810. #if defined(_MSC_VER)
  17811. #pragma warning(push)
  17812. /* GetVersion was declared deprecated */
  17813. #pragma warning(disable : 4996)
  17814. #endif
  17815. dwVersion = GetVersion();
  17816. #if defined(_MSC_VER)
  17817. #pragma warning(pop)
  17818. #endif
  17819. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17820. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17821. mg_snprintf(NULL,
  17822. NULL,
  17823. block,
  17824. sizeof(block),
  17825. ",%s\"os\" : \"Windows %u.%u\"",
  17826. eol,
  17827. (unsigned)dwMajorVersion,
  17828. (unsigned)dwMinorVersion);
  17829. system_info_length += mg_str_append(&buffer, end, block);
  17830. mg_snprintf(NULL,
  17831. NULL,
  17832. block,
  17833. sizeof(block),
  17834. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17835. eol,
  17836. (unsigned)si.wProcessorArchitecture,
  17837. (unsigned)si.dwNumberOfProcessors,
  17838. (unsigned)si.dwActiveProcessorMask);
  17839. system_info_length += mg_str_append(&buffer, end, block);
  17840. #elif defined(__ZEPHYR__)
  17841. mg_snprintf(NULL,
  17842. NULL,
  17843. block,
  17844. sizeof(block),
  17845. ",%s\"os\" : \"%s %s\"",
  17846. eol,
  17847. "Zephyr OS",
  17848. ZEPHYR_VERSION);
  17849. system_info_length += mg_str_append(&buffer, end, block);
  17850. #else
  17851. struct utsname name;
  17852. memset(&name, 0, sizeof(name));
  17853. uname(&name);
  17854. mg_snprintf(NULL,
  17855. NULL,
  17856. block,
  17857. sizeof(block),
  17858. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17859. eol,
  17860. name.sysname,
  17861. name.version,
  17862. name.release,
  17863. name.machine);
  17864. system_info_length += mg_str_append(&buffer, end, block);
  17865. #endif
  17866. }
  17867. /* Features */
  17868. {
  17869. mg_snprintf(NULL,
  17870. NULL,
  17871. block,
  17872. sizeof(block),
  17873. ",%s\"features\" : %lu"
  17874. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17875. eol,
  17876. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17877. eol,
  17878. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17879. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17880. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17881. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17882. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17883. : "",
  17884. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17885. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17886. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17887. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17888. system_info_length += mg_str_append(&buffer, end, block);
  17889. #if defined(USE_LUA)
  17890. mg_snprintf(NULL,
  17891. NULL,
  17892. block,
  17893. sizeof(block),
  17894. ",%s\"lua_version\" : \"%u (%s)\"",
  17895. eol,
  17896. (unsigned)LUA_VERSION_NUM,
  17897. LUA_RELEASE);
  17898. system_info_length += mg_str_append(&buffer, end, block);
  17899. #endif
  17900. #if defined(USE_DUKTAPE)
  17901. mg_snprintf(NULL,
  17902. NULL,
  17903. block,
  17904. sizeof(block),
  17905. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17906. eol,
  17907. (unsigned)DUK_VERSION / 10000,
  17908. ((unsigned)DUK_VERSION / 100) % 100,
  17909. (unsigned)DUK_VERSION % 100);
  17910. system_info_length += mg_str_append(&buffer, end, block);
  17911. #endif
  17912. }
  17913. /* Build date */
  17914. {
  17915. #if defined(GCC_DIAGNOSTIC)
  17916. #if GCC_VERSION >= 40900
  17917. #pragma GCC diagnostic push
  17918. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  17919. #pragma GCC diagnostic ignored "-Wdate-time"
  17920. #endif
  17921. #endif
  17922. #ifdef BUILD_DATE
  17923. const char *bd = BUILD_DATE;
  17924. #else
  17925. const char *bd = __DATE__;
  17926. #endif
  17927. mg_snprintf(
  17928. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  17929. #if defined(GCC_DIAGNOSTIC)
  17930. #if GCC_VERSION >= 40900
  17931. #pragma GCC diagnostic pop
  17932. #endif
  17933. #endif
  17934. system_info_length += mg_str_append(&buffer, end, block);
  17935. }
  17936. /* Compiler information */
  17937. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17938. {
  17939. #if defined(_MSC_VER)
  17940. mg_snprintf(NULL,
  17941. NULL,
  17942. block,
  17943. sizeof(block),
  17944. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17945. eol,
  17946. (unsigned)_MSC_VER,
  17947. (unsigned)_MSC_FULL_VER);
  17948. system_info_length += mg_str_append(&buffer, end, block);
  17949. #elif defined(__MINGW64__)
  17950. mg_snprintf(NULL,
  17951. NULL,
  17952. block,
  17953. sizeof(block),
  17954. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17955. eol,
  17956. (unsigned)__MINGW64_VERSION_MAJOR,
  17957. (unsigned)__MINGW64_VERSION_MINOR);
  17958. system_info_length += mg_str_append(&buffer, end, block);
  17959. mg_snprintf(NULL,
  17960. NULL,
  17961. block,
  17962. sizeof(block),
  17963. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17964. eol,
  17965. (unsigned)__MINGW32_MAJOR_VERSION,
  17966. (unsigned)__MINGW32_MINOR_VERSION);
  17967. system_info_length += mg_str_append(&buffer, end, block);
  17968. #elif defined(__MINGW32__)
  17969. mg_snprintf(NULL,
  17970. NULL,
  17971. block,
  17972. sizeof(block),
  17973. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17974. eol,
  17975. (unsigned)__MINGW32_MAJOR_VERSION,
  17976. (unsigned)__MINGW32_MINOR_VERSION);
  17977. system_info_length += mg_str_append(&buffer, end, block);
  17978. #elif defined(__clang__)
  17979. mg_snprintf(NULL,
  17980. NULL,
  17981. block,
  17982. sizeof(block),
  17983. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17984. eol,
  17985. __clang_major__,
  17986. __clang_minor__,
  17987. __clang_patchlevel__,
  17988. __clang_version__);
  17989. system_info_length += mg_str_append(&buffer, end, block);
  17990. #elif defined(__GNUC__)
  17991. mg_snprintf(NULL,
  17992. NULL,
  17993. block,
  17994. sizeof(block),
  17995. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17996. eol,
  17997. (unsigned)__GNUC__,
  17998. (unsigned)__GNUC_MINOR__,
  17999. (unsigned)__GNUC_PATCHLEVEL__);
  18000. system_info_length += mg_str_append(&buffer, end, block);
  18001. #elif defined(__INTEL_COMPILER)
  18002. mg_snprintf(NULL,
  18003. NULL,
  18004. block,
  18005. sizeof(block),
  18006. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18007. eol,
  18008. (unsigned)__INTEL_COMPILER);
  18009. system_info_length += mg_str_append(&buffer, end, block);
  18010. #elif defined(__BORLANDC__)
  18011. mg_snprintf(NULL,
  18012. NULL,
  18013. block,
  18014. sizeof(block),
  18015. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18016. eol,
  18017. (unsigned)__BORLANDC__);
  18018. system_info_length += mg_str_append(&buffer, end, block);
  18019. #elif defined(__SUNPRO_C)
  18020. mg_snprintf(NULL,
  18021. NULL,
  18022. block,
  18023. sizeof(block),
  18024. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18025. eol,
  18026. (unsigned)__SUNPRO_C);
  18027. system_info_length += mg_str_append(&buffer, end, block);
  18028. #else
  18029. mg_snprintf(NULL,
  18030. NULL,
  18031. block,
  18032. sizeof(block),
  18033. ",%s\"compiler\" : \"other\"",
  18034. eol);
  18035. system_info_length += mg_str_append(&buffer, end, block);
  18036. #endif
  18037. }
  18038. /* Determine 32/64 bit data mode.
  18039. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18040. {
  18041. mg_snprintf(NULL,
  18042. NULL,
  18043. block,
  18044. sizeof(block),
  18045. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18046. "char:%u/%u, "
  18047. "ptr:%u, size:%u, time:%u\"",
  18048. eol,
  18049. (unsigned)sizeof(short),
  18050. (unsigned)sizeof(int),
  18051. (unsigned)sizeof(long),
  18052. (unsigned)sizeof(long long),
  18053. (unsigned)sizeof(float),
  18054. (unsigned)sizeof(double),
  18055. (unsigned)sizeof(long double),
  18056. (unsigned)sizeof(char),
  18057. (unsigned)sizeof(wchar_t),
  18058. (unsigned)sizeof(void *),
  18059. (unsigned)sizeof(size_t),
  18060. (unsigned)sizeof(time_t));
  18061. system_info_length += mg_str_append(&buffer, end, block);
  18062. }
  18063. /* Terminate string */
  18064. if (append_eoobj) {
  18065. strcat(append_eoobj, eoobj);
  18066. }
  18067. system_info_length += sizeof(eoobj) - 1;
  18068. return (int)system_info_length;
  18069. }
  18070. /* Get context information. It can be printed or stored by the caller.
  18071. * Return the size of available information. */
  18072. int
  18073. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18074. {
  18075. #if defined(USE_SERVER_STATS)
  18076. char *end, *append_eoobj = NULL, block[256];
  18077. size_t context_info_length = 0;
  18078. #if defined(_WIN32)
  18079. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18080. #else
  18081. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18082. #endif
  18083. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18084. if ((buffer == NULL) || (buflen < 1)) {
  18085. buflen = 0;
  18086. end = buffer;
  18087. } else {
  18088. *buffer = 0;
  18089. end = buffer + buflen;
  18090. }
  18091. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18092. /* has enough space to append eoobj */
  18093. append_eoobj = buffer;
  18094. end -= sizeof(eoobj) - 1;
  18095. }
  18096. context_info_length += mg_str_append(&buffer, end, "{");
  18097. if (ms) { /* <-- should be always true */
  18098. /* Memory information */
  18099. int blockCount = (int)ms->blockCount;
  18100. int64_t totalMemUsed = ms->totalMemUsed;
  18101. int64_t maxMemUsed = ms->maxMemUsed;
  18102. if (totalMemUsed > maxMemUsed) {
  18103. maxMemUsed = totalMemUsed;
  18104. }
  18105. mg_snprintf(NULL,
  18106. NULL,
  18107. block,
  18108. sizeof(block),
  18109. "%s\"memory\" : {%s"
  18110. "\"blocks\" : %i,%s"
  18111. "\"used\" : %" INT64_FMT ",%s"
  18112. "\"maxUsed\" : %" INT64_FMT "%s"
  18113. "}",
  18114. eol,
  18115. eol,
  18116. blockCount,
  18117. eol,
  18118. totalMemUsed,
  18119. eol,
  18120. maxMemUsed,
  18121. eol);
  18122. context_info_length += mg_str_append(&buffer, end, block);
  18123. }
  18124. if (ctx) {
  18125. /* Declare all variables at begin of the block, to comply
  18126. * with old C standards. */
  18127. char start_time_str[64] = {0};
  18128. char now_str[64] = {0};
  18129. time_t start_time = ctx->start_time;
  18130. time_t now = time(NULL);
  18131. int64_t total_data_read, total_data_written;
  18132. int active_connections = (int)ctx->active_connections;
  18133. int max_active_connections = (int)ctx->max_active_connections;
  18134. int total_connections = (int)ctx->total_connections;
  18135. if (active_connections > max_active_connections) {
  18136. max_active_connections = active_connections;
  18137. }
  18138. if (active_connections > total_connections) {
  18139. total_connections = active_connections;
  18140. }
  18141. /* Connections information */
  18142. mg_snprintf(NULL,
  18143. NULL,
  18144. block,
  18145. sizeof(block),
  18146. ",%s\"connections\" : {%s"
  18147. "\"active\" : %i,%s"
  18148. "\"maxActive\" : %i,%s"
  18149. "\"total\" : %i%s"
  18150. "}",
  18151. eol,
  18152. eol,
  18153. active_connections,
  18154. eol,
  18155. max_active_connections,
  18156. eol,
  18157. total_connections,
  18158. eol);
  18159. context_info_length += mg_str_append(&buffer, end, block);
  18160. /* Queue information */
  18161. #if !defined(ALTERNATIVE_QUEUE)
  18162. mg_snprintf(NULL,
  18163. NULL,
  18164. block,
  18165. sizeof(block),
  18166. ",%s\"queue\" : {%s"
  18167. "\"length\" : %i,%s"
  18168. "\"filled\" : %i,%s"
  18169. "\"maxFilled\" : %i,%s"
  18170. "\"full\" : %s%s"
  18171. "}",
  18172. eol,
  18173. eol,
  18174. ctx->sq_size,
  18175. eol,
  18176. ctx->sq_head - ctx->sq_tail,
  18177. eol,
  18178. ctx->sq_max_fill,
  18179. eol,
  18180. (ctx->sq_blocked ? "true" : "false"),
  18181. eol);
  18182. context_info_length += mg_str_append(&buffer, end, block);
  18183. #endif
  18184. /* Requests information */
  18185. mg_snprintf(NULL,
  18186. NULL,
  18187. block,
  18188. sizeof(block),
  18189. ",%s\"requests\" : {%s"
  18190. "\"total\" : %lu%s"
  18191. "}",
  18192. eol,
  18193. eol,
  18194. (unsigned long)ctx->total_requests,
  18195. eol);
  18196. context_info_length += mg_str_append(&buffer, end, block);
  18197. /* Data information */
  18198. total_data_read =
  18199. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18200. total_data_written =
  18201. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18202. mg_snprintf(NULL,
  18203. NULL,
  18204. block,
  18205. sizeof(block),
  18206. ",%s\"data\" : {%s"
  18207. "\"read\" : %" INT64_FMT ",%s"
  18208. "\"written\" : %" INT64_FMT "%s"
  18209. "}",
  18210. eol,
  18211. eol,
  18212. total_data_read,
  18213. eol,
  18214. total_data_written,
  18215. eol);
  18216. context_info_length += mg_str_append(&buffer, end, block);
  18217. /* Execution time information */
  18218. gmt_time_string(start_time_str,
  18219. sizeof(start_time_str) - 1,
  18220. &start_time);
  18221. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18222. mg_snprintf(NULL,
  18223. NULL,
  18224. block,
  18225. sizeof(block),
  18226. ",%s\"time\" : {%s"
  18227. "\"uptime\" : %.0f,%s"
  18228. "\"start\" : \"%s\",%s"
  18229. "\"now\" : \"%s\"%s"
  18230. "}",
  18231. eol,
  18232. eol,
  18233. difftime(now, start_time),
  18234. eol,
  18235. start_time_str,
  18236. eol,
  18237. now_str,
  18238. eol);
  18239. context_info_length += mg_str_append(&buffer, end, block);
  18240. }
  18241. /* Terminate string */
  18242. if (append_eoobj) {
  18243. strcat(append_eoobj, eoobj);
  18244. }
  18245. context_info_length += sizeof(eoobj) - 1;
  18246. return (int)context_info_length;
  18247. #else
  18248. (void)ctx;
  18249. if ((buffer != NULL) && (buflen > 0)) {
  18250. *buffer = 0;
  18251. }
  18252. return 0;
  18253. #endif
  18254. }
  18255. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18256. /* Get connection information. It can be printed or stored by the caller.
  18257. * Return the size of available information. */
  18258. int
  18259. mg_get_connection_info(const struct mg_context *ctx,
  18260. int idx,
  18261. char *buffer,
  18262. int buflen)
  18263. {
  18264. const struct mg_connection *conn;
  18265. const struct mg_request_info *ri;
  18266. char *end, *append_eoobj = NULL, block[256];
  18267. size_t connection_info_length = 0;
  18268. int state = 0;
  18269. const char *state_str = "unknown";
  18270. #if defined(_WIN32)
  18271. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18272. #else
  18273. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18274. #endif
  18275. if ((buffer == NULL) || (buflen < 1)) {
  18276. buflen = 0;
  18277. end = buffer;
  18278. } else {
  18279. *buffer = 0;
  18280. end = buffer + buflen;
  18281. }
  18282. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18283. /* has enough space to append eoobj */
  18284. append_eoobj = buffer;
  18285. end -= sizeof(eoobj) - 1;
  18286. }
  18287. if ((ctx == NULL) || (idx < 0)) {
  18288. /* Parameter error */
  18289. return 0;
  18290. }
  18291. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18292. /* Out of range */
  18293. return 0;
  18294. }
  18295. /* Take connection [idx]. This connection is not locked in
  18296. * any way, so some other thread might use it. */
  18297. conn = (ctx->worker_connections) + idx;
  18298. /* Initialize output string */
  18299. connection_info_length += mg_str_append(&buffer, end, "{");
  18300. /* Init variables */
  18301. ri = &(conn->request_info);
  18302. #if defined(USE_SERVER_STATS)
  18303. state = conn->conn_state;
  18304. /* State as string */
  18305. switch (state) {
  18306. case 0:
  18307. state_str = "undefined";
  18308. break;
  18309. case 1:
  18310. state_str = "not used";
  18311. break;
  18312. case 2:
  18313. state_str = "init";
  18314. break;
  18315. case 3:
  18316. state_str = "ready";
  18317. break;
  18318. case 4:
  18319. state_str = "processing";
  18320. break;
  18321. case 5:
  18322. state_str = "processed";
  18323. break;
  18324. case 6:
  18325. state_str = "to close";
  18326. break;
  18327. case 7:
  18328. state_str = "closing";
  18329. break;
  18330. case 8:
  18331. state_str = "closed";
  18332. break;
  18333. case 9:
  18334. state_str = "done";
  18335. break;
  18336. }
  18337. #endif
  18338. /* Connection info */
  18339. if ((state >= 3) && (state < 9)) {
  18340. mg_snprintf(NULL,
  18341. NULL,
  18342. block,
  18343. sizeof(block),
  18344. "%s\"connection\" : {%s"
  18345. "\"remote\" : {%s"
  18346. "\"protocol\" : \"%s\",%s"
  18347. "\"addr\" : \"%s\",%s"
  18348. "\"port\" : %u%s"
  18349. "},%s"
  18350. "\"handled_requests\" : %u%s"
  18351. "}",
  18352. eol,
  18353. eol,
  18354. eol,
  18355. get_proto_name(conn),
  18356. eol,
  18357. ri->remote_addr,
  18358. eol,
  18359. ri->remote_port,
  18360. eol,
  18361. eol,
  18362. conn->handled_requests,
  18363. eol);
  18364. connection_info_length += mg_str_append(&buffer, end, block);
  18365. }
  18366. /* Request info */
  18367. if ((state >= 4) && (state < 6)) {
  18368. mg_snprintf(NULL,
  18369. NULL,
  18370. block,
  18371. sizeof(block),
  18372. "%s%s\"request_info\" : {%s"
  18373. "\"method\" : \"%s\",%s"
  18374. "\"uri\" : \"%s\",%s"
  18375. "\"query\" : %s%s%s%s"
  18376. "}",
  18377. (connection_info_length > 1 ? "," : ""),
  18378. eol,
  18379. eol,
  18380. ri->request_method,
  18381. eol,
  18382. ri->request_uri,
  18383. eol,
  18384. ri->query_string ? "\"" : "",
  18385. ri->query_string ? ri->query_string : "null",
  18386. ri->query_string ? "\"" : "",
  18387. eol);
  18388. connection_info_length += mg_str_append(&buffer, end, block);
  18389. }
  18390. /* Execution time information */
  18391. if ((state >= 2) && (state < 9)) {
  18392. char start_time_str[64] = {0};
  18393. char close_time_str[64] = {0};
  18394. time_t start_time = conn->conn_birth_time;
  18395. time_t close_time = 0;
  18396. double time_diff;
  18397. gmt_time_string(start_time_str,
  18398. sizeof(start_time_str) - 1,
  18399. &start_time);
  18400. #if defined(USE_SERVER_STATS)
  18401. close_time = conn->conn_close_time;
  18402. #endif
  18403. if (close_time != 0) {
  18404. time_diff = difftime(close_time, start_time);
  18405. gmt_time_string(close_time_str,
  18406. sizeof(close_time_str) - 1,
  18407. &close_time);
  18408. } else {
  18409. time_t now = time(NULL);
  18410. time_diff = difftime(now, start_time);
  18411. close_time_str[0] = 0; /* or use "now" ? */
  18412. }
  18413. mg_snprintf(NULL,
  18414. NULL,
  18415. block,
  18416. sizeof(block),
  18417. "%s%s\"time\" : {%s"
  18418. "\"uptime\" : %.0f,%s"
  18419. "\"start\" : \"%s\",%s"
  18420. "\"closed\" : \"%s\"%s"
  18421. "}",
  18422. (connection_info_length > 1 ? "," : ""),
  18423. eol,
  18424. eol,
  18425. time_diff,
  18426. eol,
  18427. start_time_str,
  18428. eol,
  18429. close_time_str,
  18430. eol);
  18431. connection_info_length += mg_str_append(&buffer, end, block);
  18432. }
  18433. /* Remote user name */
  18434. if ((ri->remote_user) && (state < 9)) {
  18435. mg_snprintf(NULL,
  18436. NULL,
  18437. block,
  18438. sizeof(block),
  18439. "%s%s\"user\" : {%s"
  18440. "\"name\" : \"%s\",%s"
  18441. "}",
  18442. (connection_info_length > 1 ? "," : ""),
  18443. eol,
  18444. eol,
  18445. ri->remote_user,
  18446. eol);
  18447. connection_info_length += mg_str_append(&buffer, end, block);
  18448. }
  18449. /* Data block */
  18450. if (state >= 3) {
  18451. mg_snprintf(NULL,
  18452. NULL,
  18453. block,
  18454. sizeof(block),
  18455. "%s%s\"data\" : {%s"
  18456. "\"read\" : %" INT64_FMT ",%s"
  18457. "\"written\" : %" INT64_FMT "%s"
  18458. "}",
  18459. (connection_info_length > 1 ? "," : ""),
  18460. eol,
  18461. eol,
  18462. conn->consumed_content,
  18463. eol,
  18464. conn->num_bytes_sent,
  18465. eol);
  18466. connection_info_length += mg_str_append(&buffer, end, block);
  18467. }
  18468. /* State */
  18469. mg_snprintf(NULL,
  18470. NULL,
  18471. block,
  18472. sizeof(block),
  18473. "%s%s\"state\" : \"%s\"",
  18474. (connection_info_length > 1 ? "," : ""),
  18475. eol,
  18476. state_str);
  18477. connection_info_length += mg_str_append(&buffer, end, block);
  18478. /* Terminate string */
  18479. if (append_eoobj) {
  18480. strcat(append_eoobj, eoobj);
  18481. }
  18482. connection_info_length += sizeof(eoobj) - 1;
  18483. return (int)connection_info_length;
  18484. }
  18485. #endif
  18486. /* Initialize this library. This function does not need to be thread safe.
  18487. */
  18488. unsigned
  18489. mg_init_library(unsigned features)
  18490. {
  18491. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18492. unsigned features_inited = features_to_init;
  18493. if (mg_init_library_called <= 0) {
  18494. /* Not initialized yet */
  18495. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18496. return 0;
  18497. }
  18498. }
  18499. mg_global_lock();
  18500. if (mg_init_library_called <= 0) {
  18501. #if defined(_WIN32)
  18502. int file_mutex_init = 1;
  18503. int wsa = 1;
  18504. #else
  18505. int mutexattr_init = 1;
  18506. #endif
  18507. int failed = 1;
  18508. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18509. if (key_create == 0) {
  18510. #if defined(_WIN32)
  18511. file_mutex_init =
  18512. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18513. if (file_mutex_init == 0) {
  18514. /* Start WinSock */
  18515. WSADATA data;
  18516. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18517. }
  18518. #else
  18519. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18520. if (mutexattr_init == 0) {
  18521. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18522. PTHREAD_MUTEX_RECURSIVE);
  18523. }
  18524. #endif
  18525. }
  18526. if (failed) {
  18527. #if defined(_WIN32)
  18528. if (wsa == 0) {
  18529. (void)WSACleanup();
  18530. }
  18531. if (file_mutex_init == 0) {
  18532. (void)pthread_mutex_destroy(&global_log_file_lock);
  18533. }
  18534. #else
  18535. if (mutexattr_init == 0) {
  18536. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18537. }
  18538. #endif
  18539. if (key_create == 0) {
  18540. (void)pthread_key_delete(sTlsKey);
  18541. }
  18542. mg_global_unlock();
  18543. (void)pthread_mutex_destroy(&global_lock_mutex);
  18544. return 0;
  18545. }
  18546. #if defined(USE_LUA)
  18547. lua_init_optional_libraries();
  18548. #endif
  18549. }
  18550. mg_global_unlock();
  18551. #if !defined(NO_SSL)
  18552. if (features_to_init & MG_FEATURES_SSL) {
  18553. if (!mg_ssl_initialized) {
  18554. char ebuf[128];
  18555. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18556. mg_ssl_initialized = 1;
  18557. } else {
  18558. (void)ebuf;
  18559. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18560. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18561. }
  18562. } else {
  18563. /* ssl already initialized */
  18564. }
  18565. }
  18566. #endif
  18567. mg_global_lock();
  18568. if (mg_init_library_called <= 0) {
  18569. mg_init_library_called = 1;
  18570. } else {
  18571. mg_init_library_called++;
  18572. }
  18573. mg_global_unlock();
  18574. return features_inited;
  18575. }
  18576. /* Un-initialize this library. */
  18577. unsigned
  18578. mg_exit_library(void)
  18579. {
  18580. if (mg_init_library_called <= 0) {
  18581. return 0;
  18582. }
  18583. mg_global_lock();
  18584. mg_init_library_called--;
  18585. if (mg_init_library_called == 0) {
  18586. #if !defined(NO_SSL)
  18587. if (mg_ssl_initialized) {
  18588. uninitialize_ssl();
  18589. mg_ssl_initialized = 0;
  18590. }
  18591. #endif
  18592. #if defined(_WIN32)
  18593. (void)WSACleanup();
  18594. (void)pthread_mutex_destroy(&global_log_file_lock);
  18595. #else
  18596. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18597. #endif
  18598. (void)pthread_key_delete(sTlsKey);
  18599. #if defined(USE_LUA)
  18600. lua_exit_optional_libraries();
  18601. #endif
  18602. mg_global_unlock();
  18603. (void)pthread_mutex_destroy(&global_lock_mutex);
  18604. return 1;
  18605. }
  18606. mg_global_unlock();
  18607. return 1;
  18608. }
  18609. /* End of civetweb.c */